* Register all bridgeable tools on the runtime under `mux` namespace. * * Tools receive the runtime's abort signal, which is aborted when: * - The sandbox timeout is exceeded * - runtime.abort() is called (e.g., from the parent's abort signal) * * This ensures nested tool calls are
(runtime: IJSRuntime)
| 77 | * not just when the parent stream is cancelled. |
| 78 | */ |
| 79 | register(runtime: IJSRuntime): void { |
| 80 | const muxObj: Record<string, (...args: unknown[]) => Promise<unknown>> = {}; |
| 81 | |
| 82 | for (const [name, tool] of this.bridgeableTools) { |
| 83 | // Capture tool for closure |
| 84 | const boundTool = tool; |
| 85 | const toolName = name; |
| 86 | |
| 87 | muxObj[name] = async (args: unknown) => { |
| 88 | // Get the runtime's abort signal - this is aborted on timeout or manual abort |
| 89 | const abortSignal = runtime.getAbortSignal(); |
| 90 | |
| 91 | // Check if already aborted before executing |
| 92 | if (abortSignal?.aborted) { |
| 93 | throw new Error("Execution aborted"); |
| 94 | } |
| 95 | |
| 96 | // Validate args against tool's Zod schema |
| 97 | const validatedArgs = this.validateArgs(toolName, boundTool, args); |
| 98 | |
| 99 | // Execute tool with full options (toolCallId and messages are required by type |
| 100 | // but not used by most tools - generate synthetic values for sandbox context) |
| 101 | const result: unknown = await boundTool.execute!(validatedArgs, { |
| 102 | abortSignal, |
| 103 | toolCallId: `ptc-${toolName}-${Date.now()}`, |
| 104 | messages: [], |
| 105 | }); |
| 106 | |
| 107 | // Ensure result is JSON-serializable |
| 108 | return this.serializeResult(result); |
| 109 | }; |
| 110 | } |
| 111 | |
| 112 | runtime.registerObject("mux", muxObj); |
| 113 | } |
| 114 | |
| 115 | private hasExecute(tool: Tool): tool is Tool & { execute: NonNullable<Tool["execute"]> } { |
| 116 | return typeof tool.execute === "function"; |
no test coverage detected