Open History to see the last commit
1import {
2 createCodeModeSystemPrompt,
3 createCodeModeTool,
4 toolsToBindings,
5} from '@tanstack/ai-code-mode'
6import { createToolRegistry } from '@tanstack/ai'
7import { selectRelevantSnippets } from './select-relevant-snippets'
8import { createSnippetManagementTools } from './create-snippet-management-tools'
9import { createSnippetsSystemPrompt } from './create-snippets-system-prompt'
10import { snippetsToTools } from './snippets-to-tools'
11import type {
12 CodeModeWithSnippetsOptions,
13 CodeModeWithSnippetsResult,
14 Snippet,
15} from './types'
16import type { ToolBinding } from '@tanstack/ai-code-mode'
17
18export type { CodeModeWithSnippetsOptions, CodeModeWithSnippetsResult }
19
20/**
21 * Create Code Mode tools and system prompt with snippets integration.
22 *
23 * This function:
24 * 1. Loads the snippet index from storage
25 * 2. Uses a cheap/fast LLM to select relevant snippets based on conversation context
26 * 3. Creates the execute_typescript tool with dynamic snippet bindings
27 * 4. Creates snippet management tools (search, get, register)
28 * 5. Generates system prompts documenting available snippets
29 * 6. Returns a ToolRegistry that allows dynamic snippet additions mid-stream
30 *
31 * @example
32 * ```typescript
33 * // Node-only file storage lives behind the `/storage` subpath:
34 * import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
35 *
36 * const { toolsRegistry, systemPrompt, selectedSnippets } = await codeModeWithSnippets({
37 * config: {
38 * driver: createNodeIsolateDriver(),
39 * tools: allTools,
40 * timeout: 60000,
41 * },
42 * adapter: openaiText('gpt-4o-mini'), // Cheap model for selection
43 * snippets: {
44 * storage: createFileSnippetStorage('./.snippets'),
45 * maxSnippetsInContext: 5,
46 * },
47 * messages,
48 * threadId,
49 * });
50 *
51 * const stream = chat({
52 * adapter: openaiText('gpt-4o'), // Main model
53 * toolRegistry: toolsRegistry, // Dynamic tool registry
54 * messages,
55 * threadId,
56 * systemPrompts: [BASE_PROMPT, systemPrompt],
57 * });
58 * ```
59 */
60export async function codeModeWithSnippets({
61 config,
62 adapter,
63 snippets,
64 messages,
65 threadId,
66 snippetsAsTools = true,
67}: CodeModeWithSnippetsOptions): Promise<CodeModeWithSnippetsResult> {
68 const { storage, maxSnippetsInContext = 5 } = snippets
69
70 // 1. Load the snippet index (lightweight metadata only)
71 const snippetIndex = await storage.loadIndex()
72
73 // 2. Use adapter to select relevant snippets based on transcript
74 const selectedSnippets = await selectRelevantSnippets({
75 adapter,
76 messages,
77 threadId,
78 snippetIndex,
79 maxSnippets: maxSnippetsInContext,
80 storage,
81 })
82
83 // Pre-compute bindings from base tools (shared across snippet executions)
84 const baseBindings = toolsToBindings(config.tools, 'external_')
85
86 // 3. Create the execute_typescript tool with dynamic snippet bindings
87 const codeModeTool = createCodeModeTool({
88 ...config,
89 // Dynamic snippet bindings - fetched at execution time
90 getSnippetBindings: async () => {
91 // Get all snippets from storage (includes newly registered ones)
92 const allSnippets = await storage.loadAll()
93 // Convert to bindings with snippet_ prefix
94 const snippetBindings: Record<string, ToolBinding> = {}
95 for (const snippet of allSnippets) {
96 // Create a simple binding that executes the snippet code
97 snippetBindings[`snippet_${snippet.name}`] = {
98 name: `snippet_${snippet.name}`,
99 description: snippet.description,
100 inputSchema: snippet.inputSchema,
101 outputSchema: snippet.outputSchema,
102 execute: async (input: unknown, toolContext) => {
103 // This is a simplified execution - the full snippetToTool handles events
104 const wrappedCode = `const input = ${JSON.stringify(input)};\n${snippet.code}`
105 const { stripTypeScript, createEventAwareBindings } =
106 await import('@tanstack/ai-code-mode')
107 const strippedCode = await stripTypeScript(wrappedCode)
108 const context = await config.driver.createContext({
109 bindings: createEventAwareBindings(
110 baseBindings,
111 () => {},
112 toolContext,
113 ),
114 timeout: config.timeout,
115 ...(config.memoryLimit !== undefined && {
116 memoryLimit: config.memoryLimit,
117 }),
118 })
119 try {
120 const result = await context.execute(strippedCode)
121 if (!result.success) {
122 throw new Error(
123 result.error?.message || 'Snippet execution failed',
124 )
125 }
126 return result.value
127 } finally {
128 await context.dispose()
129 }
130 },
131 }
132 }
133 return snippetBindings
134 },
135 })
136
137 // 4. Create a mutable tool registry
138 const registry = createToolRegistry()
139
140 // 5. Add the execute_typescript tool to the registry
141 registry.add(codeModeTool)
142
143 // 6. Create snippet management tools (they need access to the registry)
144 const snippetManagementTools = createSnippetManagementTools({
145 storage,
146 registry,
147 config,
148 baseBindings,
149 })
150
151 for (const tool of snippetManagementTools) {
152 registry.add(tool)
153 }
154
155 // 7. Convert selected snippets to direct tools and add to registry (if enabled)
156 if (snippetsAsTools && selectedSnippets.length > 0) {
157 const snippetToolsList = snippetsToTools({
158 snippets: selectedSnippets,
159 driver: config.driver,
160 tools: config.tools,
161 storage,
162 timeout: config.timeout,
163 memoryLimit: config.memoryLimit,
164 })
165
166 for (const snippetTool of snippetToolsList) {
167 registry.add(snippetTool)
168 }
169 }
170
171 // 8. Generate combined system prompt
172 const basePrompt = createCodeModeSystemPrompt(config)
173 const snippetsPrompt = createSnippetsSystemPrompt({
174 selectedSnippets,
175 totalSnippetCount: snippetIndex.length,
176 snippetsAsTools,
177 })
178 const systemPrompt = basePrompt + '\n\n' + snippetsPrompt
179
180 return {
181 toolsRegistry: registry,
182 systemPrompt,
183 selectedSnippets,
184 }
185}
186
187/**
188 * Create a Code Mode tool configuration extended with snippets.
189 * This is an alternative to codeModeWithSnippets that returns
190 * a config object instead of directly creating tools.
191 *
192 * Useful when you want more control over the tool creation process.
193 */
194export function createCodeModeWithSnippetsConfig({
195 config,
196 selectedSnippets,
197 storage,
198}: {
199 config: CodeModeWithSnippetsOptions['config']
200 selectedSnippets: Array<Snippet>
201 storage: CodeModeWithSnippetsOptions['snippets']['storage']
202}) {
203 // Create snippet tools for direct calling
204 const snippetToolsList = snippetsToTools({
205 snippets: selectedSnippets,
206 driver: config.driver,
207 tools: config.tools,
208 storage,
209 timeout: config.timeout,
210 memoryLimit: config.memoryLimit,
211 })
212
213 return {
214 ...config,
215 snippetTools: snippetToolsList,
216 selectedSnippets,
217 }
218}