Open History to see the last commit
1---
2title: Run the coding tools for many threads
3id: harness-coding-workspaces
4order: 7
5description: "Give each thread of a coding agent its own folder or sandbox, keep server secrets out of commands, let agents share files safely, watch background jobs, and move a thread to another server."
6keywords:
7 - tanstack ai
8 - harness
9 - coding agent
10 - workspace tools
11 - sandbox
12 - multi-tenant
13 - background jobs
14---
15
16Your server runs coding agents for many users. Each thread must work in its own folder or sandbox. A command must not see the API keys of your server. Two agents in one folder must not lose each other's edits. And a thread must continue when another server takes it.
17
18`workspace: { bind }` gives each thread its own workspace. The session log keeps where that workspace is, so the next server finds it again.
19
20## 1. Give each thread its own workspace
21
22Pass `workspace` to `workspaceTools()` in place of `root`. `bind` gets the run, and gives a backend with its `root`:
23
24```ts group=harness-coding-workspaces
25import { mkdir } from 'node:fs/promises'
26import { defineHarness } from '@tanstack/ai-harness'
27import { permissions } from '@tanstack/ai-harness/plugins'
28import {
29 hostBackend,
30 workspaceRoot,
31 workspaceTools,
32} from '@tanstack/ai-harness/plugins/coding'
33import { openaiText } from '@tanstack/ai-openai'
34
35export const coder = defineHarness({
36 name: 'acme/coder',
37 adapter: openaiText('gpt-6.1-sol'),
38 plugins: () => [
39 permissions(),
40 workspaceTools({
41 workspace: {
42 bind: async ({ run }) => {
43 const root = workspaceRoot('/srv/workspaces', run.tenantId ?? 'default', run.threadId)
44 await mkdir(root, { recursive: true })
45 return { ...hostBackend, root }
46 },
47 },
48 }),
49 ],
50})
51```
52
53- The tools call `bind` once for each thread, before the first turn or at the first tool call. If `bind` throws, the next turn calls it again.
54- A client sends the thread id. Do not put it in a path with `join` or a template string: an id like `../other-tenant/t-1` leads into another folder. `workspaceRoot` encodes each part, so each id gets its own folder in `/srv/workspaces`, and it throws for a path that leaves it.
55- The `root` that `bind` gives is the boundary of the file tools. A path outside it is refused. With `outside: 'ask'`, a rule that allows the path, or `bypass` mode, lets a call use it. No approval can cover it, because the root is not known before the call. The `cwd` thread setting must stay inside it.
56- The tools resolve every link with `realpath` before they read or write, while they hold the lock on the file. So a link in one thread cannot lead into the folder of another thread.
57- The session log keeps a `harness.workspace.bound` record with the place of the workspace. [Move a thread to another server](#5-move-a-thread-to-another-server) uses it.
58- Put `workspaceTools()` before [`snapshots()`](./snapshots) and [`formatter()`](./coding-tools-backends#format-each-file-after-a-write). Then they work in the workspace of each thread, and their `root` is optional.
59
60A folder on the server is not isolation: `bash` runs as the user of your server (see [Keep server secrets out of commands](#2-keep-server-secrets-out-of-commands)). When many users share the server, give each thread a sandbox. Create it in `bind`, and give the backend `owned: true`. Then the thread owns the sandbox:
61
62```ts group=harness-coding-workspaces
63import { sandboxWorkspaceBackend } from '@tanstack/ai-sandbox/harness'
64import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
65
66const docker = dockerSandbox({ image: 'node:22' })
67
68export const sandboxed = workspaceTools({
69 workspace: {
70 bind: async () => ({
71 ...sandboxWorkspaceBackend(await docker.create({}), { owned: true }),
72 root: '/workspace',
73 }),
74 },
75})
76```
77
78- A session close (an idle close, a deploy, or a move to another server) closes the backend with `'moved'`. The sandbox stays, so the next server can [reattach](#a-sandbox) it.
79- [`host.sessions.delete`](./lifecycle#delete-a-thread-for-good) ends the thread. The host reattaches the sandbox and closes it with `'closed'`, so it is destroyed. The host that deletes must know the harness: it opened the harness, or it has the harness in its [`harnesses`](./lifecycle#delete-a-thread-for-good) option. Else it warns, and the sandbox stays.
80
81## 2. Keep server secrets out of commands
82
83A command gets only a few variables of the server process:
84
85- `PATH`, `HOME`, `LANG`, `LC_ALL`, `TMPDIR`, `TEMP`, and `TMP`.
86- On Windows also `SystemRoot`, `ComSpec`, `PATHEXT`, `WINDIR`, and `USERPROFILE`.
87- `AGENT=1`, so a tool can see that an agent runs it.
88
89Provider keys, `DATABASE_URL`, and the other variables of the server are not in the env of a command. The same rule applies to `bash`, `rg`, `git`, and the formatters. Git also runs without the hooks and the `fsmonitor` of the project.
90
91With `hostBackend`, and with the local-process sandbox, this short env and the `root` are defense in depth. They are not isolation:
92
93- A command runs as the user of your server. `bash` can read every file that this user can read, for example the `.env` file of the server, or the folder of another thread.
94- `bash` can also read the env of each process of that user, for example `/proc/<pid>/environ` of the server.
95
96For users that you do not trust, use [a sandbox for each thread](#1-give-each-thread-its-own-workspace).
97
98To give commands a variable, add it to the `env` of the backend calls:
99
100```ts group=harness-coding-workspaces
101import type { WorkspaceBackend } from '@tanstack/ai-harness/plugins/coding'
102
103const extra = { NPM_TOKEN: 'npm_read_only_token' }
104const { spawn } = hostBackend
105
106const withToken: WorkspaceBackend = {
107 ...hostBackend,
108 exec: (command, options) =>
109 hostBackend.exec(command, { ...options, env: { ...options?.env, ...extra } }),
110 spawn:
111 spawn &&
112 ((command, options) =>
113 spawn(command, { ...options, env: { ...options?.env, ...extra } })),
114}
115
116export const withTokenTools = workspaceTools({ root: '/srv/repo', backend: withToken })
117```
118
119`exec` runs the foreground commands. `spawn` runs the background commands.
120
121## 3. Let agents share a folder
122
123Two agents, or two sessions, can work in the same folder. No edit is lost:
124
125- A write holds a lock on the file. The lock is shared by every session on this server, and it is keyed by the sandbox (or this server) and the real path of the file. Two roots that lead to one folder share the lock. Two sandboxes with the same root do not.
126- `write_file`, `edit_file`, and `patch` fail when the file changed after the tool read it in the same agent run. A subagent and its lead each check their own read. The model gets `src/app.ts changed since it was read. Read it again before you edit it.`, reads the file again, and tries again.
127- The check compares the size and the time of the last change. A sandbox gives no change time, so there only a change of size is seen.
128
129## 4. Watch background jobs
130
131With `background: true`, `bash` returns at once with a job id like `bash-1`. Two limits keep jobs small:
132
133- At most 8 background jobs run at a time in a session. One more gives the model a tool error. Set another limit with `maxJobs`. A running command that `session.moveToolCallToBackground()` moves counts too, and at the limit it does not move.
134- Each job keeps the newest 1 MiB of its output.
135
136When a job ends, the model gets a note, and the wake turn runs as the user whose run started the job.
137
138To show the jobs that run now, for example in a status bar, call `session.jobs()`. A [view](./lifecycle#read-a-thread-without-a-session) of `host.observe` has `jobs()` too:
139
140```ts group=harness-coding-workspaces
141import type { HarnessSession } from '@tanstack/ai-harness'
142
143export function listJobs(session: HarnessSession) {
144 for (const job of session.jobs()) {
145 console.log(`${job.jobId}: ${job.label ?? 'job'}, started by ${job.user?.id ?? 'the agent'}`)
146 }
147}
148```
149
150Each entry has:
151
152- `jobId` and `threadId`: the job, and the thread of the workspace that runs it.
153- `label`: the command, or the name of the tool that `session.moveToolCallToBackground()` moved.
154- `user` and `startedAt`: who moved the call to the background, and when the job started.
155- `running`: `true` when this host runs the job. A job of another host, or one that a crash stopped, has `false`.
156- `backendId`: the id of the process in the workspace backend, when it has one.
157
158`session.jobs()` reads the log, so it also lists the jobs of other hosts. After a restart, it lists a job until the host notes that the job stopped.
159
160Each job sends events. Listen for them in a plugin:
161
162```ts group=harness-coding-workspaces
163import { definePlugin } from '@tanstack/ai-harness'
164import { JobEnded, JobOutput, JobStarted } from '@tanstack/ai-harness/plugins/coding'
165
166export const jobLog = definePlugin({
167 name: 'acme/job-log',
168 setup: (ctx) => {
169 ctx.on(JobStarted, (job) => console.log(`${job.jobId} started: ${job.command}`))
170 ctx.on(JobOutput, (job) => process.stdout.write(job.output))
171 ctx.on(JobEnded, (job) => console.log(`${job.jobId} ended: ${job.exitCode}`))
172 },
173})
174```
175
176A client gets each event as a `CUSTOM` event with the name `harness.plugin.event`. Its value is `{ plugin, name, value }`:
177
178```ts group=harness-coding-workspaces-client
179import { createHarnessClient } from '@tanstack/ai-harness/client'
180import type { coder } from './harness'
181
182const client = createHarnessClient<typeof coder>({
183 url: '/api/harness',
184 threadId: 'fix-login',
185})
186
187for await (const { event } of client.events()) {
188 if (event.type !== 'CUSTOM' || event.name !== 'harness.plugin.event') continue
189 const { value } = event
190 if (typeof value !== 'object' || value === null) continue
191 if (!('name' in value) || value.name !== 'tanstack/workspace-tools:job-output') continue
192 if ('value' in value) console.log(value.value)
193}
194```
195
196The coding plugins send these events:
197
198| Name | When |
199| --- | --- |
200| `tanstack/workspace-tools:job-started` | A background job started. |
201| `tanstack/workspace-tools:job-output` | New output of a job. At most one event each 250 ms, with at most the newest 64 KiB. |
202| `tanstack/workspace-tools:job-ended` | A job ended, after its last output event. |
203| `tanstack/workspace-tools:stranded` | The workspace of the thread is gone. See below. |
204| `tanstack/workspace-tools:file-changed` | A file changed. The value has a unified diff of the change. See [Show live diffs](./custom-ui#show-live-diffs). |
205| `tanstack/snapshots:failed` | A snapshot failed. The turn goes on. |
206
207The formatter also sends `tanstack/formatter:rewrote` and `tanstack/formatter:failed`. See [Format each file after a write](./coding-tools-backends#format-each-file-after-a-write).
208
209## 5. Move a thread to another server
210
211One server owns a thread at a time. When it stops, another server takes the thread (see [One host drives a thread](./durable-sessions#one-host-drives-a-thread)). What happens to the workspace depends on where it is.
212
213### A sandbox
214
215The log keeps the provider and the id of the sandbox. The next server calls `reattach` in place of `bind`. Resume the sandbox there:
216
217```ts group=harness-coding-workspaces
218export const movable = workspaceTools({
219 workspace: {
220 bind: async () => ({
221 ...sandboxWorkspaceBackend(await docker.create({}), { owned: true }),
222 root: '/workspace',
223 }),
224 reattach: async ({ binding }) => {
225 if (binding.kind === 'host') return 'pinned'
226 if (binding.provider !== 'docker') return 'gone'
227 const handle = await docker.resume({ id: binding.sandboxId })
228 if (!handle) return 'gone'
229 return { ...sandboxWorkspaceBackend(handle, { owned: true }), root: binding.root }
230 },
231 },
232})
233```
234
235- Give the workspace back to continue in the same files.
236- Give `'gone'` when the sandbox is gone. Then each tool call of the thread fails with `The workspace of this thread, /workspace in the docker sandbox <id>, is gone, so the tools cannot work on it.`, and the tools send `tanstack/workspace-tools:stranded`. The session also sends a `harness.stranded` event, for clients that do not know the plugin. See the [event catalog](./protocol#event-catalog).
237- Without `reattach`, a sandbox counts as `'gone'`.
238
239### A folder on one server
240
241A folder on the disk of one server cannot move. Give each server a stable id:
242
243```ts group=harness-coding-workspaces
244import { createHarnessHost } from '@tanstack/ai-harness'
245import { memoryPersistence } from '@tanstack/ai-persistence'
246
247const host = createHarnessHost({
248 persistence: memoryPersistence(),
249 ownership: { hostId: process.env.POD_NAME ?? 'web-1' },
250})
251```
252
253- With `hostId`, a thread that uses a local folder is pinned to this server. Workers on other servers do not take it, also while the thread is idle.
254- Another server that opens the thread refuses its tool calls with `The workspace of this thread is <root> on the host web-1. Only that host can continue the thread.`
255- Keep the id the same after a restart. On Kubernetes, use the pod name of a StatefulSet. Do not use `HOSTNAME` of a Deployment pod: it changes at each restart, and the threads of the old pod stay pinned to it.
256- Without `hostId`, threads are not pinned, and every server calls `bind` again. Use this when every server sees the same folder, for example on a shared disk.
257
258The server sends a heartbeat to the log store each `ownership.renewEveryMs`. When no heartbeat came for `ownership.expiresAfterMs` (default 30 seconds), its pins do not count. Then the next server that gets work for the thread calls `reattach` with the old binding. Give a new workspace there, for example a fresh clone, to move the thread. Keep a restart shorter than `ttlMs`, or raise `ttlMs`.
259
260To move the threads of a server at once, unpin them with `host.unpin`. Its ownership must have expired first:
261
262```ts group=harness-coding-workspaces
263await host.unpin({ harness: coder, threadId: 'fix-login' })
264```
265
266### After a move
267
268- Background jobs do not move. At the next tool call of the thread, the new server stops each job that the old server left running. The model gets the note `Background job bash-1 was stopped: it ran on a host before the session moved to this one.`
269- A job that the backend cannot check stays in the log, and the model gets `Background job bash-1 may still run: it ran on a host before this one, and this host cannot stop it.` For example, `hostBackend` needs `ps` to check a job.
270- `/undo`, `/redo`, and a revert work on the new server when it reaches the same snapshot repository. See [Undo a turn](./snapshots#on-more-than-one-server).
271- [Coding agents](./coding-agents) run only on the server that owns the log. So two servers never run the agents of one shared workspace at the same time.
272
273## What you have now
274
275- A folder or a sandbox for each thread, with its root as the boundary of every tool.
276- Commands that get only a short env, and a sandbox for users that you do not trust.
277- Agents that share a folder and never lose an edit.
278- Events for every background job, and a limit on how many run.
279- Threads that move to another server with their sandbox, or stay on the server that has their folder.