Skip to content

You are currently viewing documentation for0.1.0-beta.1

Node.js SDK API reference

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.

alpha.4/a3 additions

This release additionally exports compareOperation(input: OperationComparisonInput, work?: number): Promise<OperationComparisonResult>. It compares explicit baseline/current sources scoped to the same route, method, side and version. Each source supplies kind (declared or observed), provenance, complete and JSON body. Results contain coverage, gaps, requiredness and findings with paths, compatibility and provenance. Declared schemas support a bounded type/properties/required/string-or-null-enum/items subset; unsupported constraints abstain. Observed presence never declares requiredness. This advisory utility does not change guard policy or authorize repair. Local ScalarRule/ScalarFacts types additionally enable reviewed finite string mappings, literal empty-string-to-null normalization and exact supported unit/epoch scaling through selectiveRepair, with mandatory scoped expiring facts, independent host verification and the semantic .99 gate. These additions are included in the published package pair. No hosted availability is implied.

Detection status

Available in the Beta SDKs. Published alpha.4/a3 do not include this API. Node exposes sdk.detectionStatus(): DetectionStatus. Read it after awaiting sdk.ready and after a guarded call. It performs no I/O or test call and does not read the event ring. Fields are state, engine (loading/ready/unavailable), selectedFields, requestFields, responseFields, mode, repairConfigured and lastCall. lastCall retains the latest-started call’s tool, mode, operation, complete/bypassed flags and nullable request/response metadata. Each phase exposes state, detectors, findings, reason, sufficientDetectors, insufficientDetectors, eligibleDetectors and suppressedDetectors. Snapshots and arrays are frozen. Engine ready means loaded; repairConfigured means rules were supplied, not applied.

HTTP envelope observations

Available in the Beta SDKs. Published alpha.4/a3 do not export these APIs. Signature: httpSample({status, contentType?, headers?}): HttpSample | null; compareHttpEnvelope({baseline, current}, work?): Promise<HttpObservation>. Windows contain scope {tenant, connection, operation, version, cohort}, provenance, complete, cohortStable, transportFailures, samples and optional credentialEvents. Both windows need exact scope and 64–512 independent samples. work is a u32, default 200000000; the metadata envelope cap is 262144 bytes. Invalid/unavailable comparisons return immutable unavailable evidence without throwing application errors. Exported types include HttpScope, HttpSample, HttpWindow, HttpEnvelopeInput, HttpObservation, HttpCapture, HttpObservationOptions and HttpAdapterOptions. Explicit sdk.httpAdapter(fetch, {tool, httpObservation: {scope, provenance, onObservation}}) delivers immutable metadata on a later event-loop turn. tool must equal scope.operation. Capture fields are scope, provenance, complete, sample or null, fixed reason or null, and dropped. Treat unavailable captures and overflow as incomplete collection. Express and dynamic tool-name capture are unsupported. Existing guard events, mode and upstream outcomes remain separate.

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 familyNames and detail
Configuration and callable typesMode, Operation, Callable, Config (AgindowConfig alias), Options, GuardOptions, StatisticalSelection, Transformer; complete fields in configuration.
Events and decisionsEvent (AgindowEvent alias), Verdict, PolicyFeedback, VerifiedRepair; fields in events/verdicts reference.
Repair typesSelectiveRepairOptions, RepairRule, RenameRule, RepairCheck, ScalarRule, ScalarFacts, RepairFacts; confidence, scope and synchronous verification rules in configuration.
Adapter and simulation typesToolLike, ToolMap, ToolArray, ClientOptions, SimulationInput, Simulation, SandboxContract, SandboxFields, SandboxResult. Sandbox types describe explicit offline contracts, not runtime discovery.
Audit and engine seamsAuditSink, AuditRecord, AuditDrain, Engine, EngineCall, EngineLoader. Host/test seams do not enable an external engine service.
Remote and identity typesRemoteEnvelope, RemoteOptions, RemoteAuth, RemoteAuthOptions, AccessCredential, ProofSigner, WorkloadIdentityOptions.
ErrorsAgindowSetupError 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.

ts
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.

ts
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.');

To issue a scoped API key, open the dashboard, select your organization and environment, then go to Settings → API Keys.