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 { CodeModeCallHook, 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`, `threadId`, and runtime `context`, so a
103 * tool can cancel in-flight work when the run aborts. `toolCallId` and `inputResponse` are
104 * not passed: they belong to the parent tool call, not to this nested call. Without a
105 * parent context, the context has no `threadId`.
106 *
107 * @param bindings - Original tool bindings
108 * @param emitCustomEvent - Callback to emit custom events to the stream
109 * @param parentContext - Context of the tool that runs the code (e.g. `execute_typescript`)
110 * @param hook - Optional internal hook that runs around each call. The events
111 * still fire around it.
112 */
113export function createEventAwareBindings(
114 bindings: Record<string, ToolBinding>,
115 emitCustomEvent: ToolExecutionContext['emitCustomEvent'],
116 parentContext?: ToolExecutionContext,
117 hook?: CodeModeCallHook,
118): Record<string, ToolBinding> {
119 const toolContext: ToolExecutionContext = {
120 context: parentContext?.context,
121 abortSignal: parentContext?.abortSignal,
122 threadId: parentContext?.threadId,
123 emitCustomEvent,
124 }
125
126 const wrapped: Record<string, ToolBinding> = {}
127
128 for (const [name, binding] of Object.entries(bindings)) {
129 // ponytail: the hook gets the name without the `external_` prefix of
130 // createCodeModeTool. Other names, such as `snippet_*`, stay as they are.
131 // Take the prefix as a parameter when a caller needs another one.
132 const toolName = name.replace(/^external_/, '')
133 wrapped[name] = {
134 ...binding,
135 execute: async (args: unknown) => {
136 // Emit call event
137 emitCustomEvent('code_mode:external_call', {
138 function: name,
139 args,
140 timestamp: Date.now(),
141 })
142
143 const startTime = Date.now()
144 try {
145 toolContext.abortSignal?.throwIfAborted()
146 const run = () => binding.execute(args, toolContext)
147 const result = await (hook
148 ? hook({ name: toolName, args }, run)
149 : run())
150
151 // Emit result event
152 emitCustomEvent('code_mode:external_result', {
153 function: name,
154 result,
155 duration: Date.now() - startTime,
156 })
157
158 return result
159 } catch (error) {
160 // Emit error event
161 emitCustomEvent('code_mode:external_error', {
162 function: name,
163 error: error instanceof Error ? error.message : String(error),
164 duration: Date.now() - startTime,
165 })
166 throw error
167 }
168 },
169 }
170 }
171
172 return wrapped
173}