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

coding-agent.md

200 lines9.3 KB

1---
2title: Build a coding agent
3id: harness-coding-agent
4order: 6
5description: "Turn a harness into a coding agent with file tools, permission modes, undo, a todo list, a model picker, project instructions, session titles, a cost count, and /compact."
6keywords:
7 - tanstack ai
8 - harness
9 - coding agent
10 - permissions
11 - workspace tools
12 - project instructions
13 - undo
14---
15​
16You want your own coding agent in the terminal. It reads and edits files, and runs commands after you approve them. When a turn goes wrong, you undo it. The first-party plugins in `@tanstack/ai-harness/plugins`, `@tanstack/ai-harness/plugins/node`, and `@tanstack/ai-harness/plugins/coding` give you those parts. You pick the model and the rules.
17​
18## 1. Define the agent
19​
20```ts group=harness-coding-agent
21import { randomUUID } from 'node:crypto'
22import { homedir } from 'node:os'
23import { join } from 'node:path'
24import { createInterface } from 'node:readline/promises'
25import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
26import type { RunAgentResumeItem } from '@tanstack/ai'
27import {
28 compact,
29 modelPicker,
30 permissions,
31 title,
32 todos,
33 usage,
34} from '@tanstack/ai-harness/plugins'
35import { fileCommands, projectInstructions } from '@tanstack/ai-harness/plugins/node'
36import { snapshots, workspaceTools } from '@tanstack/ai-harness/plugins/coding'
37import { openaiText } from '@tanstack/ai-openai'
38import { memoryPersistence } from '@tanstack/ai-persistence'
39​
40const root = process.cwd()
41const smart = openaiText('gpt-6.1-sol')
42const fast = openaiText('gpt-6-luna')
43​
44const coder = defineHarness({
45 name: 'acme/coder',
46 adapter: smart,
47 systemPrompts: ['You are a careful coding agent. Read before you edit.'],
48 plugins: () => [
49 permissions({ root }),
50 workspaceTools({ root }),
51 snapshots({ root, dataDir: join(homedir(), '.acme-coder', 'snapshots') }),
52 todos(),
53 modelPicker({ choices: { smart, fast }, default: 'smart' }),
54 fileCommands({ dir: `${root}/.claude/commands` }),
55 compact({ adapter: fast }),
56 title({ adapter: fast }),
57 usage(),
58 // Keep this plugin last. See "Project instructions" below.
59 projectInstructions({ root }),
60 ],
61})
62​
63const host = createHarnessHost({ persistence: memoryPersistence() })
64const session = await host.open(coder, { threadId: 'main' })
65const terminal = createInterface({
66 input: process.stdin,
67 output: process.stdout,
68})
69​
70// Print the text of every turn, also of a turn that continues after an answer.
71const stopPrinting = session.onEvent('TEXT_MESSAGE_CONTENT', ({ event }) => {
72 process.stdout.write(event.delta)
73})
74​
75// A risky call stops the turn before it runs. Ask about each approval:
76// once, always, or reject. Then send all the answers in one resolve.
77async function answerApprovals() {
78 let waits = session.snapshot().pendingWaits
79 while (waits.length > 0) {
80 const resume: Array<RunAgentResumeItem> = []
81 for (const wait of waits) {
82 const answer = await terminal.question(`\n${wait.message ?? wait.kind} (once/always/reject) `)
83 resume.push({ interruptId: wait.waitId, status: 'resolved', payload: answer })
84 }
85 const inputId = randomUUID()
86 await session.resolve({ resume, inputId })
87 await session.settled({ inputId })
88 waits = session.snapshot().pendingWaits
89 }
91​
92// Type `exit` to stop.
93let line = await terminal.question('\n> ')
94while (line !== 'exit') {
95 if (line.startsWith('/')) {
96 // `/undo`, `/model fast`, `/mode plan`, and the other plugin commands.
97 const [name = '', ...args] = line.slice(1).split(' ')
98 console.log(await session.runCommand({ name, input: args.join(' ') || undefined }))
99 } else {
100 try {
101 await session.send(line)
102 await answerApprovals()
103 } catch (error) {
104 // A failed turn rejects. Show the error and keep the loop.
105 console.error(error)
106 }
107 }
108 line = await terminal.question('\n> ')
110stopPrinting()
111terminal.close()
112await host.close()
113```
114​
115The `plugins/node` and `plugins/coding` entries run only in Node. The coding tools use the file system and the shell of the machine. A line that starts with `/` runs a command of a plugin. Any other line is a prompt.
116​
117## 2. Run it
118​
1191. Run `npx tsx coder.ts` in your project.
1202. Ask for a change. The agent reads files freely, and asks before it writes a file or runs a command.
1213. Answer `once` to allow the call, `always` to allow it from now on, or `reject` to refuse it.
1224. If you do not like the result, run `/undo`. The files go back to how they were before the turn.
123​
124## What each plugin adds
125​
126| Plugin | Adds |
127|---|---|
128| `permissions({ root })` | Asks before risky tool calls. `/mode` switches between `default`, `plan` (read-only), `acceptEdits` (edits run without asking), and `bypass`. See [Ask before risky tool calls](./permissions). |
129| `workspaceTools({ root })` | Tools that read, search, and change the files in `root`, run commands, and read web pages. A path outside `root` is refused, or asks first with `outside: 'ask'`. See [Give your agent coding tools](./coding-tools). |
130| `snapshots({ root, dataDir })` | `/undo` puts the files back as they were before the last turn, and `/redo` brings them back. It needs `git`. See [Undo a turn](./snapshots). |
131| `todos()` | A `todo_write` tool the model uses for multi-step work, and `/todos`. |
132| `modelPicker({ choices })` | `/model <name>` switches the model at the next turn. |
133| `fileCommands({ dir })` | Each `.md` file becomes a slash command. `$ARGUMENTS` is replaced by what you type after it. |
134| `compact({ adapter })` | `/compact` replaces a long conversation with a summary. |
135| `title({ adapter })` | Names the session from its first message. |
136| `usage()` | `/usage` shows the tokens and the cost of the session, with a line for each model. See [Track usage and cost](./usage). |
137| `projectInstructions({ root })` | Adds `AGENTS.md`, `CLAUDE.md`, and facts about the environment to the system prompt. |
138​
139To compact on its own before the context limit, see [Compact a harness session](./compaction).
140​
141## Project instructions
142​
143Your repository has an `AGENTS.md` or a `CLAUDE.md` with its rules. `projectInstructions({ root })` gives them to the model:
144​
145- It reads `AGENTS.md` and `CLAUDE.md` in each folder from the repository root (the folder with `.git`) down to `root`. Set other file names with `files`.
146- `global` adds files that come first, for example `['~/.config/AGENTS.md']`.
147- When `read_file` reads a file in a subfolder, the model also gets the instruction files of the folders on the way, once each.
148- An environment block gives the date, the platform, the working folder, and the git repository and branch. `env: false` turns it off.
149- When you change an instruction file, the next turn sends the new text as a note.
150​
151Put `projectInstructions()` last in the plugin list. Then a changed file goes into the conversation as a [mid-conversation change](../advanced/mid-conversation-changes), and the prompt cache stays. When the prompt of another plugin comes after it, a change builds the system prompt again, and the prompt cache starts again.
152​
153## Session titles and cost
154​
155`title({ adapter })` and `usage()` write to the session index, one entry per thread:
156​
157- `title` names the session from its first message. The turn does not wait for it.
158- When `usage` knows the cost of the session, it writes the cost. A cost that the provider reports is used as it is.
159- To price the calls of a provider that reports no cost, pass `usage({ model })`. [Track usage and cost](./usage#show-usage-and-price-the-calls) shows how.
160​
161A [sidebar of sessions](./sessions) reads the title and the cost from the index. The `usage()` state also has `contextTokens`, the size of the lead model's context at its latest call, for a context meter.
162​
163## Add more
164​
165- `agents({ adapter })`: named agents with their own prompt, tools, and model. `/agent plan` switches to a read-only agent. See [Switch between agent profiles](./agents).
166- `question()`: a `question` tool. The model asks the user to pick an option, and waits for the answer.
167- `formatter({ root })`: formats each file after a write. See [Format each file after a write](./coding-tools-backends#format-each-file-after-a-write).
168​
169## Add your own rules
170​
171Tool plugins add permission rules to the `PermissionRules` extension point. Add your own for any tool:
172​
173```ts group=harness-coding-agent
174import { PermissionRules } from '@tanstack/ai-harness/plugins'
175import { definePlugin } from '@tanstack/ai-harness'
176​
177export const noDeploys = definePlugin({
178 name: 'acme/no-deploys',
179 setup: () => ({
180 contribute: [PermissionRules.item({ tool: 'deploy_*', decision: 'deny' })],
181 }),
182})
183```
184​
185A trailing `*` matches every tool that starts with the text. The last matching rule wins. [Ask before risky tool calls](./permissions) explains the rules, the modes, and the saved answers.
186​
187The workspace tools run on your machine with your permissions. For code that you do not trust, [run the tools in a sandbox](./coding-tools-backends#run-the-tools-in-a-sandbox).
188​
189## Hand work to Claude Code or Codex
190​
191Your agent can also give tasks to coding agents you already use. [Delegate to coding agents](./coding-agents) shows how.
192​
193## What you have now
194​
195- A terminal coding agent with file tools, approvals, modes, a todo list, and a model picker.
196- `/undo` and `/redo` for the file changes of a turn.
197- The rules of your repository in every turn. A change to them keeps the prompt cache.
198- A title and a cost for each session.
199​
200Next: let the user undo more than one turn with [Undo a turn](./snapshots).