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

compatible.test.ts

462 lines14.8 KB

1/**
2 * End-to-end tests for the generic `acpCompatible` harness adapter.
3 *
4 * A fake ACP agent (the real `@agentclientprotocol/sdk` agent side, imported by
5 * absolute path so it resolves from the sandbox's temp cwd) is spawned inside a
6 * real local-process sandbox over stdio, exercising the full path: spawn → ACP
7 * `initialize`/`newSession`/`prompt` → `session/update` → AG-UI translation.
8 */
9import { afterAll, describe, expect, it } from 'vitest'
10import * as fsp from 'node:fs/promises'
11import * as os from 'node:os'
12import * as path from 'node:path'
13import { createRequire } from 'node:module'
14import { pathToFileURL } from 'node:url'
15import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
16import { SandboxCapability } from '@tanstack/ai-sandbox'
17import { acpCompatible, acpCompatibleText, buildAcpPrompt } from '../src/index'
18import type { InternalLogger } from '@tanstack/ai/adapter-internals'
19import type {
20 AdapterYieldChunk,
21 CapabilityContext,
22 ModelMessage,
23} from '@tanstack/ai'
24import type { SandboxHandle } from '@tanstack/ai-sandbox'
25​
26const require = createRequire(import.meta.url)
27const SDK_URL = pathToFileURL(require.resolve('@agentclientprotocol/sdk')).href
28​
29/**
30 * A minimal ACP agent that replies "pong", records the `initialize` and `prompt`
31 * params it received, and reports the given protocol version (defaults to the
32 * SDK's `PROTOCOL_VERSION`).
33 */
34function fakeAcpAgent(
35 protocolVersionExpr = 'PROTOCOL_VERSION',
36 reply = 'pong',
37): string {
38 return `
39import { AgentSideConnection, ndJsonStream, PROTOCOL_VERSION } from ${JSON.stringify(SDK_URL)}
40import { Readable, Writable } from 'node:stream'
41import { writeFileSync } from 'node:fs'
42​
43writeFileSync('acp-argv.txt', process.argv.join(' '))
44​
45const input = Readable.toWeb(process.stdin)
46const output = Writable.toWeb(process.stdout)
47const stream = ndJsonStream(output, input)
48​
49new AgentSideConnection((conn) => ({
50 async initialize(params) {
51 writeFileSync('acp-init.txt', JSON.stringify(params))
52 return { protocolVersion: ${protocolVersionExpr}, agentCapabilities: { loadSession: true }, authMethods: [] }
53 },
54 async newSession() {
55 return { sessionId: 'sess-1' }
56 },
57 async loadSession() {
58 return {}
59 },
60 async prompt(params) {
61 writeFileSync('acp-prompt.txt', JSON.stringify(params))
62 await conn.sessionUpdate({
63 sessionId: params.sessionId,
64 update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: ${JSON.stringify(reply)} } },
65 })
66 return { stopReason: 'end_turn' }
67 },
68 async cancel() {},
69}), stream)
72​
73const FAKE_ACP_AGENT = fakeAcpAgent()
74​
75const baseDir = path.join(os.tmpdir(), `tanstack-ai-acp-test-${Date.now()}`)
76// No removeOnDestroy: destroying a sandbox right after killing its agent races
77// the OS releasing the dir (EBUSY on Windows). Clean the tree once at the end.
78const provider = localProcessSandbox({ baseDir })
79​
80afterAll(async () => {
81 await fsp.rm(baseDir, {
82 recursive: true,
83 force: true,
84 maxRetries: 10,
85 retryDelay: 100,
86 })
87})
88​
89const noopLogger = {
90 request: () => {},
91 provider: () => {},
92 errors: () => {},
93 agentLoop: () => {},
94 warnings: () => {},
95 debug: () => {},
96} as unknown as InternalLogger
97​
98function capabilityContextWith(handle: SandboxHandle): CapabilityContext {
99 const [, provideSandbox] = SandboxCapability
100 const ctx = {
101 capabilities: { markProvided: () => {}, has: () => true },
102 } as unknown as CapabilityContext
103 provideSandbox(ctx, handle)
104 return ctx
106​
107async function collect(
108 stream: AsyncIterable<AdapterYieldChunk>,
109): Promise<Array<AdapterYieldChunk>> {
110 const out: Array<AdapterYieldChunk> = []
111 for await (const chunk of stream) out.push(chunk)
112 return out
114​
115function textOf(chunks: Array<AdapterYieldChunk>): string {
116 return chunks
117 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
118 .map((c) => (c as { delta?: string }).delta ?? '')
119 .join('')
121​
122describe('buildAcpPrompt', () => {
123 const msgs = (
124 ...parts: Array<[ModelMessage['role'], string]>
125 ): Array<ModelMessage> =>
126 parts.map(([role, content]) => ({ role, content }) as ModelMessage)
127​
128 it('returns only the trailing user message when resuming a session', () => {
129 const built = buildAcpPrompt(
130 msgs(['user', 'first'], ['assistant', 'a'], ['user', 'second']),
131 'sess-1',
132 )
133 expect(built).toEqual({ prompt: 'second', resume: 'sess-1' })
134 })
135​
136 it('flattens prior turns into a transcript preamble for a fresh session', () => {
137 const built = buildAcpPrompt(
138 msgs(['user', 'first'], ['assistant', 'reply'], ['user', 'second']),
139 undefined,
140 )
141 expect(built.resume).toBeUndefined()
142 expect(built.prompt).toBe(
143 'Previous conversation:\nUser: first\nAssistant: reply\n\nsecond',
144 )
145 })
146​
147 it('sends just the message when there is no prior context', () => {
148 expect(buildAcpPrompt(msgs(['user', 'only']), undefined)).toEqual({
149 prompt: 'only',
150 })
151 })
152​
153 it('throws (with the harness name) when the trailing message is not user text', () => {
154 expect(() =>
155 buildAcpPrompt(msgs(['assistant', 'hi']), undefined, 'pi'),
156 ).toThrow(/pi adapter requires a trailing user message/)
157 })
158})
159​
160describe('acpCompatible config validation', () => {
161 it('throws when neither command nor openTransport is provided', () => {
162 expect(() => acpCompatibleText('m', { name: 'pi' })).toThrow(
163 /needs either a "command" or an "openTransport"/,
164 )
165 })
166​
167 it('opts into combined event-source structured output', () => {
168 const adapter = acpCompatibleText('pi-fast', {
169 name: 'pi',
170 command: () => 'node fake-acp-agent.mjs',
171 })
172 expect(adapter.supportsCombinedToolsAndSchema()).toBe(true)
173 expect(adapter.combinedStructuredOutputSource()).toBe('event')
174 })
175})
176​
177describe('acpCompatible in-sandbox adapter (stdio)', () => {
178 it('spawns the harness over stdio and streams translated ACP events', async () => {
179 const sbx = await provider.create({})
180 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
181​
182 const pi = acpCompatible({
183 name: 'pi',
184 command: () => 'node fake-acp-agent.mjs',
185 })
186​
187 const chunks = await collect(
188 pi('pi-fast').chatStream({
189 model: 'pi-fast',
190 messages: [{ role: 'user', content: 'say pong' }],
191 logger: noopLogger,
192 capabilities: capabilityContextWith(sbx),
193 }),
194 )
195​
196 expect((chunks[0] as { type: string }).type).toBe('RUN_STARTED')
197 expect(textOf(chunks)).toContain('pong')
198 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
199​
200 // The session id is surfaced as a `<name>.session-id` CUSTOM event.
201 const sessionEvent = chunks.find(
202 (c) =>
203 c.type === 'CUSTOM' &&
204 (c as { name?: string }).name === 'pi.session-id',
205 )
206 expect((sessionEvent as { value?: { sessionId?: string } }).value).toEqual({
207 sessionId: 'sess-1',
208 })
209​
210 await sbx.destroy()
211 })
212​
213 it('still auto-generates a runId when none is supplied (non-durable, unchanged behavior)', async () => {
214 // This adapter does not journal, so `resolveDurableRunId` is routed
215 // through with `durable: false` (see `packages/ai-sandbox/src/durability.ts`
216 // and the Phase 3 plan's Task 5) purely so it inherits the enforcement
217 // once journaling lands, not to change today's behavior. Assert the
218 // fallback still fires: a generated, non-empty `runId` on `RUN_STARTED`.
219 const sbx = await provider.create({})
220 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
221​
222 const chunks = await collect(
223 acpCompatibleText('pi-fast', {
224 name: 'pi',
225 command: () => 'node fake-acp-agent.mjs',
226 }).chatStream({
227 model: 'pi-fast',
228 messages: [{ role: 'user', content: 'say pong' }],
229 logger: noopLogger,
230 capabilities: capabilityContextWith(sbx),
231 }),
232 )
233​
234 const runStarted = chunks[0] as { type: string; runId?: string }
235 expect(runStarted.type).toBe('RUN_STARTED')
236 expect(typeof runStarted.runId).toBe('string')
237 expect(runStarted.runId?.length).toBeGreaterThan(0)
238​
239 await sbx.destroy()
240 })
241​
242 it('passes a caller-supplied runId through unchanged', async () => {
243 const sbx = await provider.create({})
244 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
245​
246 const chunks = await collect(
247 acpCompatibleText('pi-fast', {
248 name: 'pi',
249 command: () => 'node fake-acp-agent.mjs',
250 }).chatStream({
251 model: 'pi-fast',
252 runId: 'caller-supplied-run-id',
253 messages: [{ role: 'user', content: 'say pong' }],
254 logger: noopLogger,
255 capabilities: capabilityContextWith(sbx),
256 }),
257 )
258​
259 const runStarted = chunks[0] as { type: string; runId?: string }
260 expect(runStarted.type).toBe('RUN_STARTED')
261 expect(runStarted.runId).toBe('caller-supplied-run-id')
262​
263 await sbx.destroy()
264 })
265​
266 it('resumes a session and sends only the trailing user message', async () => {
267 const sbx = await provider.create({})
268 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
269​
270 await collect(
271 acpCompatibleText('pi-fast', {
272 name: 'pi',
273 command: () => 'node fake-acp-agent.mjs',
274 }).chatStream({
275 model: 'pi-fast',
276 messages: [
277 { role: 'user', content: 'first question' },
278 { role: 'assistant', content: 'first answer' },
279 { role: 'user', content: 'follow up' },
280 ],
281 logger: noopLogger,
282 capabilities: capabilityContextWith(sbx),
283 modelOptions: { sessionId: 'sess-1' },
284 }),
285 )
286​
287 const recorded = JSON.parse(
288 await sbx.fs.read('/workspace/acp-prompt.txt'),
289 ) as { prompt: Array<{ text: string }> }
290 const sentText = recorded.prompt.map((part) => part.text).join('')
291 expect(sentText).toBe('follow up')
292 expect(sentText).not.toContain('Previous conversation')
293​
294 await sbx.destroy()
295 })
296​
297 it('passes declared models and custom modelOptions through to the command', async () => {
298 const sbx = await provider.create({})
299 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
300​
301 const pi = acpCompatible({
302 name: 'pi',
303 models: ['pi-fast', 'pi-pro'],
304 modelOptions: {} as { reasoningEffort?: 'low' | 'high' },
305 command: ({ model, modelOptions }) =>
306 `node fake-acp-agent.mjs --model ${model}` +
307 (modelOptions?.reasoningEffort
308 ? ` --effort ${modelOptions.reasoningEffort}`
309 : ''),
310 })
311​
312 await collect(
313 pi('pi-pro').chatStream({
314 model: 'pi-pro',
315 messages: [{ role: 'user', content: 'hi' }],
316 logger: noopLogger,
317 capabilities: capabilityContextWith(sbx),
318 modelOptions: { reasoningEffort: 'high' },
319 }),
320 )
321​
322 const argv = await sbx.fs.read('/workspace/acp-argv.txt')
323 expect(argv).toContain('--model pi-pro')
324 expect(argv).toContain('--effort high')
325​
326 await sbx.destroy()
327 })
328​
329 it('sends clientInfo in the initialize handshake', async () => {
330 const sbx = await provider.create({})
331 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
332​
333 await collect(
334 acpCompatibleText('pi-fast', {
335 name: 'pi',
336 command: () => 'node fake-acp-agent.mjs',
337 }).chatStream({
338 model: 'pi-fast',
339 messages: [{ role: 'user', content: 'hi' }],
340 logger: noopLogger,
341 capabilities: capabilityContextWith(sbx),
342 }),
343 )
344​
345 const init = JSON.parse(await sbx.fs.read('/workspace/acp-init.txt')) as {
346 clientInfo?: { name?: string; version?: string }
347 protocolVersion?: number
348 }
349 expect(init.clientInfo).toMatchObject({ name: '@tanstack/ai-acp' })
350 expect(typeof init.clientInfo?.version).toBe('string')
351 expect(typeof init.protocolVersion).toBe('number')
352​
353 await sbx.destroy()
354 })
355​
356 it('errors when the agent negotiates an unsupported protocol version', async () => {
357 const sbx = await provider.create({})
358 await sbx.fs.write(
359 '/workspace/fake-acp-agent.mjs',
360 fakeAcpAgent('PROTOCOL_VERSION + 1'),
361 )
362​
363 const chunks = await collect(
364 acpCompatibleText('pi-fast', {
365 name: 'pi',
366 command: () => 'node fake-acp-agent.mjs',
367 }).chatStream({
368 model: 'pi-fast',
369 messages: [{ role: 'user', content: 'hi' }],
370 logger: noopLogger,
371 capabilities: capabilityContextWith(sbx),
372 }),
373 )
374​
375 const error = chunks.find((c) => c.type === 'RUN_ERROR') as {
376 message?: string
377 }
378 expect(error).toBeDefined()
379 expect(error.message).toMatch(/protocol version/i)
380​
381 await sbx.destroy()
382 })
383​
384 it('parses the last assistant text as structured output', async () => {
385 const sbx = await provider.create({})
386 await sbx.fs.write(
387 '/workspace/fake-acp-agent.mjs',
388 fakeAcpAgent('PROTOCOL_VERSION', '{"ok":true}'),
389 )
390​
391 const chunks = await collect(
392 acpCompatibleText('pi-fast', {
393 name: 'pi',
394 command: () => 'node fake-acp-agent.mjs',
395 }).chatStream({
396 model: 'pi-fast',
397 messages: [{ role: 'user', content: 'report' }],
398 outputSchema: {
399 type: 'object',
400 properties: { ok: { type: 'boolean' } },
401 required: ['ok'],
402 },
403 logger: noopLogger,
404 capabilities: capabilityContextWith(sbx),
405 }),
406 )
407​
408 const completeIndex = chunks.findIndex(
409 (chunk) =>
410 chunk.type === 'CUSTOM' &&
411 (chunk as { name?: string }).name === 'structured-output.complete',
412 )
413 const finishedIndex = chunks.findIndex(
414 (chunk) => chunk.type === 'RUN_FINISHED',
415 )
416 const complete = chunks[completeIndex] as
417 | { value?: { object?: unknown } }
418 | undefined
419 expect(complete?.value?.object).toEqual({ ok: true })
420 expect(completeIndex).toBeGreaterThan(-1)
421 expect(finishedIndex).toBeGreaterThan(completeIndex)
422​
423 const prompt = JSON.parse(
424 await sbx.fs.read('/workspace/acp-prompt.txt'),
425 ) as { prompt?: Array<{ text?: string }> }
426 const promptText = prompt.prompt?.map((part) => part.text ?? '').join('')
427 expect(promptText).toMatch(/JSON object/i)
428​
429 await sbx.destroy()
430 })
431​
432 it('emits a parse error when the last assistant text is not JSON', async () => {
433 const sbx = await provider.create({})
434 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
435​
436 const chunks = await collect(
437 acpCompatibleText('pi-fast', {
438 name: 'pi',
439 command: () => 'node fake-acp-agent.mjs',
440 }).chatStream({
441 model: 'pi-fast',
442 messages: [{ role: 'user', content: 'report' }],
443 outputSchema: {
444 type: 'object',
445 properties: { ok: { type: 'boolean' } },
446 required: ['ok'],
447 },
448 logger: noopLogger,
449 capabilities: capabilityContextWith(sbx),
450 }),
451 )
452​
453 const error = chunks.find((chunk) => chunk.type === 'RUN_ERROR') as {
454 code?: string
455 message?: string
456 }
457 expect(error?.code).toBe('structured-output-parse-failed')
458 expect(error?.message).toMatch(/pong/)
459​
460 await sbx.destroy()
461 })
462})