@ai-sdk/harness 1.0.92 → 1.0.93
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.
- package/CHANGELOG.md +15 -0
- package/README.md +5 -1
- package/dist/agent/index.d.ts +155 -110
- package/dist/agent/index.js +292 -99
- package/dist/agent/index.js.map +1 -1
- package/dist/bridge/index.d.ts +20 -1
- package/dist/bridge/index.js +29 -5
- package/dist/bridge/index.js.map +1 -1
- package/dist/index.d.ts +100 -94
- package/dist/utils/index.d.ts +8 -2
- package/dist/utils/index.js +313 -33
- package/dist/utils/index.js.map +1 -1
- package/package.json +4 -4
- package/src/agent/harness-agent-session.ts +107 -7
- package/src/agent/harness-agent-settings.ts +86 -7
- package/src/agent/harness-agent.ts +322 -112
- package/src/agent/internal/lifecycle-state-validation.ts +3 -0
- package/src/agent/internal/run-prompt.ts +16 -6
- package/src/bridge/index.ts +73 -6
- package/src/utils/index.ts +1 -0
- package/src/utils/write-skills.ts +419 -32
- package/src/v1/harness-v1-lifecycle-state.ts +38 -0
- package/src/v1/harness-v1-session.ts +9 -40
- package/src/v1/index.ts +1 -0
package/dist/bridge/index.d.ts
CHANGED
|
@@ -109,8 +109,27 @@ interface RunBridgeOptions<TStart extends {
|
|
|
109
109
|
bridgeType: string;
|
|
110
110
|
/** Directory for `bridge-meta.json` / `start-config.json`. Created if absent. */
|
|
111
111
|
bridgeStateDir: string;
|
|
112
|
-
/**
|
|
112
|
+
/**
|
|
113
|
+
* Drive one prompt turn. Rejections surface to the host as an `error`
|
|
114
|
+
* event.
|
|
115
|
+
*
|
|
116
|
+
* Contract: once `turn.abortSignal` fires, wind down promptly — turns are
|
|
117
|
+
* serialized, and a replacement `start` waits up to
|
|
118
|
+
* {@link turnTeardownGraceMs} for this promise to settle before it
|
|
119
|
+
* proceeds anyway.
|
|
120
|
+
*/
|
|
113
121
|
onStart(start: TStart, turn: BridgeTurn): Promise<void>;
|
|
122
|
+
/**
|
|
123
|
+
* How long a replacement `start` waits for the previous turn's teardown
|
|
124
|
+
* after aborting it, in milliseconds. Turns are serialized so an aborted
|
|
125
|
+
* turn cannot emit into its replacement's event log or overlap its runtime
|
|
126
|
+
* process — but only within this bound: an adapter that does not settle
|
|
127
|
+
* `onStart` after its abort signal fires forfeits the protection for that
|
|
128
|
+
* boundary, and the new turn proceeds anyway rather than blocking forever.
|
|
129
|
+
* The default of ten seconds exceeds the Claude bridge's five-second
|
|
130
|
+
* hard-abort fallback.
|
|
131
|
+
*/
|
|
132
|
+
turnTeardownGraceMs?: number;
|
|
114
133
|
/**
|
|
115
134
|
* Produce the adapter-defined runtime resume data for `stop`. Defaults to
|
|
116
135
|
* `{}`.
|
package/dist/bridge/index.js
CHANGED
|
@@ -161,6 +161,7 @@ var ENV_TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
|
161
161
|
var WS_OPEN = 1;
|
|
162
162
|
async function runBridge(options) {
|
|
163
163
|
const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;
|
|
164
|
+
const teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;
|
|
164
165
|
const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? "";
|
|
165
166
|
const bridgeWsPort = options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? "0", 10);
|
|
166
167
|
const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;
|
|
@@ -177,6 +178,7 @@ async function runBridge(options) {
|
|
|
177
178
|
let isFirstTurn = true;
|
|
178
179
|
let turnAbort;
|
|
179
180
|
let currentUserMessages;
|
|
181
|
+
let activeTurn;
|
|
180
182
|
let debugConfig;
|
|
181
183
|
let consoleCaptureInstalled = false;
|
|
182
184
|
const envDebugEnabled = ENV_TRUTHY.has(
|
|
@@ -367,10 +369,28 @@ async function runBridge(options) {
|
|
|
367
369
|
const handleInbound = async (msg, ws) => {
|
|
368
370
|
switch (msg.type) {
|
|
369
371
|
case "start": {
|
|
372
|
+
for (; ; ) {
|
|
373
|
+
const pendingTurn = activeTurn;
|
|
374
|
+
if (pendingTurn == null) break;
|
|
375
|
+
turnAbort?.abort();
|
|
376
|
+
currentUserMessages?.close(
|
|
377
|
+
new Error("A new bridge turn replaced the active turn.")
|
|
378
|
+
);
|
|
379
|
+
let graceTimer;
|
|
380
|
+
const settled = await Promise.race([
|
|
381
|
+
pendingTurn.then(() => true),
|
|
382
|
+
new Promise((resolve) => {
|
|
383
|
+
graceTimer = setTimeout(() => resolve(false), teardownGraceMs);
|
|
384
|
+
graceTimer.unref?.();
|
|
385
|
+
})
|
|
386
|
+
]);
|
|
387
|
+
clearTimeout(graceTimer);
|
|
388
|
+
if (!settled) break;
|
|
389
|
+
}
|
|
390
|
+
let turnFinished;
|
|
391
|
+
const thisTurn = new Promise((resolve) => turnFinished = resolve);
|
|
392
|
+
activeTurn = thisTurn;
|
|
370
393
|
activeSocket = ws;
|
|
371
|
-
currentUserMessages?.close(
|
|
372
|
-
new Error("A new bridge turn replaced the active turn.")
|
|
373
|
-
);
|
|
374
394
|
const firstTurn = isFirstTurn;
|
|
375
395
|
isFirstTurn = false;
|
|
376
396
|
eventLog = [];
|
|
@@ -427,8 +447,12 @@ async function runBridge(options) {
|
|
|
427
447
|
if (currentUserMessages === userMessages) {
|
|
428
448
|
currentUserMessages = void 0;
|
|
429
449
|
}
|
|
430
|
-
|
|
431
|
-
|
|
450
|
+
if (activeTurn === thisTurn) {
|
|
451
|
+
activeTurn = void 0;
|
|
452
|
+
currentTurnState = "waiting";
|
|
453
|
+
void writeBridgeMeta("waiting");
|
|
454
|
+
}
|
|
455
|
+
turnFinished();
|
|
432
456
|
}
|
|
433
457
|
return;
|
|
434
458
|
}
|
package/dist/bridge/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bridge/index.ts","../../src/bridge/harness-bridge-capability-unsupported-error.ts"],"sourcesContent":["// Shared in-sandbox bridge runtime. Adapter `bridge.mjs` bundles re-bundle\n// this module (tsup inlines it; `ws` stays external and resolves from the\n// sandbox-installed node_modules). It owns everything generic to the bridge\n// transport — the WebSocket server, token auth, the in-memory event log +\n// monotonic `seq`, resume replay, and the lifecycle/meta files. Any number of\n// hosts may be connected; exactly one of them owns the event stream, and\n// `start`/`resume` transfer that ownership. The adapter supplies only `onStart`\n// (drive its CLI/SDK and translate to wire events) and lifecycle cleanup hooks.\n\nimport { appendFile, mkdir, writeFile } from 'node:fs/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { env as procEnv, pid, stdout } from 'node:process';\nimport { WebSocketServer, type WebSocket } from 'ws';\n\nexport { HarnessBridgeCapabilityUnsupportedError } from './harness-bridge-capability-unsupported-error';\n\nexport type BridgeState = 'init' | 'waiting' | 'running' | 'draining' | 'done';\n\n/** Outbound turn event the adapter emits. `seq` is added by the runtime. */\nexport type BridgeEvent = Record<string, unknown> & { type: string };\n\nexport type BridgeDebugLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';\n\nexport interface Experimental_BridgeUserMessage {\n readonly messageId: string;\n readonly text: string;\n accept(): void;\n reject(error: unknown): void;\n}\n\nexport interface Experimental_BridgeUserMessageQueue extends AsyncIterable<Experimental_BridgeUserMessage> {\n readonly pendingCount: number;\n close(error?: unknown): void;\n}\n\ntype InternalBridgeUserMessageQueue = Experimental_BridgeUserMessageQueue & {\n enqueue(input: { messageId: string; text: string }): void;\n};\n\ntype BridgeUserMessageResponse = {\n type: 'user-message-response';\n messageId: string;\n accepted: boolean;\n error?: { message: string };\n};\n\n/**\n * Per-session diagnostics config. The host resolves it from settings +\n * env and sends it on `start.debug`; the bridge gates console capture and\n * structured `debug-event`s on it. When disabled, nothing is captured or\n * emitted and no `seq` is consumed.\n */\nexport interface BridgeDebugConfig {\n enabled?: boolean;\n level?: BridgeDebugLevel;\n subsystems?: string[];\n}\n\nconst DEBUG_LEVEL_WEIGHT: Record<BridgeDebugLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n};\n\n/** Exact-or-dotted-prefix subsystem match (`'bridge'` matches `'bridge.turn'`). */\nfunction subsystemMatches(\n filters: string[] | undefined,\n subsystem: string,\n): boolean {\n if (!filters || filters.length === 0) return true;\n return filters.some(\n filter => subsystem === filter || subsystem.startsWith(`${filter}.`),\n );\n}\n\nfunction formatBridgeError(err: unknown): {\n name?: string;\n message: string;\n stack?: string;\n} {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n if (typeof err === 'string') {\n return { message: err };\n }\n if (err !== null && typeof err === 'object') {\n try {\n return { message: JSON.stringify(err) };\n } catch {}\n }\n return { message: String(err) };\n}\n\nfunction createBridgeUserMessageQueue(options: {\n respond(response: BridgeUserMessageResponse): void;\n}): InternalBridgeUserMessageQueue {\n const messages: Experimental_BridgeUserMessage[] = [];\n const waiters: Array<\n (result: IteratorResult<Experimental_BridgeUserMessage>) => void\n > = [];\n const entries = new Map<\n string,\n {\n response?: BridgeUserMessageResponse;\n reject(error: unknown): void;\n }\n >();\n let closed = false;\n let pendingCount = 0;\n\n const enqueue = (input: { messageId: string; text: string }): void => {\n const existing = entries.get(input.messageId);\n if (existing != null) {\n if (existing.response != null) {\n options.respond(existing.response);\n }\n return;\n }\n\n let settled = false;\n const settle = (response: BridgeUserMessageResponse): void => {\n if (settled) return;\n settled = true;\n pendingCount--;\n const entry = entries.get(input.messageId);\n if (entry != null) entry.response = response;\n options.respond(response);\n };\n const message: Experimental_BridgeUserMessage = {\n messageId: input.messageId,\n text: input.text,\n accept: () => {\n settle({\n type: 'user-message-response',\n messageId: input.messageId,\n accepted: true,\n });\n },\n reject: error => {\n settle({\n type: 'user-message-response',\n messageId: input.messageId,\n accepted: false,\n error: { message: formatBridgeError(error).message },\n });\n },\n };\n entries.set(input.messageId, {\n reject: message.reject,\n });\n pendingCount++;\n\n if (closed) {\n message.reject(\n new Error('The bridge turn is no longer accepting user messages.'),\n );\n return;\n }\n\n const waiter = waiters.shift();\n if (waiter != null) {\n waiter({ done: false, value: message });\n } else {\n messages.push(message);\n }\n };\n\n const close = (error?: unknown): void => {\n if (closed) return;\n closed = true;\n const reason =\n error ??\n new Error('The bridge turn ended before accepting the user message.');\n for (const entry of entries.values()) {\n if (entry.response == null) entry.reject(reason);\n }\n messages.length = 0;\n while (waiters.length > 0) {\n waiters.shift()!({ done: true, value: undefined });\n }\n };\n\n return {\n get pendingCount() {\n return pendingCount;\n },\n enqueue,\n close,\n [Symbol.asyncIterator]() {\n return {\n next: () => {\n const message = messages.shift();\n if (message != null) {\n return Promise.resolve({ done: false as const, value: message });\n }\n if (closed) {\n return Promise.resolve({\n done: true as const,\n value: undefined,\n });\n }\n return new Promise<IteratorResult<Experimental_BridgeUserMessage>>(\n resolve => {\n waiters.push(resolve);\n },\n );\n },\n };\n },\n };\n}\n\nfunction parseEnvList(value: string | undefined): string[] | undefined {\n if (!value) return undefined;\n const items = value\n .split(',')\n .map(item => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nconst ENV_TRUTHY = new Set(['1', 'true', 'yes', 'on']);\n\n/**\n * Per-turn surface handed to {@link RunBridgeOptions.onStart}. The adapter\n * drives its runtime against these primitives; the runtime owns the transport.\n */\nexport interface BridgeTurn {\n /**\n * Emit a turn event to the host. Stamps a monotonic `seq`, appends to the\n * in-memory replay log, and sends to the live socket (best-effort — if the\n * host is mid-reconnect the event waits in the log and is replayed on\n * resume).\n */\n emit(event: BridgeEvent): void;\n\n /**\n * Register interest in a host-executed tool result and resolve when the\n * matching `tool-result` arrives. The adapter emits the `tool-call` event\n * itself (via {@link emit}) using the same `toolCallId`.\n */\n requestToolResult(\n toolCallId: string,\n ): Promise<{ output: unknown; isError?: boolean }>;\n\n /**\n * Register interest in a host approval decision and resolve when the matching\n * `tool-approval-response` arrives. The adapter emits the\n * `tool-approval-request` event itself using the same `approvalId`.\n */\n requestToolApproval(\n approvalId: string,\n ): Promise<{ approved: boolean; reason?: string }>;\n\n readonly experimental_userMessages: Experimental_BridgeUserMessageQueue;\n\n /** Aborts when the host sends `abort`. */\n readonly abortSignal: AbortSignal;\n\n /** True for the first turn since this bridge process started. */\n readonly firstTurn: boolean;\n\n /**\n * Emit a structured diagnostic. Gated by the session's debug level +\n * subsystem filter; a no-op when diagnostics are disabled. Adapters use this\n * for runtime-level instrumentation; raw `console.*` output is captured and\n * forwarded automatically.\n */\n bridgeLog(input: {\n level?: BridgeDebugLevel;\n subsystem: string;\n message: string;\n attrs?: Record<string, unknown>;\n error?: unknown;\n }): void;\n\n /**\n * Emit a non-fatal bridge warning to stderr using the runtime's harness\n * prefix. This is diagnostic-only: it does not emit a stream event, does not\n * consume a `seq`, and does not fail the turn.\n */\n emitWarning(input: { message: string }): void;\n\n emitError(input: { error: unknown; message?: string }): void;\n}\n\nexport interface RunBridgeOptions<TStart extends { type: 'start' }> {\n /** Identifier written into `bridge-meta.json` (`'claude-code'` / `'codex'`). */\n bridgeType: string;\n /** Directory for `bridge-meta.json` / `start-config.json`. Created if absent. */\n bridgeStateDir: string;\n /** Drive one prompt turn. Rejections surface to the host as an `error` event. */\n onStart(start: TStart, turn: BridgeTurn): Promise<void>;\n /**\n * Produce the adapter-defined runtime resume data for `stop`. Defaults to\n * `{}`.\n */\n onStop?(): unknown | Promise<unknown>;\n /**\n * Perform adapter-defined destruction before the bridge exits.\n */\n onDestroy?(): void | Promise<void>;\n /** WS port. Defaults to `BRIDGE_WS_PORT` env (0 = OS-assigned). */\n port?: number;\n /** Auth token. Defaults to `BRIDGE_CHANNEL_TOKEN` env. */\n token?: string;\n /** Called with the bound port once the server is listening. */\n onListening?(port: number): void;\n /**\n * Tear the process down after `stop` / `destroy`. Defaults to closing\n * the server and calling `process.exit(0)`. Overridable for tests.\n */\n onExit?(): void;\n}\n\ntype InboundControl =\n | {\n type: 'tool-result';\n toolCallId: string;\n output: unknown;\n isError?: boolean;\n }\n | {\n type: 'tool-approval-response';\n approvalId: string;\n approved: boolean;\n reason?: string;\n }\n | { type: 'user-message'; messageId?: string; text: string }\n | { type: 'abort' }\n | { type: 'stop' }\n | { type: 'destroy' }\n | { type: 'resume'; lastSeenEventId: number };\n\nconst WS_OPEN = 1;\n\n/**\n * Boot the bridge: bind the WebSocket server, announce `bridge-ready`, and\n * service host connections for the lifetime of the process. Resolves once the\n * server is listening; the process then stays alive on the server until a\n * `stop` / `destroy` exits it.\n */\nexport interface BridgeHandle {\n /** The port the WebSocket server bound to. */\n readonly port: number;\n /** Close the WebSocket server. Does not call `process.exit`. */\n close(): Promise<void>;\n}\n\nexport async function runBridge<TStart extends { type: 'start' }>(\n options: RunBridgeOptions<TStart>,\n): Promise<BridgeHandle> {\n const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;\n const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? '';\n const bridgeWsPort =\n options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? '0', 10);\n\n const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;\n const startConfigPath = `${bridgeStateDir}/start-config.json`;\n const rerunStartConfigPath = `${bridgeStateDir}/rerun-start-config.json`;\n const eventLogPath = `${bridgeStateDir}/event-log.ndjson`;\n\n try {\n await mkdir(bridgeStateDir, { recursive: true });\n } catch {\n // Best-effort; the bridge still runs without its state files.\n }\n\n // ─── mutable runtime state ──────────────────────────────────────────\n let currentBoundPort = 0;\n let currentTurnState: BridgeState = 'init';\n /*\n * The one connection turn events stream to. A socket claims it by asking for\n * work — `start` (a turn) or `resume` (a catch-up) — never by connecting:\n * every event goes here alone, so claiming on connect would silence a turn\n * already streaming to someone else. Any number of sockets may be connected;\n * the others still exchange control frames, they just get no events.\n */\n let activeSocket: WebSocket | undefined;\n let isFirstTurn = true;\n let turnAbort: AbortController | undefined;\n let currentUserMessages: InternalBridgeUserMessageQueue | undefined;\n\n // Diagnostics. Resolved per turn from `start.debug` with a sandbox-side\n // env fallback; gates console capture + structured `debug-event`s.\n let debugConfig: BridgeDebugConfig | undefined;\n let consoleCaptureInstalled = false;\n const envDebugEnabled = ENV_TRUTHY.has(\n (procEnv.HARNESS_DEBUG ?? '').toLowerCase(),\n );\n\n // Replay log. `seq` is monotonic across the whole process — never reset —\n // because the host's `SandboxChannel` cursor (`lastSeenEventId`) lives across\n // turns. The log *contents* are cleared at the start of each turn to bound\n // memory; the just-finished turn stays replayable until the next `start`.\n let seqCounter = 0;\n let eventLog: Array<{ seq: number; line: string }> = [];\n\n /*\n * Disk mirror of the in-memory replay log. The in-memory log is lost when the\n * bridge process dies; the on-disk `event-log.ndjson` survives in the sandbox\n * filesystem so a respawned bridge (started with `BRIDGE_REPLAY_FROM_DISK=1`)\n * can reload the in-flight turn and serve a host's resume cursor —\n * `replay` recovery. Writes are batched on `setImmediate` (single-flight via\n * `flushPromise`) to keep `emit` off the disk hot path.\n */\n let diskBuffer = '';\n let flushPromise: Promise<void> | null = null;\n\n const flushEventsToDisk = async (): Promise<void> => {\n while (diskBuffer.length > 0) {\n const buf = diskBuffer;\n diskBuffer = '';\n await appendFile(eventLogPath, buf).catch(() => {\n // Best-effort crash-recovery mirror; the in-memory log is the source of\n // truth for the live connection.\n });\n }\n };\n\n const scheduleEventFlush = (): void => {\n if (flushPromise) return;\n flushPromise = new Promise<void>(resolve => {\n setImmediate(() => {\n void flushEventsToDisk().finally(resolve);\n });\n }).finally(() => {\n flushPromise = null;\n if (diskBuffer.length > 0) {\n scheduleEventFlush();\n }\n });\n };\n\n const flushPendingEventsToDisk = async (): Promise<void> => {\n if (diskBuffer.length > 0 && !flushPromise) {\n scheduleEventFlush();\n }\n // Await each in-flight flush, re-reading `flushPromise` after every await\n // since a fresh flush may have been scheduled for buffer that arrived while\n // we waited.\n let inFlight = flushPromise;\n while (inFlight) {\n await inFlight;\n inFlight = flushPromise;\n }\n };\n\n /*\n * When respawned for `replay`, reload the previous turn's log from disk before\n * accepting any connection so the very first `resume{lastSeenEventId}` can be\n * served the tail (including the terminal `finish`). The seq counter is\n * restored to the last persisted seq so it stays aligned with the host's\n * long-lived cursor. The file is NOT truncated in this mode — only a fresh\n * `start` (next turn) clears it.\n */\n const replayFromDisk = procEnv.BRIDGE_REPLAY_FROM_DISK === '1';\n if (replayFromDisk && existsSync(eventLogPath)) {\n try {\n const lines = readFileSync(eventLogPath, 'utf8')\n .split('\\n')\n .map(line => line.trim())\n .filter(Boolean);\n eventLog = lines.map(line => ({\n seq: (JSON.parse(line) as { seq: number }).seq,\n line,\n }));\n seqCounter = eventLog.at(-1)?.seq ?? 0;\n } catch {\n // Corrupt/partial log: fall back to an empty log; the host then degrades\n // to `rerun` instead of replaying a malformed tail.\n eventLog = [];\n seqCounter = 0;\n }\n }\n\n const pendingToolResults = new Map<\n string,\n (output: { output: unknown; isError?: boolean }) => void\n >();\n const pendingToolApprovals = new Map<\n string,\n (response: { approved: boolean; reason?: string }) => void\n >();\n\n // ─── persistence (best-effort meta + start config) ──────────────────\n const writeBridgeMeta = async (state: BridgeState): Promise<void> => {\n try {\n await writeFile(\n bridgeMetaPath,\n JSON.stringify({\n type: bridgeType,\n port: currentBoundPort,\n state,\n pid,\n }),\n );\n } catch {\n // Best-effort resilience metadata; not load-bearing for the active turn.\n }\n };\n\n const writeStartConfig = async (start: unknown): Promise<void> => {\n try {\n const serialized = JSON.stringify(start);\n await writeFile(startConfigPath, serialized);\n // Frozen copy: written once, restored over start-config.json by future\n // rerun-mode recovery to re-run the original turn from scratch.\n if (!existsSync(rerunStartConfigPath)) {\n await writeFile(rerunStartConfigPath, serialized);\n }\n } catch {\n // Best-effort.\n }\n };\n\n // ─── wire send + replay ─────────────────────────────────────────────\n const emit = (event: BridgeEvent): void => {\n const seq = ++seqCounter;\n const line = JSON.stringify({ ...event, seq });\n eventLog.push({ seq, line });\n diskBuffer += `${line}\\n`;\n scheduleEventFlush();\n if (activeSocket?.readyState === WS_OPEN) {\n try {\n activeSocket.send(line);\n } catch {\n // Send is best-effort: a dropped socket leaves the event in the log,\n // replayed once the host reconnects and sends `resume`.\n }\n }\n };\n\n const replay = (ws: WebSocket, afterSeq: number): void => {\n for (const entry of eventLog) {\n if (entry.seq > afterSeq && ws.readyState === WS_OPEN) {\n ws.send(entry.line);\n }\n }\n };\n\n // ─── diagnostics ──────────────────────────────────────────────\n const shouldEmitDebugEvent = (\n level: BridgeDebugLevel,\n subsystem: string,\n ): boolean => {\n if (!debugConfig?.enabled) return false;\n const threshold = debugConfig.level ?? 'debug';\n if (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;\n return subsystemMatches(debugConfig.subsystems, subsystem);\n };\n\n /*\n * Forward sandbox console output. We line-buffer the original writers (kept so\n * output still reaches the real fds) and emit one `sandbox-log` per complete\n * line. `emit` never writes to stdout/stderr, so there is no recursion.\n * Installed lazily the first time a turn enables diagnostics; once installed,\n * capture is gated per-write on `debugConfig.enabled` so a later turn can\n * disable it. Console capture is independent of the subsystem/level filter.\n */\n const rawStdoutWrite = process.stdout.write.bind(process.stdout);\n const rawStderrWrite = process.stderr.write.bind(process.stderr);\n\n const writeErrorToStderr = (input: {\n message: string;\n error: unknown;\n }): void => {\n try {\n const formatted = formatBridgeError(input.error);\n rawStderrWrite(\n `[harness:${bridgeType}:error] ${input.message}: ${formatted.message}\\n`,\n );\n if (formatted.stack) {\n rawStderrWrite(`${formatted.stack}\\n`);\n }\n } catch {}\n };\n\n const emitWarning = (input: { message: string }): void => {\n try {\n for (const line of input.message.split('\\n')) {\n if (line.trim().length > 0) {\n rawStderrWrite(`[harness:${bridgeType}:warn] ${line}\\n`);\n }\n }\n } catch {}\n };\n\n const emitError = (input: { error: unknown; message?: string }): void => {\n writeErrorToStderr({\n message: input.message ?? 'bridge error',\n error: input.error,\n });\n emit({ type: 'error', error: serialiseError(input.error) });\n };\n\n const installConsoleCapture = (): void => {\n if (consoleCaptureInstalled) return;\n consoleCaptureInstalled = true;\n const buffers: { stdout: string; stderr: string } = {\n stdout: '',\n stderr: '',\n };\n const patch =\n (stream: 'stdout' | 'stderr', raw: typeof process.stdout.write) =>\n (chunk: unknown, encoding?: unknown, cb?: unknown): boolean => {\n if (debugConfig?.enabled) {\n try {\n const enc = typeof encoding === 'string' ? encoding : 'utf8';\n const text =\n typeof chunk === 'string'\n ? chunk\n : Buffer.from(chunk as Uint8Array).toString(\n enc as BufferEncoding,\n );\n const combined = buffers[stream] + text.replace(/\\r\\n/g, '\\n');\n const parts = combined.split('\\n');\n buffers[stream] = parts.pop() ?? '';\n for (const line of parts) {\n const trimmed = line.replace(/\\s+$/, '');\n if (trimmed) {\n emit({\n type: 'sandbox-log',\n source: bridgeType,\n stream,\n line: trimmed,\n });\n }\n }\n } catch {\n // Never let capture break real output.\n }\n }\n return (raw as (c: unknown, e?: unknown, cb?: unknown) => boolean)(\n chunk,\n encoding,\n cb,\n );\n };\n process.stdout.write = patch(\n 'stdout',\n rawStdoutWrite,\n ) as typeof process.stdout.write;\n process.stderr.write = patch(\n 'stderr',\n rawStderrWrite,\n ) as typeof process.stderr.write;\n };\n\n // ─── inbound routing ────────────────────────────────────────────────\n const handleInbound = async (\n msg: TStart | InboundControl,\n ws: WebSocket,\n ): Promise<void> => {\n switch (msg.type) {\n case 'start': {\n activeSocket = ws; // asking for a turn claims the event stream\n currentUserMessages?.close(\n new Error('A new bridge turn replaced the active turn.'),\n );\n const firstTurn = isFirstTurn;\n isFirstTurn = false;\n eventLog = []; // clear previous turn; keep seqCounter monotonic\n // Mirror the in-memory clear to disk: the log tracks only the current\n // turn. Discard any unflushed tail from the prior turn first.\n diskBuffer = '';\n void writeFile(eventLogPath, '').catch(() => {});\n turnAbort = new AbortController();\n currentTurnState = 'running';\n void writeStartConfig(msg);\n void writeBridgeMeta('running');\n const startDebug = (msg as { debug?: BridgeDebugConfig }).debug;\n debugConfig = {\n enabled: startDebug?.enabled ?? envDebugEnabled,\n level:\n startDebug?.level ??\n (procEnv.HARNESS_DEBUG_LEVEL as BridgeDebugLevel | undefined),\n subsystems:\n startDebug?.subsystems ??\n parseEnvList(procEnv.HARNESS_DEBUG_SUBSYSTEMS),\n };\n if (debugConfig.enabled) {\n installConsoleCapture();\n }\n const userMessages = createBridgeUserMessageQueue({ respond: emit });\n const turn: BridgeTurn = {\n emit,\n requestToolResult: toolCallId =>\n new Promise(resolve => {\n pendingToolResults.set(toolCallId, resolve);\n }),\n requestToolApproval: approvalId =>\n new Promise(resolve => {\n pendingToolApprovals.set(approvalId, resolve);\n }),\n experimental_userMessages: userMessages,\n abortSignal: turnAbort.signal,\n firstTurn,\n bridgeLog: input => {\n const level = input.level ?? 'debug';\n if (!shouldEmitDebugEvent(level, input.subsystem)) return;\n emit({\n type: 'debug-event',\n level,\n subsystem: input.subsystem,\n message: input.message,\n ...(input.attrs ? { attrs: input.attrs } : {}),\n ...(input.error !== undefined\n ? { error: formatBridgeError(input.error) }\n : {}),\n });\n },\n emitWarning,\n emitError,\n };\n currentUserMessages = userMessages;\n try {\n await onStart(msg as TStart, turn);\n } catch (err) {\n emitError({ error: err, message: 'bridge turn failed' });\n } finally {\n userMessages.close();\n if (currentUserMessages === userMessages) {\n currentUserMessages = undefined;\n }\n currentTurnState = 'waiting';\n void writeBridgeMeta('waiting');\n }\n return;\n }\n case 'tool-result': {\n const resolver = pendingToolResults.get(msg.toolCallId);\n if (resolver) {\n pendingToolResults.delete(msg.toolCallId);\n resolver({ output: msg.output, isError: msg.isError });\n }\n return;\n }\n case 'tool-approval-response': {\n const resolver = pendingToolApprovals.get(msg.approvalId);\n if (resolver) {\n pendingToolApprovals.delete(msg.approvalId);\n resolver({ approved: msg.approved, reason: msg.reason });\n }\n return;\n }\n case 'user-message': {\n const messageId = msg.messageId ?? randomUUID();\n if (currentUserMessages == null) {\n sendControl(ws, {\n type: 'user-message-response',\n messageId,\n accepted: false,\n error: { message: 'The bridge has no active turn to steer.' },\n });\n return;\n }\n if (ws !== activeSocket) {\n sendControl(ws, {\n type: 'user-message-response',\n messageId,\n accepted: false,\n error: {\n message: 'The connection does not own the active bridge turn.',\n },\n });\n return;\n }\n currentUserMessages.enqueue({\n messageId,\n text: msg.text,\n });\n return;\n }\n case 'abort':\n turnAbort?.abort();\n return;\n case 'resume':\n activeSocket = ws; // asking for a catch-up claims it too\n // Synchronous, so no event can slip out live ahead of the replayed tail.\n replay(ws, msg.lastSeenEventId);\n return;\n case 'destroy':\n currentTurnState = 'done';\n void writeBridgeMeta('done');\n await onDestroy?.();\n drainThenExit(ws, 1000, 'destroy');\n return;\n case 'stop': {\n currentTurnState = 'done';\n void writeBridgeMeta('done');\n const data = (await onStop?.()) ?? {};\n sendControl(ws, { type: 'bridge-stop', data });\n drainThenExit(ws, 1000, 'stop');\n return;\n }\n }\n };\n\n // ─── server ─────────────────────────────────────────────────────────\n void writeBridgeMeta('init');\n\n const wss = new WebSocketServer({ port: bridgeWsPort, host: '0.0.0.0' });\n\n const exit = (): void => {\n if (options.onExit) {\n options.onExit();\n return;\n }\n wss.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 1000).unref();\n };\n\n const drainThenExit = (ws: WebSocket, code: number, reason: string): void => {\n const start = Date.now();\n const tick = (): void => {\n const drained = ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN;\n if (drained || Date.now() - start >= 5_000) {\n // Flush the on-disk log so a clean stop/destroy leaves a complete\n // event-log.ndjson for any later replay recovery.\n void flushPendingEventsToDisk().finally(() => {\n try {\n ws.close(code, reason);\n } finally {\n exit();\n }\n });\n return;\n }\n setTimeout(tick, 10).unref();\n };\n tick();\n };\n\n wss.on('listening', () => {\n const addr = wss.address();\n currentBoundPort = typeof addr === 'object' && addr ? addr.port : 0;\n currentTurnState = 'waiting';\n void writeBridgeMeta('waiting');\n stdout.write(\n JSON.stringify({\n type: 'bridge-ready',\n port: currentBoundPort,\n }) + '\\n',\n );\n options.onListening?.(currentBoundPort);\n });\n\n wss.on('connection', (ws: WebSocket, req: { url?: string }) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (url.searchParams.get('agent_bridge_token') !== expectedToken) {\n ws.close(1008, 'unauthorized');\n return;\n }\n\n // Announce liveness the instant we accept. Some sandbox runtimes complete\n // the host-side WS handshake before the connection is forwarded here; the\n // host waits for this frame before sending `start`/`resume`.\n sendControl(ws, {\n type: 'bridge-hello',\n state: currentTurnState,\n lastSeq: seqCounter,\n capabilities: { experimental_userMessageResponses: true },\n });\n\n ws.on('message', (raw: ArrayBufferLike | string) => {\n let parsed: TStart | InboundControl;\n try {\n const text =\n typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8');\n parsed = JSON.parse(text) as TStart | InboundControl;\n } catch (err) {\n sendControl(ws, {\n type: 'error',\n error: `protocol parse error: ${(err as Error).message}`,\n });\n return;\n }\n void handleInbound(parsed, ws);\n });\n\n ws.on('close', () => {\n // Only the stream owner's close matters; a socket that never claimed it,\n // or that a later `start`/`resume` displaced, closes as a no-op.\n // Crucially we do NOT abort the in-flight turn: it keeps running and its\n // events accumulate in the log for replay on reconnect.\n if (activeSocket === ws) {\n activeSocket = undefined;\n }\n });\n\n ws.on('error', () => {\n // 'close' follows; nothing to do beyond keeping the process alive.\n });\n });\n\n // Surface bridge-internal crashes to the host instead of dying silently.\n process.on('uncaughtException', err => {\n emitError({ error: err, message: 'uncaught exception' });\n });\n process.on('unhandledRejection', err => {\n emitError({ error: err, message: 'unhandled rejection' });\n });\n\n await new Promise<void>((resolve, reject) => {\n if (wss.address() != null) {\n resolve();\n return;\n }\n\n wss.once('listening', resolve);\n wss.once('error', reject);\n });\n\n return {\n port: currentBoundPort,\n close: () =>\n new Promise<void>(resolve => {\n wss.close(() => resolve());\n }),\n };\n}\n\n/*\n * Control frames answer the socket that sent the frame they reply to, so the\n * target is always explicit. Event streaming is the separate, stateful path\n * (`emit` → `activeSocket`); this one carries no state at all.\n */\nfunction sendControl(\n socket: WebSocket | undefined,\n message: Record<string, unknown>,\n): void {\n if (socket?.readyState === WS_OPEN) {\n try {\n socket.send(JSON.stringify(message));\n } catch {\n // best-effort\n }\n }\n}\n\nfunction serialiseError(err: unknown): unknown {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n return err;\n}\n","const name = 'AI_HarnessBridgeCapabilityUnsupportedError';\n\n/**\n * Signals an unsupported capability discovered inside a sandbox bridge.\n * `isInstance` also recognizes the serialized error shape received by the\n * host, where it can be translated to `HarnessCapabilityUnsupportedError`.\n */\nexport class HarnessBridgeCapabilityUnsupportedError extends Error {\n readonly harnessId?: string;\n readonly cause?: unknown;\n\n constructor({\n message,\n harnessId,\n cause,\n }: {\n message: string;\n harnessId?: string;\n cause?: unknown;\n }) {\n super(message);\n Object.defineProperty(this, 'name', { value: name });\n this.harnessId = harnessId;\n this.cause = cause;\n }\n\n static isInstance(\n error: unknown,\n ): error is HarnessBridgeCapabilityUnsupportedError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === name &&\n 'message' in error &&\n typeof error.message === 'string'\n );\n }\n}\n"],"mappings":";AASA,SAAS,YAAY,OAAO,iBAAiB;AAC7C,SAAS,YAAY,oBAAoB;AACzC,SAAS,kBAAkB;AAC3B,SAAS,OAAO,SAAS,KAAK,cAAc;AAC5C,SAAS,uBAAuC;;;ACbhD,IAAM,OAAO;AAON,IAAM,0CAAN,cAAsD,MAAM;AAAA,EAIjE,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,OAAO;AACb,WAAO,eAAe,MAAM,QAAQ,EAAE,OAAO,KAAK,CAAC;AACnD,SAAK,YAAY;AACjB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,OAAO,WACL,OACkD;AAClD,WACE,SAAS,QACT,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,QACf,aAAa,SACb,OAAO,MAAM,YAAY;AAAA,EAE7B;AACF;;;ADqBA,IAAM,qBAAuD;AAAA,EAC3D,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAGA,SAAS,iBACP,SACA,WAC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AAAA,UACd,MAAM;AAAA,UACN,OAAO,yBAA0B,IAAc,OAAO;AAAA,QACxD,CAAC;AACD;AAAA,MACF;AACA,WAAK,cAAc,QAAQ,EAAE;AAAA,IAC/B,CAAC;AAED,OAAG,GAAG,SAAS,MAAM;AAKnB,UAAI,iBAAiB,IAAI;AACvB,uBAAe;AAAA,MACjB;AAAA,IACF,CAAC;AAED,OAAG,GAAG,SAAS,MAAM;AAAA,IAErB,CAAC;AAAA,EACH,CAAC;AAGD,UAAQ,GAAG,qBAAqB,SAAO;AACrC,cAAU,EAAE,OAAO,KAAK,SAAS,qBAAqB,CAAC;AAAA,EACzD,CAAC;AACD,UAAQ,GAAG,sBAAsB,SAAO;AACtC,cAAU,EAAE,OAAO,KAAK,SAAS,sBAAsB,CAAC;AAAA,EAC1D,CAAC;AAED,QAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,QAAI,IAAI,QAAQ,KAAK,MAAM;AACzB,cAAQ;AACR;AAAA,IACF;AAEA,QAAI,KAAK,aAAa,OAAO;AAC7B,QAAI,KAAK,SAAS,MAAM;AAAA,EAC1B,CAAC;AAED,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MACL,IAAI,QAAc,aAAW;AAC3B,UAAI,MAAM,MAAM,QAAQ,CAAC;AAAA,IAC3B,CAAC;AAAA,EACL;AACF;AAOA,SAAS,YACP,QACA,SACM;AACN,MAAI,QAAQ,eAAe,SAAS;AAClC,QAAI;AACF,aAAO,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,IACrC,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,SAAS,eAAe,KAAuB;AAC7C,MAAI,eAAe,OAAO;AACxB,WAAO,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,SAAS,OAAO,IAAI,MAAM;AAAA,EAClE;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/bridge/index.ts","../../src/bridge/harness-bridge-capability-unsupported-error.ts"],"sourcesContent":["// Shared in-sandbox bridge runtime. Adapter `bridge.mjs` bundles re-bundle\n// this module (tsup inlines it; `ws` stays external and resolves from the\n// sandbox-installed node_modules). It owns everything generic to the bridge\n// transport — the WebSocket server, token auth, the in-memory event log +\n// monotonic `seq`, resume replay, and the lifecycle/meta files. Any number of\n// hosts may be connected; exactly one of them owns the event stream, and\n// `start`/`resume` transfer that ownership. The adapter supplies only `onStart`\n// (drive its CLI/SDK and translate to wire events) and lifecycle cleanup hooks.\n\nimport { appendFile, mkdir, writeFile } from 'node:fs/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport { env as procEnv, pid, stdout } from 'node:process';\nimport { WebSocketServer, type WebSocket } from 'ws';\n\nexport { HarnessBridgeCapabilityUnsupportedError } from './harness-bridge-capability-unsupported-error';\n\nexport type BridgeState = 'init' | 'waiting' | 'running' | 'draining' | 'done';\n\n/** Outbound turn event the adapter emits. `seq` is added by the runtime. */\nexport type BridgeEvent = Record<string, unknown> & { type: string };\n\nexport type BridgeDebugLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';\n\nexport interface Experimental_BridgeUserMessage {\n readonly messageId: string;\n readonly text: string;\n accept(): void;\n reject(error: unknown): void;\n}\n\nexport interface Experimental_BridgeUserMessageQueue extends AsyncIterable<Experimental_BridgeUserMessage> {\n readonly pendingCount: number;\n close(error?: unknown): void;\n}\n\ntype InternalBridgeUserMessageQueue = Experimental_BridgeUserMessageQueue & {\n enqueue(input: { messageId: string; text: string }): void;\n};\n\ntype BridgeUserMessageResponse = {\n type: 'user-message-response';\n messageId: string;\n accepted: boolean;\n error?: { message: string };\n};\n\n/**\n * Per-session diagnostics config. The host resolves it from settings +\n * env and sends it on `start.debug`; the bridge gates console capture and\n * structured `debug-event`s on it. When disabled, nothing is captured or\n * emitted and no `seq` is consumed.\n */\nexport interface BridgeDebugConfig {\n enabled?: boolean;\n level?: BridgeDebugLevel;\n subsystems?: string[];\n}\n\nconst DEBUG_LEVEL_WEIGHT: Record<BridgeDebugLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n};\n\n/** Exact-or-dotted-prefix subsystem match (`'bridge'` matches `'bridge.turn'`). */\nfunction subsystemMatches(\n filters: string[] | undefined,\n subsystem: string,\n): boolean {\n if (!filters || filters.length === 0) return true;\n return filters.some(\n filter => subsystem === filter || subsystem.startsWith(`${filter}.`),\n );\n}\n\nfunction formatBridgeError(err: unknown): {\n name?: string;\n message: string;\n stack?: string;\n} {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n if (typeof err === 'string') {\n return { message: err };\n }\n if (err !== null && typeof err === 'object') {\n try {\n return { message: JSON.stringify(err) };\n } catch {}\n }\n return { message: String(err) };\n}\n\nfunction createBridgeUserMessageQueue(options: {\n respond(response: BridgeUserMessageResponse): void;\n}): InternalBridgeUserMessageQueue {\n const messages: Experimental_BridgeUserMessage[] = [];\n const waiters: Array<\n (result: IteratorResult<Experimental_BridgeUserMessage>) => void\n > = [];\n const entries = new Map<\n string,\n {\n response?: BridgeUserMessageResponse;\n reject(error: unknown): void;\n }\n >();\n let closed = false;\n let pendingCount = 0;\n\n const enqueue = (input: { messageId: string; text: string }): void => {\n const existing = entries.get(input.messageId);\n if (existing != null) {\n if (existing.response != null) {\n options.respond(existing.response);\n }\n return;\n }\n\n let settled = false;\n const settle = (response: BridgeUserMessageResponse): void => {\n if (settled) return;\n settled = true;\n pendingCount--;\n const entry = entries.get(input.messageId);\n if (entry != null) entry.response = response;\n options.respond(response);\n };\n const message: Experimental_BridgeUserMessage = {\n messageId: input.messageId,\n text: input.text,\n accept: () => {\n settle({\n type: 'user-message-response',\n messageId: input.messageId,\n accepted: true,\n });\n },\n reject: error => {\n settle({\n type: 'user-message-response',\n messageId: input.messageId,\n accepted: false,\n error: { message: formatBridgeError(error).message },\n });\n },\n };\n entries.set(input.messageId, {\n reject: message.reject,\n });\n pendingCount++;\n\n if (closed) {\n message.reject(\n new Error('The bridge turn is no longer accepting user messages.'),\n );\n return;\n }\n\n const waiter = waiters.shift();\n if (waiter != null) {\n waiter({ done: false, value: message });\n } else {\n messages.push(message);\n }\n };\n\n const close = (error?: unknown): void => {\n if (closed) return;\n closed = true;\n const reason =\n error ??\n new Error('The bridge turn ended before accepting the user message.');\n for (const entry of entries.values()) {\n if (entry.response == null) entry.reject(reason);\n }\n messages.length = 0;\n while (waiters.length > 0) {\n waiters.shift()!({ done: true, value: undefined });\n }\n };\n\n return {\n get pendingCount() {\n return pendingCount;\n },\n enqueue,\n close,\n [Symbol.asyncIterator]() {\n return {\n next: () => {\n const message = messages.shift();\n if (message != null) {\n return Promise.resolve({ done: false as const, value: message });\n }\n if (closed) {\n return Promise.resolve({\n done: true as const,\n value: undefined,\n });\n }\n return new Promise<IteratorResult<Experimental_BridgeUserMessage>>(\n resolve => {\n waiters.push(resolve);\n },\n );\n },\n };\n },\n };\n}\n\nfunction parseEnvList(value: string | undefined): string[] | undefined {\n if (!value) return undefined;\n const items = value\n .split(',')\n .map(item => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\nconst ENV_TRUTHY = new Set(['1', 'true', 'yes', 'on']);\n\n/**\n * Per-turn surface handed to {@link RunBridgeOptions.onStart}. The adapter\n * drives its runtime against these primitives; the runtime owns the transport.\n */\nexport interface BridgeTurn {\n /**\n * Emit a turn event to the host. Stamps a monotonic `seq`, appends to the\n * in-memory replay log, and sends to the live socket (best-effort — if the\n * host is mid-reconnect the event waits in the log and is replayed on\n * resume).\n */\n emit(event: BridgeEvent): void;\n\n /**\n * Register interest in a host-executed tool result and resolve when the\n * matching `tool-result` arrives. The adapter emits the `tool-call` event\n * itself (via {@link emit}) using the same `toolCallId`.\n */\n requestToolResult(\n toolCallId: string,\n ): Promise<{ output: unknown; isError?: boolean }>;\n\n /**\n * Register interest in a host approval decision and resolve when the matching\n * `tool-approval-response` arrives. The adapter emits the\n * `tool-approval-request` event itself using the same `approvalId`.\n */\n requestToolApproval(\n approvalId: string,\n ): Promise<{ approved: boolean; reason?: string }>;\n\n readonly experimental_userMessages: Experimental_BridgeUserMessageQueue;\n\n /** Aborts when the host sends `abort`. */\n readonly abortSignal: AbortSignal;\n\n /** True for the first turn since this bridge process started. */\n readonly firstTurn: boolean;\n\n /**\n * Emit a structured diagnostic. Gated by the session's debug level +\n * subsystem filter; a no-op when diagnostics are disabled. Adapters use this\n * for runtime-level instrumentation; raw `console.*` output is captured and\n * forwarded automatically.\n */\n bridgeLog(input: {\n level?: BridgeDebugLevel;\n subsystem: string;\n message: string;\n attrs?: Record<string, unknown>;\n error?: unknown;\n }): void;\n\n /**\n * Emit a non-fatal bridge warning to stderr using the runtime's harness\n * prefix. This is diagnostic-only: it does not emit a stream event, does not\n * consume a `seq`, and does not fail the turn.\n */\n emitWarning(input: { message: string }): void;\n\n emitError(input: { error: unknown; message?: string }): void;\n}\n\nexport interface RunBridgeOptions<TStart extends { type: 'start' }> {\n /** Identifier written into `bridge-meta.json` (`'claude-code'` / `'codex'`). */\n bridgeType: string;\n /** Directory for `bridge-meta.json` / `start-config.json`. Created if absent. */\n bridgeStateDir: string;\n /**\n * Drive one prompt turn. Rejections surface to the host as an `error`\n * event.\n *\n * Contract: once `turn.abortSignal` fires, wind down promptly — turns are\n * serialized, and a replacement `start` waits up to\n * {@link turnTeardownGraceMs} for this promise to settle before it\n * proceeds anyway.\n */\n onStart(start: TStart, turn: BridgeTurn): Promise<void>;\n /**\n * How long a replacement `start` waits for the previous turn's teardown\n * after aborting it, in milliseconds. Turns are serialized so an aborted\n * turn cannot emit into its replacement's event log or overlap its runtime\n * process — but only within this bound: an adapter that does not settle\n * `onStart` after its abort signal fires forfeits the protection for that\n * boundary, and the new turn proceeds anyway rather than blocking forever.\n * The default of ten seconds exceeds the Claude bridge's five-second\n * hard-abort fallback.\n */\n turnTeardownGraceMs?: number;\n /**\n * Produce the adapter-defined runtime resume data for `stop`. Defaults to\n * `{}`.\n */\n onStop?(): unknown | Promise<unknown>;\n /**\n * Perform adapter-defined destruction before the bridge exits.\n */\n onDestroy?(): void | Promise<void>;\n /** WS port. Defaults to `BRIDGE_WS_PORT` env (0 = OS-assigned). */\n port?: number;\n /** Auth token. Defaults to `BRIDGE_CHANNEL_TOKEN` env. */\n token?: string;\n /** Called with the bound port once the server is listening. */\n onListening?(port: number): void;\n /**\n * Tear the process down after `stop` / `destroy`. Defaults to closing\n * the server and calling `process.exit(0)`. Overridable for tests.\n */\n onExit?(): void;\n}\n\ntype InboundControl =\n | {\n type: 'tool-result';\n toolCallId: string;\n output: unknown;\n isError?: boolean;\n }\n | {\n type: 'tool-approval-response';\n approvalId: string;\n approved: boolean;\n reason?: string;\n }\n | { type: 'user-message'; messageId?: string; text: string }\n | { type: 'abort' }\n | { type: 'stop' }\n | { type: 'destroy' }\n | { type: 'resume'; lastSeenEventId: number };\n\nconst WS_OPEN = 1;\n\n/**\n * Boot the bridge: bind the WebSocket server, announce `bridge-ready`, and\n * service host connections for the lifetime of the process. Resolves once the\n * server is listening; the process then stays alive on the server until a\n * `stop` / `destroy` exits it.\n */\nexport interface BridgeHandle {\n /** The port the WebSocket server bound to. */\n readonly port: number;\n /** Close the WebSocket server. Does not call `process.exit`. */\n close(): Promise<void>;\n}\n\nexport async function runBridge<TStart extends { type: 'start' }>(\n options: RunBridgeOptions<TStart>,\n): Promise<BridgeHandle> {\n const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;\n const teardownGraceMs = options.turnTeardownGraceMs ?? 10_000;\n const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? '';\n const bridgeWsPort =\n options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? '0', 10);\n\n const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;\n const startConfigPath = `${bridgeStateDir}/start-config.json`;\n const rerunStartConfigPath = `${bridgeStateDir}/rerun-start-config.json`;\n const eventLogPath = `${bridgeStateDir}/event-log.ndjson`;\n\n try {\n await mkdir(bridgeStateDir, { recursive: true });\n } catch {\n // Best-effort; the bridge still runs without its state files.\n }\n\n // ─── mutable runtime state ──────────────────────────────────────────\n let currentBoundPort = 0;\n let currentTurnState: BridgeState = 'init';\n /*\n * The one connection turn events stream to. A socket claims it by asking for\n * work — `start` (a turn) or `resume` (a catch-up) — never by connecting:\n * every event goes here alone, so claiming on connect would silence a turn\n * already streaming to someone else. Any number of sockets may be connected;\n * the others still exchange control frames, they just get no events.\n */\n let activeSocket: WebSocket | undefined;\n let isFirstTurn = true;\n let turnAbort: AbortController | undefined;\n let currentUserMessages: InternalBridgeUserMessageQueue | undefined;\n /**\n * Settles when the in-flight turn has fully wound down — `onStart`\n * returned or threw AND its completion state was recorded. `undefined`\n * between turns. A new `start` fences on this so turns never overlap.\n */\n let activeTurn: Promise<void> | undefined;\n\n // Diagnostics. Resolved per turn from `start.debug` with a sandbox-side\n // env fallback; gates console capture + structured `debug-event`s.\n let debugConfig: BridgeDebugConfig | undefined;\n let consoleCaptureInstalled = false;\n const envDebugEnabled = ENV_TRUTHY.has(\n (procEnv.HARNESS_DEBUG ?? '').toLowerCase(),\n );\n\n // Replay log. `seq` is monotonic across the whole process — never reset —\n // because the host's `SandboxChannel` cursor (`lastSeenEventId`) lives across\n // turns. The log *contents* are cleared at the start of each turn to bound\n // memory; the just-finished turn stays replayable until the next `start`.\n let seqCounter = 0;\n let eventLog: Array<{ seq: number; line: string }> = [];\n\n /*\n * Disk mirror of the in-memory replay log. The in-memory log is lost when the\n * bridge process dies; the on-disk `event-log.ndjson` survives in the sandbox\n * filesystem so a respawned bridge (started with `BRIDGE_REPLAY_FROM_DISK=1`)\n * can reload the in-flight turn and serve a host's resume cursor —\n * `replay` recovery. Writes are batched on `setImmediate` (single-flight via\n * `flushPromise`) to keep `emit` off the disk hot path.\n */\n let diskBuffer = '';\n let flushPromise: Promise<void> | null = null;\n\n const flushEventsToDisk = async (): Promise<void> => {\n while (diskBuffer.length > 0) {\n const buf = diskBuffer;\n diskBuffer = '';\n await appendFile(eventLogPath, buf).catch(() => {\n // Best-effort crash-recovery mirror; the in-memory log is the source of\n // truth for the live connection.\n });\n }\n };\n\n const scheduleEventFlush = (): void => {\n if (flushPromise) return;\n flushPromise = new Promise<void>(resolve => {\n setImmediate(() => {\n void flushEventsToDisk().finally(resolve);\n });\n }).finally(() => {\n flushPromise = null;\n if (diskBuffer.length > 0) {\n scheduleEventFlush();\n }\n });\n };\n\n const flushPendingEventsToDisk = async (): Promise<void> => {\n if (diskBuffer.length > 0 && !flushPromise) {\n scheduleEventFlush();\n }\n // Await each in-flight flush, re-reading `flushPromise` after every await\n // since a fresh flush may have been scheduled for buffer that arrived while\n // we waited.\n let inFlight = flushPromise;\n while (inFlight) {\n await inFlight;\n inFlight = flushPromise;\n }\n };\n\n /*\n * When respawned for `replay`, reload the previous turn's log from disk before\n * accepting any connection so the very first `resume{lastSeenEventId}` can be\n * served the tail (including the terminal `finish`). The seq counter is\n * restored to the last persisted seq so it stays aligned with the host's\n * long-lived cursor. The file is NOT truncated in this mode — only a fresh\n * `start` (next turn) clears it.\n */\n const replayFromDisk = procEnv.BRIDGE_REPLAY_FROM_DISK === '1';\n if (replayFromDisk && existsSync(eventLogPath)) {\n try {\n const lines = readFileSync(eventLogPath, 'utf8')\n .split('\\n')\n .map(line => line.trim())\n .filter(Boolean);\n eventLog = lines.map(line => ({\n seq: (JSON.parse(line) as { seq: number }).seq,\n line,\n }));\n seqCounter = eventLog.at(-1)?.seq ?? 0;\n } catch {\n // Corrupt/partial log: fall back to an empty log; the host then degrades\n // to `rerun` instead of replaying a malformed tail.\n eventLog = [];\n seqCounter = 0;\n }\n }\n\n const pendingToolResults = new Map<\n string,\n (output: { output: unknown; isError?: boolean }) => void\n >();\n const pendingToolApprovals = new Map<\n string,\n (response: { approved: boolean; reason?: string }) => void\n >();\n\n // ─── persistence (best-effort meta + start config) ──────────────────\n const writeBridgeMeta = async (state: BridgeState): Promise<void> => {\n try {\n await writeFile(\n bridgeMetaPath,\n JSON.stringify({\n type: bridgeType,\n port: currentBoundPort,\n state,\n pid,\n }),\n );\n } catch {\n // Best-effort resilience metadata; not load-bearing for the active turn.\n }\n };\n\n const writeStartConfig = async (start: unknown): Promise<void> => {\n try {\n const serialized = JSON.stringify(start);\n await writeFile(startConfigPath, serialized);\n // Frozen copy: written once, restored over start-config.json by future\n // rerun-mode recovery to re-run the original turn from scratch.\n if (!existsSync(rerunStartConfigPath)) {\n await writeFile(rerunStartConfigPath, serialized);\n }\n } catch {\n // Best-effort.\n }\n };\n\n // ─── wire send + replay ─────────────────────────────────────────────\n const emit = (event: BridgeEvent): void => {\n const seq = ++seqCounter;\n const line = JSON.stringify({ ...event, seq });\n eventLog.push({ seq, line });\n diskBuffer += `${line}\\n`;\n scheduleEventFlush();\n if (activeSocket?.readyState === WS_OPEN) {\n try {\n activeSocket.send(line);\n } catch {\n // Send is best-effort: a dropped socket leaves the event in the log,\n // replayed once the host reconnects and sends `resume`.\n }\n }\n };\n\n const replay = (ws: WebSocket, afterSeq: number): void => {\n for (const entry of eventLog) {\n if (entry.seq > afterSeq && ws.readyState === WS_OPEN) {\n ws.send(entry.line);\n }\n }\n };\n\n // ─── diagnostics ──────────────────────────────────────────────\n const shouldEmitDebugEvent = (\n level: BridgeDebugLevel,\n subsystem: string,\n ): boolean => {\n if (!debugConfig?.enabled) return false;\n const threshold = debugConfig.level ?? 'debug';\n if (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;\n return subsystemMatches(debugConfig.subsystems, subsystem);\n };\n\n /*\n * Forward sandbox console output. We line-buffer the original writers (kept so\n * output still reaches the real fds) and emit one `sandbox-log` per complete\n * line. `emit` never writes to stdout/stderr, so there is no recursion.\n * Installed lazily the first time a turn enables diagnostics; once installed,\n * capture is gated per-write on `debugConfig.enabled` so a later turn can\n * disable it. Console capture is independent of the subsystem/level filter.\n */\n const rawStdoutWrite = process.stdout.write.bind(process.stdout);\n const rawStderrWrite = process.stderr.write.bind(process.stderr);\n\n const writeErrorToStderr = (input: {\n message: string;\n error: unknown;\n }): void => {\n try {\n const formatted = formatBridgeError(input.error);\n rawStderrWrite(\n `[harness:${bridgeType}:error] ${input.message}: ${formatted.message}\\n`,\n );\n if (formatted.stack) {\n rawStderrWrite(`${formatted.stack}\\n`);\n }\n } catch {}\n };\n\n const emitWarning = (input: { message: string }): void => {\n try {\n for (const line of input.message.split('\\n')) {\n if (line.trim().length > 0) {\n rawStderrWrite(`[harness:${bridgeType}:warn] ${line}\\n`);\n }\n }\n } catch {}\n };\n\n const emitError = (input: { error: unknown; message?: string }): void => {\n writeErrorToStderr({\n message: input.message ?? 'bridge error',\n error: input.error,\n });\n emit({ type: 'error', error: serialiseError(input.error) });\n };\n\n const installConsoleCapture = (): void => {\n if (consoleCaptureInstalled) return;\n consoleCaptureInstalled = true;\n const buffers: { stdout: string; stderr: string } = {\n stdout: '',\n stderr: '',\n };\n const patch =\n (stream: 'stdout' | 'stderr', raw: typeof process.stdout.write) =>\n (chunk: unknown, encoding?: unknown, cb?: unknown): boolean => {\n if (debugConfig?.enabled) {\n try {\n const enc = typeof encoding === 'string' ? encoding : 'utf8';\n const text =\n typeof chunk === 'string'\n ? chunk\n : Buffer.from(chunk as Uint8Array).toString(\n enc as BufferEncoding,\n );\n const combined = buffers[stream] + text.replace(/\\r\\n/g, '\\n');\n const parts = combined.split('\\n');\n buffers[stream] = parts.pop() ?? '';\n for (const line of parts) {\n const trimmed = line.replace(/\\s+$/, '');\n if (trimmed) {\n emit({\n type: 'sandbox-log',\n source: bridgeType,\n stream,\n line: trimmed,\n });\n }\n }\n } catch {\n // Never let capture break real output.\n }\n }\n return (raw as (c: unknown, e?: unknown, cb?: unknown) => boolean)(\n chunk,\n encoding,\n cb,\n );\n };\n process.stdout.write = patch(\n 'stdout',\n rawStdoutWrite,\n ) as typeof process.stdout.write;\n process.stderr.write = patch(\n 'stderr',\n rawStderrWrite,\n ) as typeof process.stderr.write;\n };\n\n // ─── inbound routing ────────────────────────────────────────────────\n const handleInbound = async (\n msg: TStart | InboundControl,\n ws: WebSocket,\n ): Promise<void> => {\n switch (msg.type) {\n case 'start': {\n /*\n * A new turn replaces the active one — but only after the active one\n * has fully wound down. Inbound frames are dispatched concurrently,\n * and the host settles a caller abort immediately, so a retry's\n * `start` can arrive while the aborted turn is still tearing down\n * (e.g. a graceful interrupt). Without this fence the old turn would\n * keep emitting into the new turn's cleared event log, two runtime\n * processes would run side by side, and the old turn's completion\n * would mark the bridge `waiting` underneath the new turn. Abort the\n * old turn to hasten its teardown; adapters are expected to bound\n * that teardown themselves (e.g. a hard-abort fallback), but the\n * runtime does not rely on it: the wait is capped by the teardown\n * grace period, after which the new turn proceeds anyway — the\n * pre-fence overlapping behavior — rather than hanging behind a\n * teardown that never settles.\n */\n for (;;) {\n const pendingTurn = activeTurn;\n if (pendingTurn == null) break;\n turnAbort?.abort();\n currentUserMessages?.close(\n new Error('A new bridge turn replaced the active turn.'),\n );\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n const settled = await Promise.race([\n pendingTurn.then(() => true as const),\n new Promise<false>(resolve => {\n graceTimer = setTimeout(() => resolve(false), teardownGraceMs);\n graceTimer.unref?.();\n }),\n ]);\n clearTimeout(graceTimer);\n if (!settled) break;\n }\n let turnFinished!: () => void;\n const thisTurn = new Promise<void>(resolve => (turnFinished = resolve));\n activeTurn = thisTurn;\n activeSocket = ws; // asking for a turn claims the event stream\n const firstTurn = isFirstTurn;\n isFirstTurn = false;\n eventLog = []; // clear previous turn; keep seqCounter monotonic\n // Mirror the in-memory clear to disk: the log tracks only the current\n // turn. Discard any unflushed tail from the prior turn first.\n diskBuffer = '';\n void writeFile(eventLogPath, '').catch(() => {});\n turnAbort = new AbortController();\n currentTurnState = 'running';\n void writeStartConfig(msg);\n void writeBridgeMeta('running');\n const startDebug = (msg as { debug?: BridgeDebugConfig }).debug;\n debugConfig = {\n enabled: startDebug?.enabled ?? envDebugEnabled,\n level:\n startDebug?.level ??\n (procEnv.HARNESS_DEBUG_LEVEL as BridgeDebugLevel | undefined),\n subsystems:\n startDebug?.subsystems ??\n parseEnvList(procEnv.HARNESS_DEBUG_SUBSYSTEMS),\n };\n if (debugConfig.enabled) {\n installConsoleCapture();\n }\n const userMessages = createBridgeUserMessageQueue({ respond: emit });\n const turn: BridgeTurn = {\n emit,\n requestToolResult: toolCallId =>\n new Promise(resolve => {\n pendingToolResults.set(toolCallId, resolve);\n }),\n requestToolApproval: approvalId =>\n new Promise(resolve => {\n pendingToolApprovals.set(approvalId, resolve);\n }),\n experimental_userMessages: userMessages,\n abortSignal: turnAbort.signal,\n firstTurn,\n bridgeLog: input => {\n const level = input.level ?? 'debug';\n if (!shouldEmitDebugEvent(level, input.subsystem)) return;\n emit({\n type: 'debug-event',\n level,\n subsystem: input.subsystem,\n message: input.message,\n ...(input.attrs ? { attrs: input.attrs } : {}),\n ...(input.error !== undefined\n ? { error: formatBridgeError(input.error) }\n : {}),\n });\n },\n emitWarning,\n emitError,\n };\n currentUserMessages = userMessages;\n try {\n await onStart(msg as TStart, turn);\n } catch (err) {\n emitError({ error: err, message: 'bridge turn failed' });\n } finally {\n userMessages.close();\n if (currentUserMessages === userMessages) {\n currentUserMessages = undefined;\n }\n // Only the still-active turn records completion: after a fence\n // timeout a replacement turn is already running, and this stale\n // completion must not mark the bridge waiting underneath it.\n if (activeTurn === thisTurn) {\n activeTurn = undefined;\n currentTurnState = 'waiting';\n void writeBridgeMeta('waiting');\n }\n turnFinished();\n }\n return;\n }\n case 'tool-result': {\n const resolver = pendingToolResults.get(msg.toolCallId);\n if (resolver) {\n pendingToolResults.delete(msg.toolCallId);\n resolver({ output: msg.output, isError: msg.isError });\n }\n return;\n }\n case 'tool-approval-response': {\n const resolver = pendingToolApprovals.get(msg.approvalId);\n if (resolver) {\n pendingToolApprovals.delete(msg.approvalId);\n resolver({ approved: msg.approved, reason: msg.reason });\n }\n return;\n }\n case 'user-message': {\n const messageId = msg.messageId ?? randomUUID();\n if (currentUserMessages == null) {\n sendControl(ws, {\n type: 'user-message-response',\n messageId,\n accepted: false,\n error: { message: 'The bridge has no active turn to steer.' },\n });\n return;\n }\n if (ws !== activeSocket) {\n sendControl(ws, {\n type: 'user-message-response',\n messageId,\n accepted: false,\n error: {\n message: 'The connection does not own the active bridge turn.',\n },\n });\n return;\n }\n currentUserMessages.enqueue({\n messageId,\n text: msg.text,\n });\n return;\n }\n case 'abort':\n turnAbort?.abort();\n return;\n case 'resume':\n activeSocket = ws; // asking for a catch-up claims it too\n // Synchronous, so no event can slip out live ahead of the replayed tail.\n replay(ws, msg.lastSeenEventId);\n return;\n case 'destroy':\n currentTurnState = 'done';\n void writeBridgeMeta('done');\n await onDestroy?.();\n drainThenExit(ws, 1000, 'destroy');\n return;\n case 'stop': {\n currentTurnState = 'done';\n void writeBridgeMeta('done');\n const data = (await onStop?.()) ?? {};\n sendControl(ws, { type: 'bridge-stop', data });\n drainThenExit(ws, 1000, 'stop');\n return;\n }\n }\n };\n\n // ─── server ─────────────────────────────────────────────────────────\n void writeBridgeMeta('init');\n\n const wss = new WebSocketServer({ port: bridgeWsPort, host: '0.0.0.0' });\n\n const exit = (): void => {\n if (options.onExit) {\n options.onExit();\n return;\n }\n wss.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 1000).unref();\n };\n\n const drainThenExit = (ws: WebSocket, code: number, reason: string): void => {\n const start = Date.now();\n const tick = (): void => {\n const drained = ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN;\n if (drained || Date.now() - start >= 5_000) {\n // Flush the on-disk log so a clean stop/destroy leaves a complete\n // event-log.ndjson for any later replay recovery.\n void flushPendingEventsToDisk().finally(() => {\n try {\n ws.close(code, reason);\n } finally {\n exit();\n }\n });\n return;\n }\n setTimeout(tick, 10).unref();\n };\n tick();\n };\n\n wss.on('listening', () => {\n const addr = wss.address();\n currentBoundPort = typeof addr === 'object' && addr ? addr.port : 0;\n currentTurnState = 'waiting';\n void writeBridgeMeta('waiting');\n stdout.write(\n JSON.stringify({\n type: 'bridge-ready',\n port: currentBoundPort,\n }) + '\\n',\n );\n options.onListening?.(currentBoundPort);\n });\n\n wss.on('connection', (ws: WebSocket, req: { url?: string }) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (url.searchParams.get('agent_bridge_token') !== expectedToken) {\n ws.close(1008, 'unauthorized');\n return;\n }\n\n // Announce liveness the instant we accept. Some sandbox runtimes complete\n // the host-side WS handshake before the connection is forwarded here; the\n // host waits for this frame before sending `start`/`resume`.\n sendControl(ws, {\n type: 'bridge-hello',\n state: currentTurnState,\n lastSeq: seqCounter,\n capabilities: { experimental_userMessageResponses: true },\n });\n\n ws.on('message', (raw: ArrayBufferLike | string) => {\n let parsed: TStart | InboundControl;\n try {\n const text =\n typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8');\n parsed = JSON.parse(text) as TStart | InboundControl;\n } catch (err) {\n sendControl(ws, {\n type: 'error',\n error: `protocol parse error: ${(err as Error).message}`,\n });\n return;\n }\n void handleInbound(parsed, ws);\n });\n\n ws.on('close', () => {\n // Only the stream owner's close matters; a socket that never claimed it,\n // or that a later `start`/`resume` displaced, closes as a no-op.\n // Crucially we do NOT abort the in-flight turn: it keeps running and its\n // events accumulate in the log for replay on reconnect.\n if (activeSocket === ws) {\n activeSocket = undefined;\n }\n });\n\n ws.on('error', () => {\n // 'close' follows; nothing to do beyond keeping the process alive.\n });\n });\n\n // Surface bridge-internal crashes to the host instead of dying silently.\n process.on('uncaughtException', err => {\n emitError({ error: err, message: 'uncaught exception' });\n });\n process.on('unhandledRejection', err => {\n emitError({ error: err, message: 'unhandled rejection' });\n });\n\n await new Promise<void>((resolve, reject) => {\n if (wss.address() != null) {\n resolve();\n return;\n }\n\n wss.once('listening', resolve);\n wss.once('error', reject);\n });\n\n return {\n port: currentBoundPort,\n close: () =>\n new Promise<void>(resolve => {\n wss.close(() => resolve());\n }),\n };\n}\n\n/*\n * Control frames answer the socket that sent the frame they reply to, so the\n * target is always explicit. Event streaming is the separate, stateful path\n * (`emit` → `activeSocket`); this one carries no state at all.\n */\nfunction sendControl(\n socket: WebSocket | undefined,\n message: Record<string, unknown>,\n): void {\n if (socket?.readyState === WS_OPEN) {\n try {\n socket.send(JSON.stringify(message));\n } catch {\n // best-effort\n }\n }\n}\n\nfunction serialiseError(err: unknown): unknown {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n return err;\n}\n","const name = 'AI_HarnessBridgeCapabilityUnsupportedError';\n\n/**\n * Signals an unsupported capability discovered inside a sandbox bridge.\n * `isInstance` also recognizes the serialized error shape received by the\n * host, where it can be translated to `HarnessCapabilityUnsupportedError`.\n */\nexport class HarnessBridgeCapabilityUnsupportedError extends Error {\n readonly harnessId?: string;\n readonly cause?: unknown;\n\n constructor({\n message,\n harnessId,\n cause,\n }: {\n message: string;\n harnessId?: string;\n cause?: unknown;\n }) {\n super(message);\n Object.defineProperty(this, 'name', { value: name });\n this.harnessId = harnessId;\n this.cause = cause;\n }\n\n static isInstance(\n error: unknown,\n ): error is HarnessBridgeCapabilityUnsupportedError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === name &&\n 'message' in error &&\n typeof error.message === 'string'\n );\n }\n}\n"],"mappings":";AASA,SAAS,YAAY,OAAO,iBAAiB;AAC7C,SAAS,YAAY,oBAAoB;AACzC,SAAS,kBAAkB;AAC3B,SAAS,OAAO,SAAS,KAAK,cAAc;AAC5C,SAAS,uBAAuC;;;ACbhD,IAAM,OAAO;AAON,IAAM,0CAAN,cAAsD,MAAM;AAAA,EAIjE,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,OAAO;AACb,WAAO,eAAe,MAAM,QAAQ,EAAE,OAAO,KAAK,CAAC;AACnD,SAAK,YAAY;AACjB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,OAAO,WACL,OACkD;AAClD,WACE,SAAS,QACT,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,QACf,aAA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,QAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,QAAI,IAAI,QAAQ,KAAK,MAAM;AACzB,cAAQ;AACR;AAAA,IACF;AAEA,QAAI,KAAK,aAAa,OAAO;AAC7B,QAAI,KAAK,SAAS,MAAM;AAAA,EAC1B,CAAC;AAED,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MACL,IAAI,QAAc,aAAW;AAC3B,UAAI,MAAM,MAAM,QAAQ,CAAC;AAAA,IAC3B,CAAC;AAAA,EACL;AACF;AAOA,SAAS,YACP,QACA,SACM;AACN,MAAI,QAAQ,eAAe,SAAS;AAClC,QAAI;AACF,aAAO,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,IACrC,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,SAAS,eAAe,KAAuB;AAC7C,MAAI,eAAe,OAAO;AACxB,WAAO,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,SAAS,OAAO,IAAI,MAAM;AAAA,EAClE;AACA,SAAO;AACT;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as _ai_sdk_provider_utils from '@ai-sdk/provider-utils';
|
|
|
2
2
|
import { Experimental_SandboxSession, UserModelMessage, ToolSet, FlexibleSchema, Tool } from '@ai-sdk/provider-utils';
|
|
3
3
|
import { z } from 'zod/v4';
|
|
4
4
|
import * as _ai_sdk_provider from '@ai-sdk/provider';
|
|
5
|
-
import { JSONValue, LanguageModelV4ToolCall, LanguageModelV4ToolApprovalRequest, LanguageModelV4ToolResult, LanguageModelV4FinishReason, LanguageModelV4Usage, SharedV4ProviderMetadata,
|
|
5
|
+
import { JSONSchema7, JSONValue, LanguageModelV4ToolCall, LanguageModelV4ToolApprovalRequest, LanguageModelV4ToolResult, LanguageModelV4FinishReason, LanguageModelV4Usage, SharedV4ProviderMetadata, AISDKError } from '@ai-sdk/provider';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* One file to write into the sandbox as part of an adapter's bootstrap recipe.
|
|
@@ -397,6 +397,66 @@ type HarnessV1ResponseFormat = {
|
|
|
397
397
|
readonly description?: string;
|
|
398
398
|
};
|
|
399
399
|
|
|
400
|
+
/**
|
|
401
|
+
* A self-contained instruction bundle the underlying runtime can load into
|
|
402
|
+
* its context. Adapters decide how to surface skills to the runtime.
|
|
403
|
+
*/
|
|
404
|
+
type HarnessV1Skill = {
|
|
405
|
+
/** Stable identifier for the skill (kebab-case slug). */
|
|
406
|
+
readonly name: string;
|
|
407
|
+
/**
|
|
408
|
+
* Short, model-facing description. This is what the runtime sees to
|
|
409
|
+
* decide whether the skill is relevant.
|
|
410
|
+
*/
|
|
411
|
+
readonly description: string;
|
|
412
|
+
/** Full skill content the model loads when the skill is active. */
|
|
413
|
+
readonly content: string;
|
|
414
|
+
/**
|
|
415
|
+
* Additional files that belong to this skill. Adapters with native skill
|
|
416
|
+
* directories materialize these next to `SKILL.md`; adapters without native
|
|
417
|
+
* skill files include them with the skill content.
|
|
418
|
+
*/
|
|
419
|
+
readonly files?: ReadonlyArray<HarnessV1SkillFile>;
|
|
420
|
+
};
|
|
421
|
+
type HarnessV1SkillFile = {
|
|
422
|
+
/**
|
|
423
|
+
* Skill-relative POSIX path, for example `reference.md` or
|
|
424
|
+
* `references/codes.md`. Absolute paths and `..` segments are rejected by
|
|
425
|
+
* adapters before writing.
|
|
426
|
+
*/
|
|
427
|
+
readonly path: string;
|
|
428
|
+
/** UTF-8 text content for the file. */
|
|
429
|
+
readonly content: string;
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Description of a host-defined tool that the harness should make available
|
|
434
|
+
* to the underlying agent runtime.
|
|
435
|
+
*
|
|
436
|
+
* Adapters translate this into whatever shape their runtime expects (e.g.
|
|
437
|
+
* Claude Code's tool definitions, Codex CLI's tool config, an MCP server
|
|
438
|
+
* exposed to the runtime, …). The adapter does not execute the tool; when
|
|
439
|
+
* the runtime calls it, the adapter emits a `tool-call` event and waits for
|
|
440
|
+
* `submitToolResult` from the caller.
|
|
441
|
+
*/
|
|
442
|
+
type HarnessV1ToolSpec = {
|
|
443
|
+
/**
|
|
444
|
+
* Tool name the agent runtime sees. Must match the name on incoming
|
|
445
|
+
* `tool-call` events.
|
|
446
|
+
*/
|
|
447
|
+
readonly name: string;
|
|
448
|
+
/**
|
|
449
|
+
* Human-readable description handed to the runtime, used to help the model
|
|
450
|
+
* decide when to call the tool.
|
|
451
|
+
*/
|
|
452
|
+
readonly description?: string;
|
|
453
|
+
/**
|
|
454
|
+
* JSON Schema describing the expected input for the tool. Optional because
|
|
455
|
+
* some runtimes accept tools without schemas (free-form arguments).
|
|
456
|
+
*/
|
|
457
|
+
readonly inputSchema?: JSONSchema7;
|
|
458
|
+
};
|
|
459
|
+
|
|
400
460
|
type HarnessV1PendingToolApproval = {
|
|
401
461
|
readonly approvalId: string;
|
|
402
462
|
readonly toolCallId: string;
|
|
@@ -411,6 +471,32 @@ type HarnessV1PendingToolResult = {
|
|
|
411
471
|
readonly toolName: string;
|
|
412
472
|
readonly input: string;
|
|
413
473
|
};
|
|
474
|
+
/**
|
|
475
|
+
* Framework-owned settings captured when a turn begins. The same settings are
|
|
476
|
+
* passed to fresh and continued turns and persisted with unfinished-turn state
|
|
477
|
+
* so a resumed continuation cannot pick up configuration from a later turn.
|
|
478
|
+
*/
|
|
479
|
+
type HarnessV1TurnSettings = {
|
|
480
|
+
/**
|
|
481
|
+
* Skills made available to the underlying runtime for this turn. Adapters
|
|
482
|
+
* must replace skills from the preceding completed turn before starting a
|
|
483
|
+
* fresh turn. Rerun-based continuations use them to reconstruct the turn.
|
|
484
|
+
*/
|
|
485
|
+
readonly skills: ReadonlyArray<HarnessV1Skill>;
|
|
486
|
+
/**
|
|
487
|
+
* Free-form instructions for this turn. Adapters should apply them through
|
|
488
|
+
* the runtime's native system or developer instruction mechanism when
|
|
489
|
+
* supported. Rerun-based continuations use them to reconstruct the turn.
|
|
490
|
+
*/
|
|
491
|
+
readonly instructions?: string;
|
|
492
|
+
/**
|
|
493
|
+
* Host-defined tools made available to the underlying runtime for this turn.
|
|
494
|
+
* The harness emits `tool-call` events when the runtime calls one and waits
|
|
495
|
+
* for `submitToolResult`. Rerun-based continuations use them to reconstruct
|
|
496
|
+
* the turn.
|
|
497
|
+
*/
|
|
498
|
+
readonly tools: ReadonlyArray<HarnessV1ToolSpec>;
|
|
499
|
+
};
|
|
414
500
|
type HarnessV1LifecycleStateBase = {
|
|
415
501
|
/**
|
|
416
502
|
* Identifier of the harness that produced this state. Used by adapters to
|
|
@@ -458,40 +544,14 @@ type HarnessV1ContinueTurnState = HarnessV1LifecycleStateBase & {
|
|
|
458
544
|
* result before the underlying turn can continue.
|
|
459
545
|
*/
|
|
460
546
|
readonly pendingToolResults?: readonly HarnessV1PendingToolResult[];
|
|
461
|
-
};
|
|
462
|
-
type HarnessV1LifecycleState = HarnessV1ResumeSessionState | HarnessV1ContinueTurnState;
|
|
463
|
-
|
|
464
|
-
/**
|
|
465
|
-
* A self-contained instruction bundle the underlying runtime can load into
|
|
466
|
-
* its context. Adapters decide how to surface skills to the runtime.
|
|
467
|
-
*/
|
|
468
|
-
type HarnessV1Skill = {
|
|
469
|
-
/** Stable identifier for the skill (kebab-case slug). */
|
|
470
|
-
readonly name: string;
|
|
471
|
-
/**
|
|
472
|
-
* Short, model-facing description. This is what the runtime sees to
|
|
473
|
-
* decide whether the skill is relevant.
|
|
474
|
-
*/
|
|
475
|
-
readonly description: string;
|
|
476
|
-
/** Full skill content the model loads when the skill is active. */
|
|
477
|
-
readonly content: string;
|
|
478
|
-
/**
|
|
479
|
-
* Additional files that belong to this skill. Adapters with native skill
|
|
480
|
-
* directories materialize these next to `SKILL.md`; adapters without native
|
|
481
|
-
* skill files include them with the skill content.
|
|
482
|
-
*/
|
|
483
|
-
readonly files?: ReadonlyArray<HarnessV1SkillFile>;
|
|
484
|
-
};
|
|
485
|
-
type HarnessV1SkillFile = {
|
|
486
547
|
/**
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
*
|
|
548
|
+
* Framework-owned settings captured when the unfinished turn began. They
|
|
549
|
+
* are persisted outside adapter data so a resumed continuation cannot pick
|
|
550
|
+
* up settings prepared for a later turn.
|
|
490
551
|
*/
|
|
491
|
-
readonly
|
|
492
|
-
/** UTF-8 text content for the file. */
|
|
493
|
-
readonly content: string;
|
|
552
|
+
readonly turnSettings?: HarnessV1TurnSettings;
|
|
494
553
|
};
|
|
554
|
+
type HarnessV1LifecycleState = HarnessV1ResumeSessionState | HarnessV1ContinueTurnState;
|
|
495
555
|
|
|
496
556
|
/**
|
|
497
557
|
* Warning emitted by a harness adapter during a call.
|
|
@@ -802,34 +862,6 @@ declare const harnessV1StreamPartSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
802
862
|
rawValue: z.ZodUnknown;
|
|
803
863
|
}, z.core.$strip>]>;
|
|
804
864
|
|
|
805
|
-
/**
|
|
806
|
-
* Description of a host-defined tool that the harness should make available
|
|
807
|
-
* to the underlying agent runtime.
|
|
808
|
-
*
|
|
809
|
-
* Adapters translate this into whatever shape their runtime expects (e.g.
|
|
810
|
-
* Claude Code's tool definitions, Codex CLI's tool config, an MCP server
|
|
811
|
-
* exposed to the runtime, …). The adapter does not execute the tool; when
|
|
812
|
-
* the runtime calls it, the adapter emits a `tool-call` event and waits for
|
|
813
|
-
* `submitToolResult` from the caller.
|
|
814
|
-
*/
|
|
815
|
-
type HarnessV1ToolSpec = {
|
|
816
|
-
/**
|
|
817
|
-
* Tool name the agent runtime sees. Must match the name on incoming
|
|
818
|
-
* `tool-call` events.
|
|
819
|
-
*/
|
|
820
|
-
readonly name: string;
|
|
821
|
-
/**
|
|
822
|
-
* Human-readable description handed to the runtime, used to help the model
|
|
823
|
-
* decide when to call the tool.
|
|
824
|
-
*/
|
|
825
|
-
readonly description?: string;
|
|
826
|
-
/**
|
|
827
|
-
* JSON Schema describing the expected input for the tool. Optional because
|
|
828
|
-
* some runtimes accept tools without schemas (free-form arguments).
|
|
829
|
-
*/
|
|
830
|
-
readonly inputSchema?: JSONSchema7;
|
|
831
|
-
};
|
|
832
|
-
|
|
833
865
|
type HarnessV1BuiltinToolFiltering = {
|
|
834
866
|
mode: 'allow';
|
|
835
867
|
toolNames: string[];
|
|
@@ -853,17 +885,17 @@ declare function getHarnessV1BuiltinToolFilteringDenialReason(input: {
|
|
|
853
885
|
* calling the adapter, so adapters never need to derive provider-specific paths.
|
|
854
886
|
*/
|
|
855
887
|
type HarnessV1StartOptions = {
|
|
888
|
+
/**
|
|
889
|
+
* Model identifier selected by the consumer. Adapters interpret this value
|
|
890
|
+
* according to the underlying harness runtime.
|
|
891
|
+
*/
|
|
892
|
+
readonly model?: string;
|
|
856
893
|
/**
|
|
857
894
|
* Stable identifier for this harness session. Used as the underlying
|
|
858
895
|
* resource name where the adapter has a notion of a named session
|
|
859
896
|
* (sandbox name, native session id, …).
|
|
860
897
|
*/
|
|
861
898
|
readonly sessionId: string;
|
|
862
|
-
/**
|
|
863
|
-
* Skills made available to the underlying runtime for the lifetime of
|
|
864
|
-
* the session. Adapters decide how to surface them.
|
|
865
|
-
*/
|
|
866
|
-
readonly skills?: ReadonlyArray<HarnessV1Skill>;
|
|
867
899
|
/**
|
|
868
900
|
* Optional resume payload returned by a prior session lifecycle method. When
|
|
869
901
|
* provided, the adapter should resume the existing session before accepting a
|
|
@@ -917,7 +949,7 @@ type HarnessV1StartOptions = {
|
|
|
917
949
|
/**
|
|
918
950
|
* Options passed to `HarnessV1Session.doPromptTurn`.
|
|
919
951
|
*/
|
|
920
|
-
type HarnessV1PromptTurnOptions = {
|
|
952
|
+
type HarnessV1PromptTurnOptions = HarnessV1TurnSettings & {
|
|
921
953
|
/**
|
|
922
954
|
* Fresh input for this turn — either a plain string or a single
|
|
923
955
|
* `ModelMessage`. The harness session owns its own conversation history,
|
|
@@ -929,20 +961,6 @@ type HarnessV1PromptTurnOptions = {
|
|
|
929
961
|
* JSON response format must throw `HarnessCapabilityUnsupportedError`.
|
|
930
962
|
*/
|
|
931
963
|
readonly responseFormat?: HarnessV1ResponseFormat;
|
|
932
|
-
/**
|
|
933
|
-
* Host-defined tools to make available to the underlying runtime for this
|
|
934
|
-
* turn. The harness emits `tool-call` events when the runtime calls one
|
|
935
|
-
* and waits for `submitToolResult`.
|
|
936
|
-
*/
|
|
937
|
-
readonly tools?: ReadonlyArray<HarnessV1ToolSpec>;
|
|
938
|
-
/**
|
|
939
|
-
* Free-form instructions for the session. The framework supplies the same
|
|
940
|
-
* value on every turn. Adapters should append it to the runtime's native
|
|
941
|
-
* system or developer prompt when supported. Otherwise, they should prepend
|
|
942
|
-
* it to the first user message of a fresh session and rely on the runtime's
|
|
943
|
-
* persisted history when resuming.
|
|
944
|
-
*/
|
|
945
|
-
readonly instructions?: string;
|
|
946
964
|
/**
|
|
947
965
|
* Signal that aborts the in-flight turn. The adapter must cancel any
|
|
948
966
|
* underlying work and resolve `done` (with an error if appropriate).
|
|
@@ -963,24 +981,12 @@ type HarnessV1PromptTurnOptions = {
|
|
|
963
981
|
* in-flight turn rather than starting a new one. It is used to continue a turn
|
|
964
982
|
* that was previously suspended temporarily, e.g. by the workflow slice loop.
|
|
965
983
|
*/
|
|
966
|
-
type HarnessV1ContinueTurnOptions = {
|
|
984
|
+
type HarnessV1ContinueTurnOptions = HarnessV1TurnSettings & {
|
|
967
985
|
/**
|
|
968
986
|
* Response format of the in-flight turn. Rerun-based adapters use this when
|
|
969
987
|
* reconstructing the turn; attach-based adapters may ignore it.
|
|
970
988
|
*/
|
|
971
989
|
readonly responseFormat?: HarnessV1ResponseFormat;
|
|
972
|
-
/**
|
|
973
|
-
* Host-defined tools to make available for the continued turn. Same shape
|
|
974
|
-
* as `doPromptTurn`'s `tools`. An adapter that purely attaches to a live turn
|
|
975
|
-
* may ignore them; an adapter that re-drives the turn (rerun) needs them.
|
|
976
|
-
*/
|
|
977
|
-
readonly tools?: ReadonlyArray<HarnessV1ToolSpec>;
|
|
978
|
-
/**
|
|
979
|
-
* Free-form session instructions. An adapter that re-drives the runtime may
|
|
980
|
-
* need these to reconstruct its native system or developer prompt. An
|
|
981
|
-
* adapter that attaches to a live turn may ignore them.
|
|
982
|
-
*/
|
|
983
|
-
readonly instructions?: string;
|
|
984
990
|
/**
|
|
985
991
|
* Signal that aborts the continued turn. The adapter must cancel any
|
|
986
992
|
* underlying work and resolve `done` (with an error if appropriate).
|
|
@@ -1798,4 +1804,4 @@ declare class HarnessSandboxAuthenticationError extends HarnessError {
|
|
|
1798
1804
|
static isInstance(error: unknown): error is HarnessSandboxAuthenticationError;
|
|
1799
1805
|
}
|
|
1800
1806
|
|
|
1801
|
-
export { type Experimental_HarnessV1BridgeUserMessageResponse, HARNESS_V1_BUILTIN_TOOLS, HARNESS_V1_BUILTIN_TOOL_NAMES, HarnessCapabilityUnsupportedError, HarnessError, HarnessSandboxAuthenticationError, type HarnessV1, type HarnessV1Authentication, type HarnessV1AuthenticationEnvironment, type HarnessV1Bootstrap, type HarnessV1BootstrapCommand, type HarnessV1BootstrapFile, type HarnessV1BridgeDebugEvent, type HarnessV1BridgeOutboundMessage, type HarnessV1BridgeReady, type HarnessV1BridgeSandboxLog, type HarnessV1BridgeToolWire, type HarnessV1BuiltinTool, type HarnessV1BuiltinToolFiltering, type HarnessV1BuiltinToolName, type HarnessV1BuiltinToolUseKind, type HarnessV1CallWarning, type HarnessV1ContinueTurnOptions, type HarnessV1ContinueTurnState, type HarnessV1CredentialForwarding, type HarnessV1DebugConfig, type HarnessV1DebugLevel, type HarnessV1Diagnostic, type HarnessV1JSONArray, type HarnessV1JSONObject, type HarnessV1JSONSchema, type HarnessV1JSONValue, type HarnessV1LifecycleState, type HarnessV1Metadata, type HarnessV1NetworkPolicy, type HarnessV1NetworkSandboxSession, type HarnessV1Observability, type HarnessV1PendingToolApproval, type HarnessV1PendingToolResult, type HarnessV1PermissionMode, type HarnessV1PortEndpoint, type HarnessV1Prompt, type HarnessV1PromptControl, type HarnessV1PromptTurnOptions, type HarnessV1RequestTransformation, type HarnessV1RequestTransformationSources, type HarnessV1ResponseFormat, type HarnessV1ResumeSessionState, type HarnessV1SandboxProvider, type HarnessV1Session, type HarnessV1Skill, type HarnessV1StartOptions, type HarnessV1StreamPart, type HarnessV1ToolSpec, commonTool, experimental_harnessV1BridgeUserMessageInboundSchema, experimental_harnessV1BridgeUserMessageResponseSchema, getHarnessV1BuiltinToolFilteringDenialReason, harnessV1BridgeAbortInboundSchema, harnessV1BridgeBuiltinToolFilteringSchema, harnessV1BridgeDebugEventSchema, harnessV1BridgeDestroyInboundSchema, harnessV1BridgeHelloSchema, harnessV1BridgeInboundCommandSchemas, harnessV1BridgeOutboundMessageSchema, harnessV1BridgePermissionModeSchema, harnessV1BridgeReadySchema, harnessV1BridgeResponseFormatSchema, harnessV1BridgeResumeInboundSchema, harnessV1BridgeSandboxLogSchema, harnessV1BridgeStartBaseSchema, harnessV1BridgeStopInboundSchema, harnessV1BridgeStopSchema, harnessV1BridgeThreadSchema, harnessV1BridgeToolApprovalResponseInboundSchema, harnessV1BridgeToolResultInboundSchema, harnessV1BridgeToolWireSchema, harnessV1BridgeUserMessageInboundSchema, harnessV1DebugConfigSchema, harnessV1DebugLevelSchema, harnessV1DiagnosticFromBridgeFrame, harnessV1ErrorPartSchema, harnessV1FileChangePartSchema, harnessV1FinishPartSchema, harnessV1FinishStepPartSchema, harnessV1RawPartSchema, harnessV1ReasoningDeltaPartSchema, harnessV1ReasoningEndPartSchema, harnessV1ReasoningStartPartSchema, harnessV1StreamPartSchema, harnessV1StreamStartPartSchema, harnessV1TextDeltaPartSchema, harnessV1TextEndPartSchema, harnessV1TextStartPartSchema, harnessV1ToolApprovalRequestPartSchema, harnessV1ToolCallPartSchema, harnessV1ToolResultPartSchema, isHarnessV1BuiltinToolIncluded };
|
|
1807
|
+
export { type Experimental_HarnessV1BridgeUserMessageResponse, HARNESS_V1_BUILTIN_TOOLS, HARNESS_V1_BUILTIN_TOOL_NAMES, HarnessCapabilityUnsupportedError, HarnessError, HarnessSandboxAuthenticationError, type HarnessV1, type HarnessV1Authentication, type HarnessV1AuthenticationEnvironment, type HarnessV1Bootstrap, type HarnessV1BootstrapCommand, type HarnessV1BootstrapFile, type HarnessV1BridgeDebugEvent, type HarnessV1BridgeOutboundMessage, type HarnessV1BridgeReady, type HarnessV1BridgeSandboxLog, type HarnessV1BridgeToolWire, type HarnessV1BuiltinTool, type HarnessV1BuiltinToolFiltering, type HarnessV1BuiltinToolName, type HarnessV1BuiltinToolUseKind, type HarnessV1CallWarning, type HarnessV1ContinueTurnOptions, type HarnessV1ContinueTurnState, type HarnessV1CredentialForwarding, type HarnessV1DebugConfig, type HarnessV1DebugLevel, type HarnessV1Diagnostic, type HarnessV1JSONArray, type HarnessV1JSONObject, type HarnessV1JSONSchema, type HarnessV1JSONValue, type HarnessV1LifecycleState, type HarnessV1Metadata, type HarnessV1NetworkPolicy, type HarnessV1NetworkSandboxSession, type HarnessV1Observability, type HarnessV1PendingToolApproval, type HarnessV1PendingToolResult, type HarnessV1PermissionMode, type HarnessV1PortEndpoint, type HarnessV1Prompt, type HarnessV1PromptControl, type HarnessV1PromptTurnOptions, type HarnessV1RequestTransformation, type HarnessV1RequestTransformationSources, type HarnessV1ResponseFormat, type HarnessV1ResumeSessionState, type HarnessV1SandboxProvider, type HarnessV1Session, type HarnessV1Skill, type HarnessV1StartOptions, type HarnessV1StreamPart, type HarnessV1ToolSpec, type HarnessV1TurnSettings, commonTool, experimental_harnessV1BridgeUserMessageInboundSchema, experimental_harnessV1BridgeUserMessageResponseSchema, getHarnessV1BuiltinToolFilteringDenialReason, harnessV1BridgeAbortInboundSchema, harnessV1BridgeBuiltinToolFilteringSchema, harnessV1BridgeDebugEventSchema, harnessV1BridgeDestroyInboundSchema, harnessV1BridgeHelloSchema, harnessV1BridgeInboundCommandSchemas, harnessV1BridgeOutboundMessageSchema, harnessV1BridgePermissionModeSchema, harnessV1BridgeReadySchema, harnessV1BridgeResponseFormatSchema, harnessV1BridgeResumeInboundSchema, harnessV1BridgeSandboxLogSchema, harnessV1BridgeStartBaseSchema, harnessV1BridgeStopInboundSchema, harnessV1BridgeStopSchema, harnessV1BridgeThreadSchema, harnessV1BridgeToolApprovalResponseInboundSchema, harnessV1BridgeToolResultInboundSchema, harnessV1BridgeToolWireSchema, harnessV1BridgeUserMessageInboundSchema, harnessV1DebugConfigSchema, harnessV1DebugLevelSchema, harnessV1DiagnosticFromBridgeFrame, harnessV1ErrorPartSchema, harnessV1FileChangePartSchema, harnessV1FinishPartSchema, harnessV1FinishStepPartSchema, harnessV1RawPartSchema, harnessV1ReasoningDeltaPartSchema, harnessV1ReasoningEndPartSchema, harnessV1ReasoningStartPartSchema, harnessV1StreamPartSchema, harnessV1StreamStartPartSchema, harnessV1TextDeltaPartSchema, harnessV1TextEndPartSchema, harnessV1TextStartPartSchema, harnessV1ToolApprovalRequestPartSchema, harnessV1ToolCallPartSchema, harnessV1ToolResultPartSchema, isHarnessV1BuiltinToolIncluded };
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -531,7 +531,13 @@ type WriteSkillsOptions = {
|
|
|
531
531
|
}) => string;
|
|
532
532
|
trailingNewline?: boolean;
|
|
533
533
|
};
|
|
534
|
-
|
|
534
|
+
type WriteSkillsResult = {
|
|
535
|
+
changed: boolean;
|
|
536
|
+
written: string[];
|
|
537
|
+
removed: string[];
|
|
538
|
+
unchanged: string[];
|
|
539
|
+
};
|
|
540
|
+
declare function writeSkills({ sandbox, rootDir, skills, abortSignal, skillNamePattern, invalidSkillNameMessage, filePathMode, invalidSkillFilePathMessage, trailingNewline, }: WriteSkillsOptions): Promise<WriteSkillsResult>;
|
|
535
541
|
|
|
536
542
|
type BridgeReadySource = 'stdout' | 'metadata';
|
|
537
543
|
type BridgeReadyErrorContext = {
|
|
@@ -601,4 +607,4 @@ declare function resolveSandboxDefaultWorkingDirectory({ sandboxSession, abortSi
|
|
|
601
607
|
|
|
602
608
|
declare function getRestrictedSandboxSession(sandboxSession: HarnessV1NetworkSandboxSession | Experimental_SandboxSession): Experimental_SandboxSession;
|
|
603
609
|
|
|
604
|
-
export { type BridgeReadyErrorContext, type BridgeReadySource, type DiskLogRecoveryMode, type Experimental_BridgeUserMessageRequest, type Experimental_BridgeUserMessageResponse, type Experimental_BridgeUserMessageSubmitter, SandboxChannel, type SandboxChannelDebugEvent, type SandboxChannelOptions, type SandboxChannelReconnectOptions, type SkillFilePathMode, type WaitForBridgeReadyOptions, type WaitForBridgeReadyResult, type WriteSkillsOptions, applyCredentialForwarding, classifyDiskLog, createBridgeErrorHandler, createBridgeStartupError, createCredentialRequestTransformation, createSandboxCredentialEnvironment, drainBridgeProcessStream, experimental_createBridgeUserMessageSubmitter, formatBridgeError, forwardBridgeProcessStream, generateSandboxCredentialPlaceholder, getAiGatewayAuthFromEnv, getRestrictedSandboxSession, isHarnessAuthenticationEnvironment, isSandboxCredentialPlaceholder, logBridgeError, markBridgeStarting, maskSandboxCredentials, resolveSandboxDefaultWorkingDirectory, resolveSandboxHomeDir, shellQuote, waitForBridgeReady, warnCredentialBrokeringUnavailable, writeSkills };
|
|
610
|
+
export { type BridgeReadyErrorContext, type BridgeReadySource, type DiskLogRecoveryMode, type Experimental_BridgeUserMessageRequest, type Experimental_BridgeUserMessageResponse, type Experimental_BridgeUserMessageSubmitter, SandboxChannel, type SandboxChannelDebugEvent, type SandboxChannelOptions, type SandboxChannelReconnectOptions, type SkillFilePathMode, type WaitForBridgeReadyOptions, type WaitForBridgeReadyResult, type WriteSkillsOptions, type WriteSkillsResult, applyCredentialForwarding, classifyDiskLog, createBridgeErrorHandler, createBridgeStartupError, createCredentialRequestTransformation, createSandboxCredentialEnvironment, drainBridgeProcessStream, experimental_createBridgeUserMessageSubmitter, formatBridgeError, forwardBridgeProcessStream, generateSandboxCredentialPlaceholder, getAiGatewayAuthFromEnv, getRestrictedSandboxSession, isHarnessAuthenticationEnvironment, isSandboxCredentialPlaceholder, logBridgeError, markBridgeStarting, maskSandboxCredentials, resolveSandboxDefaultWorkingDirectory, resolveSandboxHomeDir, shellQuote, waitForBridgeReady, warnCredentialBrokeringUnavailable, writeSkills };
|