Skip to content

You are currently viewing documentation for0.1.0-alpha.4

Saved documentation for 0.1.0-alpha.4 (npm) / 0.1.0a3 (PyPI). Interactive tools use the current release. View latest documentation.

Remote SDK Execution

When to use remote execution

Make explicit remote AGINDOW calls from Node.js or Python, and handle transport, authentication and fallback safely. Choose remote execution when your application intentionally delegates a configured tool call to a separate HTTP guard host. You supply and operate that endpoint and its connection bindings; managed execution is not available. Use embedded execution to inspect your existing callable inside the application. Setting endpoint or apiKey on an embedded SDK never changes its transport.

Embedded executionRemote execution
Local SDK guards the supported callable boundary.Explicit helper POSTs an execution envelope to your host.
Your application invokes its existing client.Your host resolves the admitted connection/tool and invokes upstream.
Local selection, readiness and call configuration.Endpoint, host-owned credentials, transport and authentication setup.

How remote calls work

The endpoint performs the admitted upstream operation. The helper owns transport and fallback selection; your application owns reconciliation.

  1. Application
  2. Remote SDK helper
  3. HTTP endpoint
  4. Response or fallback
StepResponsibility
ApplicationSupplies the envelope and original fallback for the same logical operation.
Remote SDK helperSends JSON, refuses redirects and interprets transport/policy feedback.
HTTP endpointYour host authorizes the connection/tool, owns vendor credentials and performs the operation.
Response or fallbackReturns the upstream response, raises a policy error or invokes your original callable.

Make your first remote call

Runnable local transport exercise: use Node 22.6+ for the native TypeScript command. Install the pinned SDK from the Node or Python guide, save the selected tab as remote.mts or remote.py, then run node --experimental-strip-types remote.mts or python remote.py. Each program starts and closes its own loopback HTTP protocol fixture, prints customer data, and demonstrates fallback after shutdown. No credentials are needed for this local fixture. It does not run an AGINDOW engine or prove drift detection. For integration, replace the fixture with your configured guard host and the original read with your client; use the host-assigned connection/tool handles. Never expose this fixture as a service.

import { createServer } from 'node:http';
import { guardRemote } from 'agindow';
import type { RemoteEnvelope } from 'agindow';
let originalCalls = 0;
// Original application read. Replace with your existing client in an integration.
const readCustomer = (input: RemoteEnvelope): Response => {
  originalCalls++;
  return Response.json({ id: (input.args as { id: string }).id, name: 'Ada' });
};
// Protocol fixture only: fixed read binding, no AGINDOW engine or vendor call.
const host = createServer(async (request, response) => {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(Buffer.from(chunk));
  const input = JSON.parse(Buffer.concat(chunks).toString()) as RemoteEnvelope;
  if (request.url !== '/v1/guard' || input.tool !== 'crm.read'
    || input.connection !== 'local' || input.operation !== 'read') {
    response.writeHead(400).end(); return;
  }
  response.writeHead(200, { 'content-type': 'application/json' });
  response.end(JSON.stringify({ id: (input.args as { id: string }).id, name: 'Ada' }));
});
await new Promise<void>(resolve => host.listen(0, '127.0.0.1', resolve));
const address = host.address();
if (!address || typeof address === 'string') throw Error('Missing local address');
const options = { endpoint: `http://127.0.0.1:${address.port}/v1/guard`, timeoutMs: 1000 };
const envelope: RemoteEnvelope = {
  tool: 'crm.read', connection: 'local', operation: 'read',
  args: { id: 'customer-123' }, mode: 'observe',
};
try {
  const result = await guardRemote(readCustomer, envelope, options);
  const customer = await result.json() as { id: string };
  if (result.status !== 200 || customer.id !== 'customer-123' || originalCalls !== 0) throw Error('Remote read failed');
  console.log(result.status, customer); // 200, customer data
} finally {
  await new Promise<void>((resolve, reject) => host.close(error => error ? reject(error) : resolve()));
}
// The unavailable endpoint now invokes the original read, once for this call.
const fallback = await guardRemote(readCustomer, envelope, options);
if (fallback.status !== 200 || Number(originalCalls) !== 1) throw Error('Fallback failed');
console.log('Original read returned after transport failure');
import asyncio
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
from agindow import (RemoteEnvelope, RemoteOptions, RemoteResponse,
                     guard_remote, guard_remote_async)

original_calls = 0
# Original application read; replace with your existing client in an integration.
def read_customer(input: RemoteEnvelope) -> RemoteResponse:
    global original_calls
    original_calls += 1
    body = json.dumps({"id": "customer-123", "name": "Ada"}).encode()
    return RemoteResponse(200, {"content-type": "application/json"}, body)

