@ai-sdk/harness-opencode 1.0.177 → 1.0.179
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 +24 -0
- package/dist/bridge/host-tool-mcp.mjs.map +1 -1
- package/dist/bridge/index.mjs +24 -2
- package/dist/bridge/index.mjs.map +1 -1
- package/dist/index.d.ts +12 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -16
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/bridge/index.ts +13 -0
- package/src/opencode-auth.ts +10 -1
- package/src/opencode-harness.ts +7 -1
- package/src/opencode-subscription.ts +26 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# @ai-sdk/harness-opencode
|
|
2
2
|
|
|
3
|
+
## 1.0.179
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a97f490: fix(harness-opencode): add `auth: 'direct'` to use the selected provider's credentials or native subscription when `VERCEL_OIDC_TOKEN` or `AI_GATEWAY_API_KEY` is set
|
|
8
|
+
- Updated dependencies [6400cf8]
|
|
9
|
+
- Updated dependencies [f608c05]
|
|
10
|
+
- Updated dependencies [cab9c1f]
|
|
11
|
+
- Updated dependencies [c70adf6]
|
|
12
|
+
- @ai-sdk/provider-utils@5.0.76
|
|
13
|
+
- @ai-sdk/provider@4.0.37
|
|
14
|
+
- @ai-sdk/harness@1.0.176
|
|
15
|
+
|
|
16
|
+
## 1.0.178
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 89e6bc9: Read OpenCode subscriptions from `~/.local/share/opencode/auth.json` on Windows, where OpenCode stores them, and keep `~/.opencode/auth.json` as a fallback for the GitLab auth plugin.
|
|
21
|
+
- a54f0fd: fix(harness): abort a running turn when its host disconnects for good
|
|
22
|
+
- f779a62: fix(harness-opencode): ensure Google and Mistral models use OpenAI compatible endpoint when used with AI Gateway
|
|
23
|
+
- Updated dependencies [8e8033a]
|
|
24
|
+
- Updated dependencies [a54f0fd]
|
|
25
|
+
- @ai-sdk/harness@1.0.175
|
|
26
|
+
|
|
3
27
|
## 1.0.177
|
|
4
28
|
|
|
5
29
|
### 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 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\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}\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\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\", () => {\n\t\t\tif (activeSocket === ws) activeSocket = void 0;\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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O,MACP,OAAO,eAAe,IACtB,OACA,OAAO,UAAmC;EACxC,MAAM,YAAY,OAAO,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 { 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;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AAM;KAAiB,MAAM,UAAU,OAAO,GAAG;IAAI,CAAC;IAClE,SAAS;GACX;EACF;CACF,CACF;AACF;AAEA,MAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS"}
|
package/dist/bridge/index.mjs
CHANGED
|
@@ -137,6 +137,12 @@ const WS_OPEN = 1;
|
|
|
137
137
|
async function runBridge(options) {
|
|
138
138
|
const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;
|
|
139
139
|
const teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;
|
|
140
|
+
const hostDisconnectTimeoutMs = options.hostDisconnectTimeoutMs != null && Number.isFinite(options.hostDisconnectTimeoutMs) && options.hostDisconnectTimeoutMs > 0 ? Math.min(options.hostDisconnectTimeoutMs, 2147483647) : void 0;
|
|
141
|
+
let hostDisconnectTimer;
|
|
142
|
+
const clearHostDisconnectTimer = () => {
|
|
143
|
+
clearTimeout(hostDisconnectTimer);
|
|
144
|
+
hostDisconnectTimer = void 0;
|
|
145
|
+
};
|
|
140
146
|
const expectedToken = options.token ?? env.BRIDGE_CHANNEL_TOKEN ?? "";
|
|
141
147
|
const bridgeWsPort = options.port ?? parseInt(env.BRIDGE_WS_PORT ?? "0", 10);
|
|
142
148
|
const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;
|
|
@@ -324,6 +330,7 @@ async function runBridge(options) {
|
|
|
324
330
|
const thisTurn = new Promise((resolve) => turnFinished = resolve);
|
|
325
331
|
activeTurn = thisTurn;
|
|
326
332
|
activeSocket = ws;
|
|
333
|
+
clearHostDisconnectTimer();
|
|
327
334
|
const firstTurn = isFirstTurn;
|
|
328
335
|
isFirstTurn = false;
|
|
329
336
|
eventLog = [];
|
|
@@ -390,6 +397,7 @@ async function runBridge(options) {
|
|
|
390
397
|
activeTurn = void 0;
|
|
391
398
|
currentTurnState = "waiting";
|
|
392
399
|
writeBridgeMeta("waiting");
|
|
400
|
+
clearHostDisconnectTimer();
|
|
393
401
|
}
|
|
394
402
|
turnFinished();
|
|
395
403
|
}
|
|
@@ -456,6 +464,7 @@ async function runBridge(options) {
|
|
|
456
464
|
return;
|
|
457
465
|
case "resume":
|
|
458
466
|
activeSocket = ws;
|
|
467
|
+
clearHostDisconnectTimer();
|
|
459
468
|
replay(ws, msg.lastSeenEventId);
|
|
460
469
|
return;
|
|
461
470
|
case "destroy":
|
|
@@ -543,8 +552,18 @@ async function runBridge(options) {
|
|
|
543
552
|
}
|
|
544
553
|
handleInbound(parsed, ws);
|
|
545
554
|
});
|
|
546
|
-
ws.on("close", () => {
|
|
547
|
-
if (activeSocket === ws)
|
|
555
|
+
ws.on("close", (_code, reason) => {
|
|
556
|
+
if (activeSocket === ws) {
|
|
557
|
+
activeSocket = void 0;
|
|
558
|
+
if (hostDisconnectTimeoutMs != null && activeTurn != null && reason.toString() !== "suspended") {
|
|
559
|
+
clearHostDisconnectTimer();
|
|
560
|
+
hostDisconnectTimer = setTimeout(() => {
|
|
561
|
+
hostDisconnectTimer = void 0;
|
|
562
|
+
if (activeSocket == null) turnAbort?.abort();
|
|
563
|
+
}, hostDisconnectTimeoutMs);
|
|
564
|
+
hostDisconnectTimer.unref?.();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
548
567
|
});
|
|
549
568
|
ws.on("error", () => {});
|
|
550
569
|
});
|
|
@@ -1989,6 +2008,7 @@ env.OPENCODE_DISABLE_PROJECT_CONFIG = "1";
|
|
|
1989
2008
|
await runBridge({
|
|
1990
2009
|
bridgeType: "opencode",
|
|
1991
2010
|
bridgeStateDir,
|
|
2011
|
+
...args.hostDisconnectTimeoutMs !== void 0 ? { hostDisconnectTimeoutMs: args.hostDisconnectTimeoutMs } : {},
|
|
1992
2012
|
onStart: runTurn,
|
|
1993
2013
|
onStop: () => runtime.sessionId ? { openCodeSessionId: runtime.sessionId } : {}
|
|
1994
2014
|
});
|
|
@@ -2175,6 +2195,7 @@ function buildProviderConfig(start) {
|
|
|
2175
2195
|
const providerID = model.providerID ?? start.provider ?? env.OPENAI_NAME ?? "anthropic";
|
|
2176
2196
|
const modelID = model.modelID;
|
|
2177
2197
|
if (env.AI_GATEWAY_API_KEY && env.AI_GATEWAY_BASE_URL) return { [providerID]: {
|
|
2198
|
+
...providerID === "google" || providerID === "mistral" ? { npm: "@ai-sdk/openai-compatible" } : {},
|
|
2178
2199
|
options: {
|
|
2179
2200
|
apiKey: env.AI_GATEWAY_API_KEY,
|
|
2180
2201
|
baseURL: toOpenCodeGatewayBaseUrl(env.AI_GATEWAY_BASE_URL),
|
|
@@ -3317,6 +3338,7 @@ function parseArgs(args) {
|
|
|
3317
3338
|
const out = {};
|
|
3318
3339
|
for (let i = 0; i < args.length; i++) if (args[i] === "--workdir" && i + 1 < args.length) out.workdir = args[++i];
|
|
3319
3340
|
else if (args[i] === "--bridge-state-dir" && i + 1 < args.length) out.bridgeStateDir = args[++i];
|
|
3341
|
+
else if (args[i] === "--host-disconnect-timeout-ms" && i + 1 < args.length) out.hostDisconnectTimeoutMs = Number(args[++i]);
|
|
3320
3342
|
else if (args[i] === "--bootstrap-dir" && i + 1 < args.length) out.bootstrapDir = args[++i];
|
|
3321
3343
|
else if (args[i] === "--skills-dir" && i + 1 < args.length) out.skillsDir = args[++i];
|
|
3322
3344
|
return out;
|