@tanstack/ai-sandbox 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/dist/esm/agents-file.js +53 -34
  2. package/dist/esm/agents-file.js.map +1 -1
  3. package/dist/esm/align.d.ts +121 -0
  4. package/dist/esm/align.js +197 -0
  5. package/dist/esm/align.js.map +1 -0
  6. package/dist/esm/approvals.js +63 -29
  7. package/dist/esm/approvals.js.map +1 -1
  8. package/dist/esm/attach-preflight.d.ts +85 -0
  9. package/dist/esm/attach-preflight.js +189 -0
  10. package/dist/esm/attach-preflight.js.map +1 -0
  11. package/dist/esm/bootstrap.js +103 -117
  12. package/dist/esm/bootstrap.js.map +1 -1
  13. package/dist/esm/bridge-events.js +96 -71
  14. package/dist/esm/bridge-events.js.map +1 -1
  15. package/dist/esm/capabilities.d.ts +0 -5
  16. package/dist/esm/capabilities.js +32 -28
  17. package/dist/esm/capabilities.js.map +1 -1
  18. package/dist/esm/chunk-identity.d.ts +52 -0
  19. package/dist/esm/chunk-identity.js +102 -0
  20. package/dist/esm/chunk-identity.js.map +1 -0
  21. package/dist/esm/claim.d.ts +187 -0
  22. package/dist/esm/claim.js +349 -0
  23. package/dist/esm/claim.js.map +1 -0
  24. package/dist/esm/contracts.d.ts +13 -0
  25. package/dist/esm/driver.d.ts +83 -0
  26. package/dist/esm/driver.js +138 -0
  27. package/dist/esm/driver.js.map +1 -0
  28. package/dist/esm/durability.d.ts +263 -0
  29. package/dist/esm/durability.js +230 -0
  30. package/dist/esm/durability.js.map +1 -0
  31. package/dist/esm/errors.js +28 -24
  32. package/dist/esm/errors.js.map +1 -1
  33. package/dist/esm/file-diff.js +151 -135
  34. package/dist/esm/file-diff.js.map +1 -1
  35. package/dist/esm/git-exec.js +51 -62
  36. package/dist/esm/git-exec.js.map +1 -1
  37. package/dist/esm/harness-cwd.js +24 -19
  38. package/dist/esm/harness-cwd.js.map +1 -1
  39. package/dist/esm/index.d.ts +30 -8
  40. package/dist/esm/index.js +23 -91
  41. package/dist/esm/instance-store.d.ts +88 -0
  42. package/dist/esm/instance-store.js +67 -0
  43. package/dist/esm/instance-store.js.map +1 -0
  44. package/dist/esm/journal-bytes.d.ts +67 -0
  45. package/dist/esm/journal-bytes.js +110 -0
  46. package/dist/esm/journal-bytes.js.map +1 -0
  47. package/dist/esm/journal-reader.d.ts +66 -0
  48. package/dist/esm/journal-reader.js +228 -0
  49. package/dist/esm/journal-reader.js.map +1 -0
  50. package/dist/esm/journal-sweep.d.ts +113 -0
  51. package/dist/esm/journal-sweep.js +309 -0
  52. package/dist/esm/journal-sweep.js.map +1 -0
  53. package/dist/esm/journal.d.ts +542 -0
  54. package/dist/esm/journal.js +679 -0
  55. package/dist/esm/journal.js.map +1 -0
  56. package/dist/esm/key.js +36 -33
  57. package/dist/esm/key.js.map +1 -1
  58. package/dist/esm/middleware.d.ts +50 -2
  59. package/dist/esm/middleware.js +335 -208
  60. package/dist/esm/middleware.js.map +1 -1
  61. package/dist/esm/ngrok.js +75 -49
  62. package/dist/esm/ngrok.js.map +1 -1
  63. package/dist/esm/policy.js +43 -34
  64. package/dist/esm/policy.js.map +1 -1
  65. package/dist/esm/projection.js +16 -8
  66. package/dist/esm/projection.js.map +1 -1
  67. package/dist/esm/reap.d.ts +238 -0
  68. package/dist/esm/reap.js +355 -0
  69. package/dist/esm/reap.js.map +1 -0
  70. package/dist/esm/reclaim.d.ts +84 -0
  71. package/dist/esm/reclaim.js +106 -0
  72. package/dist/esm/reclaim.js.map +1 -0
  73. package/dist/esm/remote-tools.js +73 -62
  74. package/dist/esm/remote-tools.js.map +1 -1
  75. package/dist/esm/run.d.ts +93 -25
  76. package/dist/esm/run.js +274 -79
  77. package/dist/esm/run.js.map +1 -1
  78. package/dist/esm/runner.d.ts +119 -2
  79. package/dist/esm/runner.js +270 -51
  80. package/dist/esm/runner.js.map +1 -1
  81. package/dist/esm/sandbox.d.ts +3 -2
  82. package/dist/esm/sandbox.js +139 -123
  83. package/dist/esm/sandbox.js.map +1 -1
  84. package/dist/esm/secrets.js +39 -47
  85. package/dist/esm/secrets.js.map +1 -1
  86. package/dist/esm/setup-plan.js +22 -14
  87. package/dist/esm/setup-plan.js.map +1 -1
  88. package/dist/esm/shell.d.ts +8 -0
  89. package/dist/esm/shell.js +197 -158
  90. package/dist/esm/shell.js.map +1 -1
  91. package/dist/esm/testkit/conformance.d.ts +16 -0
  92. package/dist/esm/testkit/conformance.js +97 -0
  93. package/dist/esm/testkit/conformance.js.map +1 -0
  94. package/dist/esm/testkit/durable-run-fields-conformance.d.ts +4 -0
  95. package/dist/esm/testkit/durable-run-fields-conformance.js +95 -0
  96. package/dist/esm/testkit/durable-run-fields-conformance.js.map +1 -0
  97. package/dist/esm/testkit/journal-conformance.d.ts +51 -0
  98. package/dist/esm/testkit/journal-conformance.js +378 -0
  99. package/dist/esm/testkit/journal-conformance.js.map +1 -0
  100. package/dist/esm/testkit/reaper-conformance.d.ts +37 -0
  101. package/dist/esm/testkit/reaper-conformance.js +847 -0
  102. package/dist/esm/testkit/reaper-conformance.js.map +1 -0
  103. package/dist/esm/testkit/shell-spawn.d.ts +2 -0
  104. package/dist/esm/testkit/shell-spawn.js +60 -0
  105. package/dist/esm/testkit/shell-spawn.js.map +1 -0
  106. package/dist/esm/testkit/takeover-conformance.d.ts +24 -0
  107. package/dist/esm/testkit/takeover-conformance.js +685 -0
  108. package/dist/esm/testkit/takeover-conformance.js.map +1 -0
  109. package/dist/esm/tool-bridge.js +227 -180
  110. package/dist/esm/tool-bridge.js.map +1 -1
  111. package/dist/esm/tool-history.d.ts +62 -0
  112. package/dist/esm/tool-history.js +171 -0
  113. package/dist/esm/tool-history.js.map +1 -0
  114. package/dist/esm/watch.js +310 -236
  115. package/dist/esm/watch.js.map +1 -1
  116. package/dist/esm/workspace.d.ts +1 -1
  117. package/dist/esm/workspace.js +49 -28
  118. package/dist/esm/workspace.js.map +1 -1
  119. package/package.json +16 -6
  120. package/skills/ai-sandbox/SKILL.md +658 -20
  121. package/src/align.ts +297 -0
  122. package/src/attach-preflight.ts +292 -0
  123. package/src/capabilities.ts +4 -13
  124. package/src/chunk-identity.ts +154 -0
  125. package/src/claim.ts +479 -0
  126. package/src/contracts.ts +13 -0
  127. package/src/driver.ts +205 -0
  128. package/src/durability.ts +380 -0
  129. package/src/index.ts +212 -27
  130. package/src/instance-store.ts +122 -0
  131. package/src/journal-bytes.ts +136 -0
  132. package/src/journal-reader.ts +359 -0
  133. package/src/journal-sweep.ts +406 -0
  134. package/src/journal.ts +875 -0
  135. package/src/middleware.ts +470 -30
  136. package/src/reap.ts +723 -0
  137. package/src/reclaim.ts +191 -0
  138. package/src/run.ts +365 -75
  139. package/src/runner.ts +347 -3
  140. package/src/sandbox.ts +38 -8
  141. package/src/shell.ts +106 -38
  142. package/src/testkit/conformance.ts +117 -0
  143. package/src/testkit/durable-run-fields-conformance.ts +147 -0
  144. package/src/testkit/journal-conformance.ts +676 -0
  145. package/src/testkit/reaper-conformance.ts +1201 -0
  146. package/src/testkit/shell-spawn.ts +67 -0
  147. package/src/testkit/takeover-conformance.ts +1040 -0
  148. package/src/tool-history.ts +245 -0
  149. package/src/workspace.ts +1 -1
  150. package/dist/esm/index.js.map +0 -1
  151. package/dist/esm/run-log.d.ts +0 -81
  152. package/dist/esm/run-log.js +0 -107
  153. package/dist/esm/run-log.js.map +0 -1
  154. package/dist/esm/store.d.ts +0 -53
  155. package/dist/esm/store.js +0 -34
  156. package/dist/esm/store.js.map +0 -1
  157. package/src/run-log.ts +0 -224
  158. package/src/store.ts +0 -83
