@k9o/extension-runtime 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * k9o.webhookIngress — handler registration for verified inbound webhooks and CometD events
3
+ * ("Webhook and CometD delivery", RULED 2026-10-04).
4
+ *
5
+ * The name mirrors the manifest key (`webhookIngress[]`) and deliberately does not reuse
6
+ * `webhooks`: `webhooks.subscribe` is the platform-event consumer (a permission domain), while this is
7
+ * the vendor-facing ingress. Register by the declared `webhookIngress[].path` (for a CometD entry, the
8
+ * channel path):
9
+ *
10
+ * k9o.webhookIngress.handle("/events", async (delivery, ctx) => { ... });
11
+ *
12
+ * Delivery: the gateway verifies the signature BEFORE enqueueing, then sends a frame with the gateway-set
13
+ * `context.kind = "webhook"` and `context.webhookPath` (the registration key). The discriminator routes
14
+ * here only on that field, never to `bff.dispatch` or a hook handler, and a bff or hook frame never
15
+ * reaches this table. The handler never re-verifies and never receives the per-path HMAC secret or an
16
+ * OAuth credential. Frames go only to an ENABLED install.
17
+ *
18
+ * Semantics: any normal return acknowledges (the gateway treats any 2xx as an ack); a throw is a 5xx
19
+ * and the delivery is retried from the outbox, so handlers MUST be idempotent. `delivery.deliveryId`
20
+ * is the idempotency key (the vendor's id where the scheme has one, else a content hash; for CometD
21
+ * `cometd:<channel>:<replayId>`). Delivery is at-least-once, serial per channel.
22
+ */
23
+
24
+ import type { DispatchContext } from "../dispatch-context.ts";
25
+
26
+ /** The gateway-built delivery payload. Unknown extra fields pass through untouched. */
27
+ export type WebhookDelivery = {
28
+ /** The declared `webhookIngress` path, or the CometD channel. */
29
+ path: string;
30
+ /** Idempotency key. */
31
+ deliveryId: string;
32
+ scheme: string;
33
+ /** ISO 8601 receipt time. */
34
+ receivedAt?: string;
35
+ contentType?: string;
36
+ /** Allowlisted headers only: the declared timestamp and signature header names and `content-type`. */
37
+ headers?: Record<string, string>;
38
+ /** The raw body as a string. */
39
+ body: string;
40
+ /** The parsed JSON when the content type is JSON. */
41
+ json?: unknown;
42
+ /** CometD only. */
43
+ replayId?: number | string;
44
+ [extra: string]: unknown;
45
+ };
46
+
47
+ export type WebhookHandler = (delivery: WebhookDelivery, ctx: DispatchContext) => Promise<unknown> | unknown;
48
+
49
+ export type WebhookIngressNamespace = {
50
+ /** Register the handler for one declared path (or CometD channel). Last write wins. */
51
+ handle(path: string, handler: WebhookHandler): void;
52
+ /**
53
+ * Deliver to the handler registered for `path`. Used by the invoke server for `context.kind ===
54
+ * "webhook"` frames. `deliveryId` is the gateway-set idempotency key from the frame context and is
55
+ * REQUIRED: a frame without one is not delivered. Rejects (5xx, retried) when no
56
+ * handler is registered, the payload is not an object, or the payload disagrees with the gateway-set
57
+ * context about the path or delivery id.
58
+ */
59
+ dispatch(path: string, payload: unknown, ctx: DispatchContext, deliveryId: string): Promise<unknown>;
60
+ /** Paths that have a handler. Frozen snapshot. */
61
+ registeredPaths(): readonly string[];
62
+ };
63
+
64
+ export function makeWebhookIngress(): WebhookIngressNamespace {
65
+ const registry = new Map<string, WebhookHandler>();
66
+
67
+ return {
68
+ handle(path, handler) {
69
+ if (typeof path !== "string" || path.length === 0) throw new RangeError("webhookIngress path must be a non-empty string");
70
+ registry.set(path, handler);
71
+ },
72
+
73
+ async dispatch(path, payload, ctx, expectedDeliveryId) {
74
+ if (typeof expectedDeliveryId !== "string" || expectedDeliveryId.length === 0) {
75
+ throw new Error("webhook frame has no gateway-set deliveryId");
76
+ }
77
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
78
+ throw new Error("webhook payload must be an object");
79
+ }
80
+ const body = payload as Record<string, unknown>;
81
+ // The context is gateway-set and trusted; a payload that disagrees with it is not delivered.
82
+ if (body["path"] !== undefined && body["path"] !== path) {
83
+ throw new Error("webhook payload path does not match the delivered path");
84
+ }
85
+ if (body["deliveryId"] !== undefined && body["deliveryId"] !== expectedDeliveryId) {
86
+ throw new Error("webhook payload deliveryId does not match the frame");
87
+ }
88
+ const handler = registry.get(path);
89
+ if (handler === undefined) throw new Error("no webhook handler is registered for this path");
90
+ const result = await handler({ ...body, path, deliveryId: expectedDeliveryId } as WebhookDelivery, ctx);
91
+ return result ?? null;
92
+ },
93
+
94
+ registeredPaths() {
95
+ return Object.freeze([...registry.keys()]);
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * k9o.workflow — workflow trigger + await.
3
+ *
4
+ * trigger: fires a named workflow and returns the runId immediately
5
+ * (non-blocking; the workflow executes async on the compute pillar).
6
+ *
7
+ * await: polls the run status until completion, failure, or timeout.
8
+ * timeoutMs defaults to 30 000 ms (30 s); poll interval is 500 ms.
9
+ * On timeout, throws RuntimeKError with code WORKFLOW_AWAIT_TIMEOUT.
10
+ *
11
+ * Endpoint paths are provisional until the platform confirms canonical paths.
12
+ */
13
+
14
+ import { RuntimeKError } from "../kerror.ts";
15
+ import type { Transport } from "../http.ts";
16
+ import type { ApiResponse, WorkflowRunStatus, WorkflowTriggerResult } from "../types.ts";
17
+
18
+ const POLL_INTERVAL_MS = 500;
19
+ const DEFAULT_TIMEOUT_MS = 30_000;
20
+
21
+ export type WorkflowNamespace = {
22
+ trigger(
23
+ workflowId: string,
24
+ input?: Record<string, unknown>,
25
+ ): Promise<ApiResponse<WorkflowTriggerResult>>;
26
+ await(
27
+ workflowId: string,
28
+ runId: string,
29
+ options?: { timeoutMs?: number },
30
+ ): Promise<ApiResponse<WorkflowRunStatus>>;
31
+ };
32
+
33
+ export function makeWorkflow(
34
+ transport: Transport,
35
+ projectSlug: string,
36
+ ): WorkflowNamespace {
37
+ const runBase = (wfId: string, runId: string) =>
38
+ `/@${projectSlug}/workflows/${wfId}/runs/${runId}`;
39
+
40
+ return {
41
+ trigger: (workflowId, input = {}) =>
42
+ transport.post<WorkflowTriggerResult>(
43
+ `/@${projectSlug}/workflows/${workflowId}/trigger`,
44
+ { input },
45
+ ),
46
+
47
+ async await(workflowId, runId, options) {
48
+ const deadline = Date.now() + (options?.timeoutMs ?? DEFAULT_TIMEOUT_MS);
49
+ while (Date.now() < deadline) {
50
+ const res = await transport.get<WorkflowRunStatus>(
51
+ runBase(workflowId, runId),
52
+ );
53
+ if (res.data.status !== "running") {
54
+ return res;
55
+ }
56
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
57
+ }
58
+ throw new RuntimeKError(
59
+ "WORKFLOW_AWAIT_TIMEOUT",
60
+ `Workflow run ${runId} did not complete within ${options?.timeoutMs ?? DEFAULT_TIMEOUT_MS}ms`,
61
+ { workflowId, runId },
62
+ );
63
+ },
64
+ };
65
+ }
package/src/types.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Shared types for the @k9o/extension-runtime runtime SDK.
3
+ *
4
+ * Wire format is always camelCase JSON +
5
+ */
6
+
7
+ /** Platform response envelope */
8
+ export type ApiResponse<T> = {
9
+ data: T;
10
+ meta: Meta;
11
+ };
12
+
13
+ /**
14
+ * — the compliance-export fetch response. Kibo's own bundle type
15
+ * (`kibo-ledger`'s doc-referenced `CredentialAttestationBundle`) is NOT a fixed
16
+ * struct on the signing side either — it's canonicalized+signed as an opaque
17
+ * `serde_json::Value`, and the gateway forwards it byte-identical, never parses
18
+ * or re-shapes it. Deliberately untyped here rather than asserting field names
19
+ * this SDK has never verified against the real crypto side — the extension
20
+ * author (or the 3-step external verifier) is the one who interprets it.
21
+ */
22
+ export type CredentialAttestationBundle = Record<string, unknown>;
23
+
24
+ export type Meta = {
25
+ cursor: { next: string | null } | null;
26
+ subscription: { isInitial: boolean } | null;
27
+ idempotency: { replayed: boolean } | null;
28
+ warnings: string[] | null;
29
+ };
30
+
31
+ /** KError wire shape + */
32
+ export type KErrorPayload = {
33
+ code: string;
34
+ message: string;
35
+ context: Record<string, unknown>;
36
+ recommendation: Record<string, unknown> | null;
37
+ };
38
+
39
+ /** Sandbox context injected by the K9O runtime per the platform's env-injection contract. */
40
+ export type SandboxContext = {
41
+ /** Scoped plugin token + — actor: "extension". */
42
+ pluginToken: string;
43
+ /** Platform API base URL (e.g. https://api.k9o.io/v2). */
44
+ baseUrl: string;
45
+ /** Bound project ID per enable (e.g. proj_abc123) — immutable data-model identity. */
46
+ projectId: string;
47
+ /**
48
+ * Bound project slug — the `@<projectSlug>` path segment used in all gateway
49
+ * URL construction (e.g. "my-project" → `/@my-project/...`). Gateway resolves
50
+ * slug→id server-side; only the URL grammar uses the slug
51
+ * (the canonical path rule).
52
+ */
53
+ projectSlug: string;
54
+ /** Extension slug — used in egress routing + audit attribution. */
55
+ extensionSlug: string;
56
+ /** True when running inside k9o partner dev; absent in production. */
57
+ devMode?: boolean;
58
+ /** SHA256 fingerprint of the synthetic dev key — present when devMode is true. */
59
+ devModeKeyFingerprint?: string;
60
+ };
61
+
62
+ // --- Data types ---
63
+
64
+ export type Document = Record<string, unknown>;
65
+
66
+ export type DocumentFilter = {
67
+ /** Simple equality filter map — each key/value pair is an AND condition. */
68
+ eq?: Record<string, unknown>;
69
+ limit?: number;
70
+ cursor?: string;
71
+ };
72
+
73
+ export type Collection = {
74
+ id: string;
75
+ slug: string;
76
+ name: string;
77
+ createdAt: string;
78
+ };
79
+
80
+ export type AttributeMap = Record<string, unknown>;
81
+
82
+ // --- Identity ---
83
+
84
+ export type IdentityClaims = {
85
+ userId: string;
86
+ orgId: string;
87
+ projectId: string;
88
+ roles: string[];
89
+ extensionId: string;
90
+ extensionSlug: string;
91
+ };
92
+
93
+ // --- Policy (Maker-Checker) ---
94
+
95
+ export type PolicyResult =
96
+ | { pending: false; allowed: boolean }
97
+ | { pending: true; pendingId: string; estimatedResolutionAt: string | null };
98
+
99
+ // --- Kibo Vault ---
100
+
101
+ export type KiboEncryptResult = { ciphertext: string; keyId: string };
102
+ export type KiboDecryptResult = { plaintext: string };
103
+
104
+ // --- AI text generation ---
105
+
106
+ export type GenerateOptions = {
107
+ /** 1 to 32000. */
108
+ maxTokens?: number;
109
+ /** 0 to 2. */
110
+ temperature?: number;
111
+ /** Metering label for the call. */
112
+ usageType?: string;
113
+ /** Defaults to the organisation's default language model if omitted. */
114
+ model?: string;
115
+ };
116
+
117
+ export type GenerateResult = {
118
+ modelId: string;
119
+ content: string;
120
+ finishReason: string;
121
+ usage: { promptTokens: number; completionTokens: number; totalTokens: number };
122
+ usageType: string;
123
+ };
124
+
125
+ /** `k9o.ai.embed()` options. The model defaults to the platform's; it is the only one today. */
126
+ export type EmbedOptions = { model?: string };
127
+
128
+ /** One vector per input, in input order; every vector is `dimensions` wide. */
129
+ export type EmbedResult = {
130
+ embeddings: number[][];
131
+ model: string;
132
+ dimensions: number;
133
+ };
134
+
135
+ // --- Workflow ---
136
+
137
+ export type WorkflowTriggerResult = { runId: string };
138
+ export type WorkflowRunStatus = {
139
+ runId: string;
140
+ status: "running" | "completed" | "failed" | "cancelled";
141
+ output: Record<string, unknown> | null;
142
+ error: KErrorPayload | null;
143
+ };
package/src/warden.ts ADDED
@@ -0,0 +1,320 @@
1
+ /**
2
+ * §A.gate-guest — sole host-call surface for the Enforced Boundary runtime.
3
+ *
4
+ * Guest-side vsock bridge.
5
+ *
6
+ * Two transports, selected automatically:
7
+ *
8
+ * 1. **Direct AF_VSOCK** (primary, Linux only) — connects straight to the
9
+ * host's vsock dispatcher (`gate-dispatcher.ts`, `VMADDR_CID_HOST:9000`)
10
+ * via raw libc syscalls through `bun:ffi`. No intermediary process is
11
+ * required inside the guest: Bun has no native `AF_VSOCK` support in
12
+ * `node:net`, so this calls `socket(2)`/`connect(2)`/`write(2)`/`read(2)`
13
+ * directly against `libc.so.6`. This removes the dependency on a guest
14
+ * init/proxy process entirely — the historical assumption that "the
15
+ * Firecracker vsock ↔ UDS proxy is provided by the extension runtime"
16
+ * is replaced by this module doing the bridging itself.
17
+ * 2. **Local UDS fallback** (`K9O_GATE_SOCKET`, non-Linux / vsock-socket()
18
+ * unavailable) — preserves the original behavior for local dev/test and
19
+ * any environment that fronts the gate with a UDS proxy.
20
+ *
21
+ * Framing (both transports): 4-byte LE u32 length + UTF-8 JSON body,
22
+ * synchronous one-request→one-response per connection.
23
+ *
24
+ * §A.gate-guest invariant: this is the ONLY host-call surface exported by
25
+ * this module. No second egress path; the vsock socket connects to exactly
26
+ * one destination (VMADDR_CID_HOST:GATE_PORT), mirroring the host
27
+ * dispatcher's single-path contract.
28
+ */
29
+
30
+ import { createConnection } from "node:net";
31
+ import { dlopen, FFIType } from "bun:ffi";
32
+
33
+ const MAX_FRAME_BYTES = 1024 * 1024; // 1 MiB — matches host dispatcher bound
34
+ const DEFAULT_GATE_TIMEOUT_MS = 5000;
35
+
36
+ // AF_VSOCK guest→host well-known CID (VMADDR_CID_HOST). Matches
37
+ // gate-dispatcher.ts's GATE_PORT (9000) on the host side.
38
+ const DEFAULT_VMADDR_CID_HOST = 2;
39
+ const DEFAULT_GATE_PORT = 9000;
40
+
41
+ function gateSocketPath(): string {
42
+ return process.env["K9O_GATE_SOCKET"] ?? "/run/k9o/gate.sock";
43
+ }
44
+
45
+ function gateTimeoutMs(): number {
46
+ const v = parseInt(process.env["K9O_GATE_TIMEOUT_MS"] ?? "", 10);
47
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_GATE_TIMEOUT_MS;
48
+ }
49
+
50
+ function gateVsockCid(): number {
51
+ const v = parseInt(process.env["K9O_GATE_VSOCK_CID"] ?? "", 10);
52
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_VMADDR_CID_HOST;
53
+ }
54
+
55
+ function gateVsockPort(): number {
56
+ const v = parseInt(process.env["K9O_GATE_VSOCK_PORT"] ?? "", 10);
57
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_GATE_PORT;
58
+ }
59
+
60
+ /** `K9O_GATE_TRANSPORT`: "auto" (default, probe vsock then fall back to UDS
61
+ * only if the vsock transport itself is unavailable), "vsock" (force, no
62
+ * fallback), or "uds" (force, skip the vsock probe entirely). */
63
+ function gateTransportMode(): "auto" | "vsock" | "uds" {
64
+ const v = process.env["K9O_GATE_TRANSPORT"];
65
+ return v === "vsock" || v === "uds" ? v : "auto";
66
+ }
67
+
68
+ /** Wire response shape per ABI `WardenGateDecision`. */
69
+ export type WardenDecision = {
70
+ decision: "allow" | "deny" | "attest_required";
71
+ reason: string;
72
+ waypointClass: "standard" | "integration" | "irreversible";
73
+ receipt: { ledgerId: string; signature: string };
74
+ };
75
+
76
+ function frameRequest(tool: string, input: Record<string, unknown>): Buffer {
77
+ const body = Buffer.from(JSON.stringify({ tool, input }), "utf8");
78
+ if (body.byteLength > MAX_FRAME_BYTES) {
79
+ throw new Error(`Gate request too large (${body.byteLength} > ${MAX_FRAME_BYTES})`);
80
+ }
81
+ const frame = Buffer.allocUnsafe(4 + body.byteLength);
82
+ frame.writeUInt32LE(body.byteLength, 0);
83
+ body.copy(frame, 4);
84
+ return frame;
85
+ }
86
+
87
+ function parseResponse(buf: Buffer): WardenDecision {
88
+ if (buf.byteLength < 4) throw new Error("Gate: truncated response header");
89
+ const bodyLen = buf.readUInt32LE(0);
90
+ if (bodyLen > MAX_FRAME_BYTES) {
91
+ throw new Error(`Gate response too large (${bodyLen} > ${MAX_FRAME_BYTES})`);
92
+ }
93
+ if (buf.byteLength < 4 + bodyLen) throw new Error("Gate: truncated response body");
94
+ return JSON.parse(buf.subarray(4, 4 + bodyLen).toString("utf8")) as WardenDecision;
95
+ }
96
+
97
+ // ── AF_VSOCK transport (primary) ────────────────────────────────────────────
98
+
99
+ /** Lazily-initialized; a module that fails to load once (non-Linux, no
100
+ * libc.so.6, sandboxed FFI) is not retried per call. */
101
+ let vsockLib: ReturnType<typeof loadVsockLib> | null | undefined;
102
+
103
+ function loadVsockLib() {
104
+ const { i32, u32, ptr, u64, i64 } = FFIType;
105
+ return dlopen("libc.so.6", {
106
+ socket: { args: [i32, i32, i32], returns: i32 },
107
+ connect: { args: [i32, ptr, u32], returns: i32 },
108
+ setsockopt: { args: [i32, i32, i32, ptr, u32], returns: i32 },
109
+ // size_t is 64-bit on all Linux targets Firecracker guests run (x86_64/aarch64).
110
+ write: { args: [i32, ptr, u64], returns: i64 },
111
+ read: { args: [i32, ptr, u64], returns: i64 },
112
+ close: { args: [i32], returns: i32 },
113
+ });
114
+ }
115
+
116
+ function getVsockLib() {
117
+ if (vsockLib === undefined) {
118
+ try {
119
+ vsockLib = process.platform === "linux" ? loadVsockLib() : null;
120
+ } catch {
121
+ vsockLib = null;
122
+ }
123
+ }
124
+ return vsockLib;
125
+ }
126
+
127
+ const AF_VSOCK = 40;
128
+ const SOCK_STREAM = 1;
129
+ const SOL_SOCKET = 1;
130
+ const SO_RCVTIMEO = 20;
131
+ const SO_SNDTIMEO = 21;
132
+
133
+ /** Builds a `struct sockaddr_vm` (16 bytes, native byte order — vsock
134
+ * addresses are NOT network-byte-order like AF_INET). */
135
+ function buildSockaddrVm(cid: number, port: number): Buffer {
136
+ const addr = Buffer.alloc(16);
137
+ addr.writeUInt16LE(AF_VSOCK, 0); // svm_family
138
+ addr.writeUInt16LE(0, 2); // svm_reserved1
139
+ addr.writeUInt32LE(port, 4); // svm_port
140
+ addr.writeUInt32LE(cid, 8); // svm_cid
141
+ // bytes 12-15 (svm_flags + svm_zero[3]) already zeroed by Buffer.alloc
142
+ return addr;
143
+ }
144
+
145
+ /** `struct timeval { long tv_sec; long tv_usec; }` — 16 bytes on 64-bit Linux. */
146
+ function buildTimeval(ms: number): Buffer {
147
+ const tv = Buffer.alloc(16);
148
+ tv.writeBigInt64LE(BigInt(Math.floor(ms / 1000)), 0);
149
+ tv.writeBigInt64LE(BigInt((ms % 1000) * 1000), 8);
150
+ return tv;
151
+ }
152
+
153
+ function vsockGateCall(
154
+ tool: string,
155
+ input: Record<string, unknown>,
156
+ ): WardenDecision {
157
+ const lib = getVsockLib();
158
+ if (!lib) throw new Error("AF_VSOCK transport unavailable on this platform");
159
+ const { socket, connect, setsockopt, write, read, close } = lib.symbols;
160
+
161
+ const fd = socket(AF_VSOCK, SOCK_STREAM, 0);
162
+ if (fd < 0) throw new Error("Gate: vsock socket() failed");
163
+
164
+ try {
165
+ const timeoutMs = gateTimeoutMs();
166
+ const tv = buildTimeval(timeoutMs);
167
+ // Fail closed if the timeout itself can't be armed — a hang defeats the
168
+ // fail-closed guarantee (no JS-level timer can preempt a blocking FFI call).
169
+ if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, tv, tv.byteLength) !== 0) {
170
+ throw new Error("Gate: vsock setsockopt(SO_RCVTIMEO) failed");
171
+ }
172
+ if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, tv, tv.byteLength) !== 0) {
173
+ throw new Error("Gate: vsock setsockopt(SO_SNDTIMEO) failed");
174
+ }
175
+
176
+ const addr = buildSockaddrVm(gateVsockCid(), gateVsockPort());
177
+ if (connect(fd, addr, addr.byteLength) !== 0) {
178
+ throw new Error("Gate: vsock connect() failed (host dispatcher unreachable)");
179
+ }
180
+
181
+ const frame = frameRequest(tool, input);
182
+ let written = 0;
183
+ while (written < frame.byteLength) {
184
+ const n = BigInt(write(fd, frame.subarray(written), frame.byteLength - written) ?? -1);
185
+ if (n <= 0n) throw new Error("Gate: vsock write() failed or timed out");
186
+ written += Number(n);
187
+ }
188
+
189
+ const chunks: Buffer[] = [];
190
+ let total = 0;
191
+ let expectedTotal: number | null = null;
192
+ const readBuf = Buffer.alloc(65536);
193
+ for (;;) {
194
+ const n = BigInt(read(fd, readBuf, readBuf.byteLength) ?? -1);
195
+ if (n < 0n) throw new Error("Gate: vsock read() failed or timed out");
196
+ if (n === 0n) throw new Error("Gate: vsock connection closed before full response");
197
+ chunks.push(Buffer.from(readBuf.subarray(0, Number(n))));
198
+ total += Number(n);
199
+ if (expectedTotal === null && total >= 4) {
200
+ expectedTotal = 4 + Buffer.concat(chunks).readUInt32LE(0);
201
+ }
202
+ if (expectedTotal !== null && total >= expectedTotal) break;
203
+ }
204
+ return parseResponse(Buffer.concat(chunks));
205
+ } finally {
206
+ close(fd);
207
+ }
208
+ }
209
+
210
+ // ── Local UDS transport (fallback) ──────────────────────────────────────────
211
+
212
+ function udsGateCall(tool: string, input: Record<string, unknown>): Promise<WardenDecision> {
213
+ return new Promise<WardenDecision>((resolve, reject) => {
214
+ const socket = createConnection({ path: gateSocketPath() });
215
+ const chunks: Buffer[] = [];
216
+ let settled = false;
217
+
218
+ const timer = setTimeout(() => {
219
+ fail(new Error("Gate: response timeout — fail-closed"));
220
+ }, gateTimeoutMs());
221
+
222
+ const cleanup = () => {
223
+ clearTimeout(timer);
224
+ socket.removeAllListeners();
225
+ socket.destroy();
226
+ };
227
+
228
+ const fail = (err: unknown) => {
229
+ if (settled) return;
230
+ settled = true;
231
+ cleanup();
232
+ reject(err instanceof Error ? err : new Error(String(err)));
233
+ };
234
+
235
+ socket.on("error", fail);
236
+
237
+ socket.on("connect", () => {
238
+ try {
239
+ socket.write(frameRequest(tool, input));
240
+ } catch (e) {
241
+ fail(e);
242
+ }
243
+ });
244
+
245
+ socket.on("data", (chunk: Buffer) => {
246
+ chunks.push(chunk);
247
+ const buf = Buffer.concat(chunks);
248
+ if (buf.byteLength < 4) return;
249
+ const bodyLen = buf.readUInt32LE(0);
250
+ if (bodyLen > MAX_FRAME_BYTES) {
251
+ fail(new Error(`Gate response too large (${bodyLen} > ${MAX_FRAME_BYTES})`));
252
+ return;
253
+ }
254
+ if (buf.byteLength < 4 + bodyLen) return;
255
+ if (settled) return;
256
+ settled = true;
257
+ cleanup();
258
+ try {
259
+ resolve(parseResponse(buf));
260
+ } catch (e) {
261
+ reject(e);
262
+ }
263
+ });
264
+
265
+ socket.on("close", () => {
266
+ if (!settled) fail(new Error("Gate: connection closed before response"));
267
+ });
268
+ });
269
+ }
270
+
271
+ // ── Public API ────────────────────────────────────────────────────────────
272
+
273
+ /**
274
+ * Call the Warden gate before executing any gated action in the Enforced Boundary.
275
+ *
276
+ * Sends `{ tool, input }` (the ONLY guest-supplied fields — principal is
277
+ * injected host-side from the sandbox token) and returns the Warden's
278
+ * decision. Fail-closed: any error rejects the promise; callers MUST treat
279
+ * rejection as deny.
280
+ *
281
+ * §A.gate-guest: this is the sole host-import surface.
282
+ */
283
+ export async function warden_gate(
284
+ tool: string,
285
+ input: Record<string, unknown>,
286
+ ): Promise<WardenDecision> {
287
+ const mode = gateTransportMode();
288
+
289
+ if (mode !== "uds") {
290
+ try {
291
+ return vsockGateCall(tool, input);
292
+ } catch (e) {
293
+ if (mode === "vsock") throw e;
294
+ // "auto" mode: only fall back if the TRANSPORT itself is unavailable
295
+ // (unsupported platform / no libc symbol / socket() failed) — a real
296
+ // connect/write/read failure against a genuinely-present vsock device
297
+ // is a real gate-unreachable error and must propagate, not silently
298
+ // downgrade to a possibly-stale UDS assumption.
299
+ if (getVsockLib() !== null) throw e;
300
+ }
301
+ }
302
+
303
+ return udsGateCall(tool, input);
304
+ }
305
+
306
+ // ── Test-only internal surface ──────────────────────────────────────────────
307
+ // Pure/deterministic helpers exposed for unit testing the wire-layout logic
308
+ // without opening a real socket. Not part of the package's public API surface
309
+ // (excluded from index.ts's export list).
310
+
311
+ export const __internal = {
312
+ buildSockaddrVm,
313
+ buildTimeval,
314
+ frameRequest,
315
+ parseResponse,
316
+ gateTransportMode,
317
+ gateVsockCid,
318
+ gateVsockPort,
319
+ getVsockLib,
320
+ };