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

api.coding-tools.ts

250 lines8.2 KB

1import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join, resolve, sep } from 'node:path'
4import { createFileRoute } from '@tanstack/react-router'
5import { toServerSentEventsResponse } from '@tanstack/ai'
6import {
7 createHarnessHost,
8 defineHarness,
9 definePlugin,
10} from '@tanstack/ai-harness'
11import { permissions } from '@tanstack/ai-harness/plugins'
12import {
13 FileChanged,
14 formatter,
15 snapshots,
16 workspaceTools,
17} from '@tanstack/ai-harness/plugins/coding'
18import { sandboxWorkspaceBackend } from '@tanstack/ai-sandbox/harness'
19import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
20import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
21import type { FileChange } from '@tanstack/ai-harness/plugins/coding'
22import { createTextAdapter } from '@/lib/providers'
23​
24/**
25 * A `coding-*` scenario: one harness turn with `workspaceTools()` in `root`,
26 * as the chunks the client gets. `coding-patch` gets the `patch` tool, the
27 * other scenarios get `edit_file`. No `permissions()` is mounted, so no tool
28 * asks for approval. Only `coding-format-ask` mounts `formatter()` and
29 * `permissions()` in `acceptEdits` mode: the write asks before it runs, with
30 * its formatter in the same approval, and the route rejects the approval.
31 */
32async function* codingTurn(
33 scenario: string,
34 root: string,
35 adapter: AnyTextAdapter,
36) {
37 const formatAsk = scenario === 'coding-format-ask'
38 const host = createHarnessHost()
39 try {
40 const session = await host.open(
41 defineHarness({
42 name: 'e2e/coding-tools',
43 adapter,
44 plugins: () => [
45 workspaceTools({
46 root,
47 editStyle: scenario === 'coding-patch' ? 'patch' : 'edit',
48 }),
49 ...(formatAsk ? [permissions({ root }), formatter({ root })] : []),
50 ],
51 }),
52 {
53 threadId: scenario,
54 },
55 )
56 if (formatAsk)
57 await session.runCommand({ name: 'mode', input: 'acceptEdits' })
58 yield* session.send(`[${scenario}] run test`).stream()
59 // In acceptEdits mode, the write asks before it runs, for the write and
60 // its formatter. The turn stops with one approval wait. Reject it, and
61 // give the chunks of the turn that resumes.
62 const [wait] = formatAsk ? session.snapshot().pendingWaits : []
63 if (wait) {
64 const inputId = `answer:${wait.waitId}`
65 const receipt = await session.resolve({
66 resume: [
67 { interruptId: wait.waitId, status: 'resolved', payload: 'reject' },
68 ],
69 inputId,
70 })
71 const resumed = receipt.operationId
72 ? session.operation(receipt.operationId)
73 : undefined
74 if (resumed) yield* resumed.stream()
75 await session.settled({ inputId })
76 }
77 } finally {
78 await host.close()
79 }
81​
82/**
83 * The `coding-revert` scenario: two turns with `snapshots()`, each edits
84 * notes.txt. Between them, the user edits other.txt. Then a revert to the
85 * first prompt puts back the files of both turns.
86 */
87async function* revertTurns(root: string, adapter: AnyTextAdapter) {
88 const dataDir = await mkdtemp(join(tmpdir(), 'e2e-snapshots-'))
89 const host = createHarnessHost()
90 try {
91 const session = await host.open(
92 defineHarness({
93 name: 'e2e/coding-tools-revert',
94 adapter,
95 plugins: () => [
96 // The fixtures call `edit_file`, so the edit style must not depend
97 // on the model.
98 workspaceTools({ root, editStyle: 'edit' }),
99 snapshots({ root, dataDir }),
100 ],
101 }),
102 {
103 threadId: 'coding-revert',
104 },
105 )
106 yield* session.send('[coding-revert] run test').stream()
107 await writeFile(join(root, 'other.txt'), 'mine\n')
108 yield* session.send('[coding-revert-2] run test').stream()
109 const [prompt] = await session.transcript()
110 if (prompt?.id) await session.revert({ messageId: prompt.id })
111 } finally {
112 await host.close()
113 await rm(dataDir, { recursive: true, force: true })
114 }
116​
117/**
118 * The `coding-sandbox` scenario: one `edit_file` turn with the tools in a
119 * local-process sandbox on `root`. The tools see `/workspace`, and the
120 * sandbox maps it to `root`.
121 */
122async function* sandboxTurn(root: string, adapter: AnyTextAdapter) {
123 const sandbox = await localProcessSandbox({ dir: root }).create({})
124 const host = createHarnessHost()
125 try {
126 const session = await host.open(
127 defineHarness({
128 name: 'e2e/coding-tools-sandbox',
129 adapter,
130 plugins: () => [
131 workspaceTools({
132 root: '/workspace',
133 editStyle: 'edit',
134 backend: sandboxWorkspaceBackend(sandbox),
135 }),
136 ],
137 }),
138 {
139 threadId: 'coding-sandbox',
140 },
141 )
142 yield* session.send('[coding-sandbox] run test').stream()
143 } finally {
144 await host.close()
145 // With `dir`, destroy keeps the folder.
146 await sandbox.destroy()
147 }
149​
150/**
151 * The `coding-diffs` scenario: one turn with `snapshots()`. The model
152 * writes a.txt with `write_file`, then b.txt with `bash`. The chunks of a
153 * turn have no plugin events, so a plugin keeps the `FileChanged` events,
154 * and an `e2e.file-changes` chunk gives them. Then `/undo` puts the files
155 * back, and a last `e2e.undo-changes` chunk gives the events of the undo.
156 */
157async function* diffsTurn(root: string, adapter: AnyTextAdapter) {
158 const dataDir = await mkdtemp(join(tmpdir(), 'e2e-snapshots-'))
159 const changes: Array<FileChange> = []
160 const host = createHarnessHost()
161 try {
162 const session = await host.open(
163 defineHarness({
164 name: 'e2e/coding-tools-diffs',
165 adapter,
166 plugins: () => [
167 workspaceTools({ root }),
168 snapshots({ root, dataDir }),
169 definePlugin({
170 name: 'e2e/file-changes',
171 setup: (ctx) => {
172 ctx.on(FileChanged, (change) => changes.push(change))
173 },
174 }),
175 ],
176 }),
177 {
178 threadId: 'coding-diffs',
179 },
180 )
181 yield* session.send('[coding-diffs] run test').stream()
182 yield {
183 type: 'CUSTOM',
184 name: 'e2e.file-changes',
185 value: changes,
186 timestamp: Date.now(),
187 } satisfies StreamChunk
188 const turnEnd = changes.length
189 await session.runCommand({ name: 'undo' })
190 yield {
191 type: 'CUSTOM',
192 name: 'e2e.undo-changes',
193 value: changes.slice(turnEnd),
194 timestamp: Date.now(),
195 } satisfies StreamChunk
196 } finally {
197 await host.close()
198 await rm(dataDir, { recursive: true, force: true })
199 }
201​
202/**
203 * The coding tools of `@tanstack/ai-harness/plugins/coding` on real files.
204 * Body: `{ scenario, testId, root }`. `root` must be a folder in the temp
205 * folder, because the tools write files and run commands there. The answer
206 * is an SSE stream of the turn's chunks.
207 */
208export const Route = createFileRoute('/api/coding-tools')({
209 server: {
210 handlers: {
211 POST: async ({ request }) => {
212 const body: unknown = await request.json()
213 const field = (name: string) =>
214 typeof body === 'object' && body !== null && name in body
215 ? Reflect.get(body, name)
216 : undefined
217 const scenario = field('scenario')
218 const testId = field('testId')
219 const rootField = field('root')
220 if (typeof scenario !== 'string' || !scenario.startsWith('coding-')) {
221 return new Response('unknown scenario', { status: 400 })
222 }
223 const root = typeof rootField === 'string' ? resolve(rootField) : ''
224 if (!root.startsWith(resolve(tmpdir()) + sep)) {
225 return new Response('root must be in the temp folder', {
226 status: 400,
227 })
228 }
229 const { adapter } = createTextAdapter(
230 'openai',
231 'gpt-5.5',
232 undefined,
233 typeof testId === 'string' ? testId : undefined,
234 )
235 switch (scenario) {
236 case 'coding-revert':
237 return toServerSentEventsResponse(revertTurns(root, adapter))
238 case 'coding-sandbox':
239 return toServerSentEventsResponse(sandboxTurn(root, adapter))
240 case 'coding-diffs':
241 return toServerSentEventsResponse(diffsTurn(root, adapter))
242 default:
243 return toServerSentEventsResponse(
244 codingTurn(scenario, root, adapter),
245 )
246 }
247 },
248 },
249 },
250})