@ai-sdk/harness-opencode 1.0.179 → 1.0.182

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 CHANGED
@@ -1,5 +1,31 @@
1
1
  # @ai-sdk/harness-opencode
2
2
 
3
+ ## 1.0.182
4
+
5
+ ### Patch Changes
6
+
7
+ - 0fc1f13: chore(harness): update harness adapter underlying SDKs to their latest releases
8
+ - c849d37: feat(harness): use public-key cryptography instead of token for sandbox bridge communication
9
+ - Updated dependencies [c849d37]
10
+ - Updated dependencies [7f1c01e]
11
+ - Updated dependencies [88b9575]
12
+ - @ai-sdk/harness@1.0.179
13
+ - @ai-sdk/provider-utils@5.0.78
14
+
15
+ ## 1.0.181
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies [9f37b45]
20
+ - @ai-sdk/provider-utils@5.0.77
21
+ - @ai-sdk/harness@1.0.178
22
+
23
+ ## 1.0.180
24
+
25
+ ### Patch Changes
26
+
27
+ - @ai-sdk/harness@1.0.177
28
+
3
29
  ## 1.0.179
4
30
 
5
31
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"host-tool-mcp.mjs","names":[],"sources":["../../../harness/dist/bridge/index.js","../../src/bridge/host-tool-schemas.ts","../../src/bridge/json-schema-to-zod.ts","../../src/bridge/host-tool-mcp.ts"],"sourcesContent":["import { appendFile, mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { env, pid, stdout } from \"node:process\";\nimport { WebSocketServer } from \"ws\";\n//#region src/bridge/harness-bridge-capability-unsupported-error.ts\nconst name = \"AI_HarnessBridgeCapabilityUnsupportedError\";\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*/\nvar HarnessBridgeCapabilityUnsupportedError = class extends Error {\n\tconstructor({ message, harnessId, cause }) {\n\t\tsuper(message);\n\t\tObject.defineProperty(this, \"name\", { value: name });\n\t\tthis.harnessId = harnessId;\n\t\tthis.cause = cause;\n\t}\n\tstatic isInstance(error) {\n\t\treturn error != null && typeof error === \"object\" && \"name\" in error && error.name === name && \"message\" in error && typeof error.message === \"string\";\n\t}\n};\n//#endregion\n//#region src/utils/convert-harness-tool-model-output.ts\nfunction getNormalizedInlineImage(part) {\n\tif (part.type === \"file\" && part.mediaType.startsWith(\"image/\") && part.mediaType !== \"image/*\" && part.data.type === \"data\" && typeof part.data.data === \"string\") return {\n\t\tdata: part.data.data,\n\t\tmediaType: part.mediaType\n\t};\n}\nfunction convertHarnessToolModelOutput({ output }) {\n\tswitch (output.type) {\n\t\tcase \"text\":\n\t\tcase \"error-text\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: output.value\n\t\t\t}],\n\t\t\tisError: output.type === \"error-text\"\n\t\t};\n\t\tcase \"json\":\n\t\tcase \"error-json\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: JSON.stringify(output.value)\n\t\t\t}],\n\t\t\tisError: output.type === \"error-json\"\n\t\t};\n\t\tcase \"execution-denied\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: output.reason ?? \"Tool execution denied.\"\n\t\t\t}],\n\t\t\tisError: true\n\t\t};\n\t\tcase \"content\": return {\n\t\t\tcontent: output.value.map((part) => {\n\t\t\t\tif (part.type === \"text\") return {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: part.text\n\t\t\t\t};\n\t\t\t\tconst image = getNormalizedInlineImage(part);\n\t\t\t\tif (image != null) return {\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t...image\n\t\t\t\t};\n\t\t\t\tthrow new HarnessBridgeCapabilityUnsupportedError({ message: `Harnesses support only text and inline images in tool model output; unsupported content '${part.type}'.` });\n\t\t\t}),\n\t\t\tisError: false\n\t\t};\n\t}\n}\n//#endregion\n//#region src/bridge/index.ts\nconst DEBUG_LEVEL_WEIGHT = {\n\terror: 0,\n\twarn: 1,\n\tinfo: 2,\n\tdebug: 3,\n\ttrace: 4\n};\n/** Exact-or-dotted-prefix subsystem match (`'bridge'` matches `'bridge.turn'`). */\nfunction subsystemMatches(filters, subsystem) {\n\tif (!filters || filters.length === 0) return true;\n\treturn filters.some((filter) => subsystem === filter || subsystem.startsWith(`${filter}.`));\n}\nfunction formatBridgeError(err) {\n\tif (err instanceof Error) return {\n\t\tname: err.name,\n\t\tmessage: err.message,\n\t\tstack: err.stack\n\t};\n\tif (typeof err === \"string\") return { message: err };\n\tif (err !== null && typeof err === \"object\") try {\n\t\treturn { message: JSON.stringify(err) };\n\t} catch {}\n\treturn { message: String(err) };\n}\nfunction createBridgeUserMessageQueue(options) {\n\tconst messages = [];\n\tconst waiters = [];\n\tconst entries = /* @__PURE__ */ new Map();\n\tlet closed = false;\n\tlet pendingCount = 0;\n\tconst enqueue = (input) => {\n\t\tconst existing = entries.get(input.messageId);\n\t\tif (existing != null) {\n\t\t\tif (existing.response != null) options.respond(existing.response);\n\t\t\treturn;\n\t\t}\n\t\tlet settled = false;\n\t\tconst settle = (response) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tpendingCount--;\n\t\t\tconst entry = entries.get(input.messageId);\n\t\t\tif (entry != null) entry.response = response;\n\t\t\toptions.respond(response);\n\t\t};\n\t\tconst message = {\n\t\t\tmessageId: input.messageId,\n\t\t\ttext: input.text,\n\t\t\taccept: () => {\n\t\t\t\tsettle({\n\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\tmessageId: input.messageId,\n\t\t\t\t\taccepted: true\n\t\t\t\t});\n\t\t\t},\n\t\t\treject: (error) => {\n\t\t\t\tsettle({\n\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\tmessageId: input.messageId,\n\t\t\t\t\taccepted: false,\n\t\t\t\t\terror: { message: formatBridgeError(error).message }\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\tentries.set(input.messageId, { reject: message.reject });\n\t\tpendingCount++;\n\t\tif (closed) {\n\t\t\tmessage.reject(/* @__PURE__ */ new Error(\"The bridge turn is no longer accepting user messages.\"));\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiters.shift();\n\t\tif (waiter != null) waiter({\n\t\t\tdone: false,\n\t\t\tvalue: message\n\t\t});\n\t\telse messages.push(message);\n\t};\n\tconst close = (error) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tconst reason = error ?? /* @__PURE__ */ new Error(\"The bridge turn ended before accepting the user message.\");\n\t\tfor (const entry of entries.values()) if (entry.response == null) entry.reject(reason);\n\t\tmessages.length = 0;\n\t\twhile (waiters.length > 0) waiters.shift()({\n\t\t\tdone: true,\n\t\t\tvalue: void 0\n\t\t});\n\t};\n\treturn {\n\t\tget pendingCount() {\n\t\t\treturn pendingCount;\n\t\t},\n\t\tenqueue,\n\t\tclose,\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn { next: () => {\n\t\t\t\tconst message = messages.shift();\n\t\t\t\tif (message != null) return Promise.resolve({\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue: message\n\t\t\t\t});\n\t\t\t\tif (closed) return Promise.resolve({\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t});\n\t\t\t\treturn new Promise((resolve) => {\n\t\t\t\t\twaiters.push(resolve);\n\t\t\t\t});\n\t\t\t} };\n\t\t}\n\t};\n}\nfunction parseEnvList(value) {\n\tif (!value) return void 0;\n\tconst items = value.split(\",\").map((item) => item.trim()).filter(Boolean);\n\treturn items.length > 0 ? items : void 0;\n}\nconst ENV_TRUTHY = /* @__PURE__ */ new Set([\n\t\"1\",\n\t\"true\",\n\t\"yes\",\n\t\"on\"\n]);\nconst WS_OPEN = 1;\nasync function runBridge(options) {\n\tconst { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;\n\tconst teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;\n\tconst hostDisconnectTimeoutMs = options.hostDisconnectTimeoutMs != null && Number.isFinite(options.hostDisconnectTimeoutMs) && options.hostDisconnectTimeoutMs > 0 ? Math.min(options.hostDisconnectTimeoutMs, 2147483647) : void 0;\n\tlet hostDisconnectTimer;\n\tconst clearHostDisconnectTimer = () => {\n\t\tclearTimeout(hostDisconnectTimer);\n\t\thostDisconnectTimer = void 0;\n\t};\n\tconst expectedToken = options.token ?? env.BRIDGE_CHANNEL_TOKEN ?? \"\";\n\tconst bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? \"0\", 10);\n\tconst bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;\n\tconst startConfigPath = `${bridgeStateDir}/start-config.json`;\n\tconst rerunStartConfigPath = `${bridgeStateDir}/rerun-start-config.json`;\n\tconst eventLogPath = `${bridgeStateDir}/event-log.ndjson`;\n\ttry {\n\t\tawait mkdir(bridgeStateDir, { recursive: true });\n\t} catch {}\n\tlet currentBoundPort = 0;\n\tlet currentTurnState = \"init\";\n\tlet activeSocket;\n\tlet isFirstTurn = true;\n\tlet turnAbort;\n\tlet currentUserMessages;\n\t/**\n\t* Settles when the in-flight turn has fully wound down — `onStart`\n\t* returned or threw AND its completion state was recorded. `undefined`\n\t* between turns. A new `start` fences on this so turns never overlap.\n\t*/\n\tlet activeTurn;\n\tlet lastStartId;\n\tlet debugConfig;\n\tlet consoleCaptureInstalled = false;\n\tconst envDebugEnabled = ENV_TRUTHY.has((env.HARNESS_DEBUG ?? \"\").toLowerCase());\n\tlet seqCounter = 0;\n\tlet eventLog = [];\n\tlet diskBuffer = \"\";\n\tlet flushPromise = null;\n\tconst flushEventsToDisk = async () => {\n\t\twhile (diskBuffer.length > 0) {\n\t\t\tconst buf = diskBuffer;\n\t\t\tdiskBuffer = \"\";\n\t\t\tawait appendFile(eventLogPath, buf).catch(() => {});\n\t\t}\n\t};\n\tconst scheduleEventFlush = () => {\n\t\tif (flushPromise) return;\n\t\tflushPromise = new Promise((resolve) => {\n\t\t\tsetImmediate(() => {\n\t\t\t\tflushEventsToDisk().finally(resolve);\n\t\t\t});\n\t\t}).finally(() => {\n\t\t\tflushPromise = null;\n\t\t\tif (diskBuffer.length > 0) scheduleEventFlush();\n\t\t});\n\t};\n\tconst flushPendingEventsToDisk = async () => {\n\t\tif (diskBuffer.length > 0 && !flushPromise) scheduleEventFlush();\n\t\tlet inFlight = flushPromise;\n\t\twhile (inFlight) {\n\t\t\tawait inFlight;\n\t\t\tinFlight = flushPromise;\n\t\t}\n\t};\n\tif (env.BRIDGE_REPLAY_FROM_DISK === \"1\" && existsSync(eventLogPath)) try {\n\t\teventLog = readFileSync(eventLogPath, \"utf8\").split(\"\\n\").map((line) => line.trim()).filter(Boolean).map((line) => ({\n\t\t\tseq: JSON.parse(line).seq,\n\t\t\tline\n\t\t}));\n\t\tseqCounter = eventLog.at(-1)?.seq ?? 0;\n\t} catch {\n\t\teventLog = [];\n\t\tseqCounter = 0;\n\t}\n\tconst pendingToolResults = /* @__PURE__ */ new Map();\n\tconst bufferedToolResults = [];\n\tconst pendingToolApprovals = /* @__PURE__ */ new Map();\n\tconst writeBridgeMeta = async (state) => {\n\t\ttry {\n\t\t\tawait writeFile(bridgeMetaPath, JSON.stringify({\n\t\t\t\ttype: bridgeType,\n\t\t\t\tport: currentBoundPort,\n\t\t\t\tstate,\n\t\t\t\tpid\n\t\t\t}));\n\t\t} catch {}\n\t};\n\tconst writeStartConfig = async (start) => {\n\t\ttry {\n\t\t\tconst serialized = JSON.stringify(start);\n\t\t\tawait writeFile(startConfigPath, serialized);\n\t\t\tif (!existsSync(rerunStartConfigPath)) await writeFile(rerunStartConfigPath, serialized);\n\t\t} catch {}\n\t};\n\tconst emit = (event) => {\n\t\tconst seq = ++seqCounter;\n\t\tconst line = JSON.stringify({\n\t\t\t...event,\n\t\t\tseq\n\t\t});\n\t\teventLog.push({\n\t\t\tseq,\n\t\t\tline\n\t\t});\n\t\tdiskBuffer += `${line}\\n`;\n\t\tscheduleEventFlush();\n\t\tif (activeSocket?.readyState === WS_OPEN) try {\n\t\t\tactiveSocket.send(line);\n\t\t} catch {}\n\t};\n\tconst replay = (ws, afterSeq) => {\n\t\tfor (const entry of eventLog) if (entry.seq > afterSeq && ws.readyState === WS_OPEN) ws.send(entry.line);\n\t};\n\tconst shouldEmitDebugEvent = (level, subsystem) => {\n\t\tif (!debugConfig?.enabled) return false;\n\t\tconst threshold = debugConfig.level ?? \"debug\";\n\t\tif (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;\n\t\treturn subsystemMatches(debugConfig.subsystems, subsystem);\n\t};\n\tconst rawStdoutWrite = process.stdout.write.bind(process.stdout);\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr);\n\tconst writeErrorToStderr = (input) => {\n\t\ttry {\n\t\t\tconst formatted = formatBridgeError(input.error);\n\t\t\trawStderrWrite(`[harness:${bridgeType}:error] ${input.message}: ${formatted.message}\\n`);\n\t\t\tif (formatted.stack) rawStderrWrite(`${formatted.stack}\\n`);\n\t\t} catch {}\n\t};\n\tconst emitWarning = (input) => {\n\t\ttry {\n\t\t\tfor (const line of input.message.split(\"\\n\")) if (line.trim().length > 0) rawStderrWrite(`[harness:${bridgeType}:warn] ${line}\\n`);\n\t\t} catch {}\n\t};\n\tconst emitError = (input) => {\n\t\twriteErrorToStderr({\n\t\t\tmessage: input.message ?? \"bridge error\",\n\t\t\terror: input.error\n\t\t});\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\terror: serialiseError(input.error)\n\t\t});\n\t};\n\tconst installConsoleCapture = () => {\n\t\tif (consoleCaptureInstalled) return;\n\t\tconsoleCaptureInstalled = true;\n\t\tconst buffers = {\n\t\t\tstdout: \"\",\n\t\t\tstderr: \"\"\n\t\t};\n\t\tconst patch = (stream, raw) => (chunk, encoding, cb) => {\n\t\t\tif (debugConfig?.enabled) try {\n\t\t\t\tconst enc = typeof encoding === \"string\" ? encoding : \"utf8\";\n\t\t\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString(enc);\n\t\t\t\tconst parts = (buffers[stream] + text.replace(/\\r\\n/g, \"\\n\")).split(\"\\n\");\n\t\t\t\tbuffers[stream] = parts.pop() ?? \"\";\n\t\t\t\tfor (const line of parts) {\n\t\t\t\t\tconst trimmed = line.replace(/\\s+$/, \"\");\n\t\t\t\t\tif (trimmed) emit({\n\t\t\t\t\t\ttype: \"sandbox-log\",\n\t\t\t\t\t\tsource: bridgeType,\n\t\t\t\t\t\tstream,\n\t\t\t\t\t\tline: trimmed\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\treturn raw(chunk, encoding, cb);\n\t\t};\n\t\tprocess.stdout.write = patch(\"stdout\", rawStdoutWrite);\n\t\tprocess.stderr.write = patch(\"stderr\", rawStderrWrite);\n\t};\n\tconst handleInbound = async (msg, ws) => {\n\t\tswitch (msg.type) {\n\t\t\tcase \"start\": {\n\t\t\t\tconst startId = msg.startId;\n\t\t\t\tif (startId != null) {\n\t\t\t\t\tif (startId === lastStartId) return;\n\t\t\t\t\tlastStartId = startId;\n\t\t\t\t}\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst pendingTurn = activeTurn;\n\t\t\t\t\tif (pendingTurn == null) break;\n\t\t\t\t\tturnAbort?.abort();\n\t\t\t\t\tcurrentUserMessages?.close(/* @__PURE__ */ new Error(\"A new bridge turn replaced the active turn.\"));\n\t\t\t\t\tlet graceTimer;\n\t\t\t\t\tconst settled = await Promise.race([pendingTurn.then(() => true), new Promise((resolve) => {\n\t\t\t\t\t\tgraceTimer = setTimeout(() => resolve(false), teardownGraceMs);\n\t\t\t\t\t\tgraceTimer.unref?.();\n\t\t\t\t\t})]);\n\t\t\t\t\tclearTimeout(graceTimer);\n\t\t\t\t\tif (!settled) break;\n\t\t\t\t}\n\t\t\t\tlet turnFinished;\n\t\t\t\tconst thisTurn = new Promise((resolve) => turnFinished = resolve);\n\t\t\t\tactiveTurn = thisTurn;\n\t\t\t\tactiveSocket = ws;\n\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\tconst firstTurn = isFirstTurn;\n\t\t\t\tisFirstTurn = false;\n\t\t\t\teventLog = [];\n\t\t\t\tdiskBuffer = \"\";\n\t\t\t\twriteFile(eventLogPath, \"\").catch(() => {});\n\t\t\t\tturnAbort = new AbortController();\n\t\t\t\tcurrentTurnState = \"running\";\n\t\t\t\twriteStartConfig(msg);\n\t\t\t\twriteBridgeMeta(\"running\");\n\t\t\t\tconst startDebug = msg.debug;\n\t\t\t\tdebugConfig = {\n\t\t\t\t\tenabled: startDebug?.enabled ?? envDebugEnabled,\n\t\t\t\t\tlevel: startDebug?.level ?? env.HARNESS_DEBUG_LEVEL,\n\t\t\t\t\tsubsystems: startDebug?.subsystems ?? parseEnvList(env.HARNESS_DEBUG_SUBSYSTEMS)\n\t\t\t\t};\n\t\t\t\tif (debugConfig.enabled) installConsoleCapture();\n\t\t\t\tconst userMessages = createBridgeUserMessageQueue({ respond: emit });\n\t\t\t\tconst turn = {\n\t\t\t\t\temit,\n\t\t\t\t\trequestToolResult: (requestInput) => {\n\t\t\t\t\t\tconst request = typeof requestInput === \"string\" ? { toolCallId: requestInput } : requestInput;\n\t\t\t\t\t\tconst bufferedIndex = bufferedToolResults.findIndex((buffered) => buffered.toolCallId === request.toolCallId || request.matches?.(buffered.result) === true);\n\t\t\t\t\t\tif (bufferedIndex >= 0) return Promise.resolve(bufferedToolResults.splice(bufferedIndex, 1)[0].result);\n\t\t\t\t\t\treturn new Promise((resolve) => {\n\t\t\t\t\t\t\tpendingToolResults.set(request.toolCallId, {\n\t\t\t\t\t\t\t\tresolve,\n\t\t\t\t\t\t\t\tmatches: request.matches\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\trequestToolApproval: (approvalId) => new Promise((resolve) => {\n\t\t\t\t\t\tpendingToolApprovals.set(approvalId, resolve);\n\t\t\t\t\t}),\n\t\t\t\t\texperimental_userMessages: userMessages,\n\t\t\t\t\tabortSignal: turnAbort.signal,\n\t\t\t\t\tfirstTurn,\n\t\t\t\t\tbridgeLog: (input) => {\n\t\t\t\t\t\tconst level = input.level ?? \"debug\";\n\t\t\t\t\t\tif (!shouldEmitDebugEvent(level, input.subsystem)) return;\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"debug-event\",\n\t\t\t\t\t\t\tlevel,\n\t\t\t\t\t\t\tsubsystem: input.subsystem,\n\t\t\t\t\t\t\tmessage: input.message,\n\t\t\t\t\t\t\t...input.attrs ? { attrs: input.attrs } : {},\n\t\t\t\t\t\t\t...input.error !== void 0 ? { error: formatBridgeError(input.error) } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\temitWarning,\n\t\t\t\t\temitError\n\t\t\t\t};\n\t\t\t\tcurrentUserMessages = userMessages;\n\t\t\t\ttry {\n\t\t\t\t\tawait onStart(msg, turn);\n\t\t\t\t} catch (err) {\n\t\t\t\t\temitError({\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t\tmessage: \"bridge turn failed\"\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tuserMessages.close();\n\t\t\t\t\tif (currentUserMessages === userMessages) currentUserMessages = void 0;\n\t\t\t\t\tif (activeTurn === thisTurn) {\n\t\t\t\t\t\tactiveTurn = void 0;\n\t\t\t\t\t\tcurrentTurnState = \"waiting\";\n\t\t\t\t\t\twriteBridgeMeta(\"waiting\");\n\t\t\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\t\t}\n\t\t\t\t\tturnFinished();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst result = {\n\t\t\t\t\toutput: msg.output,\n\t\t\t\t\tisError: msg.isError,\n\t\t\t\t\ttoolResult: msg.toolResult\n\t\t\t\t};\n\t\t\t\tconst exactPending = pendingToolResults.get(msg.toolCallId);\n\t\t\t\tconst matchingPending = exactPending == null ? Array.from(pendingToolResults.entries()).find(([, pending]) => pending.matches?.(result) === true) : void 0;\n\t\t\t\tconst pending = exactPending ?? matchingPending?.[1];\n\t\t\t\tconst pendingId = exactPending != null ? msg.toolCallId : matchingPending?.[0];\n\t\t\t\tif (pending != null && pendingId != null) {\n\t\t\t\t\tpendingToolResults.delete(pendingId);\n\t\t\t\t\tpending.resolve(result);\n\t\t\t\t} else bufferedToolResults.push({\n\t\t\t\t\ttoolCallId: msg.toolCallId,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-approval-response\": {\n\t\t\t\tconst resolver = pendingToolApprovals.get(msg.approvalId);\n\t\t\t\tif (resolver) {\n\t\t\t\t\tpendingToolApprovals.delete(msg.approvalId);\n\t\t\t\t\tresolver({\n\t\t\t\t\t\tapproved: msg.approved,\n\t\t\t\t\t\treason: msg.reason\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"user-message\": {\n\t\t\t\tconst messageId = msg.messageId ?? randomUUID();\n\t\t\t\tif (currentUserMessages == null) {\n\t\t\t\t\tsendControl(ws, {\n\t\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\taccepted: false,\n\t\t\t\t\t\terror: { message: \"The bridge has no active turn to steer.\" }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (ws !== activeSocket) {\n\t\t\t\t\tsendControl(ws, {\n\t\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\taccepted: false,\n\t\t\t\t\t\terror: { message: \"The connection does not own the active bridge turn.\" }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcurrentUserMessages.enqueue({\n\t\t\t\t\tmessageId,\n\t\t\t\t\ttext: msg.text\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"abort\":\n\t\t\t\tturnAbort?.abort();\n\t\t\t\treturn;\n\t\t\tcase \"resume\":\n\t\t\t\tactiveSocket = ws;\n\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\treplay(ws, msg.lastSeenEventId);\n\t\t\t\treturn;\n\t\t\tcase \"destroy\":\n\t\t\t\tcurrentTurnState = \"done\";\n\t\t\t\twriteBridgeMeta(\"done\");\n\t\t\t\tawait onDestroy?.();\n\t\t\t\tdrainThenExit(ws, 1e3, \"destroy\");\n\t\t\t\treturn;\n\t\t\tcase \"stop\":\n\t\t\t\tcurrentTurnState = \"done\";\n\t\t\t\twriteBridgeMeta(\"done\");\n\t\t\t\tsendControl(ws, {\n\t\t\t\t\ttype: \"bridge-stop\",\n\t\t\t\t\tdata: await onStop?.() ?? {}\n\t\t\t\t});\n\t\t\t\tdrainThenExit(ws, 1e3, \"stop\");\n\t\t}\n\t};\n\twriteBridgeMeta(\"init\");\n\tconst wss = new WebSocketServer({\n\t\tport: bridgeWsPort,\n\t\thost: \"0.0.0.0\"\n\t});\n\tconst exit = () => {\n\t\tif (options.onExit) {\n\t\t\toptions.onExit();\n\t\t\treturn;\n\t\t}\n\t\twss.close(() => process.exit(0));\n\t\tsetTimeout(() => process.exit(0), 1e3).unref();\n\t};\n\tconst drainThenExit = (ws, code, reason) => {\n\t\tconst start = Date.now();\n\t\tconst tick = () => {\n\t\t\tif (ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN || Date.now() - start >= 5e3) {\n\t\t\t\tflushPendingEventsToDisk().finally(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tws.close(code, reason);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\texit();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetTimeout(tick, 10).unref();\n\t\t};\n\t\ttick();\n\t};\n\twss.on(\"listening\", () => {\n\t\tconst addr = wss.address();\n\t\tcurrentBoundPort = typeof addr === \"object\" && addr ? addr.port : 0;\n\t\tcurrentTurnState = \"waiting\";\n\t\twriteBridgeMeta(\"waiting\");\n\t\tstdout.write(JSON.stringify({\n\t\t\ttype: \"bridge-ready\",\n\t\t\tport: currentBoundPort\n\t\t}) + \"\\n\");\n\t\toptions.onListening?.(currentBoundPort);\n\t});\n\twss.on(\"connection\", (ws, req) => {\n\t\tif (new URL(req.url ?? \"/\", \"http://localhost\").searchParams.get(\"agent_bridge_token\") !== expectedToken) {\n\t\t\tws.close(1008, \"unauthorized\");\n\t\t\treturn;\n\t\t}\n\t\tsendControl(ws, {\n\t\t\ttype: \"bridge-hello\",\n\t\t\tstate: currentTurnState,\n\t\t\tlastSeq: seqCounter,\n\t\t\tcapabilities: {\n\t\t\t\tidempotentStart: true,\n\t\t\t\texperimental_userMessageResponses: true\n\t\t\t}\n\t\t});\n\t\tws.on(\"message\", (raw) => {\n\t\t\tlet parsed;\n\t\t\ttry {\n\t\t\t\tconst text = typeof raw === \"string\" ? raw : Buffer.from(raw).toString(\"utf8\");\n\t\t\t\tparsed = JSON.parse(text);\n\t\t\t} catch (err) {\n\t\t\t\tsendControl(ws, {\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror: `protocol parse error: ${err.message}`\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thandleInbound(parsed, ws);\n\t\t});\n\t\tws.on(\"close\", (_code, reason) => {\n\t\t\tif (activeSocket === ws) {\n\t\t\t\tactiveSocket = void 0;\n\t\t\t\tif (hostDisconnectTimeoutMs != null && activeTurn != null && reason.toString() !== \"suspended\") {\n\t\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\t\thostDisconnectTimer = setTimeout(() => {\n\t\t\t\t\t\thostDisconnectTimer = void 0;\n\t\t\t\t\t\tif (activeSocket == null) turnAbort?.abort();\n\t\t\t\t\t}, hostDisconnectTimeoutMs);\n\t\t\t\t\thostDisconnectTimer.unref?.();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", () => {});\n\t});\n\tprocess.on(\"uncaughtException\", (err) => {\n\t\temitError({\n\t\t\terror: err,\n\t\t\tmessage: \"uncaught exception\"\n\t\t});\n\t});\n\tprocess.on(\"unhandledRejection\", (err) => {\n\t\temitError({\n\t\t\terror: err,\n\t\t\tmessage: \"unhandled rejection\"\n\t\t});\n\t});\n\tawait new Promise((resolve, reject) => {\n\t\tif (wss.address() != null) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\twss.once(\"listening\", resolve);\n\t\twss.once(\"error\", reject);\n\t});\n\treturn {\n\t\tport: currentBoundPort,\n\t\tclose: () => new Promise((resolve) => {\n\t\t\twss.close(() => resolve());\n\t\t})\n\t};\n}\nfunction sendControl(socket, message) {\n\tif (socket?.readyState === WS_OPEN) try {\n\t\tsocket.send(JSON.stringify(message));\n\t} catch {}\n}\nfunction serialiseError(err) {\n\tif (err instanceof Error) return {\n\t\tname: err.name,\n\t\tmessage: err.message,\n\t\tstack: err.stack\n\t};\n\treturn err;\n}\n//#endregion\nexport { HarnessBridgeCapabilityUnsupportedError, convertHarnessToolModelOutput, runBridge };\n\n//# sourceMappingURL=index.js.map","import { readFileSync } from 'node:fs';\n\nexport type HostToolSchema = {\n name: string;\n description?: string;\n inputSchema?: unknown;\n};\n\nexport function readHostToolSchemasFromEnvironment(\n environment: NodeJS.ProcessEnv,\n): HostToolSchema[] {\n const serializedSchemas = environment.TOOL_SCHEMAS_PATH\n ? readFileSync(environment.TOOL_SCHEMAS_PATH, 'utf8')\n : (environment.TOOL_SCHEMAS ?? '[]');\n\n return JSON.parse(serializedSchemas) as HostToolSchema[];\n}\n","import { z } from 'zod/v4';\n\ntype JsonLiteral = string | number | boolean | null;\n\ntype JsonSchemaObject = {\n type?: string | string[];\n description?: string;\n properties?: Record<string, JsonSchemaObject>;\n required?: string[];\n items?: JsonSchemaObject;\n enum?: unknown[];\n default?: unknown;\n nullable?: boolean;\n};\n\ntype ZodShape = Record<string, z.ZodTypeAny>;\n\nexport function jsonSchemaToZodShape(input: unknown): ZodShape {\n const schema = isJsonSchemaObject(input) ? input : {};\n return toZodShape(schema);\n}\n\nfunction toZodShape(schema: JsonSchemaObject | undefined): ZodShape {\n if (!schema?.properties) return {};\n const required = new Set(schema.required);\n const shape: ZodShape = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const propType = toZodType(propSchema);\n shape[key] = required.has(key) ? propType : propType.optional();\n }\n return shape;\n}\n\nfunction toZodType(schema: JsonSchemaObject | undefined): z.ZodTypeAny {\n if (!schema) return z.any();\n\n let zType = zodForEnum(schema) ?? zodForType(schema);\n if (schema.description) zType = zType.describe(schema.description);\n if (schema.nullable) zType = zType.nullable();\n if ('default' in schema) zType = zType.meta({ default: schema.default });\n return zType;\n}\n\nfunction zodForEnum(schema: JsonSchemaObject): z.ZodTypeAny | undefined {\n if (\n !Array.isArray(schema.enum) ||\n schema.enum.length === 0 ||\n !schema.enum.every(isJsonLiteral)\n ) {\n return undefined;\n }\n return z.literal(schema.enum);\n}\n\nfunction zodForType(schema: JsonSchemaObject): z.ZodTypeAny {\n const types = Array.isArray(schema.type)\n ? schema.type.filter((t): t is string => t !== 'null')\n : ([schema.type].filter(Boolean) as string[]);\n\n switch (types[0]) {\n case 'string':\n return z.string();\n case 'number':\n return z.number();\n case 'integer':\n return z.number().int();\n case 'boolean':\n return z.boolean();\n case 'array':\n return z.array(toZodType(schema.items));\n case 'object':\n return z.object(toZodShape(schema));\n case 'null':\n return z.null();\n default:\n return z.any();\n }\n}\n\nfunction isJsonSchemaObject(input: unknown): input is JsonSchemaObject {\n return input != null && typeof input === 'object' && !Array.isArray(input);\n}\n\nfunction isJsonLiteral(value: unknown): value is JsonLiteral {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n (typeof value === 'number' && Number.isFinite(value))\n );\n}\n","#!/usr/bin/env node\n/*\n * These bridge imports are externalized by tsdown and resolved inside the\n * sandbox from src/bridge/package.json and its lockfile. Keep this file,\n * tsdown.config.ts, and the bridge package dependency list in sync.\n */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n convertHarnessToolModelOutput,\n type BridgeTurn,\n} from '@ai-sdk/harness/bridge';\nimport { readHostToolSchemasFromEnvironment } from './host-tool-schemas';\nimport { jsonSchemaToZodShape } from './json-schema-to-zod';\n\nconst schemas = readHostToolSchemasFromEnvironment(process.env);\nconst relayUrl = process.env.TOOL_RELAY_URL || '';\n\nif (!schemas.length || !relayUrl) {\n process.stderr.write(\n '[host-tool-mcp] Missing TOOL_SCHEMAS_PATH/TOOL_SCHEMAS or TOOL_RELAY_URL; exiting\\n',\n );\n process.exit(0);\n}\n\nconst server = new McpServer({ name: 'harness-tools', version: '1.0.0' });\n\nfor (const schema of schemas) {\n const shape = jsonSchemaToZodShape(schema.inputSchema);\n server.tool(\n schema.name,\n schema.description ?? '',\n shape,\n async (input: Record<string, unknown>) => {\n const requestId = crypto.randomUUID();\n try {\n const res = await fetch(relayUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ requestId, toolName: schema.name, input }),\n });\n if (!res.ok) {\n const body = await res.text();\n throw new Error(\n `Tool relay ${schema.name} failed with ${res.status}: ${body.slice(0, 500)}`,\n );\n }\n const data = (await res.json()) as {\n result?: unknown;\n isError?: boolean;\n toolResult?: Awaited<\n ReturnType<BridgeTurn['requestToolResult']>\n >['toolResult'];\n };\n if (data.toolResult != null) {\n const converted = convertHarnessToolModelOutput({\n output: data.toolResult.output,\n });\n return {\n content: converted.content.map(part =>\n part.type === 'text'\n ? part\n : {\n type: 'image' as const,\n data: part.data,\n mimeType: part.mediaType,\n },\n ),\n isError: data.isError === true || converted.isError,\n };\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(data.result ?? null),\n },\n ],\n ...(data.isError === true ? { isError: true } : {}),\n };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Error: ${String(err)}` }],\n isError: true,\n };\n }\n },\n );\n}\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n"],"mappings":";;;;;;;AAMA,MAAM,OAAO;;;;;;AAMb,IAAI,0CAA0C,cAAc,MAAM;CACjE,YAAY,EAAE,SAAS,WAAW,SAAS;EAC1C,MAAM,OAAO;EACb,OAAO,eAAe,MAAM,QAAQ,EAAE,OAAO,KAAK,CAAC;EACnD,KAAK,YAAY;EACjB,KAAK,QAAQ;CACd;CACA,OAAO,WAAW,OAAO;EACxB,OAAO,SAAS,QAAQ,OAAO,UAAU,YAAY,UAAU,SAAS,MAAM,SAAS,QAAQ,aAAa,SAAS,OAAO,MAAM,YAAY;CAC/I;AACD;AAGA,SAAS,yBAAyB,MAAM;CACvC,IAAI,KAAK,SAAS,UAAU,KAAK,UAAU,WAAW,QAAQ,KAAK,KAAK,cAAc,aAAa,KAAK,KAAK,SAAS,UAAU,OAAO,KAAK,KAAK,SAAS,UAAU,OAAO;EAC1K,MAAM,KAAK,KAAK;EAChB,WAAW,KAAK;CACjB;AACD;AACA,SAAS,8BAA8B,EAAE,UAAU;CAClD,QAAQ,OAAO,MAAf;EACC,KAAK;EACL,KAAK,cAAc,OAAO;GACzB,SAAS,CAAC;IACT,MAAM;IACN,MAAM,OAAO;GACd,CAAC;GACD,SAAS,OAAO,SAAS;EAC1B;EACA,KAAK;EACL,KAAK,cAAc,OAAO;GACzB,SAAS,CAAC;IACT,MAAM;IACN,MAAM,KAAK,UAAU,OAAO,KAAK;GAClC,CAAC;GACD,SAAS,OAAO,SAAS;EAC1B;EACA,KAAK,oBAAoB,OAAO;GAC/B,SAAS,CAAC;IACT,MAAM;IACN,MAAM,OAAO,UAAU;GACxB,CAAC;GACD,SAAS;EACV;EACA,KAAK,WAAW,OAAO;GACtB,SAAS,OAAO,MAAM,KAAK,SAAS;IACnC,IAAI,KAAK,SAAS,QAA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O,WAAW;EACpC,IAAI;GACF,MAAM,MAAM,MAAM,MAAM,UAAU;IAChC,QAAQ;IACR,SAAS,EACP,gBAAgB,mBAClB;IACA,MAAM,KAAK,UAAU;KAAE;KAAW,UAAU,OAAO;KAAM;IAAM,CAAC;GAClE,CAAC;GACD,IAAI,CAAC,IAAI,IAAI;IACX,MAAM,OAAO,MAAM,IAAI,KAAK;IAC5B,MAAM,IAAI,MACR,cAAc,OAAO,KAAK,eAAe,IAAI,OAAO,IAAI,KAAK,MAAM,GAAG,GAAG,GAC3E;GACF;GACA,MAAM,OAAQ,MAAM,IAAI,KAAK;GAO7B,IAAI,KAAK,cAAc,MAAM;IAC3B,MAAM,YAAY,8BAA8B,EAC9C,QAAQ,KAAK,WAAW,OAC1B,CAAC;IACD,OAAO;KACL,SAAS,UAAU,QAAQ,KAAI,SAC7B,KAAK,SAAS,SACV,OACA;MACE,MAAM;MACN,MAAM,KAAK;MACX,UAAU,KAAK;KACjB,CACN;KACA,SAAS,KAAK,YAAY,QAAQ,UAAU;IAC9C;GACF;GACA,OAAO;IACL,SAAS,CACP;KACE,MAAM;KACN,MAAM,KAAK,UAAU,KAAK,UAAU,IAAI;IAC1C,CACF;IACA,GAAI,KAAK,YAAY,OAAO,EAAE,SAAS,KAAK,IAAI,CAAC;GACnD;EACF,SAAS,KAAK;GACZ,OAAO;IACL,SAAS,CAAC;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO,GAAG;IAAI,CAAC;IAClE,SAAS;GACX;EACF;CACF,CACF;AACF;AAEA,MAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS"}
1
+ {"version":3,"file":"host-tool-mcp.mjs","names":[],"sources":["../../../harness/dist/bridge/index.js","../../src/bridge/host-tool-schemas.ts","../../src/bridge/json-schema-to-zod.ts","../../src/bridge/host-tool-mcp.ts"],"sourcesContent":["import { appendFile, mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createPublicKey, randomBytes, randomUUID, verify } from \"node:crypto\";\nimport { env, pid, stdout } from \"node:process\";\nimport { WebSocketServer } from \"ws\";\nimport { Buffer as Buffer$1 } from \"node:buffer\";\nconst BRIDGE_AUTH_TIMEOUT_MS = 1e4;\nconst BRIDGE_AUTH_MESSAGE_PREFIX = \"ai-sdk-harness-bridge-auth-v1\\0\";\nconst PROOF_FRAME_REGEXP = /^\\{\"type\":\"bridge-auth-proof\",\"signature\":\"([A-Za-z0-9_-]{86})\"\\}$/;\nfunction createBridgeAuthMessage({ challenge }) {\n\treturn Buffer$1.from(`${BRIDGE_AUTH_MESSAGE_PREFIX}${challenge}`, \"utf8\");\n}\nfunction serializeBridgeAuthChallengeFrame({ challenge }) {\n\treturn JSON.stringify({\n\t\ttype: \"bridge-auth-challenge\",\n\t\tchallenge\n\t});\n}\nfunction parseBridgeAuthProofFrame({ text }) {\n\treturn PROOF_FRAME_REGEXP.exec(text)?.[1];\n}\n//#endregion\n//#region src/bridge/bridge-auth.ts\nconst PUBLIC_KEY_REGEXP = /^[A-Za-z0-9_-]{43}$/;\nconst UNAUTHORIZED_CLOSE_CODE = 1008;\nconst INVALID_PUBLIC_KEY_MESSAGE = \"The bridge requires a valid Ed25519 public key for authentication.\";\nfunction parseBridgeAuthPublicKey({ publicKey }) {\n\tif (publicKey == null || !PUBLIC_KEY_REGEXP.test(publicKey)) throw new Error(INVALID_PUBLIC_KEY_MESSAGE);\n\tlet key;\n\ttry {\n\t\tkey = createPublicKey({\n\t\t\tkey: {\n\t\t\t\tkty: \"OKP\",\n\t\t\t\tcrv: \"Ed25519\",\n\t\t\t\tx: publicKey\n\t\t\t},\n\t\t\tformat: \"jwk\"\n\t\t});\n\t} catch {\n\t\tthrow new Error(INVALID_PUBLIC_KEY_MESSAGE);\n\t}\n\tif (key.asymmetricKeyType !== \"ed25519\") throw new Error(INVALID_PUBLIC_KEY_MESSAGE);\n\treturn key;\n}\nfunction authenticateBridgeConnection({ ws, publicKey, timeoutMs = BRIDGE_AUTH_TIMEOUT_MS, onAuthenticated }) {\n\tconst challenge = randomBytes(32).toString(\"hex\");\n\tconst timeout = setTimeout(() => ws.terminate(), timeoutMs);\n\ttimeout.unref?.();\n\tconst onError = () => {};\n\tws.on(\"error\", onError);\n\tws.once(\"close\", () => clearTimeout(timeout));\n\tws.once(\"message\", (raw, isBinary) => {\n\t\tclearTimeout(timeout);\n\t\tconst text = isBinary ? void 0 : rawDataToString(raw);\n\t\tconst signature = text == null ? void 0 : parseBridgeAuthProofFrame({ text });\n\t\tif (signature == null || !verify(null, createBridgeAuthMessage({ challenge }), publicKey, Buffer$1.from(signature, \"base64url\"))) {\n\t\t\tws.close(UNAUTHORIZED_CLOSE_CODE, \"unauthorized\");\n\t\t\treturn;\n\t\t}\n\t\tws.off(\"error\", onError);\n\t\tonAuthenticated();\n\t});\n\tws.send(serializeBridgeAuthChallengeFrame({ challenge }));\n}\nfunction rawDataToString(raw) {\n\tconst buffer = Array.isArray(raw) ? Buffer$1.concat(raw) : Buffer$1.isBuffer(raw) ? raw : Buffer$1.from(raw);\n\tif (buffer.byteLength > 1024) return void 0;\n\treturn buffer.toString(\"utf8\");\n}\n//#endregion\n//#region src/bridge/harness-bridge-capability-unsupported-error.ts\nconst name = \"AI_HarnessBridgeCapabilityUnsupportedError\";\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*/\nvar HarnessBridgeCapabilityUnsupportedError = class extends Error {\n\tconstructor({ message, harnessId, cause }) {\n\t\tsuper(message);\n\t\tObject.defineProperty(this, \"name\", { value: name });\n\t\tthis.harnessId = harnessId;\n\t\tthis.cause = cause;\n\t}\n\tstatic isInstance(error) {\n\t\treturn error != null && typeof error === \"object\" && \"name\" in error && error.name === name && \"message\" in error && typeof error.message === \"string\";\n\t}\n};\n//#endregion\n//#region src/utils/convert-harness-tool-model-output.ts\nfunction getNormalizedInlineImage(part) {\n\tif (part.type === \"file\" && part.mediaType.startsWith(\"image/\") && part.mediaType !== \"image/*\" && part.data.type === \"data\" && typeof part.data.data === \"string\") return {\n\t\tdata: part.data.data,\n\t\tmediaType: part.mediaType\n\t};\n}\nfunction convertHarnessToolModelOutput({ output }) {\n\tswitch (output.type) {\n\t\tcase \"text\":\n\t\tcase \"error-text\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: output.value\n\t\t\t}],\n\t\t\tisError: output.type === \"error-text\"\n\t\t};\n\t\tcase \"json\":\n\t\tcase \"error-json\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: JSON.stringify(output.value)\n\t\t\t}],\n\t\t\tisError: output.type === \"error-json\"\n\t\t};\n\t\tcase \"execution-denied\": return {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: output.reason ?? \"Tool execution denied.\"\n\t\t\t}],\n\t\t\tisError: true\n\t\t};\n\t\tcase \"content\": return {\n\t\t\tcontent: output.value.map((part) => {\n\t\t\t\tif (part.type === \"text\") return {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: part.text\n\t\t\t\t};\n\t\t\t\tconst image = getNormalizedInlineImage(part);\n\t\t\t\tif (image != null) return {\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t...image\n\t\t\t\t};\n\t\t\t\tthrow new HarnessBridgeCapabilityUnsupportedError({ message: `Harnesses support only text and inline images in tool model output; unsupported content '${part.type}'.` });\n\t\t\t}),\n\t\t\tisError: false\n\t\t};\n\t}\n}\n//#endregion\n//#region src/bridge/index.ts\nconst DEBUG_LEVEL_WEIGHT = {\n\terror: 0,\n\twarn: 1,\n\tinfo: 2,\n\tdebug: 3,\n\ttrace: 4\n};\n/** Exact-or-dotted-prefix subsystem match (`'bridge'` matches `'bridge.turn'`). */\nfunction subsystemMatches(filters, subsystem) {\n\tif (!filters || filters.length === 0) return true;\n\treturn filters.some((filter) => subsystem === filter || subsystem.startsWith(`${filter}.`));\n}\nfunction formatBridgeError(err) {\n\tif (err instanceof Error) return {\n\t\tname: err.name,\n\t\tmessage: err.message,\n\t\tstack: err.stack\n\t};\n\tif (typeof err === \"string\") return { message: err };\n\tif (err !== null && typeof err === \"object\") try {\n\t\treturn { message: JSON.stringify(err) };\n\t} catch {}\n\treturn { message: String(err) };\n}\nfunction createBridgeUserMessageQueue(options) {\n\tconst messages = [];\n\tconst waiters = [];\n\tconst entries = /* @__PURE__ */ new Map();\n\tlet closed = false;\n\tlet pendingCount = 0;\n\tconst enqueue = (input) => {\n\t\tconst existing = entries.get(input.messageId);\n\t\tif (existing != null) {\n\t\t\tif (existing.response != null) options.respond(existing.response);\n\t\t\treturn;\n\t\t}\n\t\tlet settled = false;\n\t\tconst settle = (response) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tpendingCount--;\n\t\t\tconst entry = entries.get(input.messageId);\n\t\t\tif (entry != null) entry.response = response;\n\t\t\toptions.respond(response);\n\t\t};\n\t\tconst message = {\n\t\t\tmessageId: input.messageId,\n\t\t\ttext: input.text,\n\t\t\taccept: () => {\n\t\t\t\tsettle({\n\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\tmessageId: input.messageId,\n\t\t\t\t\taccepted: true\n\t\t\t\t});\n\t\t\t},\n\t\t\treject: (error) => {\n\t\t\t\tsettle({\n\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\tmessageId: input.messageId,\n\t\t\t\t\taccepted: false,\n\t\t\t\t\terror: { message: formatBridgeError(error).message }\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\tentries.set(input.messageId, { reject: message.reject });\n\t\tpendingCount++;\n\t\tif (closed) {\n\t\t\tmessage.reject(/* @__PURE__ */ new Error(\"The bridge turn is no longer accepting user messages.\"));\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiters.shift();\n\t\tif (waiter != null) waiter({\n\t\t\tdone: false,\n\t\t\tvalue: message\n\t\t});\n\t\telse messages.push(message);\n\t};\n\tconst close = (error) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tconst reason = error ?? /* @__PURE__ */ new Error(\"The bridge turn ended before accepting the user message.\");\n\t\tfor (const entry of entries.values()) if (entry.response == null) entry.reject(reason);\n\t\tmessages.length = 0;\n\t\twhile (waiters.length > 0) waiters.shift()({\n\t\t\tdone: true,\n\t\t\tvalue: void 0\n\t\t});\n\t};\n\treturn {\n\t\tget pendingCount() {\n\t\t\treturn pendingCount;\n\t\t},\n\t\tenqueue,\n\t\tclose,\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn { next: () => {\n\t\t\t\tconst message = messages.shift();\n\t\t\t\tif (message != null) return Promise.resolve({\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue: message\n\t\t\t\t});\n\t\t\t\tif (closed) return Promise.resolve({\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t});\n\t\t\t\treturn new Promise((resolve) => {\n\t\t\t\t\twaiters.push(resolve);\n\t\t\t\t});\n\t\t\t} };\n\t\t}\n\t};\n}\nfunction parseEnvList(value) {\n\tif (!value) return void 0;\n\tconst items = value.split(\",\").map((item) => item.trim()).filter(Boolean);\n\treturn items.length > 0 ? items : void 0;\n}\nconst ENV_TRUTHY = /* @__PURE__ */ new Set([\n\t\"1\",\n\t\"true\",\n\t\"yes\",\n\t\"on\"\n]);\nconst WS_OPEN = 1;\nasync function runBridge(options) {\n\tconst { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;\n\tconst teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;\n\tconst hostDisconnectTimeoutMs = options.hostDisconnectTimeoutMs != null && Number.isFinite(options.hostDisconnectTimeoutMs) && options.hostDisconnectTimeoutMs > 0 ? Math.min(options.hostDisconnectTimeoutMs, 2147483647) : void 0;\n\tlet hostDisconnectTimer;\n\tconst clearHostDisconnectTimer = () => {\n\t\tclearTimeout(hostDisconnectTimer);\n\t\thostDisconnectTimer = void 0;\n\t};\n\tconst authPublicKey = parseBridgeAuthPublicKey({ publicKey: options.publicKey ?? env[\"BRIDGE_AUTH_PUBLIC_KEY\"] });\n\tconst bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? \"0\", 10);\n\tconst bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;\n\tconst startConfigPath = `${bridgeStateDir}/start-config.json`;\n\tconst rerunStartConfigPath = `${bridgeStateDir}/rerun-start-config.json`;\n\tconst eventLogPath = `${bridgeStateDir}/event-log.ndjson`;\n\ttry {\n\t\tawait mkdir(bridgeStateDir, { recursive: true });\n\t} catch {}\n\tlet currentBoundPort = 0;\n\tlet currentTurnState = \"init\";\n\tlet activeSocket;\n\tlet isFirstTurn = true;\n\tlet turnAbort;\n\tlet currentUserMessages;\n\t/**\n\t* Settles when the in-flight turn has fully wound down — `onStart`\n\t* returned or threw AND its completion state was recorded. `undefined`\n\t* between turns. A new `start` fences on this so turns never overlap.\n\t*/\n\tlet activeTurn;\n\tlet lastStartId;\n\tlet debugConfig;\n\tlet consoleCaptureInstalled = false;\n\tconst envDebugEnabled = ENV_TRUTHY.has((env.HARNESS_DEBUG ?? \"\").toLowerCase());\n\tlet seqCounter = 0;\n\tlet eventLog = [];\n\tlet diskBuffer = \"\";\n\tlet flushPromise = null;\n\tconst flushEventsToDisk = async () => {\n\t\twhile (diskBuffer.length > 0) {\n\t\t\tconst buf = diskBuffer;\n\t\t\tdiskBuffer = \"\";\n\t\t\tawait appendFile(eventLogPath, buf).catch(() => {});\n\t\t}\n\t};\n\tconst scheduleEventFlush = () => {\n\t\tif (flushPromise) return;\n\t\tflushPromise = new Promise((resolve) => {\n\t\t\tsetImmediate(() => {\n\t\t\t\tflushEventsToDisk().finally(resolve);\n\t\t\t});\n\t\t}).finally(() => {\n\t\t\tflushPromise = null;\n\t\t\tif (diskBuffer.length > 0) scheduleEventFlush();\n\t\t});\n\t};\n\tconst flushPendingEventsToDisk = async () => {\n\t\tif (diskBuffer.length > 0 && !flushPromise) scheduleEventFlush();\n\t\tlet inFlight = flushPromise;\n\t\twhile (inFlight) {\n\t\t\tawait inFlight;\n\t\t\tinFlight = flushPromise;\n\t\t}\n\t};\n\tif (env.BRIDGE_REPLAY_FROM_DISK === \"1\" && existsSync(eventLogPath)) try {\n\t\teventLog = readFileSync(eventLogPath, \"utf8\").split(\"\\n\").map((line) => line.trim()).filter(Boolean).map((line) => ({\n\t\t\tseq: JSON.parse(line).seq,\n\t\t\tline\n\t\t}));\n\t\tseqCounter = eventLog.at(-1)?.seq ?? 0;\n\t} catch {\n\t\teventLog = [];\n\t\tseqCounter = 0;\n\t}\n\tconst pendingToolResults = /* @__PURE__ */ new Map();\n\tconst bufferedToolResults = [];\n\tconst pendingToolApprovals = /* @__PURE__ */ new Map();\n\tconst writeBridgeMeta = async (state) => {\n\t\ttry {\n\t\t\tawait writeFile(bridgeMetaPath, JSON.stringify({\n\t\t\t\ttype: bridgeType,\n\t\t\t\tport: currentBoundPort,\n\t\t\t\tstate,\n\t\t\t\tpid\n\t\t\t}));\n\t\t} catch {}\n\t};\n\tconst writeStartConfig = async (start) => {\n\t\ttry {\n\t\t\tconst serialized = JSON.stringify(start);\n\t\t\tawait writeFile(startConfigPath, serialized);\n\t\t\tif (!existsSync(rerunStartConfigPath)) await writeFile(rerunStartConfigPath, serialized);\n\t\t} catch {}\n\t};\n\tconst emit = (event) => {\n\t\tconst seq = ++seqCounter;\n\t\tconst line = JSON.stringify({\n\t\t\t...event,\n\t\t\tseq\n\t\t});\n\t\teventLog.push({\n\t\t\tseq,\n\t\t\tline\n\t\t});\n\t\tdiskBuffer += `${line}\\n`;\n\t\tscheduleEventFlush();\n\t\tif (activeSocket?.readyState === WS_OPEN) try {\n\t\t\tactiveSocket.send(line);\n\t\t} catch {}\n\t};\n\tconst replay = (ws, afterSeq) => {\n\t\tfor (const entry of eventLog) if (entry.seq > afterSeq && ws.readyState === WS_OPEN) ws.send(entry.line);\n\t};\n\tconst shouldEmitDebugEvent = (level, subsystem) => {\n\t\tif (!debugConfig?.enabled) return false;\n\t\tconst threshold = debugConfig.level ?? \"debug\";\n\t\tif (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;\n\t\treturn subsystemMatches(debugConfig.subsystems, subsystem);\n\t};\n\tconst rawStdoutWrite = process.stdout.write.bind(process.stdout);\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr);\n\tconst writeErrorToStderr = (input) => {\n\t\ttry {\n\t\t\tconst formatted = formatBridgeError(input.error);\n\t\t\trawStderrWrite(`[harness:${bridgeType}:error] ${input.message}: ${formatted.message}\\n`);\n\t\t\tif (formatted.stack) rawStderrWrite(`${formatted.stack}\\n`);\n\t\t} catch {}\n\t};\n\tconst emitWarning = (input) => {\n\t\ttry {\n\t\t\tfor (const line of input.message.split(\"\\n\")) if (line.trim().length > 0) rawStderrWrite(`[harness:${bridgeType}:warn] ${line}\\n`);\n\t\t} catch {}\n\t};\n\tconst emitError = (input) => {\n\t\twriteErrorToStderr({\n\t\t\tmessage: input.message ?? \"bridge error\",\n\t\t\terror: input.error\n\t\t});\n\t\temit({\n\t\t\ttype: \"error\",\n\t\t\terror: serialiseError(input.error)\n\t\t});\n\t};\n\tconst installConsoleCapture = () => {\n\t\tif (consoleCaptureInstalled) return;\n\t\tconsoleCaptureInstalled = true;\n\t\tconst buffers = {\n\t\t\tstdout: \"\",\n\t\t\tstderr: \"\"\n\t\t};\n\t\tconst patch = (stream, raw) => (chunk, encoding, cb) => {\n\t\t\tif (debugConfig?.enabled) try {\n\t\t\t\tconst enc = typeof encoding === \"string\" ? encoding : \"utf8\";\n\t\t\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString(enc);\n\t\t\t\tconst parts = (buffers[stream] + text.replace(/\\r\\n/g, \"\\n\")).split(\"\\n\");\n\t\t\t\tbuffers[stream] = parts.pop() ?? \"\";\n\t\t\t\tfor (const line of parts) {\n\t\t\t\t\tconst trimmed = line.replace(/\\s+$/, \"\");\n\t\t\t\t\tif (trimmed) emit({\n\t\t\t\t\t\ttype: \"sandbox-log\",\n\t\t\t\t\t\tsource: bridgeType,\n\t\t\t\t\t\tstream,\n\t\t\t\t\t\tline: trimmed\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\treturn raw(chunk, encoding, cb);\n\t\t};\n\t\tprocess.stdout.write = patch(\"stdout\", rawStdoutWrite);\n\t\tprocess.stderr.write = patch(\"stderr\", rawStderrWrite);\n\t};\n\tconst handleInbound = async (msg, ws) => {\n\t\tswitch (msg.type) {\n\t\t\tcase \"start\": {\n\t\t\t\tconst startId = msg.startId;\n\t\t\t\tif (startId != null) {\n\t\t\t\t\tif (startId === lastStartId) return;\n\t\t\t\t\tlastStartId = startId;\n\t\t\t\t}\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst pendingTurn = activeTurn;\n\t\t\t\t\tif (pendingTurn == null) break;\n\t\t\t\t\tturnAbort?.abort();\n\t\t\t\t\tcurrentUserMessages?.close(/* @__PURE__ */ new Error(\"A new bridge turn replaced the active turn.\"));\n\t\t\t\t\tlet graceTimer;\n\t\t\t\t\tconst settled = await Promise.race([pendingTurn.then(() => true), new Promise((resolve) => {\n\t\t\t\t\t\tgraceTimer = setTimeout(() => resolve(false), teardownGraceMs);\n\t\t\t\t\t\tgraceTimer.unref?.();\n\t\t\t\t\t})]);\n\t\t\t\t\tclearTimeout(graceTimer);\n\t\t\t\t\tif (!settled) break;\n\t\t\t\t}\n\t\t\t\tlet turnFinished;\n\t\t\t\tconst thisTurn = new Promise((resolve) => turnFinished = resolve);\n\t\t\t\tactiveTurn = thisTurn;\n\t\t\t\tactiveSocket = ws;\n\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\tconst firstTurn = isFirstTurn;\n\t\t\t\tisFirstTurn = false;\n\t\t\t\teventLog = [];\n\t\t\t\tdiskBuffer = \"\";\n\t\t\t\twriteFile(eventLogPath, \"\").catch(() => {});\n\t\t\t\tturnAbort = new AbortController();\n\t\t\t\tcurrentTurnState = \"running\";\n\t\t\t\twriteStartConfig(msg);\n\t\t\t\twriteBridgeMeta(\"running\");\n\t\t\t\tconst startDebug = msg.debug;\n\t\t\t\tdebugConfig = {\n\t\t\t\t\tenabled: startDebug?.enabled ?? envDebugEnabled,\n\t\t\t\t\tlevel: startDebug?.level ?? env.HARNESS_DEBUG_LEVEL,\n\t\t\t\t\tsubsystems: startDebug?.subsystems ?? parseEnvList(env.HARNESS_DEBUG_SUBSYSTEMS)\n\t\t\t\t};\n\t\t\t\tif (debugConfig.enabled) installConsoleCapture();\n\t\t\t\tconst userMessages = createBridgeUserMessageQueue({ respond: emit });\n\t\t\t\tconst turn = {\n\t\t\t\t\temit,\n\t\t\t\t\trequestToolResult: (requestInput) => {\n\t\t\t\t\t\tconst request = typeof requestInput === \"string\" ? { toolCallId: requestInput } : requestInput;\n\t\t\t\t\t\tconst bufferedIndex = bufferedToolResults.findIndex((buffered) => buffered.toolCallId === request.toolCallId || request.matches?.(buffered.result) === true);\n\t\t\t\t\t\tif (bufferedIndex >= 0) return Promise.resolve(bufferedToolResults.splice(bufferedIndex, 1)[0].result);\n\t\t\t\t\t\treturn new Promise((resolve) => {\n\t\t\t\t\t\t\tpendingToolResults.set(request.toolCallId, {\n\t\t\t\t\t\t\t\tresolve,\n\t\t\t\t\t\t\t\tmatches: request.matches\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\trequestToolApproval: (approvalId) => new Promise((resolve) => {\n\t\t\t\t\t\tpendingToolApprovals.set(approvalId, resolve);\n\t\t\t\t\t}),\n\t\t\t\t\texperimental_userMessages: userMessages,\n\t\t\t\t\tabortSignal: turnAbort.signal,\n\t\t\t\t\tfirstTurn,\n\t\t\t\t\tbridgeLog: (input) => {\n\t\t\t\t\t\tconst level = input.level ?? \"debug\";\n\t\t\t\t\t\tif (!shouldEmitDebugEvent(level, input.subsystem)) return;\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"debug-event\",\n\t\t\t\t\t\t\tlevel,\n\t\t\t\t\t\t\tsubsystem: input.subsystem,\n\t\t\t\t\t\t\tmessage: input.message,\n\t\t\t\t\t\t\t...input.attrs ? { attrs: input.attrs } : {},\n\t\t\t\t\t\t\t...input.error !== void 0 ? { error: formatBridgeError(input.error) } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\temitWarning,\n\t\t\t\t\temitError\n\t\t\t\t};\n\t\t\t\tcurrentUserMessages = userMessages;\n\t\t\t\ttry {\n\t\t\t\t\tawait onStart(msg, turn);\n\t\t\t\t} catch (err) {\n\t\t\t\t\temitError({\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t\tmessage: \"bridge turn failed\"\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tuserMessages.close();\n\t\t\t\t\tif (currentUserMessages === userMessages) currentUserMessages = void 0;\n\t\t\t\t\tif (activeTurn === thisTurn) {\n\t\t\t\t\t\tactiveTurn = void 0;\n\t\t\t\t\t\tcurrentTurnState = \"waiting\";\n\t\t\t\t\t\twriteBridgeMeta(\"waiting\");\n\t\t\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\t\t}\n\t\t\t\t\tturnFinished();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst result = {\n\t\t\t\t\toutput: msg.output,\n\t\t\t\t\tisError: msg.isError,\n\t\t\t\t\ttoolResult: msg.toolResult\n\t\t\t\t};\n\t\t\t\tconst exactPending = pendingToolResults.get(msg.toolCallId);\n\t\t\t\tconst matchingPending = exactPending == null ? Array.from(pendingToolResults.entries()).find(([, pending]) => pending.matches?.(result) === true) : void 0;\n\t\t\t\tconst pending = exactPending ?? matchingPending?.[1];\n\t\t\t\tconst pendingId = exactPending != null ? msg.toolCallId : matchingPending?.[0];\n\t\t\t\tif (pending != null && pendingId != null) {\n\t\t\t\t\tpendingToolResults.delete(pendingId);\n\t\t\t\t\tpending.resolve(result);\n\t\t\t\t} else bufferedToolResults.push({\n\t\t\t\t\ttoolCallId: msg.toolCallId,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"tool-approval-response\": {\n\t\t\t\tconst resolver = pendingToolApprovals.get(msg.approvalId);\n\t\t\t\tif (resolver) {\n\t\t\t\t\tpendingToolApprovals.delete(msg.approvalId);\n\t\t\t\t\tresolver({\n\t\t\t\t\t\tapproved: msg.approved,\n\t\t\t\t\t\treason: msg.reason\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"user-message\": {\n\t\t\t\tconst messageId = msg.messageId ?? randomUUID();\n\t\t\t\tif (currentUserMessages == null) {\n\t\t\t\t\tsendControl(ws, {\n\t\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\taccepted: false,\n\t\t\t\t\t\terror: { message: \"The bridge has no active turn to steer.\" }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (ws !== activeSocket) {\n\t\t\t\t\tsendControl(ws, {\n\t\t\t\t\t\ttype: \"user-message-response\",\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\taccepted: false,\n\t\t\t\t\t\terror: { message: \"The connection does not own the active bridge turn.\" }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcurrentUserMessages.enqueue({\n\t\t\t\t\tmessageId,\n\t\t\t\t\ttext: msg.text\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"abort\":\n\t\t\t\tturnAbort?.abort();\n\t\t\t\treturn;\n\t\t\tcase \"resume\":\n\t\t\t\tactiveSocket = ws;\n\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\treplay(ws, msg.lastSeenEventId);\n\t\t\t\treturn;\n\t\t\tcase \"destroy\":\n\t\t\t\tcurrentTurnState = \"done\";\n\t\t\t\twriteBridgeMeta(\"done\");\n\t\t\t\tawait onDestroy?.();\n\t\t\t\tdrainThenExit(ws, 1e3, \"destroy\");\n\t\t\t\treturn;\n\t\t\tcase \"stop\":\n\t\t\t\tcurrentTurnState = \"done\";\n\t\t\t\twriteBridgeMeta(\"done\");\n\t\t\t\tsendControl(ws, {\n\t\t\t\t\ttype: \"bridge-stop\",\n\t\t\t\t\tdata: await onStop?.() ?? {}\n\t\t\t\t});\n\t\t\t\tdrainThenExit(ws, 1e3, \"stop\");\n\t\t}\n\t};\n\twriteBridgeMeta(\"init\");\n\tconst wss = new WebSocketServer({\n\t\tport: bridgeWsPort,\n\t\thost: \"0.0.0.0\"\n\t});\n\tconst exit = () => {\n\t\tif (options.onExit) {\n\t\t\toptions.onExit();\n\t\t\treturn;\n\t\t}\n\t\twss.close(() => process.exit(0));\n\t\tsetTimeout(() => process.exit(0), 1e3).unref();\n\t};\n\tconst drainThenExit = (ws, code, reason) => {\n\t\tconst start = Date.now();\n\t\tconst tick = () => {\n\t\t\tif (ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN || Date.now() - start >= 5e3) {\n\t\t\t\tflushPendingEventsToDisk().finally(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tws.close(code, reason);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\texit();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetTimeout(tick, 10).unref();\n\t\t};\n\t\ttick();\n\t};\n\twss.on(\"listening\", () => {\n\t\tconst addr = wss.address();\n\t\tcurrentBoundPort = typeof addr === \"object\" && addr ? addr.port : 0;\n\t\tcurrentTurnState = \"waiting\";\n\t\twriteBridgeMeta(\"waiting\");\n\t\tstdout.write(JSON.stringify({\n\t\t\ttype: \"bridge-ready\",\n\t\t\tport: currentBoundPort\n\t\t}) + \"\\n\");\n\t\toptions.onListening?.(currentBoundPort);\n\t});\n\twss.on(\"connection\", (ws) => authenticateBridgeConnection({\n\t\tws,\n\t\tpublicKey: authPublicKey,\n\t\tonAuthenticated: () => acceptConnection(ws)\n\t}));\n\tconst acceptConnection = (ws) => {\n\t\tsendControl(ws, {\n\t\t\ttype: \"bridge-hello\",\n\t\t\tstate: currentTurnState,\n\t\t\tlastSeq: seqCounter,\n\t\t\tcapabilities: {\n\t\t\t\tidempotentStart: true,\n\t\t\t\texperimental_userMessageResponses: true\n\t\t\t}\n\t\t});\n\t\tws.on(\"message\", (raw) => {\n\t\t\tlet parsed;\n\t\t\ttry {\n\t\t\t\tconst text = typeof raw === \"string\" ? raw : Buffer.from(raw).toString(\"utf8\");\n\t\t\t\tparsed = JSON.parse(text);\n\t\t\t} catch (err) {\n\t\t\t\tsendControl(ws, {\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror: `protocol parse error: ${err.message}`\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thandleInbound(parsed, ws);\n\t\t});\n\t\tws.on(\"close\", (_code, reason) => {\n\t\t\tif (activeSocket === ws) {\n\t\t\t\tactiveSocket = void 0;\n\t\t\t\tif (hostDisconnectTimeoutMs != null && activeTurn != null && reason.toString() !== \"suspended\") {\n\t\t\t\t\tclearHostDisconnectTimer();\n\t\t\t\t\thostDisconnectTimer = setTimeout(() => {\n\t\t\t\t\t\thostDisconnectTimer = void 0;\n\t\t\t\t\t\tif (activeSocket == null) turnAbort?.abort();\n\t\t\t\t\t}, hostDisconnectTimeoutMs);\n\t\t\t\t\thostDisconnectTimer.unref?.();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", () => {});\n\t};\n\tprocess.on(\"uncaughtException\", (err) => {\n\t\temitError({\n\t\t\terror: err,\n\t\t\tmessage: \"uncaught exception\"\n\t\t});\n\t});\n\tprocess.on(\"unhandledRejection\", (err) => {\n\t\temitError({\n\t\t\terror: err,\n\t\t\tmessage: \"unhandled rejection\"\n\t\t});\n\t});\n\tawait new Promise((resolve, reject) => {\n\t\tif (wss.address() != null) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\twss.once(\"listening\", resolve);\n\t\twss.once(\"error\", reject);\n\t});\n\treturn {\n\t\tport: currentBoundPort,\n\t\tclose: () => new Promise((resolve) => {\n\t\t\twss.close(() => resolve());\n\t\t})\n\t};\n}\nfunction sendControl(socket, message) {\n\tif (socket?.readyState === WS_OPEN) try {\n\t\tsocket.send(JSON.stringify(message));\n\t} catch {}\n}\nfunction serialiseError(err) {\n\tif (err instanceof Error) return {\n\t\tname: err.name,\n\t\tmessage: err.message,\n\t\tstack: err.stack\n\t};\n\treturn err;\n}\n//#endregion\nexport { HarnessBridgeCapabilityUnsupportedError, convertHarnessToolModelOutput, runBridge };\n\n//# sourceMappingURL=index.js.map","import { readFileSync } from 'node:fs';\n\nexport type HostToolSchema = {\n name: string;\n description?: string;\n inputSchema?: unknown;\n};\n\nexport function readHostToolSchemasFromEnvironment(\n environment: NodeJS.ProcessEnv,\n): HostToolSchema[] {\n const serializedSchemas = environment.TOOL_SCHEMAS_PATH\n ? readFileSync(environment.TOOL_SCHEMAS_PATH, 'utf8')\n : (environment.TOOL_SCHEMAS ?? '[]');\n\n return JSON.parse(serializedSchemas) as HostToolSchema[];\n}\n","import { z } from 'zod/v4';\n\ntype JsonLiteral = string | number | boolean | null;\n\ntype JsonSchemaObject = {\n type?: string | string[];\n description?: string;\n properties?: Record<string, JsonSchemaObject>;\n required?: string[];\n items?: JsonSchemaObject;\n enum?: unknown[];\n default?: unknown;\n nullable?: boolean;\n};\n\ntype ZodShape = Record<string, z.ZodTypeAny>;\n\nexport function jsonSchemaToZodShape(input: unknown): ZodShape {\n const schema = isJsonSchemaObject(input) ? input : {};\n return toZodShape(schema);\n}\n\nfunction toZodShape(schema: JsonSchemaObject | undefined): ZodShape {\n if (!schema?.properties) return {};\n const required = new Set(schema.required);\n const shape: ZodShape = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const propType = toZodType(propSchema);\n shape[key] = required.has(key) ? propType : propType.optional();\n }\n return shape;\n}\n\nfunction toZodType(schema: JsonSchemaObject | undefined): z.ZodTypeAny {\n if (!schema) return z.any();\n\n let zType = zodForEnum(schema) ?? zodForType(schema);\n if (schema.description) zType = zType.describe(schema.description);\n if (schema.nullable) zType = zType.nullable();\n if ('default' in schema) zType = zType.meta({ default: schema.default });\n return zType;\n}\n\nfunction zodForEnum(schema: JsonSchemaObject): z.ZodTypeAny | undefined {\n if (\n !Array.isArray(schema.enum) ||\n schema.enum.length === 0 ||\n !schema.enum.every(isJsonLiteral)\n ) {\n return undefined;\n }\n return z.literal(schema.enum);\n}\n\nfunction zodForType(schema: JsonSchemaObject): z.ZodTypeAny {\n const types = Array.isArray(schema.type)\n ? schema.type.filter((t): t is string => t !== 'null')\n : ([schema.type].filter(Boolean) as string[]);\n\n switch (types[0]) {\n case 'string':\n return z.string();\n case 'number':\n return z.number();\n case 'integer':\n return z.number().int();\n case 'boolean':\n return z.boolean();\n case 'array':\n return z.array(toZodType(schema.items));\n case 'object':\n return z.object(toZodShape(schema));\n case 'null':\n return z.null();\n default:\n return z.any();\n }\n}\n\nfunction isJsonSchemaObject(input: unknown): input is JsonSchemaObject {\n return input != null && typeof input === 'object' && !Array.isArray(input);\n}\n\nfunction isJsonLiteral(value: unknown): value is JsonLiteral {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n (typeof value === 'number' && Number.isFinite(value))\n );\n}\n","#!/usr/bin/env node\n/*\n * These bridge imports are externalized by tsdown and resolved inside the\n * sandbox from src/bridge/package.json and its lockfile. Keep this file,\n * tsdown.config.ts, and the bridge package dependency list in sync.\n */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n convertHarnessToolModelOutput,\n type BridgeTurn,\n} from '@ai-sdk/harness/bridge';\nimport { readHostToolSchemasFromEnvironment } from './host-tool-schemas';\nimport { jsonSchemaToZodShape } from './json-schema-to-zod';\n\nconst schemas = readHostToolSchemasFromEnvironment(process.env);\nconst relayUrl = process.env.TOOL_RELAY_URL || '';\n\nif (!schemas.length || !relayUrl) {\n process.stderr.write(\n '[host-tool-mcp] Missing TOOL_SCHEMAS_PATH/TOOL_SCHEMAS or TOOL_RELAY_URL; exiting\\n',\n );\n process.exit(0);\n}\n\nconst server = new McpServer({ name: 'harness-tools', version: '1.0.0' });\n\nfor (const schema of schemas) {\n const shape = jsonSchemaToZodShape(schema.inputSchema);\n server.tool(\n schema.name,\n schema.description ?? '',\n shape,\n async (input: Record<string, unknown>) => {\n const requestId = crypto.randomUUID();\n try {\n const res = await fetch(relayUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ requestId, toolName: schema.name, input }),\n });\n if (!res.ok) {\n const body = await res.text();\n throw new Error(\n `Tool relay ${schema.name} failed with ${res.status}: ${body.slice(0, 500)}`,\n );\n }\n const data = (await res.json()) as {\n result?: unknown;\n isError?: boolean;\n toolResult?: Awaited<\n ReturnType<BridgeTurn['requestToolResult']>\n >['toolResult'];\n };\n if (data.toolResult != null) {\n const converted = convertHarnessToolModelOutput({\n output: data.toolResult.output,\n });\n return {\n content: converted.content.map(part =>\n part.type === 'text'\n ? part\n : {\n type: 'image' as const,\n data: part.data,\n mimeType: part.mediaType,\n },\n ),\n isError: data.isError === true || converted.isError,\n };\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(data.result ?? null),\n },\n ],\n ...(data.isError === true ? { isError: true } : {}),\n };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Error: ${String(err)}` }],\n isError: true,\n };\n }\n },\n );\n}\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n"],"mappings":";;;;;;;AAuEA,MAAM,OAAO;;;;;;AAMb,IAAI,0CAA0C,cAAc,MAAM;CACjE,YAAY,EAAE,SAAS,WAAW,SAAS;EAC1C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,IAAI,MACR,cAAc,OAAO,KAAK,eAAe,IAAI,OAAO,IAAI,KAAK,MAAM,GAAG,GAAG,GAC3E;GACF;GACA,MAAM,OAAQ,MAAM,IAAI,KAAK;GAO7B,IAAI,KAAK,cAAc,MAAM;IAC3B,MAAM,YAAY,8BAA8B,EAC9C,QAAQ,KAAK,WAAW,OAC1B,CAAC;IACD,OAAO;KACL,SAAS,UAAU,QAAQ,KAAI,SAC7B,KAAK,SAAS,SACV,OACA;MACE,MAAM;MACN,MAAM,KAAK;MACX,UAAU,KAAK;KACjB,CACN;KACA,SAAS,KAAK,YAAY,QAAQ,UAAU;IAC9C;GACF;GACA,OAAO;IACL,SAAS,CACP;KACE,MAAM;KACN,MAAM,KAAK,UAAU,KAAK,UAAU,IAAI;IAC1C,CACF;IACA,GAAI,KAAK,YAAY,OAAO,EAAE,SAAS,KAAK,IAAI,CAAC;GACnD;EACF,SAAS,KAAK;GACZ,OAAO;IACL,SAAS,CAAC;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO,GAAG;IAAI,CAAC;IAClE,SAAS;GACX;EACF;CACF,CACF;AACF;AAEA,MAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS"}
@@ -1,8 +1,9 @@
1
1
  import { appendFile, lstat, mkdir, realpath, writeFile } from "node:fs/promises";
