Open History to see the last commit
1import { EventType } from '@tanstack/ai'
2import { HARNESS_EVENTS } from '@tanstack/ai-harness'
3import { isMediaRecord } from '@tanstack/ai-harness/media'
4import { attach, saveMediaLine } from './attach'
5import type { HarnessSession, Wait } from '@tanstack/ai-harness'
6
7/**
8 * The exit codes of the CLI. `needsAction` (3): the turn waits for a person
9 * (an approval, an answer, a sign-in).
10 */
11export const EXIT = {
12 ok: 0,
13 failed: 1,
14 needsAction: 3,
15 cancelled: 130,
16} as const
17
18/** What `--print` says on stderr when the turn waits for `wait`. */
19function needsActionText(wait: Wait | undefined) {
20 const what =
21 wait?.kind === 'approval'
22 ? 'an approval'
23 : wait?.kind === 'sign-in'
24 ? 'a sign-in'
25 : 'an answer'
26 const message = wait?.message ? `: ${wait.message}` : ''
27 return `The turn waits for ${what}${message}. Run without --print, in line mode, to answer it.\n`
28}
29
30interface Output {
31 write: (text: string) => unknown
32}
33
34/**
35 * Run one prompt and print it. `text` prints the answer as it streams.
36 * `ndjson` prints every AG-UI event as one JSON line. Each `@path` file in
37 * the prompt goes with it.
38 *
39 * Each media file the turn makes is saved into `mediaDir`. `ndjson` adds the
40 * saved `path` to the value of its `harness.media` event. `text` prints the
41 * saved line to stderr, so stdout keeps only the answer.
42 *
43 * When the turn waits for a person (an approval, a question, a sign-in),
44 * it stops there and resolves with `EXIT.needsAction`: nobody can answer
45 * in this mode.
46 */
47export async function runPrint(
48 session: HarnessSession,
49 prompt: string,
50 options: {
51 output: 'text' | 'ndjson'
52 stdout: Output
53 stderr: Output
54 mediaDir: string
55 },
56) {
57 const { stdout, stderr } = options
58 const input = await attach(session, prompt, { cwd: process.cwd() })
59 const operation = session.send(input)
60 /** Print the events of the turn. Resolves with its failure, if any. */
61 const stream = async (): Promise<unknown> => {
62 for await (const chunk of operation.stream()) {
63 const media =
64 chunk.type === EventType.CUSTOM &&
65 chunk.name === HARNESS_EVENTS.media &&
66 isMediaRecord(chunk.value)
67 ? chunk.value
68 : undefined
69 if (media !== undefined) {
70 const saved = await saveMediaLine(session, media, options.mediaDir)
71 if (options.output === 'text' || saved.path === undefined) {
72 stderr.write(`${saved.text}\n`)
73 }
74 if (options.output === 'ndjson') {
75 // A file that was not saved has no `path`: JSON drops `undefined`.
76 const value = { ...media, path: saved.path }
77 stdout.write(`${JSON.stringify({ ...chunk, value })}\n`)
78 }
79 } else if (options.output === 'ndjson') {
80 stdout.write(`${JSON.stringify(chunk)}\n`)
81 } else if (
82 chunk.type === EventType.TEXT_MESSAGE_CONTENT &&
83 !('subagentRunId' in chunk && chunk.subagentRunId)
84 ) {
85 stdout.write(chunk.delta)
86 }
87 }
88 return operation.then(
89 () => undefined,
90 (error: unknown) => error,
91 )
92 }
93 const stop = new AbortController()
94 // A wait of the turn ends the run of --print: nobody can answer it here.
95 const opened = session
96 .waitForRun({ runId: operation.id, signal: stop.signal })
97 .then(
98 (wait) => ({ type: 'wait' as const, wait }),
99 () => new Promise<never>(() => {}),
100 )
101 const ended = stream().then((failure) => ({ type: 'end' as const, failure }))
102 const first = await Promise.race([ended, opened])
103 stop.abort()
104 const isTurnStop =
105 first.type === 'wait' &&
106 session
107 .snapshot()
108 .pendingWaits.some(
109 ({ waitId, turn }) => turn && waitId === first.wait.waitId,
110 )
111 if (first.type === 'wait' && !isTurnStop) {
112 if (options.output === 'text') stdout.write('\n')
113 stderr.write(needsActionText(first.wait))
114 return EXIT.needsAction
115 }
116 // A turn that stopped for its waits ends its stream first.
117 const { failure } = await ended
118 if (options.output === 'text') stdout.write('\n')
119 const status = operation.status()
120 if (status === 'completed') return EXIT.ok
121 if (status === 'interrupted') {
122 const [wait] = session.snapshot().pendingWaits
123 stderr.write(needsActionText(wait))
124 return EXIT.needsAction
125 }
126 if (status === 'cancelled') return EXIT.cancelled
127 stderr.write(
128 `The turn failed: ${failure instanceof Error ? failure.message : String(failure)}\n`,
129 )
130 return EXIT.failed
131}