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

printer.ts

145 lines4.5 KB

1import { shortAnswer, signInText } from './session-view'
2import type {
3 AgentPart,
4 MediaPart,
5 SessionViewState,
6 ViewPart,
7} from '@tanstack/ai-harness/view'
8​
9/**
10 * Prints a session view as lines: streamed text as it grows, and one
11 * bracketed line per tool call, child agent, notice, question, and sign-in.
12 * Notices that line mode prints itself (command results, rejected inputs,
13 * and UI notes) are skipped.
14 *
15 * Media parts print nothing here. `onMedia` gets each new media part of an
16 * assistant message once, from the lead or from a child at any depth.
17 * `hidesSecrets`: the input hides what the user types for a secret
18 * question, so its line says so.
19 */
20export function createPrinter(
21 write: (text: string) => unknown,
22 options: { onMedia?: (part: MediaPart) => void; hidesSecrets?: boolean } = {},
23) {
24 const done = new Set<string>()
25 const written = new Map<string, number>()
26 /**
27 * The messages and parts that printed. The view keeps a message or a part
28 * that did not change, so a print walks only the new ones.
29 */
30 const printed = new WeakSet<object>()
31 // True while streamed text has no line break at its end yet.
32 let midLine = false
33 let lastStream = ''
34 let marking = false
35​
36 const line = (text: string) => {
37 if (marking) return
38 if (midLine) write('\n')
39 midLine = false
40 write(`${text}\n`)
41 }
42 const once = (key: string, text: string) => {
43 if (done.has(key)) return
44 done.add(key)
45 line(`[${text}]`)
46 }
47 const stream = (key: string, text: string) => {
48 const before = written.get(key) ?? 0
49 if (text.length <= before) return
50 written.set(key, text.length)
51 if (marking) return
52 if (midLine && key !== lastStream) write('\n')
53 write(text.slice(before))
54 midLine = true
55 lastStream = key
56 }
57 const agent = (key: string, part: AgentPart) => {
58 // A child that ended before its saved parts loaded (a reopened thread)
59 // printed its end already. Its parts that come later are old: mark them.
60 const old = done.has(`${key}:end`)
61 const wasMarking = marking
62 marking ||= old
63 once(`${key}:start`, `agent ${part.name} started`)
64 part.parts.forEach((inner, index) => {
65 if (inner.type === 'tool-call')
66 once(`${key}:${index}`, `${part.name}: tool ${inner.name}`)
67 })
68 const answer = shortAnswer(
69 part.parts
70 .map((inner) => (inner.type === 'text' ? inner.text : ''))
71 .join(''),
72 )
73 if (part.status === 'done')
74 once(
75 `${key}:end`,
76 answer
77 ? `agent ${part.name} finished: ${answer}`
78 : `agent ${part.name} finished`,
79 )
80 if (part.status === 'failed')
81 once(`${key}:end`, `agent ${part.name} failed: ${part.error ?? ''}`)
82 if (old) media(part.parts)
83 marking = wasMarking
84 }
85 const media = (parts: ReadonlyArray<ViewPart>) => {
86 for (const part of parts) {
87 if (part.type === 'agent') media(part.parts)
88 if (part.type !== 'media' || done.has(`media:${part.id}`)) continue
89 done.add(`media:${part.id}`)
90 if (!marking) options.onMedia?.(part)
91 }
92 }
93 const print = (state: SessionViewState) => {
94 for (const message of state.messages) {
95 if (printed.has(message)) continue
96 printed.add(message)
97 if (message.role === 'notice') {
98 if (message.kind === 'error' || message.kind === 'info')
99 once(message.id, message.text)
100 continue
101 }
102 if (message.role !== 'assistant') continue
103 const fresh: Array<ViewPart> = []
104 message.parts.forEach((part, index) => {
105 if (printed.has(part)) return
106 printed.add(part)
107 fresh.push(part)
108 const key = `${message.id}:${index}`
109 if (part.type === 'text') stream(key, part.text)
110 if (part.type === 'tool-call') once(key, `tool ${part.name}`)
111 if (part.type === 'agent') agent(key, part)
112 })
113 media(fresh)
114 }
115 for (const question of state.questions) {
116 const isHidden = question.secret === true && options.hidesSecrets === true
117 once(
118 `question:${question.id}`,
119 isHidden
120 ? `? ${question.message} (typing is hidden)`
121 : `? ${question.message}`,
122 )
123 }
124 for (const signIn of state.signIns)
125 once(
126 `sign-in:${signIn.connector}:${signIn.url ?? ''}`,
127 signInText(signIn),
128 )
129 }
130​
131 return {
132 print,
133 /** Mark everything in `state` as printed, for history. */
134 mark: (state: SessionViewState) => {
135 marking = true
136 print(state)
137 marking = false
138 },
139 line,
140 end: () => {
141 if (midLine) write('\n')
142 midLine = false
143 },
144 }