Open History to see the last commit
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)
70`
71}
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
105}
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
113}
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('')
120}
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 threadId: 'thread-1',
190 model: 'pi-fast',
191 messages: [{ role: 'user', content: 'say pong' }],
192 logger: noopLogger,
193 capabilities: capabilityContextWith(sbx),
194 }),
195 )
196
197 expect((chunks[0] as { type: string }).type).toBe('RUN_STARTED')
198 expect(textOf(chunks)).toContain('pong')
199 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
200
201 // The session id is surfaced as a `<name>.session-id` CUSTOM event.
202 const sessionEvent = chunks.find(
203 (c) =>
204 c.type === 'CUSTOM' &&
205 (c as { name?: string }).name === 'pi.session-id',
206 )
207 expect((sessionEvent as { value?: { sessionId?: string } }).value).toEqual({
208 sessionId: 'sess-1',
209 })
210
211 await sbx.destroy()
212 })
213
214 it('still auto-generates a runId when none is supplied (non-durable, unchanged behavior)', async () => {
215 // This adapter does not journal, so `resolveDurableRunId` is routed
216 // through with `durable: false` (see `packages/ai-sandbox/src/durability.ts`
217 // and the Phase 3 plan's Task 5) purely so it inherits the enforcement
218 // once journaling lands, not to change today's behavior. Assert the
219 // fallback still fires: a generated, non-empty `runId` on `RUN_STARTED`.
220 const sbx = await provider.create({})
221 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
222
223 const chunks = await collect(
224 acpCompatibleText('pi-fast', {
225 name: 'pi',
226 command: () => 'node fake-acp-agent.mjs',
227 }).chatStream({
228 threadId: 'thread-1',
229 model: 'pi-fast',
230 messages: [{ role: 'user', content: 'say pong' }],
231 logger: noopLogger,
232 capabilities: capabilityContextWith(sbx),
233 }),
234 )
235
236 const runStarted = chunks[0] as { type: string; runId?: string }
237 expect(runStarted.type).toBe('RUN_STARTED')
238 expect(typeof runStarted.runId).toBe('string')
239 expect(runStarted.runId?.length).toBeGreaterThan(0)
240
241 await sbx.destroy()
242 })
243
244 it('passes a caller-supplied runId through unchanged', async () => {
245 const sbx = await provider.create({})
246 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
247
248 const chunks = await collect(
249 acpCompatibleText('pi-fast', {
250 name: 'pi',
251 command: () => 'node fake-acp-agent.mjs',
252 }).chatStream({
253 threadId: 'thread-1',
254 model: 'pi-fast',
255 runId: 'caller-supplied-run-id',
256 messages: [{ role: 'user', content: 'say pong' }],
257 logger: noopLogger,
258 capabilities: capabilityContextWith(sbx),
259 }),
260 )
261
262 const runStarted = chunks[0] as { type: string; runId?: string }
263 expect(runStarted.type).toBe('RUN_STARTED')
264 expect(runStarted.runId).toBe('caller-supplied-run-id')
265
266 await sbx.destroy()
267 })
268
269 it('resumes a session and sends only the trailing user message', async () => {
270 const sbx = await provider.create({})
271 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
272
273 await collect(
274 acpCompatibleText('pi-fast', {
275 name: 'pi',
276 command: () => 'node fake-acp-agent.mjs',
277 }).chatStream({
278 threadId: 'thread-1',
279 model: 'pi-fast',
280 messages: [
281 { role: 'user', content: 'first question' },
282 { role: 'assistant', content: 'first answer' },
283 { role: 'user', content: 'follow up' },
284 ],
285 logger: noopLogger,
286 capabilities: capabilityContextWith(sbx),
287 modelOptions: { sessionId: 'sess-1' },
288 }),
289 )
290
291 const recorded = JSON.parse(
292 await sbx.fs.read('/workspace/acp-prompt.txt'),
293 ) as { prompt: Array<{ text: string }> }
294 const sentText = recorded.prompt.map((part) => part.text).join('')
295 expect(sentText).toBe('follow up')
296 expect(sentText).not.toContain('Previous conversation')
297
298 await sbx.destroy()
299 })
300
301 it('passes declared models and custom modelOptions through to the command', async () => {
302 const sbx = await provider.create({})
303 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
304
305 const pi = acpCompatible({
306 name: 'pi',
307 models: ['pi-fast', 'pi-pro'],
308 modelOptions: {} as { reasoningEffort?: 'low' | 'high' },
309 command: ({ model, modelOptions }) =>
310 `node fake-acp-agent.mjs --model ${model}` +
311 (modelOptions?.reasoningEffort
312 ? ` --effort ${modelOptions.reasoningEffort}`
313 : ''),
314 })
315
316 await collect(
317 pi('pi-pro').chatStream({
318 threadId: 'thread-1',
319 model: 'pi-pro',
320 messages: [{ role: 'user', content: 'hi' }],
321 logger: noopLogger,
322 capabilities: capabilityContextWith(sbx),
323 modelOptions: { reasoningEffort: 'high' },
324 }),
325 )
326
327 const argv = await sbx.fs.read('/workspace/acp-argv.txt')
328 expect(argv).toContain('--model pi-pro')
329 expect(argv).toContain('--effort high')
330
331 await sbx.destroy()
332 })
333
334 it('sends clientInfo in the initialize handshake', async () => {
335 const sbx = await provider.create({})
336 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
337
338 await collect(
339 acpCompatibleText('pi-fast', {
340 name: 'pi',
341 command: () => 'node fake-acp-agent.mjs',
342 }).chatStream({
343 threadId: 'thread-1',
344 model: 'pi-fast',
345 messages: [{ role: 'user', content: 'hi' }],
346 logger: noopLogger,
347 capabilities: capabilityContextWith(sbx),
348 }),
349 )
350
351 const init = JSON.parse(await sbx.fs.read('/workspace/acp-init.txt')) as {
352 clientInfo?: { name?: string; version?: string }
353 protocolVersion?: number
354 }
355 expect(init.clientInfo).toMatchObject({ name: '@tanstack/ai-acp' })
356 expect(typeof init.clientInfo?.version).toBe('string')
357 expect(typeof init.protocolVersion).toBe('number')
358
359 await sbx.destroy()
360 })
361
362 it('errors when the agent negotiates an unsupported protocol version', async () => {
363 const sbx = await provider.create({})
364 await sbx.fs.write(
365 '/workspace/fake-acp-agent.mjs',
366 fakeAcpAgent('PROTOCOL_VERSION + 1'),
367 )
368
369 const chunks = await collect(
370 acpCompatibleText('pi-fast', {
371 name: 'pi',
372 command: () => 'node fake-acp-agent.mjs',
373 }).chatStream({
374 threadId: 'thread-1',
375 model: 'pi-fast',
376 messages: [{ role: 'user', content: 'hi' }],
377 logger: noopLogger,
378 capabilities: capabilityContextWith(sbx),
379 }),
380 )
381
382 const error = chunks.find((c) => c.type === 'RUN_ERROR') as {
383 message?: string
384 }
385 expect(error).toBeDefined()
386 expect(error.message).toMatch(/protocol version/i)
387
388 await sbx.destroy()
389 })
390
391 it('parses the last assistant text as structured output', async () => {
392 const sbx = await provider.create({})
393 await sbx.fs.write(
394 '/workspace/fake-acp-agent.mjs',
395 fakeAcpAgent('PROTOCOL_VERSION', '{"ok":true}'),
396 )
397
398 const chunks = await collect(
399 acpCompatibleText('pi-fast', {
400 name: 'pi',
401 command: () => 'node fake-acp-agent.mjs',
402 }).chatStream({
403 threadId: 'thread-1',
404 model: 'pi-fast',
405 messages: [{ role: 'user', content: 'report' }],
406 outputSchema: {
407 type: 'object',
408 properties: { ok: { type: 'boolean' } },
409 required: ['ok'],
410 },
411 logger: noopLogger,
412 capabilities: capabilityContextWith(sbx),
413 }),
414 )
415
416 const completeIndex = chunks.findIndex(
417 (chunk) =>
418 chunk.type === 'CUSTOM' &&
419 (chunk as { name?: string }).name === 'structured-output.complete',
420 )
421 const finishedIndex = chunks.findIndex(
422 (chunk) => chunk.type === 'RUN_FINISHED',
423 )
424 const complete = chunks[completeIndex] as
425 | { value?: { object?: unknown } }
426 | undefined
427 expect(complete?.value?.object).toEqual({ ok: true })
428 expect(completeIndex).toBeGreaterThan(-1)
429 expect(finishedIndex).toBeGreaterThan(completeIndex)
430
431 const prompt = JSON.parse(
432 await sbx.fs.read('/workspace/acp-prompt.txt'),
433 ) as { prompt?: Array<{ text?: string }> }
434 const promptText = prompt.prompt?.map((part) => part.text ?? '').join('')
435 expect(promptText).toMatch(/JSON object/i)
436
437 await sbx.destroy()
438 })
439
440 it('emits a parse error when the last assistant text is not JSON', async () => {
441 const sbx = await provider.create({})
442 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
443
444 const chunks = await collect(
445 acpCompatibleText('pi-fast', {
446 name: 'pi',
447 command: () => 'node fake-acp-agent.mjs',
448 }).chatStream({
449 threadId: 'thread-1',
450 model: 'pi-fast',
451 messages: [{ role: 'user', content: 'report' }],
452 outputSchema: {
453 type: 'object',
454 properties: { ok: { type: 'boolean' } },
455 required: ['ok'],
456 },
457 logger: noopLogger,
458 capabilities: capabilityContextWith(sbx),
459 }),
460 )
461
462 const error = chunks.find((chunk) => chunk.type === 'RUN_ERROR') as {
463 code?: string
464 message?: string
465 }
466 expect(error?.code).toBe('structured-output-parse-failed')
467 expect(error?.message).toMatch(/pong/)
468
469 await sbx.destroy()
470 })
471})