# Protocol fixture only: fixed read binding, no engine or vendor call.
class Host(BaseHTTPRequestHandler):
    def do_POST(self) -> None:
        value = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        if (self.path != "/v1/guard" or value["tool"] != "crm.read"
                or value["connection"] != "local" or value["operation"] != "read"):
            self.send_error(400)
            return
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps({"id": value["args"]["id"], "name": "Ada"}).encode())
    def log_message(self, format: str, *args: object) -> None:
        pass

host = ThreadingHTTPServer(("127.0.0.1", 0), Host)
thread = Thread(target=host.serve_forever, daemon=True)
thread.start()
envelope = RemoteEnvelope(tool="crm.read", connection="local", operation="read",
                          args={"id": "customer-123"}, mode="observe")
options = RemoteOptions(endpoint=f"http://127.0.0.1:{host.server_port}/v1/guard",
                        timeout_seconds=1)
def show(result: RemoteResponse) -> None:
    try:
        customer = json.loads(result.read())
        assert result.status == 200 and customer["id"] == "customer-123"
        print(result.status, customer)
    finally:
        result.close()
async def main() -> None:
    # Async helper takes the same synchronous fallback, running in a worker thread.
    show(await guard_remote_async(read_customer, envelope, options))
try:
    show(guard_remote(read_customer, envelope, options))
    asyncio.run(main())
    assert original_calls == 0
finally:
    host.shutdown()
    host.server_close()
    thread.join()
# Closed endpoint: original read supplies this call's value.
show(guard_remote(read_customer, envelope, options))
assert original_calls == 1

Handle remote responses

The helper returns the HTTP response or exactly the fallback value; it does not return a universal AGINDOW result object. Returning the same response abstraction from your fallback simplifies handling, as in the example. The body belongs to the upstream API. Inspect HTTP status and X-Agindow-Status separately.

OutcomeWhat the caller receives
Completed executionNode Response; Python RemoteResponse. Parse Node bodies once; read and close Python responses.
Rejected request / authentication failureOrdinary 4xx including 401, 403 and 429 is returned. Check status; no automatic credential retry or fallback.
Transport, timeout or auth material unavailableOriginal fallback result and a bypass event, if a listener is supplied.
Unclassified guard 5xxFallback. A 5xx marked ok, degraded, repaired or bypassed preserves the completed upstream response.
Valid policy 409AgindowDriftError with phase, verdict, feedback and outcome. A response halt may retrieve a same-origin retained outcome.
Invalid setup / fallback exceptionAgindowSetupError before execution; errors from your original callable propagate.

Safe fallback behavior

A lost response does not establish that upstream never executed. For write and unknown operations, the helper requires idempotency_key before sending. Both your host and original fallback must preserve that same key and logical call, with vendor-enforced deduplication. The SDK provides no durable or distributed replay store. If the vendor cannot deduplicate, keep automated write fallback out of that integration; use a reconciliation path in the supplied original callback.

SituationFallback / next step
Known rejection before dispatchReturned 4xx or request-phase policy error. Correct setup/policy before another attempt.
Lost response / timeout / malformed policy feedbackHelper may invoke original; writes remain uncertain. Deduplicate or reconcile, never assume zero execution.
Completed remote responseReturn it, including a marked upstream 5xx. Do not replay because it failed.
Completed response-phase haltInspect error.outcome and retained evidence. Recovery failure never triggers fallback for a valid policy halt. outcome may then be only the consumed/closed policy response, not the original vendor body.
Caller body-read failure / Python cancellationNo safe-replay guarantee. Reconcile the original operation; a response-phase failure cannot undo a write.

Authentication and security

Basic endpoint authentication: explicitly pass apiKey (Node) or api_key (Python) in RemoteOptions only when the host admits that legacy credential. It sends Authorization: Bearer and emits legacy_unbound through the diagnostic callback. Obtain credentials from your host operator and secret storage; public key issuance is unavailable. Embedded Config credentials are not automatically copied into remote options. Use HTTPS for non-loopback endpoints and keep vendor secrets in host connection bindings. The local fixture intentionally needs no credential. These option-builder snippets expect your host-issued credential as an argument; they do not acquire credentials or make a call.

import type { RemoteOptions } from 'agindow';
// Pass a host-issued key from secret storage, never a vendor API key.
export function authenticatedOptions(endpoint: string, apiKey: string): RemoteOptions {
  return { endpoint, apiKey, timeoutMs: 5000,
    onAuthDiagnostic: reason => console.log(reason),
  };
}
from agindow import RemoteOptions
# Pass a host-issued key from secret storage, never a vendor API key.
def authenticated_options(endpoint: str, api_key: str) -> RemoteOptions:
    return RemoteOptions(endpoint=endpoint, api_key=api_key, timeout_seconds=5,
                         on_auth_diagnostic=print)

