@ai-sdk/harness-opencode 1.0.184 → 1.0.186

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,26 @@
1
1
  # @ai-sdk/harness-opencode
2
2
 
3
+ ## 1.0.186
4
+
5
+ ### Patch Changes
6
+
7
+ - 71bef69: feat(harness): require approval for sensitive workspace file changes in `allow-edits` permission mode
8
+ - Updated dependencies [6d50947]
9
+ - Updated dependencies [71bef69]
10
+ - @ai-sdk/provider-utils@5.0.81
11
+ - @ai-sdk/harness@1.0.183
12
+
13
+ ## 1.0.185
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [2ebc78b]
18
+ - Updated dependencies [1a94af3]
19
+ - Updated dependencies [cb4fa52]
20
+ - @ai-sdk/provider-utils@5.0.80
21
+ - @ai-sdk/harness@1.0.182
22
+ - @ai-sdk/provider@4.0.38
23
+
3
24
  ## 1.0.184
4
25
 
5
26
  ### 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 { 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,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,K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AAK,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, lstat, mkdir, readdir, realpath, 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\";\nimport path from \"node:path\";\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};\nfunction assertWriteProtectedPathEntries(entries) {\n\tfor (const entry of entries) if (typeof entry !== \"string\" || entry.length === 0 || path.posix.isAbsolute(entry) || entry.split(\"/\").some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")) throw new TypeError(`Write-protected path entries must be relative paths without empty, \".\" or \"..\" segments; received ${JSON.stringify(entry)}.`);\n}\nfunction isInsideWriteProtectionPath({ parent, candidate }) {\n\tconst relative = path.posix.relative(parent, candidate);\n\treturn relative === \"\" || relative !== \"..\" && !relative.startsWith(\"../\") && !path.posix.isAbsolute(relative);\n}\nfunction matchesWriteProtectedPath({ targets, protectedPaths, anyProtectedPathExists }) {\n\treturn targets.some((target) => protectedPaths.some((protectedPath) => isInsideWriteProtectionPath({\n\t\tparent: protectedPath,\n\t\tcandidate: target.path\n\t}) || isInsideWriteProtectionPath({\n\t\tparent: target.path,\n\t\tcandidate: protectedPath\n\t})) || anyProtectedPathExists && target.isMultiLinkFile);\n}\n//#endregion\n//#region src/bridge/is-write-protected-path.ts\n/**\n* Returns whether writing to any of `paths` touches a write-protected path and\n* therefore requires the host's approval. Runs inside the sandbox, next to the\n* files it checks.\n*\n* `writeProtectedPaths` entries are relative to `workDir` and must not contain\n* empty, `.`, or `..` segments. Relative `paths` resolve against `cwd`, which\n* defaults to `workDir`.\n*\n* A path matches when its canonical location is a protected path, lies inside\n* one, or is a parent of one. Each protected entry is protected both at its\n* literal location below the canonical working directory and at its canonical\n* location. The literal location covers parents of a protected path that is\n* itself a symlink, whose canonical location lies elsewhere.\n*\n* Protected paths are resolved on every call because the filesystem can change\n* during a session. Symlinks inside protected directories protect their\n* targets as well, so files reachable through a protected path cannot be\n* written through an unprotected alias. While any protected path exists,\n* writes to files with more than one link match too. Any resolution failure,\n* including dangling or looping symlinks, reports the write as protected.\n*/\nasync function isWriteProtectedPath({ workDir, cwd = workDir, paths, writeProtectedPaths }) {\n\tassertWriteProtectedPathEntries(writeProtectedPaths);\n\tif (paths.length === 0) return true;\n\ttry {\n\t\tconst canonicalWorkDir = await realpath(workDir);\n\t\tconst protection = await collectWriteProtectedPaths({\n\t\t\tcanonicalWorkDir,\n\t\t\tprotectedRoots: await Promise.all(writeProtectedPaths.map((entry) => resolveExistingPrefix(`${workDir}/${entry}`)))\n\t\t});\n\t\tif (protection == null) return true;\n\t\tconst targets = [];\n\t\tfor (const filePath of paths) {\n\t\t\tif (typeof filePath !== \"string\" || filePath.trim().length === 0) return true;\n\t\t\tif (!path.posix.isAbsolute(filePath) && !path.posix.isAbsolute(cwd)) return true;\n\t\t\tconst absolutePath = path.posix.isAbsolute(filePath) ? filePath : `${cwd}/${filePath}`;\n\t\t\tfor (const candidatePath of /* @__PURE__ */ new Set([absolutePath, path.posix.normalize(absolutePath)])) {\n\t\t\t\tconst target = await resolveExistingPrefix(candidatePath);\n\t\t\t\tconst stats = protection.anyRootExists ? await lstatIfExists(target) : void 0;\n\t\t\t\ttargets.push({\n\t\t\t\t\tpath: target,\n\t\t\t\t\tisMultiLinkFile: stats?.isFile() === true && stats.nlink > 1\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn matchesWriteProtectedPath({\n\t\t\ttargets,\n\t\t\tprotectedPaths: [...writeProtectedPaths.map((entry) => path.posix.join(canonicalWorkDir, entry)), ...protection.paths],\n\t\t\tanyProtectedPathExists: protection.anyRootExists\n\t\t});\n\t} catch {\n\t\treturn true;\n\t}\n}\nasync function collectWriteProtectedPaths({ canonicalWorkDir, protectedRoots }) {\n\tconst paths = [...protectedRoots];\n\tconst queue = [];\n\tlet anyRootExists = false;\n\tfor (const root of protectedRoots) {\n\t\tconst stats = await lstatIfExists(root);\n\t\tif (stats == null) continue;\n\t\tanyRootExists = true;\n\t\tif (stats.isDirectory()) queue.push(root);\n\t}\n\tconst scanned = /* @__PURE__ */ new Set();\n\tlet entryCount = 0;\n\twhile (queue.length > 0) {\n\t\tconst directory = queue.shift();\n\t\tif (scanned.has(directory)) continue;\n\t\tscanned.add(directory);\n\t\tfor (const entry of await readdir(directory, { withFileTypes: true })) {\n\t\t\tentryCount += 1;\n\t\t\tif (entryCount > 2e3) return void 0;\n\t\t\tconst entryPath = path.posix.join(directory, entry.name);\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tconst target = await realpath(entryPath);\n\t\t\t\tpaths.push(target);\n\t\t\t\tif (isInsideWriteProtectionPath({\n\t\t\t\t\tparent: canonicalWorkDir,\n\t\t\t\t\tcandidate: target\n\t\t\t\t}) && (await lstat(target)).isDirectory()) queue.push(target);\n\t\t\t} else if (entry.isDirectory()) queue.push(entryPath);\n\t\t}\n\t}\n\treturn {\n\t\tpaths,\n\t\tanyRootExists\n\t};\n}\nasync function resolveExistingPrefix(inputPath) {\n\tlet existingPath = inputPath;\n\tconst missingSegments = [];\n\twhile (await lstatIfExists(existingPath) == null) {\n\t\tconst parent = path.posix.dirname(existingPath);\n\t\tconst segment = path.posix.basename(existingPath);\n\t\tif (parent === existingPath || segment === \"..\" || segment === \".\") throw new Error(`Unable to resolve path ${JSON.stringify(inputPath)}.`);\n\t\tmissingSegments.unshift(segment);\n\t\texistingPath = parent;\n\t}\n\treturn path.posix.join(await realpath(existingPath), ...missingSegments);\n}\nasync function lstatIfExists(entryPath) {\n\ttry {\n\t\treturn await lstat(entryPath);\n\t} catch (error) {\n\t\tif (error != null && typeof error === \"object\" && \"code\" in error && error.code === \"ENOENT\") return;\n\t\tthrow error;\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, isWriteProtectedPath, 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":";;;;;;;AAwEA,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;AAmIA,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,MAA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B,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,11 +1,11 @@
