Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

coding-tools-backends.md

347 lines16.4 KB

1---
2title: Sandbox and extend the coding tools
3id: harness-coding-tools-backends
4order: 7
5description: "Run the coding tools in a sandbox or on your own backend, format each written file, and keep tool output small."
6keywords:
7 - tanstack ai
8 - harness
9 - coding agent
10 - workspace tools
11 - sandbox
12 - formatter
13 - workspace hooks
14---
15​
16Your agent must work on files that are not on this machine, or on code that you do not trust. Or you want code to run after each write, like a formatter. The [coding tools](./coding-tools) send every read, write, and command through a backend, and they run hooks after each read and write. This page shows how to change both.
17​
18## Run the tools in a sandbox
19​
20By default, the tools run on your machine, with the rights of your user. For code that you do not trust, run them in a sandbox. `sandboxWorkspaceBackend()` sends every read, write, and command to the sandbox.
21​
221. Install the sandbox packages:
23​
24<!-- ::start:tabs variant="package-manager" mode="install" -->
25​
26react: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
27vue: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
28solid: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
29svelte: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
30preact: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
31angular: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
32octane: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
33vanilla: @tanstack/ai-sandbox @tanstack/ai-sandbox-docker
34​
35<!-- ::end:tabs -->
36​
372. Start a sandbox, and give its backend to `workspaceTools()`:
38​
39```ts group=harness-coding-tools-sandbox
40import { defineHarness } from '@tanstack/ai-harness'
41import { permissions } from '@tanstack/ai-harness/plugins'
42import { workspaceTools } from '@tanstack/ai-harness/plugins/coding'
43import { openaiText } from '@tanstack/ai-openai'
44import { sandboxWorkspaceBackend } from '@tanstack/ai-sandbox/harness'
45import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
46​
47const sandbox = await dockerSandbox({ image: 'node:22' }).create({})
48// Without `dir`, the clone goes to the workspace root, /workspace.
49await sandbox.git.clone({ url: 'https://github.com/acme/web-app.git' })
50​
51const root = '/workspace'
52​
53export const sandboxed = defineHarness({
54 name: 'acme/sandboxed-coder',
55 adapter: openaiText('gpt-6.1-sol'),
56 plugins: () => [
57 permissions({ root }),
58 workspaceTools({ root, backend: sandboxWorkspaceBackend(sandbox) }),
59 ],
60})
61```
62​
63To give the agent the project folder on your machine, [copy it into the container](#copy-your-project-into-the-container).
64​
653. When you are done, stop the sandbox with `await sandbox.destroy()`.
66​
67Every provider works. Get the handle from `create()`, or from `resume()` for a sandbox that runs already. See [Providers](../sandbox/providers). To create a sandbox for each thread, and resume it on another server, see [Run the coding tools for many threads](./coding-workspaces).
68​
69In a sandbox, some things are different:
70​
71- Paths are POSIX paths in the sandbox, like `/workspace/src/a.ts`, also on a Windows host.
72- The tools check where links lead with `lstat` and `readlink` in the sandbox. A sandbox without `lstat` cannot find links, so the tools refuse every path.
73- `background: true` needs a sandbox with `capabilities.backgroundProcesses`.
74- A sandbox with `capabilities.killableProcesses` off cannot stop a command after the time limit. The call returns, and the command continues in the sandbox.
75- `list_files` and `grep` use `rg` in the sandbox. The `@vscode/ripgrep` binary is a host file, so the sandbox does not use it.
76- When the run stops, the file calls of a tool in the sandbox get the abort signal too, so they stop with the run.
77​
78### Copy your project into the container
79​
80A clone has only the commits that you pushed. To give the agent your project as it is now, copy its folder into the container. In step 2, replace the `create({})` and `git.clone()` lines with this code:
81​
82```ts group=harness-coding-tools-local-source
83import { defineWorkspace, localSource } from '@tanstack/ai-sandbox'
84import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
85​
86// Run this script in the root folder of your repository.
87const sandbox = await dockerSandbox({ image: 'node:24' }).create({
88 workspace: defineWorkspace({ source: localSource(process.cwd()) }),
89})
90```
91​
92The tools now work on your project in `/workspace`.
93​
94- The copy has every file that git does not ignore, with its uncommitted changes. Ignored files, like `node_modules`, stay on your machine, so install the dependencies in the container.
95- The copy has the current branch with its history, so `git status` in the container shows your uncommitted changes. Staged changes show as unstaged.
96- The folder must be the root of a git repository or a git worktree, and not a shallow clone. Otherwise, `create()` throws before it starts a container.
97- Your machine and the image both need `git`. `node:24` has `git`, and `alpine` does not.
98- `create()` copies the folder once. Your folder does not get the changes that the agent makes in the container.
99​
100## Write your own backend
101​
102A `WorkspaceBackend` is where the tools read and write files and run commands. Write one for another place, for example a remote machine. Every path that the tools give it is absolute.
103​
104The backend must have:
105​
106| Method | What it does |
107| --- | --- |
108| `readFile(path)` | Gives the bytes of a file. Throws when there is no file. |
109| `writeFile(path, data)` | Creates or replaces a file. Creates the missing parent folders. |
110| `stat(path)` | Gives `{ type, size, mtimeMs }`, or `undefined` when nothing is at `path`. It does not read the file. |
111| `realpath(path)` | Gives the path with every link resolved, or `undefined` when nothing is at `path`. Throws when it cannot resolve a path. |
112| `readdir(path)` | Gives the entries of a folder. A link has the type `'link'`. |
113| `exec(command, options)` | Runs a shell command and waits. Gives `{ exitCode, stdout, stderr }`. |
114​
115- `exec` resolves with the exit code of a command that fails. It does not throw.
116- After `options.timeoutMs`, `exec` stops the command with every process that it started, and gives exit code 124. `options.signal` stops it too.
117- `options.env` holds the variables to add. Give a command only these and the few variables that it needs to start. Do not give it the variables of your server.
118- When `realpath` throws, the tool call fails. So a path with a link that the backend cannot resolve is never used.
119- Each file method gets an optional last argument, `{ signal }`. It is the abort signal of the tool call. Give it to your file calls, so a stopped run stops them too. `readLines` gets `signal` in its options.
120​
121The backend can also have:
122​
123| Member | What it does | Without it |
124| --- | --- | --- |
125| `shell` | `'sh'` or `'cmd'`. Sets the path style and how arguments are quoted. | `sh` quotes, and the path style of this machine. |
126| `remove(path)` | Removes one file. | `patch` cannot delete or move files. |
127| `readLines(path, { offset, limit })` | Gives one page of a file: `{ head, size, lines, total }`. `head` is the first 8 KiB. | `read_file` reads the whole file for each page. |
128​
129For background jobs and for threads that move to another server:
130​
131| Member | What it does | Without it |
132| --- | --- | --- |
133| `spawn(command, options)` | Starts a command in the background. Gives `{ wait, kill, output, jobId? }`. `jobId` resolves with the id of the process, for `killJob`. | `background: true` gives an error. |
134| `killJob(jobId)` | Stops a job that `spawn` started, also on an earlier process or machine. Resolves `false` when no such job runs. Rejects when it cannot check that the process is the job: then the log keeps the job. | A job that a crash left running is not stopped. |
135| `exec` option `onStart(jobId)` | Gives the id of a foreground command when it starts, so a command that moves to the background can be stopped by a later host too. | A moved command has no id in the log. |
136| `binding()` | Gives `{ kind: 'sandbox', provider, sandboxId }` for a sandbox that another machine can resume. | The workspace is a folder on this host. |
137| `close({ reason })` | Releases the backend. `'closed'`: the session closed. `'moved'`: the session continues on another machine, so keep what it can resume. | Nothing to release. |
138​
139`close` must never destroy a sandbox that the backend did not create.
140​
141The fastest start is to wrap `hostBackend`. This backend logs each command before it runs:
142​
143```ts group=harness-coding-tools-backends
144import { hostBackend, workspaceTools } from '@tanstack/ai-harness/plugins/coding'
145import type { WorkspaceBackend } from '@tanstack/ai-harness/plugins/coding'
146​
147const root = process.cwd()
148​
149const logged: WorkspaceBackend = {
150 ...hostBackend,
151 exec: (command, options) => {
152 console.log(`$ ${command}`)
153 return hostBackend.exec(command, options)
154 },
156​
157export const loggedTools = workspaceTools({ root, backend: logged })
158```
159​
160Only `hostBackend` itself uses the `@vscode/ripgrep` binary. A wrapped backend uses `rg` on the `PATH`.
161​
162## Run code after a read or a write
163​
164Another plugin can add code that runs after the tools read or write a file. Add a `WorkspaceHooks` item:
165​
166```ts group=harness-coding-tools-backends
167import { definePlugin } from '@tanstack/ai-harness'
168import { WorkspaceHooks } from '@tanstack/ai-harness/plugins/coding'
169​
170export const generatedFiles = definePlugin({
171 name: 'acme/generated-files',
172 setup: () => ({
173 contribute: [
174 WorkspaceHooks.item({
175 afterRead: async (path) =>
176 path.endsWith('.gen.ts')
177 ? 'This file is generated. Change its source, not this file.'
178 : undefined,
179 afterWrite: async (path) => {
180 console.log(`changed ${path}`)
181 },
182 }),
183 ],
184 }),
185})
186```
187​
188- `afterRead` gets the absolute path. The text that it gives is added after the lines that `read_file` shows.
189- `afterWrite` runs after `write_file`, `edit_file`, and `patch`.
190- A hook runs while the tool holds the lock on that path. A hook that throws fails the tool call.
191​
192Add the plugin next to the tools: `plugins: () => [workspaceTools({ root }), generatedFiles]`.
193​
194## Refuse a write
195​
196Add a `beforeWrite` hook to stop a write before it changes a file. Return `{ refuse }`, and the tool call fails with that text:
197​
198```ts group=harness-coding-tools-refuse-write
199import { definePlugin } from '@tanstack/ai-harness'
200import { WorkspaceHooks } from '@tanstack/ai-harness/plugins/coding'
201​
202export const protectGenerated = definePlugin({
203 name: 'acme/protect-generated',
204 setup: () => ({
205 contribute: [
206 WorkspaceHooks.item({
207 beforeWrite: async (path) =>
208 path.endsWith('.gen.ts')
209 ? { refuse: `${path} is generated. Change its source.` }
210 : undefined,
211 }),
212 ],
213 }),
214})
215```
216​
217- `beforeWrite` gets the absolute path. It runs before `write_file`, `edit_file`, and `patch` change the file.
218- A `patch` asks for each file that it changes before its first write. One refusal fails the whole patch, and no file changes.
219- The hook runs before the tool takes the lock on the path.
220​
221## Format each file after a write
222​
223The model writes code that your formatter changes later, and the diff gets noisy. `formatter()` formats each file that the tools write:
224​
225```ts group=harness-coding-tools-backends
226import { defineHarness } from '@tanstack/ai-harness'
227import { permissions } from '@tanstack/ai-harness/plugins'
228import { formatter } from '@tanstack/ai-harness/plugins/coding'
229import { openaiText } from '@tanstack/ai-openai'
230​
231export const formatted = defineHarness({
232 name: 'acme/formatted-coder',
233 adapter: openaiText('gpt-6.1-sol'),
234 plugins: () => [
235 permissions({ root }),
236 workspaceTools({ root }),
237 formatter({ root }),
238 ],
239})
240```
241​
242At the first write of a session, `formatter()` looks at the files in `root`. For each file, the first formatter that the project uses for that file type runs.
243​
244For JavaScript, TypeScript, JSON, CSS, and other web files:
245​
246| Formatter | Runs when `root` has |
247| --- | --- |
248| prettier | `.prettierrc*`, `prettier.config.*`, or a `prettier` field in `package.json` |
249| biome | `biome.json` or `biome.jsonc` |
250| oxfmt | `.oxfmtrc*`, or `oxfmt` in the `devDependencies` |
251​
252These three run with `npx --no-install`, so the project must have them installed.
253​
254For other languages:
255​
256| Formatter | Files | Runs when `root` has |
257| --- | --- | --- |
258| ruff | `.py`, `.pyi` | `ruff.toml`, `.ruff.toml`, or `[tool.ruff]` in `pyproject.toml` |
259| gofmt | `.go` | `go.mod` |
260| rustfmt | `.rs` | `Cargo.toml` |
261​
262Add your own formatter. Your formatters come before the built-in ones:
263​
264```ts group=harness-coding-tools-backends
265export const withToml = formatter({
266 root,
267 formatters: [
268 {
269 name: 'taplo',
270 extensions: ['.toml'],
271 command: (file) => `taplo fmt ${file}`,
272 },
273 ],
274})
275```
276​
277- `command` gets the absolute path, already quoted for the shell.
278- `when(project)` limits a formatter to some projects. Without it, the formatter is used in every project.
279- `builtins: false` turns the built-in formatters off.
280- `timeoutMs` limits each run. The default is 20 seconds.
281- In a sandbox or on your own backend, give `formatter()` the same `backend` as `workspaceTools()`.
282- With [`workspaceTools({ workspace: { bind } })`](./coding-workspaces) before it, `formatter()` runs in the workspace of each thread. Leave out `root` and `backend`.
283​
284A formatter that fails, stops at the time limit, or is not installed does not fail the tool call. The file stays as the tool wrote it, and the plugin sends `FormatFailed`. A formatter that changes the file sends `FormatterRewrote` with `{ path, formatter }`:
285​
286```ts group=harness-coding-tools-backends
287import { FormatFailed } from '@tanstack/ai-harness/plugins/coding'
288​
289export const formatAlerts = definePlugin({
290 name: 'acme/format-alerts',
291 setup: (ctx) => {
292 ctx.on(FormatFailed, (failure) =>
293 console.warn(`${failure.path}: ${failure.message}`),
294 )
295 },
296})
297```
298​
299Clients get the same events as a `harness.plugin.event` with the name `tanstack/formatter:failed` or `tanstack/formatter:rewrote`.
300​
301### One approval covers the write and its formatter
302​
303A formatter runs code from the project, like `prettier.config.js`. The model can change that code with an edit. So with `permissions()`, the rules decide the formatter as a part of the call that writes. The rule names the run `formatter:prettier`, `formatter:biome`, and so on.
304​
305The rules decide before the call runs, and the formatter runs after the write. The call never stops in the middle to ask.
306​
307- When the formatter asks, the call asks one time for the write and the formatter, also in `acceptEdits` mode. Answer that [approval](./permissions#answer-an-approval) with `resolve`.
308- A `reject` stops the call. Nothing is written, and the formatter does not run.
309- Answer `always` once, and the formatter runs without a question in this project. The answer is tied to a hash of the formatter config files, like `prettier.config.js` and `package.json`. When they change, the next write asks again.
310- A rule that denies the formatter keeps the write. The tool result says that the formatter did not run.
311- A rule can allow a formatter: `{ tool: 'formatter:prettier', decision: 'allow' }`. Without `permissions()`, the formatter runs without a question.
312​
313[Formatters](./permissions#formatters) shows what each mode does.
314​
315## Keep tool output small
316​
317One tool result with a full log or a big JSON file fills the context of the model. `boundToolOutput()` cuts every tool result that is too long:
318​
319```ts group=harness-coding-tools-backends
320import { boundToolOutput } from '@tanstack/ai-harness/plugins/node'
321​
322export const bounded = defineHarness({
323 name: 'acme/bounded-coder',
324 adapter: openaiText('gpt-6.1-sol'),
325 plugins: () => [
326 workspaceTools({ root }),
327 boundToolOutput({ dir: '.agent/tool-output' }),
328 ],
329})
330```
331​
332- A result over 2000 lines or 50 KiB keeps its first lines and gets a note. Set other limits with `maxLines` and `maxBytes`.
333- With `dir`, the full output goes to a file in `dir`, and the note gives the path. Files older than `retentionDays` (default 7) are removed.
334- It cuts the result of every tool, MCP tools too, in the lead turn and in agent runs.
335- An error stays an error. Images and other content parts do not change.
336​
337`read_file` and `bash` keep their output inside the default limits, so `boundToolOutput()` does not cut them again.
338​
339## What you have now
340​
341- The coding tools in a sandbox, with one option.
342- Your project in a Docker container, with its uncommitted changes.
343- A backend of your own for another place.
344- Code that runs after each read and each write.
345- Formatted files after each write, and tool results that fit the context.
346​
347Next: let the user undo the changes of a turn with [snapshots](./snapshots).