Open History to see the last commit
1import { Readable } from 'node:stream'
2import { EventType } from '@tanstack/ai'
3import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
4
5const now = () => Date.now()
6
7/** The chunks of a model call that answers `text`. */
8export const textTurn = (text: string): Array<StreamChunk> => [
9 { type: EventType.RUN_STARTED, runId: 'r', threadId: 't', timestamp: now() },
10 {
11 type: EventType.TEXT_MESSAGE_START,
12 messageId: 'm',
13 role: 'assistant',
14 timestamp: now(),
15 },
16 {
17 type: EventType.TEXT_MESSAGE_CONTENT,
18 messageId: 'm',
19 delta: text,
20 timestamp: now(),
21 },
22 { type: EventType.TEXT_MESSAGE_END, messageId: 'm', timestamp: now() },
23 {
24 type: EventType.RUN_FINISHED,
25 runId: 'r',
26 threadId: 't',
27 timestamp: now(),
28 metadata: { tanstack: { finishReason: 'stop' } },
29 },
30]
31
32/** The chunks of a model call that calls the tool `name` with `args`. */
33export const toolTurn = (name: string, args: string): Array<StreamChunk> => [
34 { type: EventType.RUN_STARTED, runId: 'r', threadId: 't', timestamp: now() },
35 {
36 type: EventType.TOOL_CALL_START,
37 toolCallId: 'call_1',
38 toolCallName: name,
39 timestamp: now(),
40 },
41 {
42 type: EventType.TOOL_CALL_ARGS,
43 toolCallId: 'call_1',
44 delta: args,
45 timestamp: now(),
46 },
47 { type: EventType.TOOL_CALL_END, toolCallId: 'call_1', timestamp: now() },
48 {
49 type: EventType.RUN_FINISHED,
50 runId: 'r',
51 threadId: 't',
52 timestamp: now(),
53 metadata: { tanstack: { finishReason: 'tool_calls' } },
54 },
55]
56
57/** A model call that the test drives. It gets the abort signal of the call. */
58type LiveTurn = (signal: AbortSignal | undefined) => AsyncIterable<StreamChunk>
59
60/** A promise that the test resolves with `open`. */
61export function gate() {
62 let open = () => {}
63 const opened = new Promise<void>((resolve) => {
64 open = resolve
65 })
66 return { open, opened }
67}
68
69/** Resolves when `signal` aborts. Never resolves without a signal. */
70function whenAborted(signal: AbortSignal | undefined) {
71 return new Promise<void>((resolve) => {
72 if (signal?.aborted) resolve()
73 signal?.addEventListener('abort', () => resolve(), { once: true })
74 })
75}
76
77/**
78 * A model call that streams `text`, then holds until `release` resolves or
79 * the call is aborted (a cancel). Then it ends.
80 */
81export function heldTurn(text: string, release: Promise<void>): LiveTurn {
82 const chunks = textTurn(text)
83 return async function* (signal) {
84 yield* chunks.slice(0, 3)
85 await Promise.race([release, whenAborted(signal)])
86 yield* chunks.slice(3)
87 }
88}
89
90/**
91 * A model that answers each call with the next of `turns`, and keeps the
92 * messages of each call in `seen`.
93 */
94export function scripted(turns: Array<Array<StreamChunk> | LiveTurn>) {
95 let call = 0
96 const seen: Array<Array<{ role: string; content: unknown }>> = []
97 const adapter: AnyTextAdapter = {
98 kind: 'text',
99 name: 'mock',
100 model: 'test-model',
101 // `~types` holds types only. Its values are never read, so they are casts.
102 '~types': {
103 providerOptions: {} as Record<string, unknown>,
104 inputModalities: ['text'] as readonly ['text'],
105 messageMetadataByModality: {
106 text: undefined as unknown,
107 image: undefined as unknown,
108 audio: undefined as unknown,
109 video: undefined as unknown,
110 document: undefined as unknown,
111 },
112 toolCapabilities: [] as ReadonlyArray<string>,
113 toolCallMetadata: undefined as unknown,
114 systemPromptMetadata: undefined as never,
115 },
116 chatStream: (options) => {
117 seen.push(options.messages)
118 const turn = turns[call] ?? textTurn('')
119 call += 1
120 if (typeof turn === 'function') {
121 return turn(
122 options.abortController?.signal ??
123 options.request?.signal ??
124 undefined,
125 )
126 }
127 return (async function* () {
128 yield* turn
129 })()
130 },
131 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
132 }
133 return { adapter, seen }
134}
135
136/** An stdout or stderr that keeps what is written. */
137export function capture() {
138 let text = ''
139 return {
140 write: (chunk: string) => (text += chunk),
141 get text() {
142 return text
143 },
144 }
145}
146
147/** `stream` as the stdin of runCli, as a terminal or as a pipe. */
148export function asStdin(stream: Readable, { isTTY }: { isTTY: boolean }) {
149 // NodeJS.ReadStream is a TTY socket. A test cannot make one without a real
150 // terminal, and runCli only reads the lines and `isTTY`, so this casts.
151 return Object.assign(stream, { isTTY }) as unknown as NodeJS.ReadStream
152}
153
154/** A stdin that reads `lines`, as a terminal or as a pipe. */
155export function stdinFrom(lines: Array<string>, options: { isTTY: boolean }) {
156 return asStdin(Readable.from(lines), options)
157}