Types and conventions
Import public names from agindow. P/R below stand for the original callable ParamSpec and return type. Config and event names are Python-specific; ready is a synchronous property. The practical guide covers decorators and async calls first.
Construct an instance
Signature: Agindow(config: Config | None = None, *, engine: Engine | None = None, selection: dict[str, object] | None = None, selective_repair: SelectiveRepair | None = None, work: int = 200_000_000, **overrides: object)
Parameters: config supplies an optional Config object. Keyword overrides supply Python call settings. selection/work/selective_repair are construction-only. engine is an advanced host/test seam and cannot be combined with selective repair.
Returns: An Agindow instance; construction attempts the engine load synchronously. An explicit Config object replaces resolved configuration as documented.
Failures: Invalid configuration raises AgindowSetupError. Engine load exceptions are retained in load_error; later guarded calls bypass.
Usage: sdk = Agindow(mode="observe")
Inspect readiness
Signature: sdk.ready: bool; sdk.load_error: Exception | None
Parameters: No parameters. Read the properties after construction.
Returns: ready indicates that an engine exists, while load_error retains its load failure. Neither establishes that a detector is selected.
Failures: Never await sdk.ready. A failed load preserves original calls via bypass rather than an SDK-generated request exception.
Usage: if not sdk.ready: print("Inspection unavailable")
Decorate or guard a callable
Signature: sdk.guard(fn=None, *, tool: str | None = None, operation: Operation = "read", **changes: object)
Parameters: fn is Callable[P, R]; omitted fn returns a decorator. tool names the operation; operation labels read/write/unknown, while changes supplies call policy.
Returns: Callable[P, R] or a decorator producing it. Sync functions stay sync; coroutine functions stay async. Arguments, results and exceptions retain the original behavior in observe mode.
Failures: Invalid setup raises AgindowSetupError. Original exceptions/cancellation propagate. Policy can raise AgindowDriftError; response-phase outcome may already be completed.
Usage: @sdk.guard(tool="orders.get", operation="read")
Wrap a callable directly
Signature: sdk.wrap(target: Callable[P, R], *, tool: str | None = None, operation: Operation = "read", **changes: object) -> Callable[P, R]
Parameters: target is one callable, not a Node-style tool collection/client/HTTP adapter.
Returns: A guarded callable with the same sync/async contract.
Failures: Same setup, policy, upstream and availability semantics as guard; no automatic Python framework selection.
Usage: read = sdk.wrap(client.get_order, tool="orders.get")
Apply task-local scopes
Signature: sdk.context(**options: object) -> Scope
Parameters: Python call-policy overrides for this SDK instance. Scope supports __enter__/__exit__ and __aenter__/__aexit__.
Returns: A synchronous/asynchronous context manager. It applies ContextVar overrides and restores the previous scope on exit. Executing calls retain a frozen snapshot.
Failures: Invalid options or re-entering the same active scope raises AgindowSetupError. Context exit does not swallow application exceptions or cancellation.
Usage: async with sdk.context(mode="observe"): await read_order()
Update future calls
Signature: sdk.configure(**changes: object) -> None
Parameters: Python call-policy fields; construction-only engine selection is separate. Decorator keyword overrides can take precedence over instance/context settings.
Returns: None; future calls use the updated policy and resized event buffer.
Failures: Invalid changes raise AgindowSetupError. Do not assume Node revision precedence is identical.
Usage: sdk.configure(mode="observe", buffer=100)
Subscribe to local events
Signature: sdk.on(kind: EventType, listener: Callable[[Event], None]) -> Callable[[], None]
Parameters: kind is drift, repair, blocked, bypass or error. EventType describes those literals; use an event kind string at the public call boundary.
Returns: An unsubscribe callable. Listeners receive Event metadata with snake_case fields.
Failures: Listener exceptions are contained. A callback cannot authorize a repair or establish persistence.
Usage: stop = sdk.on("bypass", lambda event: print(event.tool)); stop()
Read local events
Signature: sdk.recent() -> tuple[Event, ...]
Parameters: No parameters. Config.buffer defaults to 100; 0 disables retention.
Returns: A bounded event tuple. No normal-success event is emitted. Empty history does not establish detector eligibility or safety.
Failures: Local history is not durable storage and does not imply an audit artifact was retained.
Usage: events = sdk.recent()
Close the engine
Signature: sdk.close() -> None
Parameters: No parameters. Use a finally block when your instance owns a finite operation lifecycle.
Returns: None. Releases the engine and contains cleanup faults; subsequent guarded calls bypass.
Failures: Cleanup failure must not replace upstream outcomes. Closing an instance is distinct from cancelling a vendor operation.
Usage: sdk.close()
Configure reviewed repair
Signature: SelectiveRepair(rules: tuple[RenameRule, ...], verify: Callable[[RepairCheck], bool])
Parameters: RenameRule(tool, side, source, target, migration, confidence) scopes reviewed top-level fields. RepairCheck(before: str, after: str, rule: RenameRule) supplies immutable JSON to a synchronous independent verifier.
Returns: A construction option passed as selective_repair. Acceptance requires reviewed facts, complete capture, confidence and repair/strict mode.
Failures: Invalid rules raise AgindowSetupError. Verifier faults or async results bypass. A false verifier does not authorize application; existing findings are not cleared to force repair.
Usage: sdk = Agindow(selective_repair=reviewed_repair, mode="observe")
Use the module-level instance
Signature: default() -> Agindow
Parameters: No parameters. Lazily constructs one module-owned instance.
Returns: Module-level guard, wrap, context, configure and recent delegate to that instance. Their callable/return contracts match the instance methods.
Failures: No module-level on or close helper is exported; call default().on(...) or default().close() explicitly. Prefer independent instances for application-owned lifecycles.
Usage: from agindow import guard, context, configure, recent
Call a remote host synchronously
Signature: guard_remote(original: Callable[[RemoteEnvelope], R], envelope: RemoteEnvelope, options: RemoteOptions) -> RemoteResponse | R
Parameters: original supplies fallback. RemoteEnvelope(tool, connection, operation, args, mode, idempotency_key=None); RemoteOptions(endpoint, api_key=None, timeout_seconds=5, on_event=None, auth=None, on_auth_diagnostic=None).
Returns: RemoteResponse(status, headers, body) or fallback R. response.read(amount=None) returns bytes; response.close() releases its transport.
Failures: Setup misuse raises AgindowSetupError; valid policy feedback raises AgindowDriftError. Transport/auth failure can fallback. A completed vendor outcome is not blindly replayed; writes/unknown need the same vendor-enforced idempotency key.
Usage: response = guard_remote(fallback, envelope, options)
Call a remote host asynchronously
Signature: async guard_remote_async(original: Callable[[RemoteEnvelope], R], envelope: RemoteEnvelope, options: RemoteOptions) -> RemoteResponse | R
Parameters: Same envelope/options and synchronous fallback contract as guard_remote. The blocking transport executes in a worker thread.
Returns: Awaitable yielding RemoteResponse or R; close remote responses after reading.
Failures: Same setup, policy and fallback rules. Cancelling the await does not prove a worker/vendor write stopped.
Usage: response = await guard_remote_async(fallback, envelope, options)
Sign proofs and refresh remote identity
Signature: RemoteAuth(acquire, signer, *, now=time, schedule=True, allow_legacy_fallback=False, legacy_key=None, on_diagnostic=None)
Parameters: acquire: Callable[[str], AccessCredential]; AccessCredential(access_token: str, expires_at: int). ProofSigner(public_x: str, sign: Callable[[bytes], bytes]) keeps host-owned Ed25519 custody.
Returns: RemoteAuth.headers(method, target) -> dict[str, str] | None; refresh() -> bool; close() -> None. ProofSigner.thumbprint and proof(token, method, target, now) -> str. Acquisition runs at setup/background refresh, not guarded calls.
Failures: Initial unavailable identity without explicit fallback raises AgindowSetupError. Failed refresh returns false and unavailable headers return None. Invalid public keys/targets refuse. Close stops timers and releases cached credentials.
Usage: auth = RemoteAuth(acquire, signer)
Prepare workload acquisition
Signature: workload_identity(*, exchange_endpoint, registration, tools, audience="agindow:guard", ttl=300, token_file=None, assertion=None) -> Callable[[str], AccessCredential]
Parameters: exchange_endpoint and registration are strings; tools is tuple[str, ...]. Optional token_file: str and assertion: Callable[[], str] supply host-owned workload material.
Returns: An acquire callback for RemoteAuth; registration fixes authority. No tenant argument grants scope.
Failures: Invalid endpoint raises AgindowSetupError; missing assertions and failed exchanges fail acquisition. Provider I/O occurs outside guarded calls, with no automatic registration.
Usage: acquire = workload_identity(exchange_endpoint=url, registration=registration, tools=tools)
Configuration, models and exceptions
Config is a frozen dataclass with mode, fail_closed, api_key, endpoint, allowed_tools, deny_tools, buffer and on_event. Mode and Operation are literal type aliases. Event, Verdict, PolicyFeedback and VerifiedRepair are frozen data models; Python Verdict does not expose Node detector-name arrays. AgindowSetupError identifies deterministic ValueError setup misuse. AgindowDriftError is a RuntimeError exposing tool, mode, phase, verdict, outcome, code, hint, drift_class, drift_id and audit_url. The Python root exports Agindow, Scope, Config, Event, Mode, Operation, PolicyFeedback, Verdict, VerifiedRepair, the two error classes, RenameRule, RepairCheck, SelectiveRepair, remote models/functions, RemoteAuth, AccessCredential, ProofSigner and workload_identity, plus default/guard/wrap/context/configure/recent. It exports no Node adapters, simulation method, CLI or guest audit drain.
Observe candidate diagnostic
This local injected-engine diagnostic checks observe policy without a vendor call. Synthetic replacement metadata does not demonstrate configured drift detection or an applied repair.
from agindow import Agindow
from agindow.types import Verdict, VerifiedRepair
class _Call:
@property
def request(self) -> Verdict:
return Verdict()
def finish(self, value: object) -> Verdict:
return Verdict(
drift_class="shape",
findings=1,
confidence=0.99,
repair=VerifiedRepair(value={"current": "synthetic-value"}, changes=(("old", "field_renamed"),)),
)
def close(self) -> None:
return None
class _Candidate:
def begin(self, value: object, mode: str, operation: str, fail_closed: bool, tool: str) -> _Call:
return _Call()
payload = {"old": "synthetic-value"}
# Synthetic candidate engine: only a fixture, not the default WASM engine.
sdk = Agindow(mode="observe", engine=_Candidate())
@sdk.guard(tool="vendor.read")
def read() -> dict[str, str]:
return payload
result = read()
if result is not payload or "old" not in result:
raise AssertionError("Observe applied a candidate")
print("Synthetic fixture: offered patch remained unapplied in observe.")Advanced scope and availability fixture
This retained local diagnostic fixture covers sync/async ContextVar scopes, identity and a closed-engine bypass. It is deliberately synthetic and does not report vendor drift. The practical guide uses a normal API read instead.
import asyncio
from agindow import Agindow
sdk = Agindow(mode="observe")
payload = {"id": "synthetic-customer"}
@sdk.guard(tool="vendor.read", operation="read")
def read() -> dict[str, str]:
return payload
@sdk.guard(tool="vendor.read", operation="read")
async def read_async() -> dict[str, str]:
return payload
with sdk.context(mode="observe"):
assert read() is payload
async def main() -> None:
async with sdk.context(mode="observe"):
assert await read_async() is payload
asyncio.run(main())
# A closed engine is a labelled availability fixture, not vendor drift.
sdk.close()
assert read() is payload
assert len([event for event in sdk.recent() if event.type == "bypass"]) == 1
print("Synthetic fixture: sync/async identity retained; closed engine bypassed once.")