@@ -1 +1 @@
1
- {"version":3,"file":"tool-bridge.js","sources":["../../src/tool-bridge.ts"],"sourcesContent":["/**\n * MCP tool-proxy bridge, shared by all harness adapters.\n *\n * Exposes chat()-provided server tools to an in-sandbox agent as an MCP server.\n * The agent (inside the sandbox) calls `mcp__tanstack__<tool>`; the call is\n * proxied OUT to a bridge endpoint, where the tool's `execute()` runs in the\n * orchestrator process (with its closures / DB / secrets), and the result is\n * returned into the sandbox.\n *\n * The bridge is split into a transport-agnostic CORE and a TRANSPORT:\n * - {@link createToolBridgeCore} owns tool dispatch + the permission resolver\n * (no I/O). It is what makes the bridge portable.\n * - {@link startHostToolBridge} is the `node:http` transport for a long-running\n * host (laptop / CI / Docker orchestrator). It binds loopback unless the\n * sandbox must reach it via `host.docker.internal`, and authenticates with a\n * constant-time bearer check.\n * - A serverless/edge orchestrator (e.g. a Durable Object) instead serves the\n * SAME core from its own `fetch` handler — no raw TCP listener — see\n * {@link handleBridgeJsonRpc} and the Cloudflare example.\n */\nimport { createServer } from 'node:http'\nimport { randomBytes, timingSafeEqual } from 'node:crypto'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { AddressInfo } from 'node:net'\nimport type { AnyTool } from '@tanstack/ai'\n\n/**\n * Name of the bridged MCP server. The agent sees tools as\n * `mcp__tanstack__<tool>`; each adapter's stream translator strips this prefix\n * so tool-call events match the names the application registered.\n */\nexport const BRIDGED_MCP_SERVER_NAME = 'tanstack'\n\n/** Hostname the sandbox uses to reach the bridge endpoint, per provider. */\nexport function hostForSandbox(provider: string): string {\n return provider === 'docker' ? 'host.docker.internal' : '127.0.0.1'\n}\n\n/** Result of a permission decision returned to the harness's prompt tool. */\nexport interface PermissionToolResult {\n behavior: 'allow' | 'deny'\n message?: string\n updatedInput?: unknown\n}\n\nexport interface BridgePermission {\n toolName: string\n resolve: (input: {\n tool_name?: string\n input?: unknown\n }) => PermissionToolResult | Promise<PermissionToolResult>\n}\n\nexport interface ToolBridgeCoreOptions {\n /** Runtime context forwarded to each tool's `execute()`. */\n context?: unknown\n /** Abort signal forwarded to each tool's `execute()`. */\n signal?: AbortSignal\n /**\n * Forwarded to each tool's `execute()` so a bridged tool can stream progress /\n * custom events back to the client mid-execution (e.g. code mode's\n * `code_mode:console` logs). Without it those events are silently dropped — the\n * bridge runs out-of-band from the main tool executor, so the executor's own\n * `emitCustomEvent` never reaches a bridged tool. The harness adapter supplies\n * one that injects a CUSTOM chunk into its live output stream.\n */\n emitCustomEvent?: (eventName: string, value: Record<string, unknown>) => void\n /**\n * Optional permission-prompt tool (e.g. for Claude Code's\n * `--permission-prompt-tool`). When set, the bridge exposes an extra MCP tool\n * `<name>` whose handler returns the orchestrator's allow/deny decision.\n */\n permission?: BridgePermission\n}\n\n/** An MCP tool descriptor as advertised to the in-sandbox agent. */\nexport interface ToolDescriptor {\n name: string\n description?: string\n inputSchema: { type: 'object'; [key: string]: unknown }\n}\n\n/**\n * Coerce a tool's `inputSchema` into the object-schema shape MCP advertises,\n * substituting an empty object schema when it isn't already a JSON-schema object\n * (project rule: a guard, not an `as` cast).\n */\nfunction toObjectSchema(schema: unknown): {\n type: 'object'\n [key: string]: unknown\n} {\n if (\n schema !== null &&\n typeof schema === 'object' &&\n 'type' in schema &&\n schema.type === 'object'\n ) {\n return { ...schema, type: 'object' }\n }\n return { type: 'object', properties: {} }\n}\n\n/** MCP `tools/call` result shape. */\nexport interface ToolCallResult {\n content: Array<{ type: 'text'; text: string }>\n isError?: boolean\n}\n\n/**\n * Transport-agnostic bridge logic: list tools, and dispatch a tool/permission\n * call. No sockets, no auth — a transport ({@link startHostToolBridge} or a\n * `fetch` handler) wraps this and owns I/O + the bearer check.\n */\nexport interface ToolBridgeCore {\n listTools: () => Array<ToolDescriptor>\n callTool: (name: string, args: unknown) => Promise<ToolCallResult>\n}\n\n/** Build the transport-agnostic bridge core for the given tools. */\nexport function createToolBridgeCore(\n tools: Array<AnyTool>,\n options: ToolBridgeCoreOptions = {},\n): ToolBridgeCore {\n const toolsByName = new Map(tools.map((tool) => [tool.name, tool]))\n const permission = options.permission\n\n const permissionDescriptor: ToolDescriptor | undefined = permission\n ? {\n name: permission.toolName,\n description:\n 'Permission prompt: returns {behavior:\"allow\"|\"deny\"} for a requested action.',\n inputSchema: { type: 'object', properties: {} },\n }\n : undefined\n\n return {\n listTools() {\n return [\n ...tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: toObjectSchema(tool.inputSchema),\n })),\n ...(permissionDescriptor ? [permissionDescriptor] : []),\n ]\n },\n\n async callTool(name, args) {\n if (permission && name === permission.toolName) {\n const result = await permission.resolve(args ?? {})\n return { content: [{ type: 'text', text: JSON.stringify(result) }] }\n }\n const tool = toolsByName.get(name)\n if (!tool?.execute) throw new Error(`Unknown tool: ${name}`)\n try {\n const result: unknown = await tool.execute(args ?? {}, {\n context: options.context,\n abortSignal: options.signal,\n // No-op default so tools that always call it (e.g. code mode) don't\n // crash when the transport didn't wire a sink.\n emitCustomEvent: options.emitCustomEvent ?? (() => {}),\n })\n const text =\n typeof result === 'string' ? result : JSON.stringify(result)\n return { content: [{ type: 'text', text }] }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n isError: true,\n content: [\n { type: 'text', text: `Tool execution failed: ${message}` },\n ],\n }\n }\n },\n }\n}\n\n/**\n * Minimal JSON-RPC dispatcher over a {@link ToolBridgeCore}, so a `fetch`-based\n * transport (Worker / Durable Object) can serve MCP `initialize` / `tools/list`\n * / `tools/call` without the node-specific HTTP transport. Returns the JSON-RPC\n * response object, or `null` for a notification (no `id`).\n */\nexport async function handleBridgeJsonRpc(\n core: ToolBridgeCore,\n message: unknown,\n): Promise<unknown> {\n if (message === null || typeof message !== 'object') {\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: 'Invalid Request' },\n }\n }\n const rpc = message as { id?: unknown; method?: unknown; params?: unknown }\n const id = rpc.id ?? null\n const respond = (result: unknown): unknown => ({ jsonrpc: '2.0', id, result })\n switch (rpc.method) {\n case 'initialize':\n return respond({\n protocolVersion: '2024-11-05',\n capabilities: { tools: {} },\n serverInfo: { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },\n })\n case 'notifications/initialized':\n return null\n case 'tools/list':\n return respond({ tools: core.listTools() })\n case 'tools/call': {\n const params = (rpc.params ?? {}) as {\n name?: unknown\n arguments?: unknown\n }\n if (typeof params.name !== 'string') {\n return {\n jsonrpc: '2.0',\n id,\n error: { code: -32602, message: 'Invalid params: name' },\n }\n }\n return respond(await core.callTool(params.name, params.arguments ?? {}))\n }\n default:\n return {\n jsonrpc: '2.0',\n id,\n error: { code: -32601, message: 'Method not found' },\n }\n }\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <token>` header against the\n * expected token. Length mismatch returns false early (token length is not\n * secret); equal-length comparison is timing-safe.\n */\nexport function timingSafeBearerEqual(\n header: string | undefined,\n token: string,\n): boolean {\n if (header === undefined) return false\n const a = Buffer.from(header)\n const b = Buffer.from(`Bearer ${token}`)\n if (a.length !== b.length) return false\n return timingSafeEqual(a, b)\n}\n\nexport interface HostToolBridge {\n /** MCP server name; tools appear to the agent as `mcp__<name>__<tool>`. */\n name: string\n /** URL the SANDBOX uses to reach this bridge. */\n url: string\n /** Per-run bearer token gating the endpoint. */\n token: string\n close: () => Promise<void>\n}\n\nexport interface StartBridgeOptions extends ToolBridgeCoreOptions {\n /** Hostname the sandbox uses to reach the host (e.g. `host.docker.internal`). */\n hostForSandbox: string\n /**\n * Address to bind the listener to. Defaults to `127.0.0.1` (loopback) and is\n * widened to `0.0.0.0` only when the sandbox reaches the host via\n * `host.docker.internal` (a container can't reach the host's loopback).\n */\n bindAddress?: string\n}\n\nfunction buildMcpServer(core: ToolBridgeCore): McpServer {\n const server = new McpServer(\n { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },\n { capabilities: { tools: {} } },\n )\n server.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: core.listTools(),\n }))\n server.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const result = await core.callTool(\n request.params.name,\n request.params.arguments ?? {},\n )\n return {\n content: result.content,\n ...(result.isError ? { isError: true } : {}),\n }\n })\n return server\n}\n\n/**\n * Start the `node:http` MCP tool-proxy bridge for the given tools. For a\n * long-running host (laptop / CI / Docker orchestrator). Serverless/edge\n * orchestrators serve {@link createToolBridgeCore} from their own `fetch`\n * handler instead.\n */\nexport async function startHostToolBridge(\n tools: Array<AnyTool>,\n options: StartBridgeOptions,\n): Promise<HostToolBridge> {\n const token = randomBytes(24).toString('hex')\n const core = createToolBridgeCore(tools, options)\n // Loopback by default; widen to all interfaces only for the Docker bridge,\n // which a container reaches via host.docker.internal (host gateway).\n const bindAddress =\n options.bindAddress ??\n (options.hostForSandbox === 'host.docker.internal'\n ? '0.0.0.0'\n : '127.0.0.1')\n\n const httpServer = createServer((req, res) => {\n void (async () => {\n if (!timingSafeBearerEqual(req.headers['authorization'], token)) {\n res.writeHead(401).end('unauthorized')\n return\n }\n const server = buildMcpServer(core)\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n })\n res.on('close', () => {\n void transport.close()\n void server.close()\n })\n await server.connect(transport)\n\n let body = ''\n for await (const chunk of req) body += chunk\n let parsed: unknown\n try {\n parsed = body ? JSON.parse(body) : undefined\n } catch {\n // Malformed agent request → 400, distinct from an internal 500.\n if (!res.headersSent) res.writeHead(400).end('invalid JSON body')\n return\n }\n await transport.handleRequest(req, res, parsed)\n })().catch((error: unknown) => {\n // Log the underlying fault — on the host/Docker path there is no run-log\n // capturing it, so swallowing it leaves an operator with nothing.\n console.error('[tool-bridge] request handler failed:', error)\n if (!res.headersSent) res.writeHead(500).end('bridge error')\n })\n })\n\n await new Promise<void>((resolve) =>\n httpServer.listen(0, bindAddress, resolve),\n )\n const port = (httpServer.address() as AddressInfo).port\n const url = `http://${options.hostForSandbox}:${port}/mcp`\n\n return {\n name: BRIDGED_MCP_SERVER_NAME,\n url,\n token,\n close: () =>\n new Promise<void>((resolve) => httpServer.close(() => resolve())),\n }\n}\n\n/** A provisioned, reachable bridge endpoint (same shape as {@link HostToolBridge}). */\nexport type ProvisionedBridge = HostToolBridge\n\nexport interface ToolBridgeProvisionOptions extends ToolBridgeCoreOptions {\n /** Sandbox provider name, to derive how the sandbox reaches the bridge. */\n provider: string\n}\n\n/**\n * Stands up the tool-bridge endpoint for a run. The seam that makes the bridge\n * portable across runtimes: a harness adapter asks its capability context for a\n * provisioner and uses {@link nodeHttpBridgeProvisioner} as the default (host /\n * Docker). A serverless/edge orchestrator PROVIDES its own — e.g. a Durable\n * Object that mounts {@link createToolBridgeCore} / {@link handleBridgeJsonRpc}\n * on its `fetch` handler and returns a sandbox-reachable URL — so no raw TCP\n * listener is needed.\n */\nexport interface ToolBridgeProvisioner {\n provision: (\n tools: Array<AnyTool>,\n options: ToolBridgeProvisionOptions,\n ) => Promise<ProvisionedBridge>\n}\n\n/** Default provisioner: a `node:http` listener on the host. */\nexport const nodeHttpBridgeProvisioner: ToolBridgeProvisioner = {\n provision(tools, options) {\n const { provider, ...core } = options\n return startHostToolBridge(tools, {\n hostForSandbox: hostForSandbox(provider),\n ...core,\n })\n },\n}\n"],"names":[],"mappings":";;;;;AAoCO,MAAM,0BAA0B;AAGhC,SAAS,eAAe,UAA0B;AACvD,SAAO,aAAa,WAAW,yBAAyB;AAC1D;AAmDA,SAAS,eAAe,QAGtB;AACA,MACE,WAAW,QACX,OAAO,WAAW,YAClB,UAAU,UACV,OAAO,SAAS,UAChB;AACA,WAAO,EAAE,GAAG,QAAQ,MAAM,SAAA;AAAA,EAC5B;AACA,SAAO,EAAE,MAAM,UAAU,YAAY,CAAA,EAAC;AACxC;AAmBO,SAAS,qBACd,OACA,UAAiC,IACjB;AAChB,QAAM,cAAc,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAClE,QAAM,aAAa,QAAQ;AAE3B,QAAM,uBAAmD,aACrD;AAAA,IACE,MAAM,WAAW;AAAA,IACjB,aACE;AAAA,IACF,aAAa,EAAE,MAAM,UAAU,YAAY,CAAA,EAAC;AAAA,EAAE,IAEhD;AAEJ,SAA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YAAa,KAAI,UAAU,GAAG,EAAE,IAAI,mBAAmB;AAChE;AAAA,MACF;AACA,YAAM,UAAU,cAAc,KAAK,KAAK,MAAM;AAAA,IAChD,GAAA,EAAK,MAAM,CAAC,UAAmB;AAG7B,cAAQ,MAAM,yCAAyC,KAAK;AAC5D,UAAI,CAAC,IAAI,YAAa,KAAI,UAAU,GAAG,EAAE,IAAI,cAAc;AAAA,IAC7D,CAAC;AAAA,EACH,CAAC;AAED,QAAM,IAAI;AAAA,IAAc,CAAC,YACvB,WAAW,OAAO,GAAG,aAAa,OAAO;AAAA,EAAA;AAE3C,QAAM,OAAQ,WAAW,QAAA,EAA0B;AACnD,QAAM,MAAM,UAAU,QAAQ,cAAc,IAAI,IAAI;AAEpD,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,OAAO,MACL,IAAI,QAAc,CAAC,YAAY,WAAW,MAAM,MAAM,SAAS,CAAC;AAAA,EAAA;AAEtE;AA2BO,MAAM,4BAAmD;AAAA,EAC9D,UAAU,OAAO,SAAS;AACxB,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AAC9B,WAAO,oBAAoB,OAAO;AAAA,MAChC,gBAAgB,eAAe,QAAQ;AAAA,MACvC,GAAG;AAAA,IAAA,CACJ;AAAA,EACH;AACF;"}
1
+ {"version":3,"file":"tool-bridge.js","names":[],"sources":["../../src/tool-bridge.ts"],"sourcesContent":["/**\n * MCP tool-proxy bridge, shared by all harness adapters.\n *\n * Exposes chat()-provided server tools to an in-sandbox agent as an MCP server.\n * The agent (inside the sandbox) calls `mcp__tanstack__<tool>`; the call is\n * proxied OUT to a bridge endpoint, where the tool's `execute()` runs in the\n * orchestrator process (with its closures / DB / secrets), and the result is\n * returned into the sandbox.\n *\n * The bridge is split into a transport-agnostic CORE and a TRANSPORT:\n * - {@link createToolBridgeCore} owns tool dispatch + the permission resolver\n * (no I/O). It is what makes the bridge portable.\n * - {@link startHostToolBridge} is the `node:http` transport for a long-running\n * host (laptop / CI / Docker orchestrator). It binds loopback unless the\n * sandbox must reach it via `host.docker.internal`, and authenticates with a\n * constant-time bearer check.\n * - A serverless/edge orchestrator (e.g. a Durable Object) instead serves the\n * SAME core from its own `fetch` handler — no raw TCP listener — see\n * {@link handleBridgeJsonRpc} and the Cloudflare example.\n */\nimport { createServer } from 'node:http'\nimport { randomBytes, timingSafeEqual } from 'node:crypto'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { AddressInfo } from 'node:net'\nimport type { AnyTool } from '@tanstack/ai'\n\n/**\n * Name of the bridged MCP server. The agent sees tools as\n * `mcp__tanstack__<tool>`; each adapter's stream translator strips this prefix\n * so tool-call events match the names the application registered.\n */\nexport const BRIDGED_MCP_SERVER_NAME = 'tanstack'\n\n/** Hostname the sandbox uses to reach the bridge endpoint, per provider. */\nexport function hostForSandbox(provider: string): string {\n return provider === 'docker' ? 'host.docker.internal' : '127.0.0.1'\n}\n\n/** Result of a permission decision returned to the harness's prompt tool. */\nexport interface PermissionToolResult {\n behavior: 'allow' | 'deny'\n message?: string\n updatedInput?: unknown\n}\n\nexport interface BridgePermission {\n toolName: string\n resolve: (input: {\n tool_name?: string\n input?: unknown\n }) => PermissionToolResult | Promise<PermissionToolResult>\n}\n\nexport interface ToolBridgeCoreOptions {\n /** Runtime context forwarded to each tool's `execute()`. */\n context?: unknown\n /** Abort signal forwarded to each tool's `execute()`. */\n signal?: AbortSignal\n /**\n * Forwarded to each tool's `execute()` so a bridged tool can stream progress /\n * custom events back to the client mid-execution (e.g. code mode's\n * `code_mode:console` logs). Without it those events are silently dropped — the\n * bridge runs out-of-band from the main tool executor, so the executor's own\n * `emitCustomEvent` never reaches a bridged tool. The harness adapter supplies\n * one that injects a CUSTOM chunk into its live output stream.\n */\n emitCustomEvent?: (eventName: string, value: Record<string, unknown>) => void\n /**\n * Optional permission-prompt tool (e.g. for Claude Code's\n * `--permission-prompt-tool`). When set, the bridge exposes an extra MCP tool\n * `<name>` whose handler returns the orchestrator's allow/deny decision.\n */\n permission?: BridgePermission\n}\n\n/** An MCP tool descriptor as advertised to the in-sandbox agent. */\nexport interface ToolDescriptor {\n name: string\n description?: string\n inputSchema: { type: 'object'; [key: string]: unknown }\n}\n\n/**\n * Coerce a tool's `inputSchema` into the object-schema shape MCP advertises,\n * substituting an empty object schema when it isn't already a JSON-schema object\n * (project rule: a guard, not an `as` cast).\n */\nfunction toObjectSchema(schema: unknown): {\n type: 'object'\n [key: string]: unknown\n} {\n if (\n schema !== null &&\n typeof schema === 'object' &&\n 'type' in schema &&\n schema.type === 'object'\n ) {\n return { ...schema, type: 'object' }\n }\n return { type: 'object', properties: {} }\n}\n\n/** MCP `tools/call` result shape. */\nexport interface ToolCallResult {\n content: Array<{ type: 'text'; text: string }>\n isError?: boolean\n}\n\n/**\n * Transport-agnostic bridge logic: list tools, and dispatch a tool/permission\n * call. No sockets, no auth — a transport ({@link startHostToolBridge} or a\n * `fetch` handler) wraps this and owns I/O + the bearer check.\n */\nexport interface ToolBridgeCore {\n listTools: () => Array<ToolDescriptor>\n callTool: (name: string, args: unknown) => Promise<ToolCallResult>\n}\n\n/** Build the transport-agnostic bridge core for the given tools. */\nexport function createToolBridgeCore(\n tools: Array<AnyTool>,\n options: ToolBridgeCoreOptions = {},\n): ToolBridgeCore {\n const toolsByName = new Map(tools.map((tool) => [tool.name, tool]))\n const permission = options.permission\n\n const permissionDescriptor: ToolDescriptor | undefined = permission\n ? {\n name: permission.toolName,\n description:\n 'Permission prompt: returns {behavior:\"allow\"|\"deny\"} for a requested action.',\n inputSchema: { type: 'object', properties: {} },\n }\n : undefined\n\n return {\n listTools() {\n return [\n ...tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: toObjectSchema(tool.inputSchema),\n })),\n ...(permissionDescriptor ? [permissionDescriptor] : []),\n ]\n },\n\n async callTool(name, args) {\n if (permission && name === permission.toolName) {\n const result = await permission.resolve(args ?? {})\n return { content: [{ type: 'text', text: JSON.stringify(result) }] }\n }\n const tool = toolsByName.get(name)\n if (!tool?.execute) throw new Error(`Unknown tool: ${name}`)\n try {\n const result: unknown = await tool.execute(args ?? {}, {\n context: options.context,\n abortSignal: options.signal,\n // No-op default so tools that always call it (e.g. code mode) don't\n // crash when the transport didn't wire a sink.\n emitCustomEvent: options.emitCustomEvent ?? (() => {}),\n })\n const text =\n typeof result === 'string' ? result : JSON.stringify(result)\n return { content: [{ type: 'text', text }] }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n isError: true,\n content: [\n { type: 'text', text: `Tool execution failed: ${message}` },\n ],\n }\n }\n },\n }\n}\n\n/**\n * Minimal JSON-RPC dispatcher over a {@link ToolBridgeCore}, so a `fetch`-based\n * transport (Worker / Durable Object) can serve MCP `initialize` / `tools/list`\n * / `tools/call` without the node-specific HTTP transport. Returns the JSON-RPC\n * response object, or `null` for a notification (no `id`).\n */\nexport async function handleBridgeJsonRpc(\n core: ToolBridgeCore,\n message: unknown,\n): Promise<unknown> {\n if (message === null || typeof message !== 'object') {\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: 'Invalid Request' },\n }\n }\n const rpc = message as { id?: unknown; method?: unknown; params?: unknown }\n const id = rpc.id ?? null\n const respond = (result: unknown): unknown => ({ jsonrpc: '2.0', id, result })\n switch (rpc.method) {\n case 'initialize':\n return respond({\n protocolVersion: '2024-11-05',\n capabilities: { tools: {} },\n serverInfo: { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },\n })\n case 'notifications/initialized':\n return null\n case 'tools/list':\n return respond({ tools: core.listTools() })\n case 'tools/call': {\n const params = (rpc.params ?? {}) as {\n name?: unknown\n arguments?: unknown\n }\n if (typeof params.name !== 'string') {\n return {\n jsonrpc: '2.0',\n id,\n error: { code: -32602, message: 'Invalid params: name' },\n }\n }\n return respond(await core.callTool(params.name, params.arguments ?? {}))\n }\n default:\n return {\n jsonrpc: '2.0',\n id,\n error: { code: -32601, message: 'Method not found' },\n }\n }\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <token>` header against the\n * expected token. Length mismatch returns false early (token length is not\n * secret); equal-length comparison is timing-safe.\n */\nexport function timingSafeBearerEqual(\n header: string | undefined,\n token: string,\n): boolean {\n if (header === undefined) return false\n const a = Buffer.from(header)\n const b = Buffer.from(`Bearer ${token}`)\n if (a.length !== b.length) return false\n return timingSafeEqual(a, b)\n}\n\nexport interface HostToolBridge {\n /** MCP server name; tools appear to the agent as `mcp__<name>__<tool>`. */\n name: string\n /** URL the SANDBOX uses to reach this bridge. */\n url: string\n /** Per-run bearer token gating the endpoint. */\n token: string\n close: () => Promise<void>\n}\n\nexport interface StartBridgeOptions extends ToolBridgeCoreOptions {\n /** Hostname the sandbox uses to reach the host (e.g. `host.docker.internal`). */\n hostForSandbox: string\n /**\n * Address to bind the listener to. Defaults to `127.0.0.1` (loopback) and is\n * widened to `0.0.0.0` only when the sandbox reaches the host via\n * `host.docker.internal` (a container can't reach the host's loopback).\n */\n bindAddress?: string\n}\n\nfunction buildMcpServer(core: ToolBridgeCore): McpServer {\n const server = new McpServer(\n { name: BRIDGED_MCP_SERVER_NAME, version: '1.0.0' },\n { capabilities: { tools: {} } },\n )\n server.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: core.listTools(),\n }))\n server.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const result = await core.callTool(\n request.params.name,\n request.params.arguments ?? {},\n )\n return {\n content: result.content,\n ...(result.isError ? { isError: true } : {}),\n }\n })\n return server\n}\n\n/**\n * Start the `node:http` MCP tool-proxy bridge for the given tools. For a\n * long-running host (laptop / CI / Docker orchestrator). Serverless/edge\n * orchestrators serve {@link createToolBridgeCore} from their own `fetch`\n * handler instead.\n */\nexport async function startHostToolBridge(\n tools: Array<AnyTool>,\n options: StartBridgeOptions,\n): Promise<HostToolBridge> {\n const token = randomBytes(24).toString('hex')\n const core = createToolBridgeCore(tools, options)\n // Loopback by default; widen to all interfaces only for the Docker bridge,\n // which a container reaches via host.docker.internal (host gateway).\n const bindAddress =\n options.bindAddress ??\n (options.hostForSandbox === 'host.docker.internal'\n ? '0.0.0.0'\n : '127.0.0.1')\n\n const httpServer = createServer((req, res) => {\n void (async () => {\n if (!timingSafeBearerEqual(req.headers['authorization'], token)) {\n res.writeHead(401).end('unauthorized')\n return\n }\n const server = buildMcpServer(core)\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n })\n res.on('close', () => {\n void transport.close()\n void server.close()\n })\n await server.connect(transport)\n\n let body = ''\n for await (const chunk of req) body += chunk\n let parsed: unknown\n try {\n parsed = body ? JSON.parse(body) : undefined\n } catch {\n // Malformed agent request → 400, distinct from an internal 500.\n if (!res.headersSent) res.writeHead(400).end('invalid JSON body')\n return\n }\n await transport.handleRequest(req, res, parsed)\n })().catch((error: unknown) => {\n // Log the underlying fault — on the host/Docker path there is no run-log\n // capturing it, so swallowing it leaves an operator with nothing.\n console.error('[tool-bridge] request handler failed:', error)\n if (!res.headersSent) res.writeHead(500).end('bridge error')\n })\n })\n\n await new Promise<void>((resolve) =>\n httpServer.listen(0, bindAddress, resolve),\n )\n const port = (httpServer.address() as AddressInfo).port\n const url = `http://${options.hostForSandbox}:${port}/mcp`\n\n return {\n name: BRIDGED_MCP_SERVER_NAME,\n url,\n token,\n close: () =>\n new Promise<void>((resolve) => httpServer.close(() => resolve())),\n }\n}\n\n/** A provisioned, reachable bridge endpoint (same shape as {@link HostToolBridge}). */\nexport type ProvisionedBridge = HostToolBridge\n\nexport interface ToolBridgeProvisionOptions extends ToolBridgeCoreOptions {\n /** Sandbox provider name, to derive how the sandbox reaches the bridge. */\n provider: string\n}\n\n/**\n * Stands up the tool-bridge endpoint for a run. The seam that makes the bridge\n * portable across runtimes: a harness adapter asks its capability context for a\n * provisioner and uses {@link nodeHttpBridgeProvisioner} as the default (host /\n * Docker). A serverless/edge orchestrator PROVIDES its own — e.g. a Durable\n * Object that mounts {@link createToolBridgeCore} / {@link handleBridgeJsonRpc}\n * on its `fetch` handler and returns a sandbox-reachable URL — so no raw TCP\n * listener is needed.\n */\nexport interface ToolBridgeProvisioner {\n provision: (\n tools: Array<AnyTool>,\n options: ToolBridgeProvisionOptions,\n ) => Promise<ProvisionedBridge>\n}\n\n/** Default provisioner: a `node:http` listener on the host. */\nexport const nodeHttpBridgeProvisioner: ToolBridgeProvisioner = {\n provision(tools, options) {\n const { provider, ...core } = options\n return startHostToolBridge(tools, {\n hostForSandbox: hostForSandbox(provider),\n ...core,\n })\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,0BAA0B;;AAGvC,SAAgB,eAAe,UAA0B;CACvD,OAAO,aAAa,WAAW,yBAAyB;AAC1D;;;;;;AAmDA,SAAS,eAAe,QAGtB;CACA,IACE,WAAW,QACX,OAAO,WAAW,YAClB,UAAU,UACV,OAAO,SAAS,UAEhB,OAAO;EAAE,GAAG;EAAQ,MAAM;CAAS;CAErC,OAAO;EAAE,MAAM;EAAU,YAAY,CAAC;CAAE;AAC1C;;AAmBA,SAAgB,qBACd,OACA,UAAiC,CAAC,GAClB;CAChB,MAAM,cAAc,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CAClE,MAAM,aAAa,QAAQ;CAE3B,MAAM,uBAAmD,aACrD;EACE,MAAM,WAAW;EACjB,aACE;EACF,aAAa;GAAE,MAAM;GAAU,YAAY,CAAC;EAAE;CAChD,IACA,KAAA;CAEJ,OAAO;EACL,YAAY;GACV,OAAO,CACL,GAAG,MAAM,KAAK,UAAU;IACtB,MAAM,KAAK;IACX,aAAa,KAAK;IAClB,aAAa,eAAe,KAAK,WAAW;GAC9C,EAAE,GACF,GAAI,uBAAuB,CAAC,oBAAoB,IAAI,CAAC,CACvD;EACF;EA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AAQ;EACvC,GAAG;CACL,CAAC;AACH,EACF"}
@@ -0,0 +1,62 @@
1
+ import { ModelMessage, StreamChunk } from '@tanstack/ai';
2
+ /**
3
+ * What the recorder writes into. `ChatMiddlewareContext.messages` is a
4
+ * `ReadonlyArray`, so the transcript grows by REPLACING the array — the same way the
5
+ * engine itself syncs `middlewareCtx.messages`.
6
+ */
7
+ interface TranscriptTarget {
8
+ messages: ReadonlyArray<ModelMessage>;
9
+ }
10
+ export interface ToolHistoryRecorder {
11
+ /** Feed every chunk. Observes only — never transforms or drops. */
12
+ observe: (chunk: StreamChunk, target: TranscriptTarget) => void;
13
+ /**
14
+ * Re-append anything missing from the transcript.
15
+ *
16
+ * The engine reassigns `middlewareCtx.messages` from its own array whenever it
17
+ * syncs config (once per agent iteration), which discards writes made during the
18
+ * previous iteration's stream. Reconciling at each iteration boundary and again at
19
+ * finish makes the result independent of that, and independent of where this
20
+ * middleware sits relative to persistence in the middleware array.
21
+ */
22
+ reconcile: (target: TranscriptTarget) => void;
23
+ }
24
+ /**
25
+ * True when this tool call was executed by the HARNESS inside the sandbox, and
26
+ * recorded into the transcript for display, rather than executed by the agent loop.
27
+ *
28
+ * Use it to decide what your own `MessageStore` keeps — these calls are display
29
+ * history, so dropping or capping them is safe (they are already stripped from the
30
+ * request to the model on the next turn). Also works on a `tool-call` UI part, whose
31
+ * `metadata` is copied straight from the model message.
32
+ *
33
+ * `metadata` is `unknown` on both, so the key can only be read behind a typeof/`in`
34
+ * check; this mirrors the core `isProviderExecutedToolCall` convention.
35
+ *
36
+ * ```ts
37
+ * import { isSandboxToolCall } from '@tanstack/ai-sandbox'
38
+ *
39
+ * const kept = messages.filter(
40
+ * (message) => !message.toolCalls?.every(isSandboxToolCall),
41
+ * )
42
+ * ```
43
+ */
44
+ export declare function isSandboxToolCall(toolCall: {
45
+ metadata?: unknown;
46
+ } | null | undefined): boolean;
47
+ export declare function createToolHistoryRecorder(): ToolHistoryRecorder;
48
+ /**
49
+ * Drop recorded harness tool calls from a list of messages bound for the model.
50
+ *
51
+ * A stored transcript becomes the history for the NEXT turn. These calls name tools
52
+ * the provider was never given, and one triage-sized run is hundreds of kilobytes of
53
+ * tool output — so replaying them is wasteful at best and rejected at worst. They stay
54
+ * in `ctx.messages` (which is what gets stored and rendered); only the request to the
55
+ * model loses them.
56
+ *
57
+ * An assistant message is dropped only when EVERY call on it is observed, so a mixed
58
+ * message — one engine tool call plus one harness tool call — is left alone rather than
59
+ * silently losing the engine's half.
60
+ */
61
+ export declare function stripObservedToolCalls(messages: ReadonlyArray<ModelMessage>): Array<ModelMessage>;
62
+ export {};
@@ -0,0 +1,171 @@
1
+ import { EventType } from "@tanstack/ai";
2
+ //#region src/tool-history.ts
3
+ /**
4
+ * Turn a harness's PASSTHROUGH tool-call chunks into transcript messages, so a
5
+ * finished run's tool cards survive a reload.
6
+ *
7
+ * Why this is needed at all: a harness executes its tools INSIDE the sandbox, so
8
+ * `chat()` only relays its `TOOL_CALL_*` chunks — it never writes an assistant
9
+ * message for them (`addAssistantToolCallMessage` is gated on the engine having
10
+ * executed the tool itself). Chat persistence stores `ctx.messages`, so the whole
11
+ * tool history existed only in the delivery log. Replaying that log is what makes
12
+ * "switch away and come back" show everything; a FINISHED thread has no run to
13
+ * rejoin, hydrates from the message store instead, and so came back as nothing but
14
+ * the prompt and the final answer.
15
+ *
16
+ * Recording the calls as ordinary `toolCalls` + `role: 'tool'` messages needs no new
17
+ * wire format and no client change: `modelMessagesToUIMessages` already merges a tool
18
+ * result into the call it belongs to and marks the part complete, and
19
+ * `reconstructChat` already runs that converter.
20
+ */
21
+ /**
22
+ * Metadata key set on every tool call recorded here.
23
+ *
24
+ * INTERNAL, and deliberately not exported: an app asks {@link isSandboxToolCall}
25
+ * instead of knowing the key. Renaming it is a storage-visible change, because it ends
26
+ * up inside stored `toolCalls[].metadata`, so the recorder test pins the literal.
27
+ */
28
+ var SANDBOX_OBSERVED = "sandboxObserved";
29
+ /**
30
+ * True when this tool call was executed by the HARNESS inside the sandbox, and
31
+ * recorded into the transcript for display, rather than executed by the agent loop.
32
+ *
33
+ * Use it to decide what your own `MessageStore` keeps — these calls are display
34
+ * history, so dropping or capping them is safe (they are already stripped from the
35
+ * request to the model on the next turn). Also works on a `tool-call` UI part, whose
36
+ * `metadata` is copied straight from the model message.
37
+ *
38
+ * `metadata` is `unknown` on both, so the key can only be read behind a typeof/`in`
39
+ * check; this mirrors the core `isProviderExecutedToolCall` convention.
40
+ *
41
+ * ```ts
42
+ * import { isSandboxToolCall } from '@tanstack/ai-sandbox'
43
+ *
44
+ * const kept = messages.filter(
45
+ * (message) => !message.toolCalls?.every(isSandboxToolCall),
46
+ * )
47
+ * ```
48
+ */
49
+ function isSandboxToolCall(toolCall) {
50
+ const metadata = toolCall?.metadata;
51
+ return typeof metadata === "object" && metadata !== null && SANDBOX_OBSERVED in metadata && metadata[SANDBOX_OBSERVED] === true;
52
+ }
53
+ /** Does the transcript already carry this tool call, from any source? */
54
+ function hasCall(messages, id) {
55
+ return messages.some((message) => message.toolCalls?.some((call) => call.id === id));
56
+ }
57
+ /** Does the transcript already carry this tool result? */
58
+ function hasResult(messages, id) {
59
+ return messages.some((message) => message.role === "tool" && message.toolCallId === id);
60
+ }
61
+ function callMessage(id, name, args) {
62
+ return {
63
+ role: "assistant",
64
+ content: null,
65
+ toolCalls: [{
66
+ id,
67
+ type: "function",
68
+ function: {
69
+ name,
70
+ arguments: args
71
+ },
72
+ metadata: { [SANDBOX_OBSERVED]: true }
73
+ }]
74
+ };
75
+ }
76
+ function resultMessage(id, content) {
77
+ return {
78
+ role: "tool",
79
+ toolCallId: id,
80
+ content
81
+ };
82
+ }
83
+ function createToolHistoryRecorder() {
84
+ const open = /* @__PURE__ */ new Map();
85
+ /** Completed calls in the order they ran — the order `reconcile` restores. */
86
+ const recorded = [];
87
+ const results = /* @__PURE__ */ new Map();
88
+ function appendCall(target, id, name, args) {
89
+ if (hasCall(target.messages, id)) return;
90
+ target.messages = [...target.messages, callMessage(id, name, args)];
91
+ }
92
+ function appendResult(target, id, content) {
93
+ if (hasResult(target.messages, id)) return;
94
+ target.messages = [...target.messages, resultMessage(id, content)];
95
+ }
96
+ return {
97
+ observe(chunk, target) {
98
+ if (chunk.type === EventType.TOOL_CALL_START) {
99
+ const name = chunk.toolCallName ?? chunk.toolName;
100
+ if (!name) return;
101
+ open.set(chunk.toolCallId, {
102
+ name,
103
+ args: ""
104
+ });
105
+ return;
106
+ }
107
+ if (chunk.type === EventType.TOOL_CALL_ARGS) {
108
+ const call = open.get(chunk.toolCallId);
109
+ if (!call) return;
110
+ call.args = chunk.args ?? call.args + chunk.delta;
111
+ return;
112
+ }
113
+ if (chunk.type === EventType.TOOL_CALL_END) {
114
+ const call = open.get(chunk.toolCallId);
115
+ if (!call) return;
116
+ open.delete(chunk.toolCallId);
117
+ const args = chunk.input !== void 0 ? JSON.stringify(chunk.input) : call.args;
118
+ recorded.push({
119
+ id: chunk.toolCallId,
120
+ name: call.name,
121
+ args
122
+ });
123
+ appendCall(target, chunk.toolCallId, call.name, args);
124
+ return;
125
+ }
126
+ if (chunk.type === EventType.TOOL_CALL_RESULT) {
127
+ if (typeof chunk.content !== "string") return;
128
+ results.set(chunk.toolCallId, chunk.content);
129
+ appendResult(target, chunk.toolCallId, chunk.content);
130
+ }
131
+ },
132
+ reconcile(target) {
133
+ for (const { id, name, args } of recorded) {
134
+ appendCall(target, id, name, args);
135
+ const result = results.get(id);
136
+ if (result !== void 0) appendResult(target, id, result);
137
+ }
138
+ }
139
+ };
140
+ }
141
+ /**
142
+ * Drop recorded harness tool calls from a list of messages bound for the model.
143
+ *
144
+ * A stored transcript becomes the history for the NEXT turn. These calls name tools
145
+ * the provider was never given, and one triage-sized run is hundreds of kilobytes of
146
+ * tool output — so replaying them is wasteful at best and rejected at worst. They stay
147
+ * in `ctx.messages` (which is what gets stored and rendered); only the request to the
148
+ * model loses them.
149
+ *
150
+ * An assistant message is dropped only when EVERY call on it is observed, so a mixed
151
+ * message — one engine tool call plus one harness tool call — is left alone rather than
152
+ * silently losing the engine's half.
153
+ */
154
+ function stripObservedToolCalls(messages) {
155
+ const dropped = /* @__PURE__ */ new Set();
156
+ const kept = [];
157
+ for (const message of messages) {
158
+ const calls = message.toolCalls;
159
+ if (calls && calls.length > 0 && calls.every(isSandboxToolCall)) {
160
+ for (const call of calls) dropped.add(call.id);
161
+ continue;
162
+ }
163
+ if (message.role === "tool" && message.toolCallId !== void 0 && dropped.has(message.toolCallId)) continue;
164
+ kept.push(message);
165
+ }
166
+ return kept;
167
+ }
168
+ //#endregion
169
+ export { createToolHistoryRecorder, isSandboxToolCall, stripObservedToolCalls };
170
+
171
+ //# sourceMappingURL=tool-history.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-history.js","names":[],"sources":["../../src/tool-history.ts"],"sourcesContent":["/**\n * Turn a harness's PASSTHROUGH tool-call chunks into transcript messages, so a\n * finished run's tool cards survive a reload.\n *\n * Why this is needed at all: a harness executes its tools INSIDE the sandbox, so\n * `chat()` only relays its `TOOL_CALL_*` chunks — it never writes an assistant\n * message for them (`addAssistantToolCallMessage` is gated on the engine having\n * executed the tool itself). Chat persistence stores `ctx.messages`, so the whole\n * tool history existed only in the delivery log. Replaying that log is what makes\n * \"switch away and come back\" show everything; a FINISHED thread has no run to\n * rejoin, hydrates from the message store instead, and so came back as nothing but\n * the prompt and the final answer.\n *\n * Recording the calls as ordinary `toolCalls` + `role: 'tool'` messages needs no new\n * wire format and no client change: `modelMessagesToUIMessages` already merges a tool\n * result into the call it belongs to and marks the part complete, and\n * `reconstructChat` already runs that converter.\n */\nimport { EventType } from '@tanstack/ai'\nimport type { ModelMessage, StreamChunk } from '@tanstack/ai'\n\n/**\n * Metadata key set on every tool call recorded here.\n *\n * INTERNAL, and deliberately not exported: an app asks {@link isSandboxToolCall}\n * instead of knowing the key. Renaming it is a storage-visible change, because it ends\n * up inside stored `toolCalls[].metadata`, so the recorder test pins the literal.\n */\nconst SANDBOX_OBSERVED = 'sandboxObserved'\n\n/**\n * What the recorder writes into. `ChatMiddlewareContext.messages` is a\n * `ReadonlyArray`, so the transcript grows by REPLACING the array — the same way the\n * engine itself syncs `middlewareCtx.messages`.\n */\ninterface TranscriptTarget {\n messages: ReadonlyArray<ModelMessage>\n}\n\ninterface OpenCall {\n name: string\n /** Accumulated `TOOL_CALL_ARGS` deltas; superseded by `input` when the adapter sends it. */\n args: string\n}\n\nexport interface ToolHistoryRecorder {\n /** Feed every chunk. Observes only — never transforms or drops. */\n observe: (chunk: StreamChunk, target: TranscriptTarget) => void\n /**\n * Re-append anything missing from the transcript.\n *\n * The engine reassigns `middlewareCtx.messages` from its own array whenever it\n * syncs config (once per agent iteration), which discards writes made during the\n * previous iteration's stream. Reconciling at each iteration boundary and again at\n * finish makes the result independent of that, and independent of where this\n * middleware sits relative to persistence in the middleware array.\n */\n reconcile: (target: TranscriptTarget) => void\n}\n\n/**\n * True when this tool call was executed by the HARNESS inside the sandbox, and\n * recorded into the transcript for display, rather than executed by the agent loop.\n *\n * Use it to decide what your own `MessageStore` keeps — these calls are display\n * history, so dropping or capping them is safe (they are already stripped from the\n * request to the model on the next turn). Also works on a `tool-call` UI part, whose\n * `metadata` is copied straight from the model message.\n *\n * `metadata` is `unknown` on both, so the key can only be read behind a typeof/`in`\n * check; this mirrors the core `isProviderExecutedToolCall` convention.\n *\n * ```ts\n * import { isSandboxToolCall } from '@tanstack/ai-sandbox'\n *\n * const kept = messages.filter(\n * (message) => !message.toolCalls?.every(isSandboxToolCall),\n * )\n * ```\n */\nexport function isSandboxToolCall(\n toolCall: { metadata?: unknown } | null | undefined,\n): boolean {\n const metadata = toolCall?.metadata\n return (\n typeof metadata === 'object' &&\n metadata !== null &&\n SANDBOX_OBSERVED in metadata &&\n metadata[SANDBOX_OBSERVED] === true\n )\n}\n\n/** Does the transcript already carry this tool call, from any source? */\nfunction hasCall(messages: ReadonlyArray<ModelMessage>, id: string): boolean {\n return messages.some((message) =>\n message.toolCalls?.some((call) => call.id === id),\n )\n}\n\n/** Does the transcript already carry this tool result? */\nfunction hasResult(messages: ReadonlyArray<ModelMessage>, id: string): boolean {\n return messages.some(\n (message) => message.role === 'tool' && message.toolCallId === id,\n )\n}\n\nfunction callMessage(id: string, name: string, args: string): ModelMessage {\n return {\n role: 'assistant',\n content: null,\n toolCalls: [\n {\n id,\n type: 'function',\n function: { name, arguments: args },\n metadata: { [SANDBOX_OBSERVED]: true },\n },\n ],\n }\n}\n\nfunction resultMessage(id: string, content: string): ModelMessage {\n return { role: 'tool', toolCallId: id, content }\n}\n\nexport function createToolHistoryRecorder(): ToolHistoryRecorder {\n const open = new Map<string, OpenCall>()\n /** Completed calls in the order they ran — the order `reconcile` restores. */\n const recorded: Array<{ id: string; name: string; args: string }> = []\n const results = new Map<string, string>()\n\n function appendCall(\n target: TranscriptTarget,\n id: string,\n name: string,\n args: string,\n ): void {\n // An id already present is either the engine's own (it executed the tool itself)\n // or a chunk seen before — a journal replay on takeover re-emits the whole\n // stream. Either way a second write would duplicate the card.\n if (hasCall(target.messages, id)) return\n target.messages = [...target.messages, callMessage(id, name, args)]\n }\n\n function appendResult(\n target: TranscriptTarget,\n id: string,\n content: string,\n ): void {\n if (hasResult(target.messages, id)) return\n target.messages = [...target.messages, resultMessage(id, content)]\n }\n\n const recorder: ToolHistoryRecorder = {\n // An if/else chain rather than a `switch`: only four of the ~20 chunk types are\n // interesting here, and a `switch` on `chunk.type` has to enumerate all of them\n // to satisfy the exhaustiveness lint.\n observe(chunk, target) {\n if (chunk.type === EventType.TOOL_CALL_START) {\n // `toolCallName` is the AG-UI field; `toolName` is its deprecated alias, and\n // that alias is what several harness adapters still emit.\n const name = chunk.toolCallName ?? chunk.toolName\n if (!name) return\n open.set(chunk.toolCallId, { name, args: '' })\n return\n }\n if (chunk.type === EventType.TOOL_CALL_ARGS) {\n const call = open.get(chunk.toolCallId)\n if (!call) return\n // `args` is the accumulated-so-far field. Prefer it over stitching deltas:\n // an adapter that sends both would otherwise double the arguments.\n call.args = chunk.args ?? call.args + chunk.delta\n return\n }\n if (chunk.type === EventType.TOOL_CALL_END) {\n const call = open.get(chunk.toolCallId)\n if (!call) return\n open.delete(chunk.toolCallId)\n // `input` is the final PARSED input, so it beats the streamed string, which\n // can be a truncated fragment if the arguments stream was cut short.\n const args =\n chunk.input !== undefined ? JSON.stringify(chunk.input) : call.args\n recorded.push({ id: chunk.toolCallId, name: call.name, args })\n appendCall(target, chunk.toolCallId, call.name, args)\n return\n }\n if (chunk.type === EventType.TOOL_CALL_RESULT) {\n // AG-UI types `content` as a string; anything else is not a result we can\n // store as a `role: 'tool'` message.\n if (typeof chunk.content !== 'string') return\n results.set(chunk.toolCallId, chunk.content)\n appendResult(target, chunk.toolCallId, chunk.content)\n }\n },\n\n reconcile(target) {\n for (const { id, name, args } of recorded) {\n appendCall(target, id, name, args)\n const result = results.get(id)\n // The result goes straight after its own call, so a restored transcript reads\n // in the order the tools actually ran.\n if (result !== undefined) appendResult(target, id, result)\n }\n },\n }\n return recorder\n}\n\n/**\n * Drop recorded harness tool calls from a list of messages bound for the model.\n *\n * A stored transcript becomes the history for the NEXT turn. These calls name tools\n * the provider was never given, and one triage-sized run is hundreds of kilobytes of\n * tool output — so replaying them is wasteful at best and rejected at worst. They stay\n * in `ctx.messages` (which is what gets stored and rendered); only the request to the\n * model loses them.\n *\n * An assistant message is dropped only when EVERY call on it is observed, so a mixed\n * message — one engine tool call plus one harness tool call — is left alone rather than\n * silently losing the engine's half.\n */\nexport function stripObservedToolCalls(\n messages: ReadonlyArray<ModelMessage>,\n): Array<ModelMessage> {\n const dropped = new Set<string>()\n const kept: Array<ModelMessage> = []\n for (const message of messages) {\n const calls = message.toolCalls\n if (calls && calls.length > 0 && calls.every(isSandboxToolCall)) {\n for (const call of calls) dropped.add(call.id)\n continue\n }\n // Orphaning a result is worse than keeping it: a provider rejects a tool result\n // whose call is not in the history.\n if (\n message.role === 'tool' &&\n message.toolCallId !== undefined &&\n dropped.has(message.toolCallId)\n ) {\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