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

commands.test.ts

248 lines8.3 KB

1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { EventType, defineAgent } from '@tanstack/ai'
4import {
5 configOption,
6 createHarnessHost,
7 defineCommand,
8 defineHarness,
9 definePlugin,
10} from '@tanstack/ai-harness'
11import { memoryPersistence } from '@tanstack/ai-persistence'
12import { HELP_TEXT, handleLine, parseAnswer } from '../src/commands'
13import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
14​
15/** A model that answers `echo: <text>`, or waits for cancel on "wait". */
16function model(): AnyTextAdapter {
17 return {
18 kind: 'text',
19 name: 'mock',
20 model: 'test-model',
21 // `~types` holds types only. Its values are never read, so they are casts.
22 '~types': {
23 providerOptions: {} as Record<string, unknown>,
24 inputModalities: ['text'] as readonly ['text'],
25 messageMetadataByModality: {
26 text: undefined as unknown,
27 image: undefined as unknown,
28 audio: undefined as unknown,
29 video: undefined as unknown,
30 document: undefined as unknown,
31 },
32 toolCapabilities: [] as ReadonlyArray<string>,
33 toolCallMetadata: undefined as unknown,
34 systemPromptMetadata: undefined as never,
35 },
36 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
37 chatStream: (options) =>
38 (async function* (): AsyncGenerator<StreamChunk> {
39 const said = String(options.messages.at(-1)?.content ?? '')
40 const now = Date.now()
41 yield {
42 type: EventType.RUN_STARTED,
43 runId: 'r',
44 threadId: 't',
45 timestamp: now,
46 }
47 if (said === 'wait') {
48 const signal =
49 options.abortController?.signal ?? options.request?.signal
50 await new Promise<void>((resolve) => {
51 if (!signal || signal.aborted) return resolve()
52 signal.addEventListener('abort', () => resolve(), { once: true })
53 })
54 return
55 }
56 yield {
57 type: EventType.TEXT_MESSAGE_START,
58 messageId: 'm',
59 role: 'assistant',
60 timestamp: now,
61 }
62 yield {
63 type: EventType.TEXT_MESSAGE_CONTENT,
64 messageId: 'm',
65 delta: `echo: ${said}`,
66 timestamp: now,
67 }
68 yield {
69 type: EventType.TEXT_MESSAGE_END,
70 messageId: 'm',
71 timestamp: now,
72 }
73 yield {
74 type: EventType.RUN_FINISHED,
75 runId: 'r',
76 threadId: 't',
77 timestamp: now,
78 metadata: { tanstack: { finishReason: 'stop' } },
79 }
80 })(),
81 }
83​
84const tools = definePlugin({
85 name: 'test/tools',
86 setup: () => ({
87 config: {
88 level: configOption.select({ options: ['low', 'high'], default: 'low' }),
89 },
90 commands: {
91 quiet: defineCommand({
92 description: 'Returns nothing',
93 run: () => undefined,
94 }),
95 stats: defineCommand({
96 description: 'Returns an object',
97 run: () => ({ ok: true }),
98 }),
99 broken: defineCommand({
100 description: 'Throws',
101 run: () => {
102 throw new Error('it broke')
103 },
104 }),
105 echo: defineCommand({
106 description: 'Echoes',
107 run: (input: unknown) => input,
108 }),
109 confirm: defineCommand({
110 description: 'Asks a yes or no question',
111 run: async (_input, { step }) => {
112 const answer = await step.ask({
113 name: 'sure',
114 message: 'Sure?',
115 schema: z.boolean(),
116 })
117 return answer ? 'confirmed' : 'declined'
118 },
119 }),
120 'connect:svc': defineCommand({
121 description: 'Sign in',
122 run: () => 'Connected to Svc.',
123 }),
124 'disconnect:svc': defineCommand({
125 description: 'Sign out',
126 run: () => {
127 throw new Error('not signed in')
128 },
129 }),
130 },
131 }),
132})
133​
134const counter = defineAgent({
135 name: 'counter',
136 description: 'Counts letters',
137 inputSchema: z.object({ word: z.string() }),
138 run: async (ctx) => ctx.input.word.length,
139})
140​
141async function open(plugins = true) {
142 const host = createHarnessHost({ persistence: memoryPersistence() })
143 const session = await host.open(
144 defineHarness({
145 name: 'test/cli-commands',
146 adapter: model(),
147 ...(plugins ? { agents: [counter], plugins: () => [tools] } : {}),
148 }),
149 {
150 threadId: 't',
151 },
152 )
153 const say = async (line: string) => {
154 const result = await handleLine(session, line)
155 return result.type === 'notice' ? result.text : result.type
156 }
157 return { host, session, say }
159​
160describe('handleLine', () => {
161 it('answers built-in commands for a bare harness', async () => {
162 const { host, say } = await open(false)
163 expect(await say(' ')).toBe('')
164 expect(await say('/help')).toBe(HELP_TEXT)
165 expect(await say('/config')).toBe('This harness has no settings.')
166 expect(await say('/agents')).toBe('This harness has no agents.')
167 expect(await say('/cancel')).toBe('Nothing is running.')
168 expect(await say('/status')).toBe(
169 'Status: idle. Running: nothing. Queued turns: 0.',
170 )
171 expect(await say('/nope')).toBe('Unknown command: /nope. Type /help.')
172 expect(await say('/exit')).toBe('exit')
173 expect(await say('/quit')).toBe('exit')
174 await host.close()
175 })
176​
177 it('lists plugin commands, settings, and agents, and changes settings', async () => {
178 const { host, say } = await open()
179 expect(await say('/help')).toContain('Plugin commands:\n')
180 expect(await say('/help')).toContain('/quiet Returns nothing')
181 expect(await say('/config')).toBe(' level = "low"')
182 expect(await say('/config level high')).toBe('level changed.')
183 expect(await say('/config level extreme')).toMatch(/^Not changed: /)
184 expect(await say('/agents')).toBe(' counter: Counts letters')
185 await host.close()
186 })
187​
188 it('runs plugin commands and shows their results or errors', async () => {
189 const { host, say } = await open()
190 expect(await say('/quiet')).toBe('Done.')
191 expect(await say('/stats')).toBe('{\n "ok": true\n}')
192 expect(await say('/broken')).toBe('/broken failed: it broke')
193 expect(await say('/echo {"a":1}')).toBe('{\n "a": 1\n}')
194 expect(await say('/echo plain words')).toBe('plain words')
195 expect(await say('/connect svc')).toBe('Connected to Svc.')
196 expect(await say('/disconnect svc')).toBe(
197 '/disconnect:svc failed: not signed in',
198 )
199 await host.close()
200 })
201​
202 it('starts agents in the background and checks their input', async () => {
203 const { host, say } = await open()
204 expect(await say('/agent')).toBe('Unknown agent: (none)')
205 expect(await say('/agent ghost')).toBe('Unknown agent: ghost')
206 expect(await say('/agent counter {bad')).toContain('must be JSON')
207 expect(await say('/agent counter {"word":"four"}')).toBe(
208 'Started counter in the background.',
209 )
210 await host.close()
211 })
212​
213 it('answers questions, including a rejected answer, then shows the result later', async () => {
214 const { host, session } = await open()
215 const asked = await handleLine(session, '/confirm')
216 expect(asked).toMatchObject({ type: 'notice', text: '' })
217 const later = asked.type === 'notice' ? asked.later : undefined
218 expect(later).toBeDefined()
219 expect(session.snapshot().pendingWaits).toHaveLength(1)
220 expect(await handleLine(session, 'maybe')).toMatchObject({
221 text: expect.stringMatching(/^Answer again: /),
222 })
223 expect(await handleLine(session, 'y')).toMatchObject({ text: '' })
224 expect(await later).toBe('confirmed')
225 await host.close()
226 })
227​
228 it('prompts when idle, steers while running, and cancels', async () => {
229 const { host, session, say } = await open()
230 expect(await say('wait')).toBe('sent')
231 await vi.waitFor(() => expect(session.snapshot().status).toBe('running'))
232 expect(await say('/status')).toMatch(/^Status: running\. Running: chat/)
233 expect(await say('go faster')).toBe('sent')
234 expect(await say('/cancel')).toBe('Cancelled.')
235 await host.close()
236 })
237})
238​
239describe('parseAnswer', () => {
240 it('reads yes and no for boolean questions, JSON, and plain text', () => {
241 const boolean = { type: 'boolean' }
242 expect(parseAnswer('Yes', boolean)).toBe(true)
243 expect(parseAnswer(' n ', boolean)).toBe(false)
244 expect(parseAnswer('yes', { type: 'string' })).toBe('yes')
245 expect(parseAnswer('{"n":2}', undefined)).toEqual({ n: 2 })
246 expect(parseAnswer('', undefined)).toBeUndefined()
247 })
248})