Open History to see the last commit
1---
2title: Code mode in a harness
3id: harness-code-mode
4order: 13
5description: "Let the harness model write one TypeScript program that calls many tools, also the coding tools under their permission rules, and run it in an isolate. Any TanStack AI isolate driver plugs in."
6keywords:
7 - tanstack ai
8 - harness
9 - code mode
10 - isolate
11 - quickjs
12 - permissions
13---
14
15Your agent has many read-only tools, and it calls them one at a time. Each call is a model round trip, and every tool schema goes into every request. With code mode, the model writes one TypeScript program that calls the tools it needs, and the program runs in an isolate. The read-only tools leave the tool list and become functions in that program. The [coding tools](#run-the-coding-tools-in-a-program) can move too, and each of their calls keeps its permission rules.
16
17## 1. Add the plugin
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21react: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
22vue: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
23solid: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
24svelte: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
25preact: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
26angular: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
27octane: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
28vanilla: @tanstack/ai-code-mode @tanstack/ai-isolate-quickjs
29
30<!-- ::end:tabs -->
31
32```ts group=harness-code-mode
33import { toolDefinition } from '@tanstack/ai'
34import { codeMode } from '@tanstack/ai-code-mode/harness'
35import { defineHarness } from '@tanstack/ai-harness'
36import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
37import { openaiText } from '@tanstack/ai-openai'
38import { z } from 'zod'
39
40const issues = [{ id: 'ENG-1', title: 'Fix login', state: 'open' }]
41
42const listIssues = toolDefinition({
43 name: 'list_issues',
44 description: 'List the issues of the team',
45 inputSchema: z.object({ state: z.enum(['open', 'closed']) }),
46}).server(async ({ state }) => issues.filter((issue) => issue.state === state))
47
48const getIssue = toolDefinition({
49 name: 'get_issue',
50 description: 'Get one issue by id',
51 inputSchema: z.object({ id: z.string() }),
52}).server(async ({ id }) => issues.find((issue) => issue.id === id) ?? null)
53
54export const assistant = defineHarness({
55 name: 'acme/assistant',
56 adapter: openaiText('gpt-6.1-sol'),
57 tools: [listIssues, getIssue],
58 plugins: () => [codeMode({ driver: createQuickJSIsolateDriver() })],
59})
60```
61
62The model now has an `execute_typescript` tool. Inside the program, each moved tool is an `external_*` function, for example `external_list_issues({ state: 'open' })`.
63
64## 2. Pick the isolate
65
66`driver` takes any isolate driver. Change one line to run the programs somewhere else:
67
68| Driver | Package | Runs in |
69| --- | --- | --- |
70| `createQuickJSIsolateDriver()` | `@tanstack/ai-isolate-quickjs` | WebAssembly, on any runtime |
71| `createQuickJSBunIsolateDriver()` | `@tanstack/ai-isolate-quickjs-bun` | Native QuickJS in Bun |
72| `createNodeIsolateDriver()` | `@tanstack/ai-isolate-node` | A V8 isolate in Node |
73| `createCloudflareIsolateDriver()` | `@tanstack/ai-isolate-cloudflare` | A Cloudflare Worker |
74| `createDaytonaIsolateDriver()` | `@tanstack/ai-isolate-daytona` | A Daytona sandbox |
75| `createE2BIsolateDriver()` | `@tanstack/ai-isolate-e2b` | An E2B sandbox |
76
77[Code mode isolates](../code-mode/code-mode-isolates) has the options of each driver.
78
79## 3. Choose which tools move
80
81By default, code mode moves only the tools whose calls need no question and no check:
82
83- The tool runs on the server and does not set `needsApproval`.
84- The permission rules allow it in plan mode. A tool with an `edit` or `execute` rule stays.
85- The tool does not declare `PermissionResources`, so the rules check no path or command of its calls. The coding tools stay.
86
87Where the permission rules come from:
88
89- With [`permissions()`](./permissions) in the plugin list, code mode asks it about each tool. The answer is the one a call gets in plan mode: your `rules` win, and a tool with no rule gets your `default`. So with `default: 'ask'`, a tool with no rule stays.
90- Without `permissions()`, code mode reads the rules that tool plugins add.
91
92Every other tool stays a normal tool call, with its approvals.
93
94Code mode also adds `allow` rules for `execute_typescript` and `discover_tools`, so a program itself does not ask, also with `default: 'ask'`. Each call in the program gets the rules of its own tool. Your own `rules` still win: `{ tool: 'execute_typescript', decision: 'ask' }` asks before each program. With `getSnippetBindings`, code mode adds no rule, because a snippet runs code of its own.
95
96To pick the tools yourself, pass `include`:
97
98```ts group=harness-code-mode
99export const onlyIssues = codeMode({
100 driver: createQuickJSIsolateDriver(),
101 include: (tool) => tool.name.endsWith('_issue') || tool.name.endsWith('_issues'),
102})
103```
104
105- `include` can also pick a tool that asks or that declares `PermissionResources`, for example a [coding tool](#run-the-coding-tools-in-a-program). Each call of such a tool in a program gets the decision of a direct call.
106- `include` never moves a tool with `needsApproval`, or a tool that the rules deny in the mode of the session. A `deny` rule with a `resource` also counts, for example `{ tool: 'read_file', resource: '.env', decision: 'deny' }`. Such a tool stays a normal tool call, and code mode writes one warning to the host `logger` (the console by default).
107- The rules decide again at each turn, in the permission mode of the session. So in `plan` mode, a tool that edits or runs a command stays a normal tool call.
108- A safe tool with `metadata.codeMode: true` moves even when `include` does not pick it.
109
110The other options of `createCodeMode` pass through: `timeout`, `memoryLimit`, `lazyToolsConfig`, and more.
111
112## 4. Send only the tool names
113
114The prompt of code mode lists each moved tool with its full TypeScript type. With 100 tools, that is a lot of tokens on every turn, and most turns use a few tools. Set `lazy: true`, and the prompt lists only the names:
115
116```ts group=harness-code-mode
117export const lazyCodeMode = codeMode({
118 driver: createQuickJSIsolateDriver(),
119 lazy: true,
120 lazyToolsConfig: { includeDescription: 'first-sentence' },
121})
122```
123
124The model then works in three steps:
125
1261. It reads the tool names in the prompt.
1272. It calls `discover_tools` with the names it needs, and gets their TypeScript signatures.
1283. It calls those tools in `execute_typescript`.
129
130`includeDescription` sets what the prompt shows with each name: `'none'` (the default, the name only), `'first-sentence'`, or `'full'`. Tools that stay outside code mode keep their full schema.
131
132## Run the coding tools in a program
133
134To fix a bug, the model reads a file, edits it, and runs the tests. Each step is a tool call and a model round trip. Move the [coding tools](./coding-tools) into code mode, and one program does all the steps. Each call in the program still gets the [permission rules](./permissions) of its tool.
135
136```ts group=harness-code-mode-coding
137import { codeMode } from '@tanstack/ai-code-mode/harness'
138import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
139import { permissions } from '@tanstack/ai-harness/plugins'
140import { workspaceTools } from '@tanstack/ai-harness/plugins/coding'
141import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
142import { openaiText } from '@tanstack/ai-openai'
143import { memoryPersistence } from '@tanstack/ai-persistence'
144
145const root = process.cwd()
146
147export const coder = defineHarness({
148 name: 'acme/coder',
149 adapter: openaiText('gpt-6.1-sol'),
150 plugins: () => [
151 permissions({ root }),
152 workspaceTools({ root }),
153 codeMode({ driver: createQuickJSIsolateDriver(), include: () => true }),
154 ],
155})
156```
157
158`include: () => true` picks every tool of this harness. Mount `codeMode()` after `workspaceTools()`. Then the program gets the same edit tool as the model: `editStyle` picks `edit_file` or `patch`. With the default `'auto'`, a GPT model gets `patch`.
159
160Each `external_*` call of a coding tool gets the decision of a direct call, for the paths and the commands of the call:
161
162- `allow`: the call runs.
163- `deny`: the call throws in the program, with the reason. For example, in `plan` mode a read of `.env` throws `This tool is not allowed in plan mode.`
164- `ask`: the program waits for the user. A yes runs the call, and a no makes the call throw.
165
166The prompt of code mode tells the model that these calls can wait and can throw.
167
168### Answer the question
169
170A call that asks opens a [wait](./waits) of kind `question`, with the schema of an approval. The turn does not stop while the program waits. Answer the question with `session.answer`:
171
172```ts group=harness-code-mode-coding
173const host = createHarnessHost({ persistence: memoryPersistence() })
174const session = await host.open(coder, { threadId: 'main' })
175
176const turn = session.send('Run the tests, then fix the first failure.')
177const wait = await session.waitForRun({ runId: turn.id })
178// wait.kind is 'question'. wait.message is, for example:
179// Allow bash {"command":"pnpm test"}? Answer once, always, or reject.
180await session.answer({ questionId: wait.waitId, value: 'once' })
181```
182
183In a UI, the question is an item of `questions` in a [session view](./custom-ui#show-a-question). In the [CLI](./cli#commands-in-line-mode), type the answer.
184
185```ts group=harness-code-mode-coding
186import { createSessionView } from '@tanstack/ai-harness/view'
187
188const view = createSessionView(session)
189
190// Your buttons call this with 'once', 'always', or 'reject'.
191async function answerQuestion(answer: 'once' | 'always' | 'reject') {
192 const [question] = view.store.get().questions
193 await question?.answer(answer)
194}
195```
196
197- `'once'` runs the call. `'always'` also saves an allow rule, as a direct approval does.
198- `'reject'` rejects the call, so it throws. `{ answer: 'reject', message: 'Use pnpm, not npm.' }` also gives the program your message as the error.
199- An answer that does not fit the schema, for example `'y'`, gets a `rejected` receipt, and the question stays open.
200- The program continues after the answer. Each later call that asks opens a new question.
201- In an agent that the model calls as a tool, a call that asks does not run. That agent cannot ask the user, so the call throws.
202
203### Time limits and host stops
204
205A program has 30 seconds by default. With a coding tool in it, the default is 10 minutes, because the wait for the user counts. Set `timeout` in milliseconds to change it. When the time runs out, the program stops, and its open question closes.
206
207With a coding tool, `execute_typescript` is a [durable tool](./durable-tools). The session log keeps the result of each finished call of a coding tool. After a host stop, the next host runs the program again: a finished call returns its kept result, and the same question waits. If the stop cut an edit or a command while it ran, that call throws and does not run again.
208
209## Keep direct calls
210
211A moved tool leaves the tool list of the model. Then the model needs a program even for one small call. Set `directCalls: 'keep'`, and the model can call each moved tool directly too:
212
213```ts group=harness-code-mode
214export const keepDirect = codeMode({
215 driver: createQuickJSIsolateDriver(),
216 directCalls: 'keep',
217})
218```
219
220- `'remove'` (default): a moved tool is only a function in the program.
221- `'keep'`: a moved tool is also a normal tool. A direct call gets its approval, as any tool call does.
222- `directCalls` is also a session setting: `session.setPluginSetting({ key: 'directCalls', value: 'keep' })`, or `/config directCalls keep` in the [CLI](./cli#commands-in-line-mode). A change applies from the next turn.
223- A client can change it only with `directCalls` in `expose.config`. See [Choose what clients can change](./connect#choose-what-clients-can-change).
224
225## Tools that appear while the session runs
226
227The plugin chooses the tools again before every turn. A plugin that finds tools at run time with `discoverTools` (for example after a sign-in) adds them first, and code mode picks from them on the next turn. Tool names that are not JavaScript identifiers, for example `notion-search`, get a safe name inside the program: `external_notion_search`. When two tools get the same safe name, only the first one moves. The other one stays a normal tool call.
228
229## What you have now
230
231- One `execute_typescript` tool in place of many tool calls.
232- Programs that read, edit, and run commands, under the same permission rules as a direct call.
233- With `lazy: true`, a prompt that lists only the tool names.
234- Programs that run in the isolate you choose.
235- An approval for each call that asks, in a program or as a normal tool call.