Open History to see the last commit
1import { createHarnessHost } from '@tanstack/ai-harness'
2import { createSessionView } from '@tanstack/ai-harness/view'
3import { USAGE, parseCliArgs } from './args'
4import { attach, defaultMediaDir } from './attach'
5import { runLines } from './lines'
6import { loadOptional } from './optional'
7import { EXIT, runPrint } from './print'
8import { createToken, serve } from './serve'
9import { cancelTurn, stopOnSignals } from './signals'
10import type {
11 AnyHarness,
12 HarnessHost,
13 HarnessPersistence,
14 HarnessSession,
15 HarnessUser,
16 UserInput,
17} from '@tanstack/ai-harness'
18import type { CredentialStore } from '@tanstack/ai/byok'
19import type {
20 SessionView,
21 SessionViewSource,
22 ViewAgentSendOptions,
23 ViewSendOptions,
24} from '@tanstack/ai-harness/view'
25import type {
26 AcpAgentModule,
27 McpHarnessModule,
28 McpStdioModule,
29} from './optional'
30import type { SignalSource } from './signals'
31
32/** The error for a flag whose optional package is missing or too old. */
33function needs(flag: string, name: string): Error {
34 return new Error(
35 `${flag} needs ${name} with harness support. Install it next to @tanstack/ai-harness-cli.`,
36 )
37}
38
39export interface RunCliOptions<U extends HarnessUser = HarnessUser> {
40 /** Where sessions keep state. Default: in memory. Do not set it with `host`. */
41 persistence?: HarnessPersistence
42 /**
43 * Where users' keys and sign-ins are saved. Default: in memory. Do not set
44 * it with `host`.
45 */
46 credentials?: CredentialStore
47 /**
48 * Your own host, so the CLI keeps its hooks: ownership, recovery, and stores.
49 * You own it: the CLI does not close it. Do not set it with `persistence`
50 * or `credentials`. With host `access`, give `user` too. `--serve`
51 * then reads the user of each request with `access.getUser`, and `--mcp`
52 * refuses to start, as stdio has no login.
53 */
54 host?: HarnessHost<U>
55 /**
56 * Who uses the CLI. Sessions open as this user in every mode, so
57 * credentials and provider keys are theirs. On a host without access,
58 * `--serve` runs each request with the token as them.
59 */
60 user?: U
61 /** Default: `process.argv.slice(2)`. */
62 argv?: ReadonlyArray<string>
63 stdin?: NodeJS.ReadStream
64 stdout?: { write: (text: string) => unknown }
65 stderr?: { write: (text: string) => unknown }
66 env?: Record<string, string | undefined>
67 /**
68 * Your own screen for an interactive terminal, with any UI library. It gets
69 * a ready session view and resolves when the user quits. Piped input and
70 * the other modes (`--print`, `--acp`, `--mcp`, `--serve`) do not use it.
71 * `view.send(text)` sends each `@path` file in `text`, as line mode does.
72 * A saved child agent of a reopened thread shows only its card until the
73 * screen calls `view.loadAgent({ id })`.
74 */
75 ui?: (view: SessionView) => Promise<void> | void
76 /**
77 * Where the CLI hears SIGINT and SIGTERM. Default: `process`. A test can
78 * give an `EventEmitter` and emit the signals.
79 *
80 * In every mode, a signal cancels the running turn. A second signal, or a
81 * signal while no turn runs, closes what the CLI opened, and `runCli`
82 * resolves to 130 (SIGINT) or 143 (SIGTERM). A host that the CLI made
83 * closes with `recoverable: true`, so a durable host runs the cut work
84 * again. Your own `host` stays open: the CLI releases only its handle of
85 * the session, and does not wait for a turn that ignores the cancel.
86 */
87 signals?: SignalSource
88}
89
90/**
91 * Show `ui` on a view of `session`. Resolves when the ui ends, or when a
92 * signal stops the CLI (`stopped` resolves).
93 */
94async function showUi(
95 session: HarnessSession,
96 ui: NonNullable<RunCliOptions['ui']>,
97 stopped: Promise<number>,
98) {
99 const view = createSessionView(attachingSource(session))
100 try {
101 await view.ready
102 await Promise.race([ui(view), stopped])
103 } finally {
104 view.dispose()
105 }
106 return EXIT.ok
107}
108
109/**
110 * The session for a `ui` view: a typed message or steer sends its `@path`
111 * files, as in line mode. The other members go to the session as they are.
112 */
113function attachingSource(session: HarnessSession) {
114 const withFiles = (message: UserInput) =>
115 typeof message === 'string'
116 ? attach(session, message, { cwd: process.cwd() })
117 : Promise.resolve(message)
118 // `Required`: a member that is not here fails the typecheck. A view whose
119 // source has no member shows an error for that action.
120 const source: Required<SessionViewSource> = {
121 // The view shows a failed operation from its events, so only a file that
122 // cannot go rejects here. It becomes an error notice in the view.
123 send: (
124 message: UserInput,
125 sendOptions?: ViewSendOptions | ViewAgentSendOptions,
126 ) =>
127 withFiles(message).then((input) => {
128 const operation =
129 sendOptions?.to !== undefined
130 ? session.send(input, sendOptions)
131 : session.send(input, sendOptions)
132 operation.then(undefined, () => {})
133 return operation.receipt
134 }),
135 resolve: (options) => session.resolve(options),
136 cancel: (options) => session.cancel(options),
137 continueWithoutMessage: () => session.continueWithoutMessage(),
138 cancelInput: (options) => session.cancelInput(options),
139 changeInputDelivery: (change) => session.changeInputDelivery(change),
140 updateThreadSettings: (options) => session.updateThreadSettings(options),
141 reset: (options) => session.reset(options),
142 revert: (options) => session.revert(options),
143 unrevert: () => session.unrevert(),
144 answer: (answer) => session.answer(answer),
145 runCommand: (options) => session.runCommand(options),
146 setPluginSetting: (change) => session.setPluginSetting(change),
147 events: (options) => session.events(options),
148 snapshot: () => session.snapshot(),
149 transcript: () => session.transcript(),
150 describe: () => session.describe(),
151 mediaUrl: (options) => session.mediaUrl(options),
152 loadMedia: (options) => session.loadMedia(options),
153 putMedia: (file) => session.putMedia(file),
154 agentTranscript: (options) => session.agentTranscript(options),
155 }
156 return source
157}
158
159/**
160 * Run a harness from the terminal. Resolves to the process exit code: 130
161 * or 143 when SIGINT or SIGTERM stops it (see `signals`).
162 *
163 * @example
164 * ```ts
165 * #!/usr/bin/env node
166 * process.exitCode = await runCli(studio)
167 * ```
168 */
169export async function runCli<U extends HarnessUser = HarnessUser>(
170 harness: AnyHarness,
171 options: RunCliOptions<U> = {},
172): Promise<number> {
173 const stdout = options.stdout ?? process.stdout
174 const stderr = options.stderr ?? process.stderr
175 const stdin = options.stdin ?? process.stdin
176 const env = options.env ?? process.env
177
178 let args
179 try {
180 args = parseCliArgs(options.argv ?? process.argv.slice(2))
181 } catch (error) {
182 stderr.write(
183 `${error instanceof Error ? error.message : String(error)}\n\n${USAGE}\n`,
184 )
185 return EXIT.failed
186 }
187 if (args.help) {
188 stdout.write(`${USAGE}\n`)
189 return EXIT.ok
190 }
191
192 if (options.host && (options.persistence || options.credentials)) {
193 stderr.write(
194 'Give runCli a host, or persistence and credentials, not both.\n',
195 )
196 return EXIT.failed
197 }
198 const host: HarnessHost<U> =
199 options.host ??
200 createHarnessHost({
201 ...(options.persistence ? { persistence: options.persistence } : {}),
202 ...(options.credentials ? { credentials: options.credentials } : {}),
203 })
204 const { user } = options
205 const approvals = args.yes ? 'auto' : 'ask'
206 // The session modes cancel the turn of their session. The other modes
207 // have no turn of their own, so a signal stops them at once.
208 let cancel = () => false
209 const stop = stopOnSignals(options.signals ?? process, () => cancel())
210 /** The handle of the session modes. The CLI releases it at the end. */
211 let session: HarnessSession | undefined
212 /**
213 * The run of --print waits for a person. A durable host keeps the wait,
214 * so a later run (or another machine) answers it.
215 */
216 let isWaiting = false
217 try {
218 if (args.acp) {
219 const acp = await loadOptional<AcpAgentModule>(
220 '@tanstack/ai-acp/agent',
221 'serveAcp',
222 )
223 if (!acp) throw needs('--acp', '@tanstack/ai-acp')
224 const connection = acp.serveAcp({ host, harness, user })
225 const code = await Promise.race([
226 connection.closed.then(() => EXIT.ok),
227 stop.stopped,
228 ])
229 connection.close()
230 // ponytail: serveAcp reads process.stdin and does not stop at close,
231 // and a stdin that flows keeps the process alive. Pause it here until
232 // the ACP stdio stream stops reading at close.
233 if (stop.signal.aborted) process.stdin.pause()
234 return code
235 }
236
237 if (args.mcp) {
238 // A host with access reads the user of each HTTP request.
239 if (host.hasAccess) {
240 throw new Error(
241 '--mcp serves over stdio, which has no login, so it cannot use a host with access. Give runCli a host without access, and the local user as the user option.',
242 )
243 }
244 const [mcp, stdio] = await Promise.all([
245 loadOptional<McpHarnessModule>(
246 '@tanstack/ai-mcp/harness',
247 'createHarnessMcpServer',
248 ),
249 loadOptional<McpStdioModule>(
250 '@tanstack/ai-mcp/server/stdio',
251 'serveMCPStdio',
252 ),
253 ])
254 if (!mcp || !stdio) throw needs('--mcp', '@tanstack/ai-mcp')
255 const server = await mcp.createHarnessMcpServer({
256 host,
257 harness,
258 // One local user: every call runs as them.
259 openAccess: user ? { user } : true,
260 threadId: args.thread,
261 approvals,
262 // A local client can attach the files of the working folder by path.
263 filePaths: [process.cwd()],
264 })
265 // stdout carries only MCP messages. The server stops when stdin ends.
266 const ended = new Promise<number>((resolve) => {
267 stdin.once('end', () => resolve(EXIT.ok))
268 })
269 const served = stdio.serveMCPStdio(server)
270 const code = await Promise.race([ended, stop.stopped])
271 await served.close()
272 return code
273 }
274
275 if (args.serve) {
276 const token = args.token ?? env.HARNESS_TOKEN ?? createToken()
277 const mediaKey = args.mediaKey ?? env.HARNESS_MEDIA_KEY
278 const server = await serve({
279 host,
280 harness,
281 port: args.port,
282 hostname: args.hostname,
283 token,
284 ...(mediaKey !== undefined ? { mediaKey } : {}),
285 threadId: args.thread,
286 approvals,
287 ...(user ? { user } : {}),
288 })
289 stderr.write(`Serving ${harness.name} at ${server.url}\n`)
290 if (!args.token && !env.HARNESS_TOKEN) stderr.write(`Token: ${token}\n`)
291 const code = await stop.stopped
292 await server.close()
293 return code
294 }
295
296 session = await host.open(harness, {
297 threadId: args.thread,
298 ...(user ? { user } : {}),
299 })
300 cancel = cancelTurn(session)
301 // Relative to the working folder, as a relative --media-dir is.
302 const mediaDir = args.mediaDir ?? defaultMediaDir(harness.name)
303 const running =
304 args.print !== undefined
305 ? runPrint(session, args.print, {
306 output: args.output,
307 stdout,
308 stderr,
309 mediaDir,
310 })
311 : stdin.isTTY && options.ui
312 ? showUi(session, options.ui, stop.stopped)
313 : runLines(session, stdin, stdout, {
314 interactive: Boolean(stdin.isTTY),
315 mediaDir,
316 signal: stop.signal,
317 onCtrlC: () => stop.receive('SIGINT'),
318 }).then(() => EXIT.ok)
319 const code = await Promise.race([running, stop.stopped])
320 isWaiting = code === EXIT.needsAction
321 if (!stop.signal.aborted) {
322 // A signal that cancelled the turn of --print gives its exit code.
323 return code === EXIT.cancelled ? (stop.exitCode() ?? code) : code
324 }
325 // A host that the CLI made closes now, so the mode ends with its
326 // session, and its running work stops as on a crash: a durable host runs
327 // it again. On your own host, the CLI releases its handle and does not
328 // wait: a turn that ignores the cancel runs on in your host. Work that
329 // the close cuts can fail, and the signal gives the exit code.
330 if (options.host) {
331 await session.close()
332 running.catch(() => {})
333 return await stop.stopped
334 }
335 await host.close({ recoverable: true })
336 await running.catch(() => {})
337 return await stop.stopped
338 } catch (error) {
339 stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
340 return EXIT.failed
341 } finally {
342 stop.dispose()
343 await session?.close()
344 // A host the caller gave stays open: the caller owns it. After a
345 // signal, its running work stops as on a crash, so a durable host runs
346 // it again.
347 if (!options.host) {
348 await host.close({ recoverable: stop.signal.aborted || isWaiting })
349 }
350 }
351}
352
353export { parseCliArgs, USAGE } from './args'
354export type { CliArgs } from './args'
355export { EXIT } from './print'