( options: CreateCodeToolOptions )
| 88 | } |
| 89 | |
| 90 | export function createCodeTool( |
| 91 | options: CreateCodeToolOptions |
| 92 | ): Tool<CodeInput, CodeOutput> { |
| 93 | const providers = normalizeProviders(options.tools); |
| 94 | |
| 95 | // Build type block and resolved providers for each provider. |
| 96 | const typeBlocks: string[] = []; |
| 97 | const resolvedProviders: ResolvedProvider[] = []; |
| 98 | |
| 99 | for (const provider of providers) { |
| 100 | const name = provider.name ?? "codemode"; |
| 101 | const filtered = filterTools(provider.tools); |
| 102 | const types = |
| 103 | provider.types ?? generateTypes(filtered as ToolDescriptors, name); |
| 104 | typeBlocks.push(types); |
| 105 | const resolved: ResolvedProvider = { name, fns: extractFns(filtered) }; |
| 106 | if (provider.positionalArgs) resolved.positionalArgs = true; |
| 107 | resolvedProviders.push(resolved); |
| 108 | } |
| 109 | |
| 110 | const typeBlock = typeBlocks.filter(Boolean).join("\n\n"); |
| 111 | |
| 112 | const executor = options.executor; |
| 113 | |
| 114 | const description = (options.description ?? DEFAULT_DESCRIPTION).replace( |
| 115 | "{{types}}", |
| 116 | typeBlock |
| 117 | ); |
| 118 | |
| 119 | return tool({ |
| 120 | description, |
| 121 | inputSchema: codeSchema, |
| 122 | execute: async ({ code }) => { |
| 123 | const normalizedCode = normalizeCode(code); |
| 124 | |
| 125 | const executeResult = await executor.execute( |
| 126 | normalizedCode, |
| 127 | resolvedProviders |
| 128 | ); |
| 129 | |
| 130 | if (executeResult.error) { |
| 131 | const logCtx = executeResult.logs?.length |
| 132 | ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` |
| 133 | : ""; |
| 134 | throw new Error( |
| 135 | `Code execution failed: ${executeResult.error}${logCtx}` |
| 136 | ); |
| 137 | } |
| 138 | |
| 139 | const output: CodeOutput = { code, result: executeResult.result }; |
| 140 | if (executeResult.logs) output.logs = executeResult.logs; |
| 141 | return output; |
| 142 | } |
| 143 | }); |
| 144 | } |
no test coverage detected