Open History to see the last commit
1import { spawn } from 'node:child_process'
2import { createHash, randomUUID } from 'node:crypto'
3import { existsSync } from 'node:fs'
4import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
5import { dirname, join, resolve } from 'node:path'
6import { createInterface } from 'node:readline'
7import { fileURLToPath } from 'node:url'
8import { EventType } from '@tanstack/ai'
9import { HARNESS_PROTOCOL_VERSION } from './protocol'
10import type { AnyTextAdapter, ModelMessage, StreamChunk } from '@tanstack/ai'
11import type { HostFrame } from './protocol'
12
13/** What a built harness says about itself. Fields are claims; deploy policy decides. */
14export interface HarnessManifestV1 {
15 format: 'tanstack-ai-harness'
16 version: 1
17 name: string
18 /** sha256 of the bundle. */
19 digest: string
20 /** The bundle file, relative to the manifest. */
21 entry: string
22 runtime: { kind: 'node'; major: number }
23 protocol: typeof HARNESS_PROTOCOL_VERSION
24 agents: Array<{ name: string; produces?: string }>
25 plugins: Array<{ name: string }>
26 requires: {
27 filesystem: boolean
28 processExecution: boolean
29 network: 'model-only' | 'declared'
30 }
31}
32
33export interface BuildHarnessOptions {
34 /** The module that exports the harness. */
35 entry: string
36 /** The export name. Default `'default'`. */
37 export?: string
38 outDir: string
39 /**
40 * Also build a single executable of `compile.entry` (for example a file
41 * that calls `runCli`) with Bun.
42 */
43 compile?: { entry: string; outfile: string; target?: string }
44 /** The Bun executable. Default `'bun'`. */
45 bun?: string
46}
47
48const MANIFEST = 'harness.manifest.json'
49const BUNDLE = 'harness.js'
50
51function run(
52 command: string,
53 args: Array<string>,
54 cwd: string,
55): Promise<string> {
56 // On Windows, npm installs Bun as a `.cmd` shim, which only a shell can
57 // start. The arguments are paths this module builds, quoted for cmd.
58 const viaShell = process.platform === 'win32' && !/\.exe$/i.test(command)
59 return new Promise((done, fail) => {
60 const child = viaShell
61 ? spawn(
62 command,
63 args.map((arg) => `"${arg}"`),
64 { cwd, stdio: ['ignore', 'pipe', 'pipe'], shell: true },
65 )
66 : spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })
67 let stdout = ''
68 let stderr = ''
69 child.stdout.on('data', (data: Buffer) => (stdout += data.toString()))
70 child.stderr.on('data', (data: Buffer) => (stderr += data.toString()))
71 child.on('error', (error) =>
72 fail(
73 new Error(
74 `Could not run ${command}. buildHarness uses Bun: install it from https://bun.sh. (${error.message})`,
75 ),
76 ),
77 )
78 child.on('close', (code) =>
79 code === 0
80 ? done(stdout)
81 : fail(
82 new Error(
83 `${command} ${args[0] ?? ''} failed:\n${stderr || stdout}`,
84 ),
85 ),
86 )
87 })
88}
89
90/**
91 * Bundle a harness into a worker artifact: `harness.js` (starts a worker on
92 * stdin and stdout) and `harness.manifest.json`. With `compile`, also build a
93 * single executable.
94 *
95 * The build imports `entry` in a child process to read the harness name,
96 * agents, and plugin names. Importing a module runs its code.
97 */
98export async function buildHarness(options: BuildHarnessOptions): Promise<{
99 manifest: HarnessManifestV1
100 bundle: string
101 executable?: string
102}> {
103 const bun = options.bun ?? 'bun'
104 const entry = resolve(options.entry)
105 const outDir = resolve(options.outDir)
106 const exportName = options.export ?? 'default'
107 // Bun resolves plain absolute paths, not file:// URLs. Forward slashes
108 // keep Windows paths valid inside the generated modules.
109 const slash = (path: string) => path.split('\\').join('/')
110 const entryPath = slash(entry)
111 const builtWorker = fileURLToPath(new URL('./worker.js', import.meta.url))
112 // From source (tests), the worker module is still TypeScript.
113 const workerModule = slash(
114 existsSync(builtWorker) ? builtWorker : builtWorker.replace(/\.js$/, '.ts'),
115 )
116 await mkdir(outDir, { recursive: true })
117
118 // Temporary files sit next to the entry, so its imports resolve the same way.
119 const id = randomUUID().slice(0, 8)
120 const bootstrap = join(dirname(entry), `.harness-worker-${id}.mjs`)
121 const describe = join(dirname(entry), `.harness-describe-${id}.mjs`)
122 try {
123 await writeFile(
124 bootstrap,
125 [
126 `import * as entry from ${JSON.stringify(entryPath)}`,
127 `import { runHarnessWorker } from ${JSON.stringify(workerModule)}`,
128 `await runHarnessWorker(entry[${JSON.stringify(exportName)}])`,
129 ].join('\n'),
130 )
131 await writeFile(
132 describe,
133 [
134 `const entry = await import(${JSON.stringify(entryPath)})`,
135 `const harness = entry[${JSON.stringify(exportName)}]`,
136 `if (!harness || harness.kind !== 'tanstack-ai-harness') throw new Error(${JSON.stringify(`Export ${exportName} of ${entryPath} is not a harness.`)})`,
137 `const agents = [...(harness.agents ?? []), ...(harness.subagents?.agents ?? [])]`,
138 `const plugins = harness.plugins ? harness.plugins().map((plugin) => ({ name: plugin.name })) : []`,
139 `console.log(JSON.stringify({ name: harness.name, agents: agents.map((agent) => ({ name: agent.name, ...(agent.produces ? { produces: agent.produces } : {}) })), plugins }))`,
140 ].join('\n'),
141 )
142
143 const bundle = join(outDir, BUNDLE)
144 await run(
145 bun,
146 ['build', bootstrap, '--target=node', `--outfile=${bundle}`],
147 dirname(entry),
148 )
149 const described: {
150 name: string
151 agents: HarnessManifestV1['agents']
152 plugins: HarnessManifestV1['plugins']
153 } = JSON.parse(
154 (await run(bun, [describe], dirname(entry))).trim().split('\n').at(-1) ??
155 '{}',
156 )
157 const names = described.plugins.map((plugin) => plugin.name)
158 // Snapshots run git in the workspace, like the workspace tools.
159 const usesWorkspace =
160 names.includes('tanstack/workspace-tools') ||
161 names.includes('tanstack/snapshots')
162 const manifest: HarnessManifestV1 = {
163 format: 'tanstack-ai-harness',
164 version: 1,
165 name: described.name,
166 digest: createHash('sha256')
167 .update(await readFile(bundle))
168 .digest('hex'),
169 entry: BUNDLE,
170 runtime: {
171 kind: 'node',
172 major: Number(process.versions.node.split('.')[0]),
173 },
174 protocol: HARNESS_PROTOCOL_VERSION,
175 agents: described.agents,
176 plugins: described.plugins,
177 requires: {
178 filesystem:
179 usesWorkspace || names.includes('tanstack/project-instructions'),
180 processExecution: usesWorkspace,
181 network: names.some((name) => name.startsWith('connector/'))
182 ? 'declared'
183 : 'model-only',
184 },
185 }
186 await writeFile(
187 join(outDir, MANIFEST),
188 `${JSON.stringify(manifest, null, 2)}\n`,
189 )
190
191 let executable: string | undefined
192 if (options.compile) {
193 executable = resolve(options.compile.outfile)
194 await run(
195 bun,
196 [
197 'build',
198 resolve(options.compile.entry),
199 '--compile',
200 `--outfile=${executable}`,
201 ...(options.compile.target
202 ? [`--target=${options.compile.target}`]
203 : []),
204 ],
205 dirname(resolve(options.compile.entry)),
206 )
207 }
208 return { manifest, bundle, ...(executable ? { executable } : {}) }
209 } finally {
210 await rm(bootstrap, { force: true })
211 await rm(describe, { force: true })
212 }
213}
214
215/** Read and check the manifest of a built harness. */
216export async function readManifest(dir: string): Promise<HarnessManifestV1> {
217 const manifest: unknown = JSON.parse(
218 await readFile(join(resolve(dir), MANIFEST), 'utf8'),
219 )
220 if (
221 typeof manifest !== 'object' ||
222 manifest === null ||
223 !('format' in manifest) ||
224 manifest.format !== 'tanstack-ai-harness' ||
225 !('version' in manifest) ||
226 manifest.version !== 1
227 ) {
228 throw new Error(`${dir} has no tanstack-ai-harness v1 manifest.`)
229 }
230 // The format and version checks above identify the file.
231 return manifest as HarnessManifestV1
232}
233
234const FORWARDED = new Set<string>([
235 EventType.TEXT_MESSAGE_START,
236 EventType.TEXT_MESSAGE_CONTENT,
237 EventType.TEXT_MESSAGE_END,
238 EventType.REASONING_START,
239 EventType.REASONING_MESSAGE_START,
240 EventType.REASONING_MESSAGE_CONTENT,
241 EventType.REASONING_MESSAGE_END,
242 EventType.REASONING_END,
243])
244
245interface Worker {
246 send: (frame: object) => void
247 frames: (listener: (frame: HostFrame) => void) => () => void
248 /** True for the `requestId` of a frame that was sent to this worker. */
249 sent: (requestId: string) => boolean
250 kill: () => void
251}
252
253function startWorker(
254 node: string,
255 bundle: string,
256 threadId: string,
257 onExit: () => void,
258): Worker {
259 const child = spawn(node, [bundle], { stdio: ['pipe', 'pipe', 'inherit'] })
260 const listeners = new Set<(frame: HostFrame) => void>()
261 // A worker that fails to start or stops fails the streams that wait on it.
262 const requestIds = new Set<string>()
263 const fail = (message: string) => {
264 onExit()
265 for (const listener of listeners)
266 listener({
267 type: 'harness.error',
268 message,
269 code: 'internal',
270 requestId: 'worker',
271 })
272 }
273 child.on('error', (error) => fail(`The worker failed: ${error.message}`))
274 child.on('exit', (code, signal) =>
275 fail(`The worker stopped (${signal ?? `exit code ${code}`}).`),
276 )
277 child.stdin.on('error', () => {})
278 createInterface({ input: child.stdout }).on('line', (line) => {
279 try {
280 const frame = JSON.parse(line) as HostFrame
281 for (const listener of listeners) listener(frame)
282 } catch {
283 // A line that is not a frame (for example a stray log) is skipped.
284 }
285 })
286 const send = (frame: object) => {
287 if ('requestId' in frame && typeof frame.requestId === 'string')
288 requestIds.add(frame.requestId)
289 child.stdin.write(`${JSON.stringify(frame)}\n`)
290 }
291 send({ type: 'harness.subscribe', threadId })
292 return {
293 send,
294 frames: (listener) => {
295 listeners.add(listener)
296 return () => listeners.delete(listener)
297 },
298 sent: (requestId) => requestIds.has(requestId),
299 kill: () => {
300 child.stdin.end()
301 child.kill()
302 },
303 }
304}
305
306/** The content of the last user message: a string or its content parts. */
307function lastUserInput(messages: ReadonlyArray<ModelMessage>) {
308 return messages.findLast((entry) => entry.role === 'user')?.content ?? ''
309}
310
311/**
312 * Use a built harness as the model of a `chat()` call. Each outer thread gets
313 * its own worker process (`node harness.js`). Call `dispose()` to stop them.
314 */
315export async function artifactText(
316 dir: string,
317 options: { node?: string } = {},
318): Promise<AnyTextAdapter & { dispose: () => void }> {
319 const manifest = await readManifest(dir)
320 const bundle = join(resolve(dir), manifest.entry)
321 // Checked now, and again before each worker starts.
322 const checkDigest = async () => {
323 const digest = createHash('sha256')
324 .update(await readFile(bundle))
325 .digest('hex')
326 if (digest !== manifest.digest) {
327 throw new Error(
328 `The bundle in ${dir} does not match its manifest digest.`,
329 )
330 }
331 }
332 await checkDigest()
333 const workers = new Map<string, Worker>()
334 let requests = 0
335
336 return {
337 kind: 'text',
338 name: 'harness-artifact',
339 model: manifest.name,
340 '~types': {
341 providerOptions: {} as Record<string, unknown>,
342 inputModalities: ['text'] as readonly ['text'],
343 messageMetadataByModality: {
344 text: undefined as unknown,
345 image: undefined as unknown,
346 audio: undefined as unknown,
347 video: undefined as unknown,
348 document: undefined as unknown,
349 },
350 toolCapabilities: [] as ReadonlyArray<string>,
351 toolCallMetadata: undefined as unknown,
352 systemPromptMetadata: undefined as never,
353 },
354 dispose: () => {
355 for (const worker of workers.values()) worker.kill()
356 workers.clear()
357 },
358 structuredOutput: () =>
359 Promise.reject(
360 new Error('artifactText does not support structured output.'),
361 ),
362 chatStream: (chatOptions) =>
363 (async function* (): AsyncGenerator<StreamChunk> {
364 const { threadId } = chatOptions
365 let worker = workers.get(threadId)
366 if (!worker) {
367 await checkDigest()
368 const started = startWorker(
369 options.node ?? process.execPath,
370 bundle,
371 threadId,
372 () => {
373 if (workers.get(threadId) === started) workers.delete(threadId)
374 },
375 )
376 worker = started
377 workers.set(threadId, worker)
378 }
379 const runId = chatOptions.runId ?? `artifact-${Date.now().toString(36)}`
380 const requestId = `r${(requests += 1)}`
381 const queue: Array<HostFrame> = []
382 let wake: (() => void) | undefined
383 const stop = worker.frames((frame) => {
384 queue.push(frame)
385 wake?.()
386 })
387 worker.send({
388 type: 'harness.input',
389 requestId,
390 input: { op: 'prompt', message: lastUserInput(chatOptions.messages) },
391 })
392 yield {
393 type: EventType.RUN_STARTED,
394 runId,
395 threadId,
396 timestamp: Date.now(),
397 }
398 let operationId: string | undefined
399 let finished = false
400 const early: Array<Extract<HostFrame, { type: 'harness.event' }>> = []
401 try {
402 while (true) {
403 if (queue.length === 0) {
404 await new Promise<void>((resolveWait) => (wake = resolveWait))
405 wake = undefined
406 }
407 const frame = queue.shift()
408 if (!frame) continue
409 if (frame.type === 'harness.error') {
410 // The error of another input of this worker, for example the
411 // cancel of an older turn, is not about this turn.
412 if (frame.requestId !== requestId && worker.sent(frame.requestId))
413 continue
414 throw new Error(frame.message, {
415 cause: { code: frame.code, requestId: frame.requestId },
416 })
417 }
418 if (
419 frame.type === 'harness.receipt' &&
420 frame.requestId === requestId
421 ) {
422 if (frame.status === 'rejected')
423 throw new Error(
424 frame.reason ?? 'The worker refused the prompt.',
425 )
426 operationId = frame.operationId
427 queue.unshift(
428 ...early.filter((entry) => entry.operationId === operationId),
429 )
430 continue
431 }
432 if (frame.type !== 'harness.event') continue
433 if (!operationId) {
434 early.push(frame)
435 continue
436 }
437 if (frame.operationId !== operationId) continue
438 const event = frame.event
439 if (
440 FORWARDED.has(event.type) &&
441 !('subagentRunId' in event && event.subagentRunId)
442 )
443 yield event
444 if (event.type === EventType.RUN_ERROR)
445 throw new Error(event.message)
446 if (
447 event.type === EventType.CUSTOM &&
448 event.name === 'harness.operation.finished'
449 ) {
450 finished = true
451 break
452 }
453 }
454 } finally {
455 stop()
456 // The caller stopped early (abort or break): cancel the turn too.
457 if (!finished && operationId) {
458 worker.send({
459 type: 'harness.input',
460 requestId: `${requestId}-cancel`,
461 input: { op: 'cancel', operationId },
462 })
463 }
464 }
465 yield {
466 type: EventType.RUN_FINISHED,
467 runId,
468 threadId,
469 timestamp: Date.now(),
470 metadata: { tanstack: { finishReason: 'stop' } },
471 }
472 })(),
473 }
474}