Open History to see the last commit
1import {
2 convertSchemaToJsonSchema,
3 isStandardSchema,
4 parseWithStandardSchema,
5} from '@tanstack/ai'
6import type { ToolExecutionContext } from '@tanstack/ai'
7import type { CodeModeTool, ToolBinding } from '../types'
8
9/**
10 * Convert an array of TanStack AI tools to a Record of ToolBindings
11 *
12 * @param tools - Array of tools to convert
13 * @param prefix - Optional prefix to add to binding names (e.g., 'external_')
14 */
15export function toolsToBindings(
16 tools: Array<CodeModeTool>,
17 prefix: string = '',
18): Record<string, ToolBinding> {
19 const bindings: Record<string, ToolBinding> = {}
20
21 for (const tool of tools) {
22 const bindingName = `${prefix}${tool.name}`
23 bindings[bindingName] = toolToBinding(tool, prefix)
24 }
25
26 return bindings
27}
28
29/**
30 * Convert a single TanStack AI tool to a ToolBinding
31 *
32 * @param tool - Tool to convert
33 * @param prefix - Optional prefix to add to binding name (e.g., 'external_')
34 * @throws Error if the tool doesn't have an execute function
35 */
36export function toolToBinding(
37 tool: CodeModeTool,
38 prefix: string = '',
39): ToolBinding {
40 // Convert schemas (Zod or Standard Schema) to JSON Schema
41 const inputSchema = convertSchemaToJsonSchema(tool.inputSchema) || {
42 type: 'object',
43 properties: {},
44 }
45
46 const outputSchema = tool.outputSchema
47 ? convertSchemaToJsonSchema(tool.outputSchema)
48 : undefined
49
50 if (typeof tool.execute !== 'function') {
51 throw new Error(
52 `Tool "${tool.name}" does not have an execute function. ` +
53 `Code Mode requires server tools with implementations.`,
54 )
55 }
56
57 const toolExecute = tool.execute
58 const execute = async (args: unknown, context?: ToolExecutionContext) => {
59 let input = args
60 if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {
61 try {
62 input = parseWithStandardSchema(tool.inputSchema, args)
63 } catch (error) {
64 const message =
65 error instanceof Error ? error.message : 'Validation failed'
66 throw new Error(
67 `Input validation failed for tool ${tool.name}: ${message}`,
68 )
69 }
70 }
71
72 let result = await Promise.resolve(toolExecute(input, context))
73
74 if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {
75 try {
76 result = parseWithStandardSchema(tool.outputSchema, result)
77 } catch (error) {
78 const message =
79 error instanceof Error ? error.message : 'Validation failed'
80 throw new Error(
81 `Output validation failed for tool ${tool.name}: ${message}`,
82 )
83 }
84 }
85
86 return result
87 }
88
89 return {
90 name: `${prefix}${tool.name}`,
91 description: tool.description,
92 inputSchema,
93 outputSchema,
94 execute,
95 }
96}
97
98/**
99 * Create event-aware bindings that emit custom events for each external function call.
100 * Wraps each binding's execute function to emit events before and after execution.
101 *
102 * Each call gets the parent tool's `abortSignal` and runtime `context`, so a tool
103 * can cancel in-flight work when the run aborts. `toolCallId` and `inputResponse` are not
104 * passed: they belong to the parent tool call, not to this nested call.
105 *
106 * @param bindings - Original tool bindings
107 * @param emitCustomEvent - Callback to emit custom events to the stream
108 * @param parentContext - Context of the tool that runs the code (e.g. `execute_typescript`)
109 */
110export function createEventAwareBindings(
111 bindings: Record<string, ToolBinding>,
112 emitCustomEvent: ToolExecutionContext['emitCustomEvent'],
113 parentContext?: ToolExecutionContext,
114): Record<string, ToolBinding> {
115 const toolContext: ToolExecutionContext = {
116 context: parentContext?.context,
117 abortSignal: parentContext?.abortSignal,
118 emitCustomEvent,
119 }
120
121 const wrapped: Record<string, ToolBinding> = {}
122
123 for (const [name, binding] of Object.entries(bindings)) {
124 wrapped[name] = {
125 ...binding,
126 execute: async (args: unknown) => {
127 // Emit call event
128 emitCustomEvent('code_mode:external_call', {
129 function: name,
130 args,
131 timestamp: Date.now(),
132 })
133
134 const startTime = Date.now()
135 try {
136 toolContext.abortSignal?.throwIfAborted()
137 const result = await binding.execute(args, toolContext)
138
139 // Emit result event
140 emitCustomEvent('code_mode:external_result', {
141 function: name,
142 result,
143 duration: Date.now() - startTime,
144 })
145
146 return result
147 } catch (error) {
148 // Emit error event
149 emitCustomEvent('code_mode:external_error', {
150 function: name,
151 error: error instanceof Error ? error.message : String(error),
152 duration: Date.now() - startTime,
153 })
154 throw error
155 }
156 },
157 }
158 }
159
160 return wrapped
161}