Open History to see the last commit
1---
2title: Code Mode with Skills
3id: code-mode-with-skills
4order: 3
5description: "Teach Code Mode to save and reuse working code as named skills backed by persistent storage — faster follow-up requests and composable agent memory."
6keywords:
7 - tanstack ai
8 - code mode
9 - skills
10 - skill library
11 - register_skill
12 - reusable snippets
13 - agent memory
14 - skill storage
15---
16
17Skills extend [Code Mode](./code-mode.md) with a persistent library of reusable TypeScript snippets. When the LLM writes a useful piece of code — say, a function that fetches and ranks NPM packages — it can save that code as a _skill_. On future requests, relevant skills are loaded from storage and made available as first-class tools the LLM can call without re-writing the logic.
18
19> **Different from agent-authoring skills.** The skills on this page are _runtime_ snippets the chat LLM saves and reuses. If you're looking to teach your coding assistant (Claude Code, Cursor, etc.) how TanStack AI itself works, see [Agent Skills (TanStack Intent)](../getting-started/agent-skills).
20
21## Overview
22
23The skills system has two integration paths:
24
25| Approach | Entry point | Skill selection | Best for |
26|----------|-------------|----------------|----------|
27| **High-level** | `codeModeWithSkills()` | Automatic (LLM-based) | New projects, turnkey setup |
28| **Manual** | Individual functions (`skillsToTools`, `createSkillManagementTools`, etc.) | You decide which skills to load | Full control, existing setups |
29
30Both paths share the same storage, trust, and execution primitives — they differ only in how skills are selected and assembled.
31
32## How It Works
33
34A request with skills enabled goes through these stages:
35
36```
37┌─────────────────────────────────────────────────────┐
38│ 1. Load skill index (metadata only, no code) │
39├─────────────────────────────────────────────────────┤
40│ 2. Select relevant skills (LLM call — fast model) │
41├─────────────────────────────────────────────────────┤
42│ 3. Build tool registry │
43│ ├── execute_typescript (Code Mode sandbox) │
44│ ├── search_skills / get_skill / register_skill │
45│ └── skill tools (one per selected skill) │
46├─────────────────────────────────────────────────────┤
47│ 4. Generate system prompt │
48│ ├── Code Mode type stubs │
49│ └── Skill library documentation │
50├─────────────────────────────────────────────────────┤
51│ 5. Main chat() call (strong model) │
52│ ├── Can call skill tools directly │
53│ ├── Can write code via execute_typescript │
54│ └── Can register new skills for future use │
55└─────────────────────────────────────────────────────┘
56```
57
58### LLM calls
59
60There are **two** LLM interactions per request when using the high-level API:
61
621. **Skill selection** (`selectRelevantSkills`) — A single chat call using the adapter you provide. It sends the last 5 conversation messages plus a catalog of skill names/descriptions, and asks the model to return a JSON array of relevant skill names. This should be a cheap/fast model (e.g., `gpt-4o-mini`, `claude-haiku-4-5`).
63
642. **Main chat** — The primary `chat()` call with your full model. This is where the LLM reasons, calls tools, writes code, and registers skills.
65
66The selection call is lightweight — it only sees skill metadata (names, descriptions, usage hints), not full code. If there are no skills in storage or no messages, it short-circuits and skips the LLM call entirely.
67
68## High-Level API: `codeModeWithSkills()`
69
70### Installation
71
72```bash
73pnpm add @tanstack/ai-code-mode-skills
74```
75
76### Usage
77
78```typescript
79import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'
80import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
81import { codeModeWithSkills } from '@tanstack/ai-code-mode-skills'
82import { createFileSkillStorage } from '@tanstack/ai-code-mode-skills/storage'
83import { openaiText } from '@tanstack/ai-openai'
84
85const storage = createFileSkillStorage({ directory: './.skills' })
86const driver = createNodeIsolateDriver()
87
88const { toolsRegistry, systemPrompt, selectedSkills } = await codeModeWithSkills({
89 config: {
90 driver,
91 tools: [myTool1, myTool2],
92 timeout: 60_000,
93 memoryLimit: 128,
94 },
95 adapter: openaiText('gpt-4o-mini'), // cheap model for skill selection
96 skills: {
97 storage,
98 maxSkillsInContext: 5,
99 },
100 messages, // current conversation
101})
102
103const stream = chat({
104 adapter: openaiText('gpt-4o'), // strong model for reasoning
105 toolRegistry: toolsRegistry,
106 messages,
107 systemPrompts: ['You are a helpful assistant.', systemPrompt],
108 agentLoopStrategy: maxIterations(15),
109})
110```
111
112`codeModeWithSkills` returns:
113
114| Property | Type | Description |
115|----------|------|-------------|
116| `toolsRegistry` | `ToolRegistry` | Mutable registry containing all tools. Pass to `chat()` via `toolRegistry`. |
117| `systemPrompt` | `string` | Combined Code Mode + skill library documentation. |
118| `selectedSkills` | `Array<Skill>` | Skills the selection model chose for this conversation. |
119
120### What goes into the registry
121
122The registry is populated with:
123
124- **`execute_typescript`** — The Code Mode sandbox tool. Inside the sandbox, skills are also available as `skill_*` functions (loaded dynamically at execution time).
125- **`search_skills`** — Search the skill library by query. Returns matching skill metadata.
126- **`get_skill`** — Retrieve full details (including code) for a specific skill.
127- **`register_skill`** — Save working code as a new skill. Newly registered skills are immediately added to the registry as callable tools.
128- **One tool per selected skill** — Each selected skill becomes a direct tool (prefixed with `[SKILL]` in its description) that the LLM can call without going through `execute_typescript`.
129
130## Manual API
131
132If you want full control — for example, loading all skills instead of using LLM-based selection — use the lower-level functions directly. This is the approach used in the `ts-code-mode-web` example.
133
134```typescript
135import { chat, maxIterations } from '@tanstack/ai'
136import { createCodeMode } from '@tanstack/ai-code-mode'
137import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
138import {
139 createAlwaysTrustedStrategy,
140 createSkillManagementTools,
141 createSkillsSystemPrompt,
142 skillsToTools,
143} from '@tanstack/ai-code-mode-skills'
144import { createFileSkillStorage } from '@tanstack/ai-code-mode-skills/storage'
145
146const trustStrategy = createAlwaysTrustedStrategy()
147const storage = createFileSkillStorage({
148 directory: './.skills',
149 trustStrategy,
150})
151const driver = createNodeIsolateDriver()
152
153// 1. Create Code Mode tool + prompt
154const { tool: codeModeTool, systemPrompt: codeModePrompt } =
155 createCodeMode({
156 driver,
157 tools: [myTool1, myTool2],
158 timeout: 60_000,
159 memoryLimit: 128,
160 })
161
162// 2. Load all skills and convert to tools
163const allSkills = await storage.loadAll()
164const skillIndex = await storage.loadIndex()
165
166const skillTools = allSkills.length > 0
167 ? skillsToTools({
168 skills: allSkills,
169 driver,
170 tools: [myTool1, myTool2],
171 storage,
172 timeout: 60_000,
173 memoryLimit: 128,
174 })
175 : []
176
177// 3. Create management tools
178const managementTools = createSkillManagementTools({
179 storage,
180 trustStrategy,
181})
182
183// 4. Generate skill library prompt
184const skillsPrompt = createSkillsSystemPrompt({
185 selectedSkills: allSkills,
186 totalSkillCount: skillIndex.length,
187 skillsAsTools: true,
188})
189
190// 5. Assemble and call chat()
191const stream = chat({
192 adapter: openaiText('gpt-4o'),
193 tools: [codeModeTool, ...managementTools, ...skillTools],
194 messages,
195 systemPrompts: [BASE_PROMPT, codeModePrompt, skillsPrompt],
196 agentLoopStrategy: maxIterations(15),
197})
198```
199
200This approach skips the selection LLM call entirely — you load whichever skills you want and pass them in directly.
201
202## Skill Storage
203
204Skills are persisted through the `SkillStorage` interface. Two implementations are provided:
205
206### File storage (production)
207
208```typescript
209import { createFileSkillStorage } from '@tanstack/ai-code-mode-skills/storage'
210
211const storage = createFileSkillStorage({
212 directory: './.skills',
213 trustStrategy, // optional, defaults to createDefaultTrustStrategy()
214})
215```
216
217Creates a directory structure:
218
219```
220.skills/
221 _index.json # Lightweight catalog for fast loading
222 fetch_github_stats/
223 meta.json # Description, schemas, hints, stats
224 code.ts # TypeScript source
225 compare_npm_packages/
226 meta.json
227 code.ts
228```
229
230### Memory storage (testing)
231
232```typescript
233import { createMemorySkillStorage } from '@tanstack/ai-code-mode-skills/storage'
234
235const storage = createMemorySkillStorage()
236```
237
238Keeps everything in memory. Useful for tests and demos.
239
240### Storage interface
241
242Both implementations satisfy this interface:
243
244| Method | Description |
245|--------|-------------|
246| `loadIndex()` | Load lightweight metadata for all skills (no code) |
247| `loadAll()` | Load all skills with full details including code |
248| `get(name)` | Get a single skill by name |
249| `save(skill)` | Create or update a skill |
250| `delete(name)` | Remove a skill |
251| `search(query, options?)` | Search skills by text query |
252| `updateStats(name, success)` | Record an execution result for trust tracking |
253
254## Trust Strategies
255
256Skills start untrusted and earn trust through successful executions. The trust level is metadata only — it does not currently gate execution. Four built-in strategies are available:
257
258```typescript
259import {
260 createDefaultTrustStrategy,
261 createAlwaysTrustedStrategy,
262 createRelaxedTrustStrategy,
263 createCustomTrustStrategy,
264} from '@tanstack/ai-code-mode-skills'
265```
266
267| Strategy | Initial level | Provisional | Trusted |
268|----------|--------------|-------------|---------|
269| **Default** | `untrusted` | 10+ runs, ≥90% success | 100+ runs, ≥95% success |
270| **Relaxed** | `untrusted` | 3+ runs, ≥80% success | 10+ runs, ≥90% success |
271| **Always trusted** | `trusted` | — | — |
272| **Custom** | Configurable | Configurable | Configurable |
273
274```typescript
275const strategy = createCustomTrustStrategy({
276 initialLevel: 'untrusted',
277 provisionalThreshold: { executions: 5, successRate: 0.85 },
278 trustedThreshold: { executions: 50, successRate: 0.95 },
279})
280```
281
282## Skill Lifecycle
283
284### Registration
285
286When the LLM produces useful code via `execute_typescript`, the system prompt instructs it to call `register_skill` with:
287
288- `name` — snake_case identifier (becomes the tool name)
289- `description` — what the skill does
290- `code` — TypeScript source that receives an `input` variable
291- `inputSchema` / `outputSchema` — JSON Schema strings
292- `usageHints` — when to use this skill
293- `dependsOn` — other skills this one calls
294
295The skill is saved to storage and (if a `ToolRegistry` was provided) immediately added as a callable tool in the current session.
296
297### Execution
298
299When a skill tool is called, the system:
300
3011. Wraps the skill code with `const input = <serialized input>;`
3022. Strips TypeScript syntax to plain JavaScript
3033. Creates a fresh sandbox context with `external_*` bindings
3044. Executes the code and returns the result
3055. Updates execution stats (success/failure count) asynchronously
306
307### Selection (high-level API only)
308
309On each new request, `selectRelevantSkills`:
310
3111. Takes the last 5 conversation messages as context
3122. Builds a catalog from the skill index (name + description + first usage hint)
3133. Asks the adapter to return a JSON array of relevant skill names (max `maxSkillsInContext`)
3144. Loads full skill data for the selected names
315
316If parsing fails or the model returns invalid JSON, it falls back to an empty selection — the request proceeds without pre-loaded skills, but the LLM can still search and use skills via the management tools.
317
318## Skills as Tools vs. Sandbox Bindings
319
320The `skillsAsTools` option (default: `true`) controls how skills are exposed:
321
322| Mode | How the LLM calls a skill | Pros | Cons |
323|------|--------------------------|------|------|
324| **As tools** (`true`) | Direct tool call: `skill_name({ ... })` | Simpler for the LLM, shows in tool-call UI, proper input validation | One tool per skill in the tool list |
325| **As bindings** (`false`) | Inside `execute_typescript`: `await skill_fetch_data({ ... })` | Skills composable in code, fewer top-level tools | LLM must write code to use them |
326
327When `skillsAsTools` is enabled, the system prompt documents each skill with its schema, usage hints, and example calls. When disabled, skills appear as typed `skill_*` functions in the sandbox type stubs.
328
329## Custom Events
330
331Skill execution emits events through the TanStack AI event system:
332
333| Event | When | Payload |
334|-------|------|---------|
335| `code_mode:skill_call` | Skill tool invoked | `{ skill, input, timestamp }` |
336| `code_mode:skill_result` | Skill completed successfully | `{ skill, result, duration, timestamp }` |
337| `code_mode:skill_error` | Skill execution failed | `{ skill, error, duration, timestamp }` |
338| `skill:registered` | New skill saved via `register_skill` | `{ id, name, description, timestamp }` |
339
340To render these events in your React app alongside Code Mode execution events, see [Showing Code Mode in the UI](./client-integration).
341
342## Tips
343
344- **Use a cheap model for selection.** The selection call only needs to match skill names to conversation context — `gpt-4o-mini` or `claude-haiku-4-5` work well.
345- **Start without skills.** Get Code Mode working first, then add `@tanstack/ai-code-mode-skills` once you have tools that produce reusable patterns.
346- **Monitor the skill count.** As the library grows, consider increasing `maxSkillsInContext` or switching to the manual API where you control which skills load.
347- **Newly registered skills are available on the next message,** not in the current turn's tool list (unless using `ToolRegistry` with the high-level API, which adds them immediately).
348- **Skills can call other skills.** Inside the sandbox, both `external_*` and `skill_*` functions are available. Set `dependsOn` when registering to document these relationships.
349
350## Next Steps
351
352- [Code Mode](./code-mode) — Core Code Mode setup and API reference
353- [Showing Code Mode in the UI](./client-integration) — Display execution progress in your React app
354- [Isolate Drivers](./code-mode-isolates) — Compare sandbox runtimes