Types and conventions
This reference describes the paired Node package selected above. Generic F is a Callable; T is the input object type. SDK means ReturnType<typeof createAgindow>, not an additional exported class. Runtime imports come from agindow; use import type for interfaces. The practical guide introduces the call flow before these signatures.
Create and initialize
Signature: createAgindow(options?: Options, load?: EngineLoader): SDK
Parameters: options supplies initial configuration, selection, work, selectiveRepair or audit. load is an advanced engine-loader seam; ordinary integrations use the default bundled engine.
Returns: An independent instance. sdk.ready is Promise<void>, resolving after the load attempt. The exported agindow singleton is created with default options.
Failures: Invalid deterministic setup throws AgindowSetupError. Engine loading failure is contained; subsequent calls emit bypass. Promise settlement does not guarantee loading succeeded or detection is configured.
Usage: const sdk = createAgindow({ mode: 'observe' }); await sdk.ready;
Guard a callable
Signature: sdk.guard<F extends Callable>(fn: F, options?: GuardOptions): F
Parameters: fn is your original function. options supplies tool, operation (read by default), toolName, inputShape and call policy. Explicitly label writes/unknown operations.
Returns: The original callable type, argument and receiver behavior; synchronous remains synchronous and a Promise result remains asynchronous. Observe returns the original result by reference.
Failures: Setup misuse throws AgindowSetupError. Original exceptions propagate; policy can throw AgindowDriftError. Internal faults bypass. A response halt can follow upstream completion.
Usage: const read = sdk.guard(() => client.orders.get(id), { tool: 'orders.get', operation: 'read' });
Choose a boundary automatically
Signature: sdk.wrap<T extends object>(target: T, options?: ClientOptions): T
Parameters: target may be a callable, supported tool map/array, client or HTTP target. Use an explicit adapter if more than one shape matches.
Returns: A wrapped target of type T. Unknown or unsupported targets can remain unchanged with a warning; that is not proof of inspection.
Failures: Ambiguity and deterministic misuse can throw AgindowSetupError. Per-call errors follow guard semantics.
Usage: const guarded = sdk.wrap(readOrder, { tool: 'orders.get' });
Adapt tools
Signature: sdk.toolAdapter<T extends object>(target: T, options?: GuardOptions): T
Parameters: A supported ToolMap/ToolArray or executor shape. Names and operation labels come from supported entries or explicit options.
Returns: A wrapped target preserving supported executor metadata and receivers.
Failures: Unsupported/immutable executors may remain unchanged with warnings. A class requires its supported framework executor hook; response formatting repair can bypass.
Usage: const guardedTools = sdk.toolAdapter(tools);
Adapt an API client
Signature: sdk.clientAdapter<T extends object>(target: T, options?: ClientOptions): T
Parameters: A supported client object. ClientOptions.tool accepts a string or dynamic function. Authentication, connection and storage methods are excluded from HTTP interception.
Returns: A wrapped target of type T with supported method receivers preserved.
Failures: Unsupported or immutable methods can be unchanged. Runtime call failures follow guard; no complete framework batch/stream guarantee.
Usage: const guardedClient = sdk.clientAdapter(client);
Adapt HTTP
Signature: sdk.httpAdapter<T extends object>(target: T, options?: GuardOptions): T
Parameters: A supported fetch/HTTP/Express shape and optional tool/operation policy. Supported request/response projections are adapter-specific.
Returns: An HTTP-shaped target of type T. A returned Response stays a Response.
Failures: Incomplete, opaque or streaming bodies can bypass inspection rather than inventing evidence. Unsupported forms do not gain automatic repair.
Usage: const guardedFetch = sdk.httpAdapter(fetch, { tool: 'orders.get' });
Update future-call policy
Signature: sdk.configure(config: Config): void
Parameters: config contains call policy, not construction-only selection, work or selectiveRepair. Later revisions affect future calls, including previously created guards.
Returns: void; an executing call retains its frozen configuration.
Failures: Invalid explicit configuration throws AgindowSetupError. Semantic-write protections and strict policy cannot be disabled by failClosed opt-out.
Usage: sdk.configure({ mode: 'observe' });
Subscribe to events
Signature: sdk.on(kind: Event['type'], listener: (event: Event) => void): () => void
Parameters: kind is drift, repair, blocked, bypass or error; listener receives bounded frozen metadata.
Returns: An unsubscribe function. No success event is emitted solely for completing a call.
Failures: Listener faults are contained. Events are not durable storage and cannot change the engine decision.
Usage: const stop = sdk.on('bypass', event => console.warn(event.tool)); stop();
Read recent events
Signature: sdk.recent(): readonly Event[]
Parameters: No parameters. buffer defaults to 100; 0 disables retention.
Returns: A bounded history in emission order. Empty history does not prove detection was selected, eligible or drift-free.
Failures: Missing optional audit/feedback metadata remains absent; history is process-local and not a durable archive.
Usage: const events = sdk.recent();
Simulate a recording
Signature: sdk.simulate(tool: string, input: SimulationInput): Simulation
Parameters: input requires recorded, with optional args, partial, contract and guard policy. No provider request is made.
Returns: status (no_drift/observed/blocked/bypassed/repaired/degraded), driftClass, confidence, changes, byte_identical and wouldWrite. A supplied sandbox contract is a distinct evaluation path.
Failures: Partial evidence and internal failures return bypassed; invalid setup can throw AgindowSetupError. Simulation does not establish real vendor acceptance.
Usage: const result = sdk.simulate('orders.get', { recorded: savedOrder, operation: 'read' });
Drain the optional audit FIFO
Signature: sdk.drainAudit(sink: AuditSink, limit?: number): Promise<AuditDrain>
Parameters: sink persists a detached AuditRecord after the guarded call. limit defaults to 64. Construction requires explicit audit options; cannot be combined with selectiveRepair.
Returns: A Promise with delivered, pending, dropped and available. Acknowledge only after persistence succeeds.
Failures: Unavailable guest/drain or sink failure stays visible through the receipt; no durable replay guarantee is supplied.
Usage: const receipt = await sdk.drainAudit(persistAudit);
Execute through an explicit remote host
Signature: guardRemote<T>(original: (input: RemoteEnvelope) => T | Promise<T>, envelope: RemoteEnvelope, options: RemoteOptions): Promise<Response | T>
Parameters: original is your fallback, envelope describes the scoped call, and options requires endpoint with optional timeoutMs (5000), apiKey or auth, onEvent and onAuthDiagnostic. Writes/unknown require idempotency_key.
Returns: A fetch Response or original fallback result T. Read the response body once.
Failures: Setup misuse can throw AgindowSetupError; valid policy feedback throws AgindowDriftError. Unavailable transport/auth can fallback; completed vendor outcomes are not blindly replayed. No hosted endpoint is provided.
Usage: const response = await guardRemote(fallback, envelope, options);
Create remote authentication
Signature: createRemoteAuth(options: RemoteAuthOptions): Promise<RemoteAuth>
Parameters: options.acquire(thumbprint) returns Promise<AccessCredential> with accessToken and Unix-seconds expiresAt. Optional signer, now, schedule, allowLegacyFallback, legacyKey and onDiagnostic control local lifecycle.
Returns: A session with headers(method, target), refresh(): Promise<boolean>, close(): void. Header generation reads memory/signs locally; acquisition/refresh is off-path.
Failures: Unavailable initial identity without an explicitly accepted legacy fallback throws AgindowSetupError. headers may return undefined and refresh may return false. Close stops timers and clears cached credentials.
Usage: const auth = await createRemoteAuth({ acquire });
Create a proof signer
Signature: createProofSigner(): ProofSigner
Parameters: No parameters. Creates an ephemeral Ed25519 keypair inside this process.
Returns: thumbprint and proof(token, method, target, now): string; now is Unix seconds. No private-key serialization is exposed.
Failures: Invalid HTTP proof targets can throw AgindowSetupError. A response-provided key does not establish trust.
Usage: const signer = createProofSigner();
Prepare workload acquisition
Signature: workloadIdentity(options: WorkloadIdentityOptions): (thumbprint: string) => Promise<AccessCredential>
Parameters: Required exchangeEndpoint, registration and tools. Optional audience, ttl, tokenFile or assertion callback. Registration grants scope, not a local tenant string.
Returns: An acquire callback for createRemoteAuth. Assertion/file/provider I/O runs only during setup/background refresh.
Failures: Invalid endpoint throws AgindowSetupError; unavailable assertion or failed exchange rejects acquisition. No machine registration is automatically provisioned.
Usage: const acquire = workloadIdentity(identityOptions);
Default exports and public types
agindow is the default SDK instance. Module-level guard, wrap, toolAdapter, clientAdapter, httpAdapter and simulate delegate to it. There is no module-level configure/on/recent export and no embedded sdk.close method. Use the instance for configuration and event lifecycle.
| Export family | Names and detail |
|---|---|
| Configuration and callable types | Mode, Operation, Callable, Config (AgindowConfig alias), Options, GuardOptions, StatisticalSelection, Transformer; complete fields in configuration. |
| Events and decisions | Event (AgindowEvent alias), Verdict, PolicyFeedback, VerifiedRepair; fields in events/verdicts reference. |
| Repair types | SelectiveRepairOptions, RenameRule, RepairCheck; confidence, scope and synchronous verification rules in configuration. |
| Adapter and simulation types | ToolLike, ToolMap, ToolArray, ClientOptions, SimulationInput, Simulation, SandboxContract, SandboxFields, SandboxResult. Sandbox types describe explicit offline contracts, not runtime discovery. |
| Audit and engine seams | AuditSink, AuditRecord, AuditDrain, Engine, EngineCall, EngineLoader. Host/test seams do not enable an external engine service. |
| Remote and identity types | RemoteEnvelope, RemoteOptions, RemoteAuth, RemoteAuthOptions, AccessCredential, ProofSigner, WorkloadIdentityOptions. |
| Errors | AgindowSetupError and AgindowDriftError: phase, verdict, outcome, code, hint, driftClass, driftId and auditUrl. Optional/missing evidence is not a link guarantee. |
Observe candidate diagnostic
This synthetic injected-engine fixture checks that observe retains the original result even when a candidate replacement is offered. It is a local policy diagnostic, not vendor detection or a live repair.
import { createAgindow } from 'agindow';
import type { Verdict } from 'agindow';
const pass: Verdict = { halt: false, bypassed: false, class: null, findings: 0, detectors: 0, malformed: false };
const payload = { old: 'synthetic-value' };
// Synthetic candidate engine: only a fixture, not the default WASM engine.
const sdk = createAgindow({ mode: 'observe' }, async () => ({
begin: () => ({ request: pass, close() {}, finish: () => ({ ...pass,
class: 'shape', findings: 1, confidence: 0.99,
repair: { verified: true, value: { current: 'synthetic-value' }, changes: [{ path: 'old', kind: 'field_renamed', to: 'current' }] },
}) }),
}));
await sdk.ready;
const result = sdk.guard(() => payload, { tool: 'vendor.read' })();
if (result !== payload || !('old' in result)) throw Error('Observe applied a candidate');
console.log('Synthetic fixture: offered patch remained unapplied in observe.');Advanced availability fixture
This retained local test fixture intentionally makes an engine unavailable and verifies identity and one bypass. It is a diagnostic exercise, not drift detection or the first integration example. No vendor service is contacted.
import { createAgindow } from 'agindow';
const sdk = createAgindow({ mode: 'observe' });
await sdk.ready;
const payload = { id: 'synthetic-customer' };
let calls = 0;
const read = sdk.guard(() => { calls++; return payload; }, { tool: 'vendor.read', operation: 'read' });
const result = read();
if (result !== payload || calls !== 1) throw Error('Fixture identity changed');
// A labelled unavailable-engine fixture produces one bypass without a hosted key.
const unavailable = createAgindow({ mode: 'observe' }, async () => { throw Error('Synthetic loading fault'); });
await unavailable.ready;
const fallback = unavailable.wrap(() => payload);
if (fallback() !== payload || unavailable.recent().filter(e => e.type === 'bypass').length !== 1) throw Error('Missing bypass');
sdk.configure({ mode: 'observe' });
console.log('Synthetic fixture: original result retained; unavailable engine bypassed once.');