1
- import { appendFile, lstat, mkdir, realpath, writeFile } from "node:fs/promises";
1
+ import { appendFile, lstat, mkdir, readdir, realpath, writeFile } from "node:fs/promises";
2
2
  import { existsSync, globSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
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
6
  import { Buffer as Buffer$1 } from "node:buffer";
7
- import { homedir } from "node:os";
8
7
  import path from "node:path";
8
+ import { homedir } from "node:os";
9
9
  import { isDeepStrictEqual } from "node:util";
10
10
  import { createOpencodeClient, createOpencodeServer } from "@opencode-ai/sdk/v2";
11
11
  import { rgPath } from "@vscode/ripgrep";
@@ -72,6 +72,132 @@ function rawDataToString(raw) {
72
72
  if (buffer.byteLength > 1024) return void 0;
73
73
  return buffer.toString("utf8");
74
74
  }
75
+ function assertWriteProtectedPathEntries(entries) {
76
+ for (const entry of entries) if (typeof entry !== "string" || entry.length === 0 || path.posix.isAbsolute(entry) || entry.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) throw new TypeError(`Write-protected path entries must be relative paths without empty, "." or ".." segments; received ${JSON.stringify(entry)}.`);
77
+ }
78
+ function isInsideWriteProtectionPath({ parent, candidate }) {
79
+ const relative = path.posix.relative(parent, candidate);
80
+ return relative === "" || relative !== ".." && !relative.startsWith("../") && !path.posix.isAbsolute(relative);
81
+ }
82
+ function matchesWriteProtectedPath({ targets, protectedPaths, anyProtectedPathExists }) {
83
+ return targets.some((target) => protectedPaths.some((protectedPath) => isInsideWriteProtectionPath({
84
+ parent: protectedPath,
85
+ candidate: target.path
86
+ }) || isInsideWriteProtectionPath({
87
+ parent: target.path,
88
+ candidate: protectedPath
89
+ })) || anyProtectedPathExists && target.isMultiLinkFile);
90
+ }
91
+ /**
92
+ * Returns whether writing to any of `paths` touches a write-protected path and
93
+ * therefore requires the host's approval. Runs inside the sandbox, next to the
94
+ * files it checks.
95
+ *
96
+ * `writeProtectedPaths` entries are relative to `workDir` and must not contain
97
+ * empty, `.`, or `..` segments. Relative `paths` resolve against `cwd`, which
98
+ * defaults to `workDir`.
99
+ *
100
+ * A path matches when its canonical location is a protected path, lies inside
101
+ * one, or is a parent of one. Each protected entry is protected both at its
102
+ * literal location below the canonical working directory and at its canonical
103
+ * location. The literal location covers parents of a protected path that is
104
+ * itself a symlink, whose canonical location lies elsewhere.
105
+ *
106
+ * Protected paths are resolved on every call because the filesystem can change
107
+ * during a session. Symlinks inside protected directories protect their
108
+ * targets as well, so files reachable through a protected path cannot be
109
+ * written through an unprotected alias. While any protected path exists,
110
+ * writes to files with more than one link match too. Any resolution failure,
111
+ * including dangling or looping symlinks, reports the write as protected.
112
+ */
113
+ async function isWriteProtectedPath({ workDir, cwd = workDir, paths, writeProtectedPaths }) {
114
+ assertWriteProtectedPathEntries(writeProtectedPaths);
115
+ if (paths.length === 0) return true;
116
+ try {
117
+ const canonicalWorkDir = await realpath(workDir);
118
+ const protection = await collectWriteProtectedPaths({
119
+ canonicalWorkDir,
120
+ protectedRoots: await Promise.all(writeProtectedPaths.map((entry) => resolveExistingPrefix(`${workDir}/${entry}`)))
121
+ });
122
+ if (protection == null) return true;
123
+ const targets = [];
124
+ for (const filePath of paths) {
125
+ if (typeof filePath !== "string" || filePath.trim().length === 0) return true;
126
+ if (!path.posix.isAbsolute(filePath) && !path.posix.isAbsolute(cwd)) return true;
127
+ const absolutePath = path.posix.isAbsolute(filePath) ? filePath : `${cwd}/${filePath}`;
128
+ for (const candidatePath of /* @__PURE__ */ new Set([absolutePath, path.posix.normalize(absolutePath)])) {
129
+ const target = await resolveExistingPrefix(candidatePath);
130
+ const stats = protection.anyRootExists ? await lstatIfExists(target) : void 0;
131
+ targets.push({
132
+ path: target,
133
+ isMultiLinkFile: stats?.isFile() === true && stats.nlink > 1
134
+ });
135
+ }
136
+ }
137
+ return matchesWriteProtectedPath({
138
+ targets,
139
+ protectedPaths: [...writeProtectedPaths.map((entry) => path.posix.join(canonicalWorkDir, entry)), ...protection.paths],
140
+ anyProtectedPathExists: protection.anyRootExists
141
+ });
142
+ } catch {
143
+ return true;
144
+ }
145
+ }
146
+ async function collectWriteProtectedPaths({ canonicalWorkDir, protectedRoots }) {
147
+ const paths = [...protectedRoots];
148
+ const queue = [];
149
+ let anyRootExists = false;
150
+ for (const root of protectedRoots) {
151
+ const stats = await lstatIfExists(root);
152
+ if (stats == null) continue;
153
+ anyRootExists = true;
154
+ if (stats.isDirectory()) queue.push(root);
155
+ }
156
+ const scanned = /* @__PURE__ */ new Set();
157
+ let entryCount = 0;
158
+ while (queue.length > 0) {
159
+ const directory = queue.shift();
160
+ if (scanned.has(directory)) continue;
161
+ scanned.add(directory);
162
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
163
+ entryCount += 1;
164
+ if (entryCount > 2e3) return void 0;
165
+ const entryPath = path.posix.join(directory, entry.name);
166
+ if (entry.isSymbolicLink()) {
167
+ const target = await realpath(entryPath);
168
+ paths.push(target);
169
+ if (isInsideWriteProtectionPath({
170
+ parent: canonicalWorkDir,
171
+ candidate: target
172
+ }) && (await lstat(target)).isDirectory()) queue.push(target);
173
+ } else if (entry.isDirectory()) queue.push(entryPath);
174
+ }
175
+ }
176
+ return {
177
+ paths,
178
+ anyRootExists
179
+ };
180
+ }
181
+ async function resolveExistingPrefix(inputPath) {
182
+ let existingPath = inputPath;
183
+ const missingSegments = [];
184
+ while (await lstatIfExists(existingPath) == null) {
185
+ const parent = path.posix.dirname(existingPath);
186
+ const segment = path.posix.basename(existingPath);
187
+ if (parent === existingPath || segment === ".." || segment === ".") throw new Error(`Unable to resolve path ${JSON.stringify(inputPath)}.`);
188
+ missingSegments.unshift(segment);
189
+ existingPath = parent;
190
+ }
191
+ return path.posix.join(await realpath(existingPath), ...missingSegments);
192
+ }
193
+ async function lstatIfExists(entryPath) {
194
+ try {
195
+ return await lstat(entryPath);
196
+ } catch (error) {
197
+ if (error != null && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
198
+ throw error;
199
+ }
200
+ }
75
201
  const DEBUG_LEVEL_WEIGHT = {
76
202
  error: 0,
77
203
  warn: 1,
@@ -1917,7 +2043,35 @@ function toOpenCodePromptParts(prompt) {
1917
2043
  }
1918
2044
  //#endregion
1919
2045
  //#region src/bridge/permission-paths.ts
2046
+ const OPENCODE_WRITE_PROTECTED_PATHS = [
2047
+ ".agents/skills",
2048
+ ".opencode",
2049
+ "opencode.json",
2050
+ "opencode.jsonc",
2051
+ ".claude/skills"
2052
+ ];
1920
2053
  async function areOpenCodePermissionPathsTrusted(options) {
2054
+ const resolved = resolveOpenCodePermissionTargets(options);
2055
+ if (resolved == null) return false;
2056
+ return areFileToolPathsTrusted({
2057
+ workDir: options.workDir,
2058
+ cwd: options.workDir,
2059
+ paths: resolved.targets,
2060
+ access: resolved.access,
2061
+ readableSkillRoots: options.readableSkillRoots
2062
+ });
2063
+ }
2064
+ async function areOpenCodePermissionPathsWriteProtected(options) {
2065
+ const resolved = resolveOpenCodePermissionTargets(options);
2066
+ if (resolved == null) return true;
2067
+ if (resolved.access !== "write") return false;
2068
+ return isWriteProtectedPath({
2069
+ workDir: options.workDir,
2070
+ paths: resolved.targets,
2071
+ writeProtectedPaths: OPENCODE_WRITE_PROTECTED_PATHS
2072
+ });
2073
+ }
2074
+ function resolveOpenCodePermissionTargets(options) {
1921
2075
  const args = options.toolCall?.input;
1922
2076
  const nativeName = options.toolCall?.nativeName;
1923
2077
  const access = ["edit", "write"].includes(options.action) || [
@@ -1927,7 +2081,7 @@ async function areOpenCodePermissionPathsTrusted(options) {
1927
2081
  ].includes(nativeName ?? "") ? "write" : "read";
1928
2082
  let targets;
1929
2083
  if (Array.isArray(options.metadata?.files)) {
1930
- if (options.metadata.files.length === 0) return false;
2084
+ if (options.metadata.files.length === 0) return void 0;
1931
2085
  targets = options.metadata.files.flatMap((value) => {
1932
2086
  if (value == null || typeof value !== "object") return [void 0];
1933
2087
  const file = value;
@@ -1948,15 +2102,12 @@ async function areOpenCodePermissionPathsTrusted(options) {
1948
2102
  else if (typeof options.metadata?.filepath === "string" && options.action !== "edit") targets = [options.metadata.filepath];
1949
2103
  else if (options.action === "edit" && typeof options.metadata?.filepath === "string" && path.posix.isAbsolute(options.metadata.filepath)) targets = [options.metadata.filepath];
1950
2104
  else if (options.action === "read" && options.resources.length > 0 && options.resources.every((value) => path.posix.isAbsolute(value))) targets = options.resources;
1951
- else return false;
1952
- if (!targets.every((value) => typeof value === "string")) return false;
1953
- return areFileToolPathsTrusted({
1954
- workDir: options.workDir,
1955
- cwd: options.workDir,
1956
- paths: targets,
2105
+ else return;
2106
+ if (!targets.every((value) => typeof value === "string")) return void 0;
2107
+ return {
1957
2108
  access,
1958
- readableSkillRoots: options.readableSkillRoots
1959
- });
2109
+ targets
2110
+ };
1960
2111
  }
1961
2112
  async function areFileToolPathsTrusted(options) {
1962
2113
  if (options.paths.length === 0) return false;
@@ -3110,14 +3261,16 @@ async function selectPermissionReply({ context, sessionId, toolCall, metadata, a
3110
3261
  "ls"
3111
3262
  ].includes(toolName);
3112
3263
  const kind = action === "external_directory" && nativeName ? nativeName === "apply_patch" ? "edit" : TOOL_KIND[toWireToolName(nativeName)] ?? "bash" : TOOL_KIND[toolName] ?? "bash";
3113
- if ((permissionMode === "allow-edits" ? kind === "readonly" || kind === "edit" : kind === "readonly") && (!filePermission || await areOpenCodePermissionPathsTrusted({
3264
+ const allowed = permissionMode === "allow-edits" ? kind === "readonly" || kind === "edit" : kind === "readonly";
3265
+ const permissionPathOptions = {
3114
3266
  action,
3115
3267
  resources,
3116
3268
  metadata,
3117
3269
  toolCall,
3118
3270
  workDir: workdir,
3119
3271
  readableSkillRoots: context.readableSkillRoots
3120
- }))) return { reply: "once" };
3272
+ };
3273
+ if (allowed && (!filePermission || await areOpenCodePermissionPathsTrusted(permissionPathOptions) && !await areOpenCodePermissionPathsWriteProtected(permissionPathOptions))) return { reply: "once" };
3121
3274
  const decision = await requestApproval();
3122
3275
  return decision.approved ? { reply: "once" } : {
3123
3276
  reply: "reject",