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