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

worker.ts

144 lines4.4 KB

1import { randomUUID } from 'node:crypto'
2import { createInterface } from 'node:readline'
3import { createHarnessHost } from './host'
4import { scrubbedBy } from './session/harness-session'
5import {
6 applyInput,
7 HARNESS_PROTOCOL_VERSION,
8 versionError,
9 parseControlFrame,
10 requestIdOf,
11} from './protocol'
12import { wireFrame } from './wire'
13import type { AnyHarness } from './define'
14import type { HarnessPersistence } from './host'
15import type { ControlFrame, HarnessErrorCode, HostFrame } from './protocol'
16​
17export interface HarnessWorkerOptions {
18 input?: NodeJS.ReadableStream
19 output?: { write: (text: string) => unknown }
20 persistence?: HarnessPersistence
22​
23/**
24 * Run a harness as a worker: session-tier frames as NDJSON on stdin and
25 * stdout. The first frame must be `harness.subscribe`. The worker exits when
26 * stdin closes, or after a `subscribe` with a `v` that it does not speak.
27 * `artifactText` starts workers like this.
28 *
29 * @example
30 * ```ts
31 * await runHarnessWorker(assistant)
32 * ```
33 */
34export async function runHarnessWorker(
35 harness: AnyHarness,
36 options: HarnessWorkerOptions = {},
37): Promise<void> {
38 const output = options.output ?? process.stdout
39 const send = (frame: HostFrame | string) =>
40 output.write(
41 `${typeof frame === 'string' ? frame : JSON.stringify(frame)}\n`,
42 )
43 const host = createHarnessHost(
44 options.persistence ? { persistence: options.persistence } : {},
45 )
46 const reader = new AbortController()
47 let session: Awaited<ReturnType<typeof host.open>> | undefined
48 const lines = createInterface({
49 input: options.input ?? process.stdin,
50 crlfDelay: Infinity,
51 })
52​
53 // The error frame names the request that failed, so the client can match
54 // it. A frame with no `requestId` gets one from the worker. The message
55 // has no secrets of the session once it is open.
56 const fail = (
57 error: unknown,
58 requestId: string,
59 code: HarnessErrorCode = 'internal',
60 ) => {
61 const scrubbed = scrubbedBy(session, error)
62 send({
63 type: 'harness.error',
64 message: scrubbed instanceof Error ? scrubbed.message : String(scrubbed),
65 code,
66 requestId,
67 })
68 }
69​
70 try {
71 for await (const line of lines) {
72 if (line.trim() === '') continue
73 // Read the id before the full parse: a frame with a bad `input` still
74 // names its request.
75 const requestId = requestIdOf(line) ?? randomUUID()
76 let frame: ControlFrame
77 try {
78 frame = parseControlFrame(line)
79 } catch (error) {
80 fail(error, requestId, 'invalid_frame')
81 continue
82 }
83 try {
84 if (frame.type === 'harness.subscribe') {
85 if (session) {
86 fail(new Error('Already subscribed.'), requestId, 'invalid_frame')
87 continue
88 }
89 const refused = versionError(frame.v)
90 if (refused) {
91 // The worker speaks no other version, so it stops.
92 send({ type: 'harness.error', requestId, ...refused })
93 break
94 }
95 session = await host.open(harness, { threadId: frame.threadId })
96 send({
97 type: 'harness.hello',
98 v: HARNESS_PROTOCOL_VERSION,
99 threadId: frame.threadId,
100 })
101 const events = session.events({
102 ...(frame.from ? { from: frame.from } : {}),
103 signal: reader.signal,
104 })
105 void (async () => {
106 // Each event goes out as an AG-UI wire chunk.
107 for await (const entry of events) send(wireFrame(entry))
108 })().catch((error: unknown) => fail(error, requestId))
109 continue
110 }
111 if (!session) {
112 fail(
113 new Error('Send harness.subscribe first.'),
114 requestId,
115 'invalid_frame',
116 )
117 continue
118 }
119 if (frame.type === 'harness.snapshot') {
120 send({ type: 'harness.snapshot', snapshot: session.snapshot() })
121 continue
122 }
123 const receipt = await applyInput({
124 harness,
125 session,
126 input: frame.input,
127 ...(frame.traceparent ? { traceparent: frame.traceparent } : {}),
128 })
129 send({
130 type: 'harness.receipt',
131 requestId: frame.requestId,
132 ...receipt,
133 })
134 } catch (error) {
135 fail(error, requestId)
136 }
137 }
138 } finally {
139 reader.abort()
140 // The worker holds one handle for its life.
141 await session?.close()
142 await host.close()
143 }