Open History to see the last commit
1---
2title: Give your agent coding tools
3id: harness-coding-tools
4order: 6
5description: "Let a harness agent read, change, and search files, run commands, and read web pages, with a question before each risky call."
6keywords:
7 - tanstack ai
8 - harness
9 - coding agent
10 - workspace tools
11 - permissions
12 - formatter
13---
14
15Your agent must read and change the files of a project, search them, and run commands like `pnpm test`. It must stay in that project, and it must ask before it changes a file. `workspaceTools()` gives the model these tools for one folder. `permissions()` asks the user before each risky call.
16
17## 1. Install
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21react: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
22vue: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
23solid: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
24svelte: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
25preact: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
26angular: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
27octane: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
28vanilla: @tanstack/ai @tanstack/ai-harness @tanstack/ai-persistence @tanstack/ai-openai
29
30<!-- ::end:tabs -->
31
32Two optional packages make the tools better:
33
34<!-- ::start:tabs variant="package-manager" mode="install" -->
35
36react: @vscode/ripgrep turndown
37vue: @vscode/ripgrep turndown
38solid: @vscode/ripgrep turndown
39svelte: @vscode/ripgrep turndown
40preact: @vscode/ripgrep turndown
41angular: @vscode/ripgrep turndown
42octane: @vscode/ripgrep turndown
43vanilla: @vscode/ripgrep turndown
44
45<!-- ::end:tabs -->
46
47- `@vscode/ripgrep`: a fast `rg` binary for `list_files` and `grep`. Without it, the tools use `rg` on the `PATH`. Without `rg`, they use `git ls-files`, then a walk through the folders.
48- `turndown`: `webfetch` gives HTML pages as Markdown. Without it, HTML pages come back as plain text.
49
50## 2. Add the tools
51
52```ts group=harness-coding-tools
53import { randomUUID } from 'node:crypto'
54import { createInterface } from 'node:readline/promises'
55import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
56import type { RunAgentResumeItem } from '@tanstack/ai'
57import { permissions } from '@tanstack/ai-harness/plugins'
58import { workspaceTools } from '@tanstack/ai-harness/plugins/coding'
59import { openaiText } from '@tanstack/ai-openai'
60import { memoryPersistence } from '@tanstack/ai-persistence'
61
62const root = process.cwd()
63
64const coder = defineHarness({
65 name: 'acme/coder',
66 adapter: openaiText('gpt-6.1-sol'),
67 plugins: () => [permissions({ root }), workspaceTools({ root })],
68})
69
70const host = createHarnessHost({ persistence: memoryPersistence() })
71const session = await host.open(coder, { threadId: 'main' })
72const terminal = createInterface({
73 input: process.stdin,
74 output: process.stdout,
75})
76
77// Print the text of every turn, also of a turn that continues after an answer.
78const stopPrinting = session.onEvent('TEXT_MESSAGE_CONTENT', ({ event }) => {
79 process.stdout.write(event.delta)
80})
81
82// A risky call stops the turn before it runs. Ask about each approval of
83// the turn, then send all the answers in one resolve.
84async function answerApprovals() {
85 let waits = session.snapshot().pendingWaits
86 while (waits.length > 0) {
87 const resume: Array<RunAgentResumeItem> = []
88 for (const wait of waits) {
89 const answer = await terminal.question(`\n${wait.message ?? wait.kind} (once/always/reject) `)
90 resume.push({ interruptId: wait.waitId, status: 'resolved', payload: answer })
91 }
92 const inputId = randomUUID()
93 await session.resolve({ resume, inputId })
94 await session.settled({ inputId })
95 waits = session.snapshot().pendingWaits
96 }
97}
98
99// Send each line as a prompt. Type `exit` to stop.
100let line = await terminal.question('\n> ')
101while (line !== 'exit') {
102 try {
103 await session.send(line)
104 await answerApprovals()
105 } catch (error) {
106 // A failed turn rejects. Show the error and keep the loop.
107 console.error(error)
108 }
109 line = await terminal.question('\n> ')
110}
111stopPrinting()
112terminal.close()
113await host.close()
114```
115
116`@tanstack/ai-harness/plugins/coding` runs only in Node. The tools use the file system and the shell of the machine. For code that you do not trust, [run the tools in a sandbox](./coding-tools-backends#run-the-tools-in-a-sandbox).
117
118## 3. Run it
119
1201. Run `npx tsx coder.ts` in your project.
1212. Ask: `find the failing test and fix it`.
1223. When the agent wants to change a file or run a command, the turn stops, and the script asks in the terminal. Answer `once`, `always`, or `reject`.
123
124The agent reads and searches without a question. For a full coding agent with undo, a todo list, and a model picker, see [Build a coding agent](./coding-agent).
125
126## The tools
127
128### Read and search
129
130These tools run without a question.
131
132| Tool | What it does |
133| --- | --- |
134| `read_file` | Reads a text file as numbered lines, at most 2000 lines or 50 KiB a page. The model reads more with `offset` and `limit`. |
135| `list_files` | Lists the files in a folder. An optional glob, like `src/**/*.ts`, filters them. |
136| `grep` | Searches the file contents with a regular expression. Gives `file:line: text`. |
137
138- `read_file` gives images (PNG, JPEG, GIF, WebP) and PDFs up to 256 KB to the model as media. For a bigger file, the model gets an error that tells it to make a smaller copy.
139- `read_file` refuses a binary file with a short note. For a missing file, it names up to 3 files with a close name.
140- `list_files` and `grep` skip the files that `.gitignore` names, the `.git` and `node_modules` folders, and links.
141- `list_files` shows at most 1000 files. `grep` shows at most 200 matches.
142
143### Change files
144
145These tools ask first.
146
147| Tool | What it does |
148| --- | --- |
149| `write_file` | Creates or replaces a file. |
150| `edit_file` | Replaces text in a file. The old text must be in the file once, unless the model sets `replaceAll`. |
151| `patch` | Applies a patch that adds, deletes, updates, or moves files. |
152
153A model gets `edit_file` or `patch`, not both. Every model gets `write_file`. The `editStyle` option picks the edit tool:
154
155- `'auto'` (default): GPT models (ids that start with `gpt-`, or `o` and a digit, like `o3`) get `patch`. Other models get `edit_file`.
156- `'edit'` or `'patch'`: every model gets that tool.
157
158`edit_file` keeps the line endings and the byte order mark of the file. It also finds text that is different only in Unicode form or in the spaces at the end of a line.
159
160When a file changed after the model read it, for example by another agent, the three tools fail. The model reads the file again, then edits it.
161
162To let the user undo the changes of a turn, add [snapshots](./snapshots).
163
164### Commands and the web
165
166| Tool | What it does | Asks first |
167| --- | --- | --- |
168| `bash` | Runs a shell command in the working folder. | Yes |
169| `webfetch` | Reads a web page by its URL. | Yes |
170| `websearch` | Searches the web. It is there only with a search provider. | No |
171
172For `bash`:
173
174- The model gets the exit code and the last 1000 lines (20 KiB) of the output.
175- A command stops after 2 minutes, with exit code 124. Every process that it started stops too. Set another limit with `bashTimeoutMs`. The model can ask for up to 10 minutes.
176- With `spillDir`, long output goes to a file in that folder, and the model gets the path. `spillDir` is relative to `root`, or absolute. The file has `[redacted]` in place of each secret of the session, the same as the tool result. See [Keep tokens out of the log and the model](./auth#keep-tokens-out-of-the-log-and-the-model).
177- A command gets only a few variables of your process, like `PATH` and `HOME`. Your provider keys are not in its env. On the host this is not isolation: a command can still read the files of your server. See [Keep server secrets out of commands](./coding-workspaces#2-keep-server-secrets-out-of-commands).
178
179With `background: true`, the call returns at once with a job id. When the job ends, the model gets a note with the output, and a new turn starts. That turn runs as the user whose run started the job.
180
181- The time limit does not apply to a background job.
182- At most 8 background jobs run at a time in a session. Set another limit with `maxJobs`. Each job keeps the newest 1 MiB of its output.
183- When the session closes, the background jobs stop.
184- The log keeps each background job until it ends. When a crash stops a job, the next host adds the note "Background job bash-1 stopped when the host restarted."
185
186On Windows, the default backend runs commands in `cmd.exe`. A program name like `rg` or `gradlew` comes from the `PATH` only, not from the working folder. So a cloned repo cannot put its own `rg.cmd` in place of `rg`. To run a script in the working folder, give its path: `.\gradlew build`.
187
188For `webfetch`:
189
190- It reads `http` and `https` URLs only, and follows at most 5 redirects.
191- It refuses `localhost`, private network addresses, and cloud metadata addresses. It checks the DNS answer of each connection.
192- HTML comes back as Markdown, or as text without `turndown`. The model can ask for `format: 'html'`. Text and JSON come back as they are.
193- The model gets the first 256 KB of a page, with a note when there is more. It reads at most 5 MB.
194- It stops after 30 seconds, and the model can ask for up to 120 seconds.
195
196Change the web tools with the `web` option:
197
198- `web: false`: no web tools.
199- `web: { allowPrivateHosts: true }`: `webfetch` can read `localhost` and your private network. Set it only for a model that is allowed to reach your network.
200- `web: { search }`: adds `websearch`.
201
202There is no built-in search engine. Give `websearch` a `SearchProvider`:
203
204```ts group=harness-coding-tools
205import type { SearchProvider } from '@tanstack/ai-harness/plugins/coding'
206import { searchTheWeb } from './search'
207
208const search: SearchProvider = {
209 search: (query, { limit, signal }) => searchTheWeb(query, { limit, signal }),
210}
211
212export const withSearch = workspaceTools({ root, web: { search } })
213```
214
215The provider gives at most `limit` results. Each result is `{ title, url, snippet? }`. The model reads a result with `webfetch`.
216
217## Permissions and approvals
218
219Each tool tells `permissions()` what kind of call it makes:
220
221| Tools | `default` mode | `plan` mode |
222| --- | --- | --- |
223| `read_file`, `list_files`, `grep`, `websearch` | Runs | Runs |
224| `write_file`, `edit_file`, `patch` | Asks | Denied |
225| `bash` | Asks | Denied |
226| `webfetch` | Asks | Denied |
227
228- `acceptEdits` mode runs the edits without a question. `bash` still asks.
229- `bypass` mode runs every call.
230- `read_file` asks for a `.env` file.
231- `grep` skips each file that `read_file` asks about or denies, also in `plan` mode. A note at the end gives the number of skipped files.
232- `list_files` still shows the names of these files. A name is not the contents.
233
234Let `webfetch` run without a question with one rule:
235
236```ts group=harness-coding-tools
237export const trustTheWeb = permissions({
238 root,
239 rules: [{ tool: 'webfetch', decision: 'allow' }],
240})
241```
242
243In `plan` mode, a call that asks is denied. This rule makes `webfetch` an allow, so `webfetch` runs in `plan` mode too.
244
245Each call also tells `permissions()` the paths or the commands that it touches. So a rule with a `resource` can allow one folder or one command:
246
247```ts group=harness-coding-tools
248export const trustTests = permissions({
249 root,
250 rules: [
251 { tool: 'edit_file', resource: 'src/**', decision: 'allow' },
252 { tool: 'bash', resource: 'pnpm test*', decision: 'allow' },
253 ],
254})
255```
256
257- Paths match from `root`. Give `permissions()` and `workspaceTools()` the same `root`.
258- A rule also matches the real path of a link, and the stricter decision wins. So a link `notes` to `.env` asks, and a `deny` for `secrets/**` also stops a link to `secrets`.
259- The rules decide every path before the call runs, so a tool never asks while it runs. In a [code mode program](./code-mode#run-the-coding-tools-in-a-program), a call that asks makes the program wait, and the turn does not stop.
260- `bash` splits a command at `&&`, `||`, `;`, `|`, and new lines. Every part must be allowed.
261- A command with `$(`, a backtick, or a heredoc never gets an allow.
262
263[Permissions](./permissions) explains the rules, the modes, and the saved answers.
264
265## Outside paths and the working folder
266
267### A path outside `root`
268
269The tools refuse a path outside `root`. To let the user approve it, set `outside: 'ask'`:
270
271```ts group=harness-coding-tools
272export const askOutside = workspaceTools({ root, outside: 'ask' })
273```
274
275`permissions()` decides the outside path before the call runs. The path is a part of the one [approval](./permissions#answer-an-approval) of the call, so the tool never stops in the middle of a call to ask. For a direct call, the turn stops, and you answer with `resolve`. In a [code mode program](./code-mode#answer-the-question), the program waits, and you answer with `session.answer`.
276
277- `once` allows this call. `always` also saves an allow rule for the path.
278- `reject` stops the call. The call does not run, so nothing is read or written.
279- A link in `root` that leads out of `root` counts as outside. The rules decide its real path.
280- `bypass` mode allows every path without a question. Without `permissions()`, nobody can approve the path, so the tool refuses it.
281- With `permissions()`, `grep` skips the files outside `root`, because `read_file` asks for them. A `read_file` rule for that folder, for example `{ tool: 'read_file', resource: '/shared/**', decision: 'allow' }`, lets `grep` show them.
282
283With a [workspace for each thread](./coding-workspaces), the root is not known before the call, so no approval can cover an outside path. Then only a rule that allows the path, or `bypass` mode, lets the call use it.
284
285### A working folder for each thread
286
287Each thread can work in its own folder in `root`. Set the `cwd` thread setting:
288
289```ts group=harness-coding-tools-cwd
290import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
291import { workspaceTools } from '@tanstack/ai-harness/plugins/coding'
292import { memoryPersistence } from '@tanstack/ai-persistence'
293import { openaiText } from '@tanstack/ai-openai'
294
295const repos = defineHarness({
296 name: 'acme/repos',
297 adapter: openaiText('gpt-6.1-sol'),
298 plugins: () => [workspaceTools({ root: '/srv/repos' })],
299})
300
301const host = createHarnessHost({ persistence: memoryPersistence() })
302const session = await host.open(repos, { threadId: 'fix-login' })
303await session.updateThreadSettings({ settings: { cwd: 'web-app' } })
304```
305
306- Relative paths start in `/srv/repos/web-app`, and `bash` runs there.
307- The system prompt tells the model the working folder.
308- Permission rules still match paths from `root`, for example `web-app/src/**`.
309- `cwd` is relative to `root`. The tools refuse a `cwd` outside `root`, also with `outside: 'ask'`.
310
311[Store settings per thread](./thread-settings) shows how a client sets `cwd`.
312
313## What you have now
314
315- An agent that reads, searches, and changes the files of one folder, and runs commands in it.
316- A question before each edit, command, and web fetch.
317- A working folder for each thread, and a question before a path outside `root`.
318
319Next: run the same tools in a sandbox, or format each file after a write. See [Sandbox and extend the coding tools](./coding-tools-backends). To give each thread its own folder on a server, see [Run the coding tools for many threads](./coding-workspaces).