Open History to see the last commit
1import { attach } from './attach'
2import type {
3 HarnessSession,
4 SessionSnapshot,
5 UserInput,
6} from '@tanstack/ai-harness'
7
8/** The first question wait of `snapshot` that no turn holds: `answer` takes it. */
9export function firstQuestion({ pendingWaits }: SessionSnapshot) {
10 return pendingWaits.find(({ turn, kind }) => !turn && kind === 'question')
11}
12
13export const HELP_TEXT = [
14 'Type a message and press Enter. While the agent works, a new message steers it.',
15 'Commands:',
16 ' /agents list the agents',
17 ' /agent <name> [json] run an agent in the background',
18 ' /config [key value] show or change a setting',
19 ' /connect <id> sign in to a connector (and /disconnect <id>)',
20 ' /cancel cancel the running turn',
21 ' /status show the session status',
22 ' /exit quit',
23].join('\n')
24
25/** A command argument: JSON when it parses, else the text itself. */
26function parseArg(text: string): unknown {
27 if (text === '') return undefined
28 try {
29 return JSON.parse(text)
30 } catch {
31 return text
32 }
33}
34
35function show(value: unknown): string {
36 if (value === undefined) return 'Done.'
37 return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
38}
39
40/**
41 * Turn the user's reply into an answer: `y`/`n` for yes-or-no questions,
42 * JSON when it parses, else the text.
43 */
44export function parseAnswer(reply: string, schema: unknown): unknown {
45 const text = reply.trim()
46 const isBoolean =
47 typeof schema === 'object' &&
48 schema !== null &&
49 'type' in schema &&
50 schema.type === 'boolean'
51 if (isBoolean && /^(y|yes)$/i.test(text)) return true
52 if (isBoolean && /^(n|no)$/i.test(text)) return false
53 return parseArg(text)
54}
55
56async function runCommand(
57 session: HarnessSession,
58 name: string,
59 input: unknown,
60): Promise<LineResult> {
61 const describe = (
62 outcome: { ok: true; value: unknown } | { ok: false; error: unknown },
63 ) =>
64 outcome.ok
65 ? show(outcome.value)
66 : `/${name} failed: ${outcome.error instanceof Error ? outcome.error.message : String(outcome.error)}`
67 const operation = session.runCommand({ name, input })
68 const settled = Promise.resolve(
69 operation.then(
70 (value) => ({ ok: true as const, value }),
71 (error: unknown) => ({ ok: false as const, error }),
72 ),
73 )
74 // A command that asks a question waits for the next line, so return now
75 // and print its result when it is done.
76 const stop = new AbortController()
77 const asked = session
78 .waitForRun({ runId: operation.id, signal: stop.signal })
79 .then(
80 () => true,
81 () => false,
82 )
83 const isAsking = await Promise.race([settled.then(() => false), asked])
84 stop.abort()
85 if (isAsking) {
86 return { type: 'notice', text: '', later: settled.then(describe) }
87 }
88 return { type: 'notice', text: describe(await settled) }
89}
90
91/** What the UI does after a line of input. */
92export type LineResult =
93 | { type: 'notice'; text: string; later?: Promise<string> }
94 | { type: 'exit' }
95 | { type: 'sent' }
96
97/**
98 * Handle one line of user input: a slash command, a steer while a turn runs,
99 * or a new prompt. Used by the line mode, and by any UI that calls it. A
100 * prompt or a steer sends each `@path` file (relative to the working folder)
101 * with it. A command and an answer do not.
102 */
103export async function handleLine(
104 session: HarnessSession,
105 line: string,
106): Promise<LineResult> {
107 const text = line.trim()
108 if (text === '') return { type: 'notice', text: '' }
109 const question = firstQuestion(session.snapshot())
110 if (question) {
111 // A secret (a key) is the text as typed: `123456` stays a string.
112 const receipt = await session.answer({
113 questionId: question.waitId,
114 value: question.secret ? text : parseAnswer(text, question.schema),
115 })
116 return {
117 type: 'notice',
118 text:
119 receipt.status === 'rejected'
120 ? `Answer again: ${receipt.reason ?? ''}`
121 : '',
122 }
123 }
124 if (!text.startsWith('/')) {
125 let input: UserInput
126 try {
127 input = await attach(session, text, { cwd: process.cwd() })
128 } catch (error) {
129 // A file that cannot go (a type it does not know, too big) stops the send.
130 return {
131 type: 'notice',
132 text: error instanceof Error ? error.message : String(error),
133 }
134 }
135 // While a turn runs, the message joins it. Else it starts a turn. The
136 // session decides this when it stores the message, so there is no race.
137 const operation = session.send(input, { busy: 'steer' })
138 // The view shows a failed turn from its events.
139 operation.then(undefined, () => {})
140 const receipt = await operation.receipt
141 if (receipt.status === 'rejected')
142 return { type: 'notice', text: `Not sent: ${receipt.reason}` }
143 return { type: 'sent' }
144 }
145 const [name = '', ...rest] = text.slice(1).split(' ')
146 const argText = rest.join(' ').trim()
147 switch (name) {
148 case 'help': {
149 const commands = session.commands()
150 return {
151 type: 'notice',
152 text:
153 commands.length === 0
154 ? HELP_TEXT
155 : `${HELP_TEXT}\nPlugin commands:\n${commands
156 .map((command) => ` /${command.name} ${command.description}`)
157 .join('\n')}`,
158 }
159 }
160 case 'config': {
161 const [key = '', ...valueParts] = argText.split(' ')
162 if (!key) {
163 const entries = Object.entries(session.pluginSettings())
164 return {
165 type: 'notice',
166 text:
167 entries.length === 0
168 ? 'This harness has no settings.'
169 : entries
170 .map(
171 ([option, entry]) =>
172 ` ${option} = ${JSON.stringify(entry.value)}`,
173 )
174 .join('\n'),
175 }
176 }
177 const receipt = await session.setPluginSetting({
178 key,
179 value: parseArg(valueParts.join(' ').trim()),
180 })
181 return {
182 type: 'notice',
183 text:
184 receipt.status === 'rejected'
185 ? `Not changed: ${receipt.reason ?? ''}`
186 : `${key} changed.`,
187 }
188 }
189 case 'connect':
190 case 'disconnect':
191 return runCommand(session, `${name}:${argText}`, undefined)
192 case 'exit':
193 case 'quit':
194 return { type: 'exit' }
195 case 'cancel': {
196 const receipt = await session.cancel()
197 return {
198 type: 'notice',
199 text:
200 receipt.status === 'rejected' ? 'Nothing is running.' : 'Cancelled.',
201 }
202 }
203 case 'status': {
204 const snapshot = session.snapshot()
205 const active = snapshot.activeOperations
206 .map((operation) => operation.agent ?? operation.kind)
207 .join(', ')
208 return {
209 type: 'notice',
210 text: `Status: ${snapshot.status}. Running: ${active || 'nothing'}. Queued turns: ${snapshot.queuedTurns}.`,
211 }
212 }
213 case 'agents': {
214 const agents = session.registry.list()
215 return {
216 type: 'notice',
217 text:
218 agents.length === 0
219 ? 'This harness has no agents.'
220 : agents
221 .map((agent) => ` ${agent.name}: ${agent.description}`)
222 .join('\n'),
223 }
224 }
225 case 'agent': {
226 const [agentName = '', ...inputParts] = argText.split(' ')
227 const handle = session.agent(agentName)
228 if (!handle)
229 return {
230 type: 'notice',
231 text: `Unknown agent: ${agentName || '(none)'}`,
232 }
233 const inputText = inputParts.join(' ').trim()
234 let input: unknown
235 try {
236 input = inputText === '' ? undefined : JSON.parse(inputText)
237 } catch {
238 return {
239 type: 'notice',
240 text: 'The agent input must be JSON, for example {"vendor":"acme"}.',
241 }
242 }
243 const operation = handle.start(input, { startTurnWhenDone: true })
244 operation.then(
245 () => {},
246 () => {},
247 )
248 return { type: 'notice', text: `Started ${agentName} in the background.` }
249 }
250 default:
251 if (session.commands().some((command) => command.name === name)) {
252 return runCommand(session, name, parseArg(argText))
253 }
254 return { type: 'notice', text: `Unknown command: /${name}. Type /help.` }
255 }
256}