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

session-view.ts

122 lines4.1 KB

1import { parseAnswer } from './commands'
2import type { RunAgentResumeItem } from '@tanstack/ai'
3import type {
4 HarnessSession,
5 SessionSnapshot,
6 Wait,
7} from '@tanstack/ai-harness'
8import type { SignIn } from '@tanstack/ai-harness/view'
9​
10/** The waits of the stopped turn, in order. One resolve answers them all. */
11export function turnWaits(snapshot: SessionSnapshot) {
12 return snapshot.pendingWaits.filter(({ turn }) => turn)
14​
15const isYes = (text: string) => /^y(es)?$/i.test(text.trim())
16​
17/**
18 * The answer of the reply `text` to `wait`, by its kind and schema:
19 *
20 * - `approval`: `y` approves and `n` rejects. Any other reply is read with
21 * the schema of the wait (for example `always` for an approval of
22 * `permissions()`), and an approval with no schema rejects it.
23 * - `question` and `human`: the reply, read with the schema.
24 * - `sign-in`: `y` goes on after the sign-in. Any other reply skips it.
25 * - `client-tool`: a terminal cannot run it, so any reply skips it.
26 */
27export function answerOf(wait: Wait, text: string): RunAgentResumeItem {
28 const resolved = (payload: unknown): RunAgentResumeItem => ({
29 interruptId: wait.waitId,
30 status: 'resolved',
31 payload,
32 })
33 const skipped: RunAgentResumeItem = {
34 interruptId: wait.waitId,
35 status: 'cancelled',
36 }
37 switch (wait.kind) {
38 case 'approval': {
39 const reply = text.trim()
40 if (isYes(reply)) return resolved(true)
41 if (/^no?$/i.test(reply) || wait.schema === undefined) {
42 return resolved(false)
43 }
44 return resolved(parseAnswer(reply, wait.schema))
45 }
46 case 'question':
47 case 'human':
48 return resolved(parseAnswer(text, wait.schema))
49 case 'sign-in':
50 return isYes(text) ? resolved(true) : skipped
51 case 'client-tool':
52 return skipped
53 }
55​
56/** The line that asks the user for the answer to `wait`. */
57export function waitQuestion(wait: Wait) {
58 const message = wait.message ?? wait.waitId
59 switch (wait.kind) {
60 case 'approval':
61 return `Approve ${message}? [y/n]`
62 case 'question':
63 case 'human':
64 return `? ${message}`
65 case 'sign-in':
66 return `${message} Sign in, then answer y to go on, or n to skip. [y/n]`
67 case 'client-tool':
68 return `${message}: this tool runs in a client, not here. Send any line to skip it.`
69 }
71​
72/** Open an http(s) URL in the default browser. No shell is involved. */
73export function openUrl(url: string) {
74 if (!/^https?:\/\//.test(url)) return
75 void import('node:child_process').then(({ spawn }) => {
76 const [command, args] =
77 process.platform === 'win32'
78 ? // Not `cmd /c start`: cmd would read `&` in the URL as a command separator.
79 ['rundll32', ['url.dll,FileProtocolHandler', url]]
80 : process.platform === 'darwin'
81 ? ['open', [url]]
82 : ['xdg-open', [url]]
83 try {
84 spawn(command, args, { stdio: 'ignore', detached: true }).unref()
85 } catch {
86 // The notice still shows the URL.
87 }
88 })
90​
91/**
92 * Resolves when no chat turn runs or waits in the queue, or when a wait is
93 * open (see `session.waitForRun`): the user answers it on the next line.
94 */
95export async function waitIdle(session: HarnessSession) {
96 while (true) {
97 const snapshot = session.snapshot()
98 if (snapshot.pendingWaits.length > 0) return
99 const chatActive = snapshot.activeOperations.some(
100 (operation) => operation.kind === 'chat',
101 )
102 const isIdle =
103 snapshot.status !== 'running' && !chatActive && snapshot.queuedTurns === 0
104 if (isIdle) return
105 await new Promise((resolve) => setTimeout(resolve, 20))
106 }
108​
109/** The first 200 characters of a child's answer, on one line. */
110export function shortAnswer(text: string) {
111 const line = text.replace(/\s+/g, ' ').trim()
112 return line.length > 200 ? `${line.slice(0, 200)}...` : line
114​
115/** The sign-in line for a connector: its link and code, or the command. */
116export function signInText(signIn: SignIn) {
117 const code = signIn.userCode ? ` and enter the code ${signIn.userCode}` : ''
118 const where = signIn.url
119 ? ` Open ${signIn.url}${code}.`
120 : ` Run /connect ${signIn.connector}.`
121 return `Sign in to ${signIn.connector}.${where}`