2
2
  import { existsSync, globSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
- import { randomBytes, randomUUID } from "node:crypto";
3
+ import { createPublicKey, randomBytes, randomUUID, verify } from "node:crypto";
4
4
  import { argv, env, pid, stdout } from "node:process";
5
5
  import { WebSocketServer } from "ws";
6
+ import { Buffer as Buffer$1 } from "node:buffer";
6
7
  import { homedir } from "node:os";
7
8
  import path from "node:path";
8
9
  import { isDeepStrictEqual } from "node:util";
@@ -10,6 +11,67 @@ import { createOpencodeClient, createOpencodeServer } from "@opencode-ai/sdk/v2"
10
11
  import { rgPath } from "@vscode/ripgrep";
11
12
  import { createServer } from "node:http";
12
13
  //#region ../harness/dist/bridge/index.js
14
+ const BRIDGE_AUTH_TIMEOUT_MS = 1e4;
15
+ const BRIDGE_AUTH_MESSAGE_PREFIX = "ai-sdk-harness-bridge-auth-v1\0";
16
+ const PROOF_FRAME_REGEXP = /^\{"type":"bridge-auth-proof","signature":"([A-Za-z0-9_-]{86})"\}$/;
17
+ function createBridgeAuthMessage({ challenge }) {
18
+ return Buffer$1.from(`${BRIDGE_AUTH_MESSAGE_PREFIX}${challenge}`, "utf8");
19
+ }
20
+ function serializeBridgeAuthChallengeFrame({ challenge }) {
21
+ return JSON.stringify({
22
+ type: "bridge-auth-challenge",
23
+ challenge
24
+ });
25
+ }
26
+ function parseBridgeAuthProofFrame({ text }) {
27
+ return PROOF_FRAME_REGEXP.exec(text)?.[1];
28
+ }
29
+ const PUBLIC_KEY_REGEXP = /^[A-Za-z0-9_-]{43}$/;
30
+ const UNAUTHORIZED_CLOSE_CODE = 1008;
31
+ const INVALID_PUBLIC_KEY_MESSAGE = "The bridge requires a valid Ed25519 public key for authentication.";
32
+ function parseBridgeAuthPublicKey({ publicKey }) {
33
+ if (publicKey == null || !PUBLIC_KEY_REGEXP.test(publicKey)) throw new Error(INVALID_PUBLIC_KEY_MESSAGE);
34
+ let key;
35
+ try {
36
+ key = createPublicKey({
37
+ key: {
38
+ kty: "OKP",
39
+ crv: "Ed25519",
40
+ x: publicKey
41
+ },
42
+ format: "jwk"
43
+ });
44
+ } catch {
45
+ throw new Error(INVALID_PUBLIC_KEY_MESSAGE);
46
+ }
47
+ if (key.asymmetricKeyType !== "ed25519") throw new Error(INVALID_PUBLIC_KEY_MESSAGE);
48
+ return key;
49
+ }
50
+ function authenticateBridgeConnection({ ws, publicKey, timeoutMs = BRIDGE_AUTH_TIMEOUT_MS, onAuthenticated }) {
51
+ const challenge = randomBytes(32).toString("hex");
52
+ const timeout = setTimeout(() => ws.terminate(), timeoutMs);
53
+ timeout.unref?.();
54
+ const onError = () => {};
55
+ ws.on("error", onError);
56
+ ws.once("close", () => clearTimeout(timeout));
57
+ ws.once("message", (raw, isBinary) => {
58
+ clearTimeout(timeout);
59
+ const text = isBinary ? void 0 : rawDataToString(raw);
60
+ const signature = text == null ? void 0 : parseBridgeAuthProofFrame({ text });
61
+ if (signature == null || !verify(null, createBridgeAuthMessage({ challenge }), publicKey, Buffer$1.from(signature, "base64url"))) {
62
+ ws.close(UNAUTHORIZED_CLOSE_CODE, "unauthorized");
63
+ return;
64
+ }
65
+ ws.off("error", onError);
66
+ onAuthenticated();
67
+ });
68
+ ws.send(serializeBridgeAuthChallengeFrame({ challenge }));
69
+ }
70
+ function rawDataToString(raw) {
71
+ const buffer = Array.isArray(raw) ? Buffer$1.concat(raw) : Buffer$1.isBuffer(raw) ? raw : Buffer$1.from(raw);
72
+ if (buffer.byteLength > 1024) return void 0;
73
+ return buffer.toString("utf8");
74
+ }
13
75
  const DEBUG_LEVEL_WEIGHT = {
14
76
  error: 0,
15
77
  warn: 1,
@@ -143,7 +205,7 @@ async function runBridge(options) {
143
205
  clearTimeout(hostDisconnectTimer);
144
206
  hostDisconnectTimer = void 0;
145
207
  };
146
- const expectedToken = options.token ?? env.BRIDGE_CHANNEL_TOKEN ?? "";
208
+ const authPublicKey = parseBridgeAuthPublicKey({ publicKey: options.publicKey ?? env["BRIDGE_AUTH_PUBLIC_KEY"] });
147
209
  const bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? "0", 10);
148
210
  const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;
149
211
  const startConfigPath = `${bridgeStateDir}/start-config.json`;
@@ -524,11 +586,12 @@ async function runBridge(options) {
524
586
  }) + "\n");
525
587
  options.onListening?.(currentBoundPort);
526
588
  });
527
- wss.on("connection", (ws, req) => {
528
- if (new URL(req.url ?? "/", "http://localhost").searchParams.get("agent_bridge_token") !== expectedToken) {
529
- ws.close(1008, "unauthorized");
530
- return;
531
- }
589
+ wss.on("connection", (ws) => authenticateBridgeConnection({
590
+ ws,
591
+ publicKey: authPublicKey,
592
+ onAuthenticated: () => acceptConnection(ws)
593
+ }));
594
+ const acceptConnection = (ws) => {
532
595
  sendControl(ws, {
533
596
  type: "bridge-hello",
534
597
  state: currentTurnState,
@@ -566,7 +629,7 @@ async function runBridge(options) {
566
629
  }
567
630
  });
568
631
  ws.on("error", () => {});
569
- });
632
+ };
570
633
  process.on("uncaughtException", (err) => {
571
634
  emitError({
572
635
  error: err,