Customer-key host opt-in

Local unreleased source supports dashboard keys at the optional hosted guard wrapper with the closed sdk.remote scope. The existing apiKey / api_key option sends the same Bearer key and selects sdk.remote with X-Agindow-Key-Use. Host policy separately binds tenant, environment, connection/tool routes and quotas. Verification uses only a locally installed signed snapshot and non-extractable scoped HMAC material; refresh and withdrawal happen outside calls. Stale snapshot state bypasses inspection once; known credential and scope refusals remain 401 / 403. Operator digest credentials remain separate optional bootstrap credentials. Ordinary onboarding uses dashboard scopes after host qualification; it does not mint per-customer Cloudflare digests. No default installation provider, public hosted endpoint or hosted-key onboarding is enabled, and this source change does not advance published package versions.

Prepare sender-bound credentials

When your host supports workload identity, prefer an explicitly acquired auth session. Node createProofSigner() returns thumbprint and proof(token, method, target, now). await createRemoteAuth({acquire, signer?, schedule?}) calls your acquire(thumbprint) outside guarded calls; it must exchange against your trusted identity service and return {accessToken, expiresAt} in Unix seconds. Pass {endpoint, auth} to guardRemote and close the session at shutdown. Python RemoteAuth(acquire, signer, schedule=True) requires a host-owned ProofSigner(public_x, sign); acquire(thumbprint) returns AccessCredential(access_token, expires_at). Its refresh() is synchronous and returns bool; close() stops background refresh. workload_identity prepares the explicit platform identity source. Both languages require trusted exchange setup; no signer or credentials are discovered from the envelope. headers(method, target) never acquires identity inside a call; refresh runs separately. Expired/unavailable proof material invokes fallback, while an endpoint 401/403 remains a response. Do not pass both auth and apiKey/api_key. Legacy fallback requires explicit auth-session opt-in; it is never automatic discovery.

Options and return values

Exact public call signatures; T is your original callback return type. The Python async helper expects a synchronous original callback, not an async function.

APISignature and result
NodeguardRemote<T>(original: (input: RemoteEnvelope) => T | Promise<T>, input: RemoteEnvelope, options: RemoteOptions): Promise<Response | T>
Python responseRemoteResponse exposes status, headers, read(amount=None) -> bytes and close() -> None. Close after consuming the body.
Python syncguard_remote(original: Callable[[RemoteEnvelope], R], input: RemoteEnvelope, options: RemoteOptions) -> RemoteResponse | R
Python asyncawait guard_remote_async(original, input, options) -> RemoteResponse | R; blocking transport runs in a worker thread. Cancellation does not prove upstream stopped.

Transport option reference

Remote options are independent of SDK construction. Node callbacks receive camelCase event fields; Python receives snake_case fields. Listener faults are contained and local events are not durable audit records.

Node / PythonDefault and behavior
endpoint / endpointRequired full HTTP(S) /v1/guard URL, no userinfo. Python rejects fragments. Neither helper follows redirects.
timeoutMs / timeout_seconds5000 ms / 5 seconds; positive finite values. Node max 2147483647 ms.
Node timeoutDeadline covers initial fetch and feedback; retained recovery uses remaining time. Successful response-body consumption is caller-owned and outside this deadline.
Python timeoutSocket transport timeout, not a strict total deadline; recovery uses remaining budget. Body reading and cancellation differ from Node.
apiKey / api_keyAbsent; explicit legacy Bearer credential. Must match agw_test_ or agw_live_ plus 32–256 URL-safe characters.
auth / authAbsent; pre-acquired sender-bound session. Mutually exclusive with the direct API-key option.
onEvent / on_eventAbsent; callback for bypass metadata. Node includes reason and latencyUs; Python latency_us.
onAuthDiagnostic / on_auth_diagnosticAbsent; callback receives legacy_unbound when a direct key is used.

Envelope differences

Both APIs require tool, connection, operation, args and mode; write/unknown requires idempotency_key. args is a JSON-compatible application value, not an arbitrary upstream URL or credential container. Node permits optional metadata. Python RemoteEnvelope has no metadata or durability keyword. Omit reserved durability. A mode does not configure detector windows; current execution hosts do not apply selective repair. Embedded reviewed repair is configured separately. For all field limits and the closed HTTP schema use the execution reference.