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

lines.ts

196 lines6.5 KB

1import { createInterface } from 'node:readline'
2import { createSessionView } from '@tanstack/ai-harness/view'
3import { saveMediaLine } from './attach'
4import { firstQuestion, handleLine } from './commands'
5import { createPrinter } from './printer'
6import {
7 answerOf,
8 openUrl,
9 turnWaits,
10 waitIdle,
11 waitQuestion,
12} from './session-view'
13import type { RunAgentResumeItem } from '@tanstack/ai'
14import type { HarnessSession } from '@tanstack/ai-harness'
15​
16interface Output {
17 write: (text: string) => unknown
19​
20/** A terminal, which can stop showing what the user types. A pipe cannot. */
21function isTerminal(input: NodeJS.ReadableStream): input is NodeJS.ReadStream {
22 return 'isTTY' in input && input.isTTY === true && 'setRawMode' in input
24​
25/**
26 * The text of a line typed in raw mode, where the terminal does not edit
27 * it: a backspace removes the character before it, and other control
28 * characters are dropped.
29 */
30function typedText(raw: string) {
31 let text = ''
32 for (const char of raw) {
33 if (char === '\u007f' || char === '\b') text = text.slice(0, -1)
34 else if (char >= ' ') text += char
35 }
36 return text
38​
39/**
40 * Hide what the user types in a terminal while a secret question (a key)
41 * waits. Raw mode stops the echo. It also makes Ctrl+C a typed character
42 * and not SIGINT, so this calls `onCtrlC`. Does nothing for a pipe.
43 */
44function secretTyping(input: NodeJS.ReadableStream, onCtrlC: () => void) {
45 const terminal = isTerminal(input) ? input : undefined
46 let hidden = false
47 const onKeys = (chunk: unknown) => {
48 if (!String(chunk).includes('\u0003')) return
49 show()
50 onCtrlC()
51 }
52 const show = () => {
53 if (!terminal || !hidden) return
54 hidden = false
55 terminal.off('data', onKeys)
56 terminal.setRawMode(false)
57 }
58 return {
59 canHide: terminal !== undefined,
60 isHidden: () => hidden,
61 hide: () => {
62 if (!terminal || hidden) return
63 hidden = true
64 terminal.setRawMode(true)
65 terminal.on('data', onKeys)
66 },
67 show,
68 }
70​
71/**
72 * The line mode: one message or command per line. When a turn stops for
73 * its waits, each next line answers one of them, by its kind and schema
74 * (see `answerOf`: `y` approves an approval). After the last one, the turn
75 * goes on. A question of a command or a durable tool takes the next line.
76 * In a terminal, the answer to a secret question (a key) is not shown as
77 * the user types. Line mode never prints the answer.
78 *
79 * `interactive`: the user types the lines (a terminal). Each line acts at
80 * once: `/cancel` cancels the running turn, and a message steers it. Sign-in
81 * links open in the browser. Without it (piped input), each line waits for
82 * the turn that the line before it started, so a script runs in order.
83 * `mediaDir`: the folder for the media a turn makes. Each new file is saved
84 * there, with one `[image saved: <path>]` line.
85 * `signal`: stop reading lines when it aborts.
86 * `onCtrlC`: runs on Ctrl+C while typing is hidden, as the terminal then
87 * sends no SIGINT.
88 */
89export async function runLines(
90 session: HarnessSession,
91 input: NodeJS.ReadableStream,
92 stdout: Output,
93 options: {
94 interactive?: boolean
95 mediaDir: string
96 signal: AbortSignal
97 onCtrlC: () => void
98 },
99) {
100 const view = createSessionView(session)
101 const saves: Array<Promise<unknown>> = []
102 const typing = secretTyping(input, options.onCtrlC)
103 const printer = createPrinter((text) => stdout.write(text), {
104 onMedia: (part) => {
105 const saved = saveMediaLine(session, part, options.mediaDir)
106 saves.push(saved.then(({ text }) => printer.line(text)))
107 },
108 hidesSecrets: typing.canHide,
109 })
110 await view.ready
111 // Line mode prints only what happens from now on.
112 printer.mark(view.store.get())
113 const printing = view.store.subscribe((state) => printer.print(state))
114 const stopOpening = options.interactive
115 ? view.on('signIn', (signIn) => {
116 if (signIn.url) openUrl(signIn.url)
117 })
118 : () => {}
119 const line = printer.line
120​
121 const lines = createInterface({
122 input,
123 crlfDelay: Infinity,
124 signal: options.signal,
125 })
126 const pendingLater: Array<Promise<void>> = []
127 /** The answers to the waits of the stopped turn so far, by wait id. */
128 const decided = new Map<string, RunAgentResumeItem>()
129 /**
130 * Wait for the turn to end. Then ask for its next wait that has no
131 * answer, and hide the typing for a secret question. In a terminal, this
132 * runs while the next lines are read. Only one runs at a time, so each
133 * wait is asked once.
134 */
135 const afterTurn = async () => {
136 await waitIdle(session)
137 const after = session.snapshot()
138 const ask =
139 after.status === 'requires_action'
140 ? turnWaits(after).find(({ waitId }) => !decided.has(waitId))
141 : undefined
142 if (ask) line(waitQuestion(ask))
143 if (firstQuestion(after)?.secret) typing.hide()
144 }
145 let waiting: Promise<void> | undefined
146 try {
147 for await (const raw of lines) {
148 // Lines that came before the stop do not run.
149 if (options.signal.aborted) break
150 const typed = typing.isHidden() ? typedText(raw) : raw
151 typing.show()
152 const snapshot = session.snapshot()
153 const waits = turnWaits(snapshot)
154 const next = waits.find(({ waitId }) => !decided.has(waitId))
155 if (snapshot.status === 'requires_action' && next) {
156 decided.set(next.waitId, answerOf(next, typed))
157 // One resolve answers every wait of the turn.
158 if (waits.every(({ waitId }) => decided.has(waitId))) {
159 const resume = waits.flatMap(
160 ({ waitId }) => decided.get(waitId) ?? [],
161 )
162 decided.clear()
163 await session.resolve({ resume })
164 }
165 } else {
166 const result = await handleLine(session, typed)
167 if (result.type === 'exit') break
168 if (result.type === 'notice' && result.text) line(result.text)
169 if (result.type === 'notice' && result.later) {
170 pendingLater.push(result.later.then((text) => line(text)))
171 }
172 }
173 if (!options.interactive) {
174 await afterTurn()
175 continue
176 }
177 // A secret question that the line asked hides the next line at once.
178 if (firstQuestion(session.snapshot())?.secret) typing.hide()
179 waiting ??= afterTurn().finally(() => {
180 waiting = undefined
181 })
182 }
183 } finally {
184 typing.show()
185 }
186 lines.close()
187 await waiting
188 await Promise.allSettled(pendingLater)
189 await waitIdle(session)
190 stopOpening()
191 printing.unsubscribe()
192 printer.print(view.store.get())
193 await Promise.allSettled(saves)
194 view.dispose()
195 printer.end()