@acryldev/driver-acp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ // The ACP client against the official ACP v1 JSON schema (vendored in `acp-v1/`, see `../provenance.json`): every message the client sends, and every
2
+ // message the test agent sends it, is checked twice, as a whole JSON-RPC message (the schema's `Client` and `Agent` unions) and by its method's own definition
3
+ // (`InitializeRequest`, `SessionNotification`, ...). The client is written from that schema rather than ported from an SDK, so a drift shows up here.
4
+ import assert from 'node:assert/strict'
5
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { test } from 'node:test'
9
+ import { type ChatDriver, createDrivers } from '@acryldev/drivers'
10
+ import { instance, pinnedInstance } from '@acryldev/instance'
11
+ import { Context } from '@deepseek-ai/cordis'
12
+ import { Ajv2020 } from 'ajv/dist/2020.js'
13
+ import * as driverAcp from '../index.ts'
14
+
15
+ const int = (min: number, max: number) => ({
16
+ type: 'number' as const,
17
+ validate: (n: number) => Number.isInteger(n) && n >= min && n <= max,
18
+ })
19
+ const ajv = new Ajv2020({
20
+ strict: false,
21
+ allErrors: true,
22
+ formats: {
23
+ uint16: int(0, 65_535),
24
+ uint32: int(0, 2 ** 32 - 1),
25
+ int32: int(-(2 ** 31), 2 ** 31 - 1),
26
+ uint64: int(0, Number.MAX_SAFE_INTEGER),
27
+ int64: int(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
28
+ double: { type: 'number', validate: (n: number) => Number.isFinite(n) },
29
+ uri: { type: 'string', validate: (s: string) => URL.canParse(s) },
30
+ },
31
+ })
32
+ ajv.addSchema(
33
+ JSON.parse(readFileSync(join(import.meta.dirname, 'acp-v1', 'schema.json'), 'utf8')),
34
+ 'acp',
35
+ )
36
+
37
+ function validator(ref: string) {
38
+ const validate = ajv.getSchema(`acp#${ref}`)
39
+ if (!validate) throw new Error(`the ACP schema has no ${ref}`)
40
+ return validate
41
+ }
42
+ /** The whole message, by who sends it: the schema's top-level `Agent` and `Client` unions. */
43
+ const envelope = { toAgent: validator('/anyOf/1'), toClient: validator('/anyOf/0') }
44
+
45
+ /** The definition each message is checked against, by direction and method; a response is found by the method of the request it answers. */
46
+ const DEFINITIONS = {
47
+ toAgent: {
48
+ request: {
49
+ initialize: 'InitializeRequest',
50
+ 'session/new': 'NewSessionRequest',
51
+ 'session/prompt': 'PromptRequest',
52
+ },
53
+ notification: { 'session/cancel': 'CancelNotification' },
54
+ response: { 'session/request_permission': 'RequestPermissionResponse' },
55
+ },
56
+ toClient: {
57
+ request: { 'session/request_permission': 'RequestPermissionRequest' },
58
+ notification: { 'session/update': 'SessionNotification' },
59
+ response: {
60
+ initialize: 'InitializeResponse',
61
+ 'session/new': 'NewSessionResponse',
62
+ 'session/prompt': 'PromptResponse',
63
+ },
64
+ },
65
+ } as const
66
+
67
+ type Direction = keyof typeof DEFINITIONS
68
+ interface WireMessage {
69
+ id?: number | string
70
+ method?: string
71
+ params?: unknown
72
+ result?: unknown
73
+ error?: unknown
74
+ }
75
+
76
+ /** Checks every recorded message; returns the definitions that were used, so the test can see it covered them all. */
77
+ function check(wire: Array<{ direction: Direction; message: WireMessage }>): Set<string> {
78
+ const methods = new Map<string, string>()
79
+ const used = new Set<string>()
80
+ for (const { direction, message } of wire) {
81
+ const whole = envelope[direction]
82
+ assert.ok(
83
+ whole(message),
84
+ `${direction} ${JSON.stringify(message)}: ${ajv.errorsText(whole.errors)}`,
85
+ )
86
+ let definition: string | undefined
87
+ if (message.method !== undefined) {
88
+ const kind = message.id === undefined ? 'notification' : 'request'
89
+ if (message.id !== undefined)
90
+ methods.set(`${direction}:${String(message.id)}`, message.method)
91
+ definition = (DEFINITIONS[direction][kind] as Record<string, string>)[message.method]
92
+ assert.ok(
93
+ definition,
94
+ `${direction} sent ${kind} ${message.method}, which this test does not know`,
95
+ )
96
+ const validate = validator(`/$defs/${definition}`)
97
+ assert.ok(
98
+ validate(message.params),
99
+ `${direction} ${message.method}: ${ajv.errorsText(validate.errors)}`,
100
+ )
101
+ } else if (message.error === undefined) {
102
+ const asked = methods.get(
103
+ `${direction === 'toAgent' ? 'toClient' : 'toAgent'}:${String(message.id)}`,
104
+ )
105
+ assert.ok(asked, `${direction} answered ${String(message.id)}, which nobody asked`)
106
+ definition = (DEFINITIONS[direction].response as Record<string, string>)[asked]
107
+ assert.ok(definition, `${direction} answered ${asked}, which this test does not know`)
108
+ const validate = validator(`/$defs/${definition}`)
109
+ assert.ok(
110
+ validate(message.result),
111
+ `${direction} answer to ${asked}: ${ajv.errorsText(validate.errors)}`,
112
+ )
113
+ }
114
+ if (definition) used.add(definition)
115
+ }
116
+ return used
117
+ }
118
+
119
+ test('every message of a session, both ways, is valid ACP v1: the handshake, text, tools, a permission, a cancel, a refusal, an error', async () => {
120
+ const saved = { NODE_ENV: process.env.NODE_ENV, ACRYL_DOOR: process.env.ACRYL_DOOR }
121
+ process.env.NODE_ENV = 'test'
122
+ delete process.env.ACRYL_DOOR
123
+ const root = mkdtempSync(join(tmpdir(), 'acp-wire-'))
124
+ const wireFile = join(root, 'wire.jsonl')
125
+ const app = new Context()
126
+ try {
127
+ await app.plugin(instance, pinnedInstance(join(root, '.acrylblends'), { root })).await()
128
+ const registry = createDrivers()
129
+ app.provide('drivers', registry)
130
+ const fiber = app.plugin(driverAcp, {
131
+ agents: {
132
+ fake: {
133
+ command: process.execPath,
134
+ args: [join(import.meta.dirname, 'fake-agent.mjs')],
135
+ env: { FAKE_ACP_WIRE: wireFile },
136
+ },
137
+ },
138
+ })
139
+ await fiber.await()
140
+ const driver = registry.get('acp:fake') as ChatDriver
141
+ for (const message of ['hello', 'permission', 'refuse', 'nonsense']) {
142
+ for await (const _ of driver.start({ message, signal: new AbortController().signal })) {
143
+ // Only the wire is checked here; driver-acp.test.ts checks the events.
144
+ }
145
+ }
146
+ const stop = new AbortController()
147
+ for await (const _ of driver.start({ message: 'wait', signal: stop.signal })) stop.abort()
148
+ await fiber.dispose()
149
+
150
+ const wire = readFileSync(wireFile, 'utf8')
151
+ .trim()
152
+ .split('\n')
153
+ .map((line) => JSON.parse(line) as { direction: Direction; message: WireMessage })
154
+ const used = check(wire)
155
+ const all = Object.values(DEFINITIONS).flatMap((kinds) =>
156
+ Object.values(kinds).flatMap((byMethod) => Object.values(byMethod)),
157
+ )
158
+ assert.deepEqual(
159
+ [...used].sort(),
160
+ [...new Set(all)].sort(),
161
+ 'the session used every message the client speaks',
162
+ )
163
+ } finally {
164
+ rmSync(root, { recursive: true, force: true })
165
+ for (const [key, value] of Object.entries(saved)) {
166
+ if (value === undefined) delete process.env[key]
167
+ else process.env[key] = value
168
+ }
169
+ }
170
+ })
171
+
172
+ test('the check itself refuses what is not ACP: a wrong protocol version and an update without its kind', () => {
173
+ const jsonrpc = '2.0'
174
+ assert.throws(
175
+ () =>
176
+ check([
177
+ {
178
+ direction: 'toAgent',
179
+ message: {
180
+ jsonrpc,
181
+ id: 1,
182
+ method: 'initialize',
183
+ params: { protocolVersion: 'one' },
184
+ } as WireMessage,
185
+ },
186
+ ]),
187
+ /toAgent initialize: /u,
188
+ )
189
+ assert.throws(
190
+ () =>
191
+ check([
192
+ {
193
+ direction: 'toClient',
194
+ message: {
195
+ jsonrpc,
196
+ method: 'session/update',
197
+ params: { sessionId: 's', update: { content: { type: 'text', text: 'x' } } },
198
+ } as WireMessage,
199
+ },
200
+ ]),
201
+ /toClient session\/update: /u,
202
+ )
203
+ })
@@ -0,0 +1,338 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { afterEach, test } from 'node:test'
6
+ import { agent, memory, model, tools } from '@acryldev/agent'
7
+ import * as panel from '@acryldev/agent-panel'
8
+ import { builder } from '@acryldev/builder'
9
+ import { type ChatDriver, type ChatEvent, createDrivers, type Drivers } from '@acryldev/drivers'
10
+ import { extensions } from '@acryldev/extensions'
11
+ import { instance, pinnedInstance } from '@acryldev/instance'
12
+ import * as router from '@acryldev/router'
13
+ import * as state from '@acryldev/state'
14
+ import { Context } from '@deepseek-ai/cordis'
15
+ import * as driverAcp from '../index.ts'
16
+
17
+ const cleanup: Array<() => Promise<void> | void> = []
18
+ afterEach(async () => {
19
+ for (const step of cleanup.splice(0).reverse()) await step()
20
+ })
21
+
22
+ const FAKE = join(import.meta.dirname, 'fake-agent.mjs')
23
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
24
+
25
+ /** Development mode for the plugin, restored afterwards. */
26
+ function development(): void {
27
+ const saved = { NODE_ENV: process.env.NODE_ENV, ACRYL_DOOR: process.env.ACRYL_DOOR }
28
+ process.env.NODE_ENV = 'test'
29
+ delete process.env.ACRYL_DOOR
30
+ cleanup.push(() => {
31
+ for (const [key, value] of Object.entries(saved)) {
32
+ if (value === undefined) delete process.env[key]
33
+ else process.env[key] = value
34
+ }
35
+ })
36
+ }
37
+
38
+ /** An app folder, and the file the fake agents write their pids to. */
39
+ function folder() {
40
+ const root = mkdtempSync(join(tmpdir(), 'acp-root-'))
41
+ cleanup.push(() => rmSync(root, { recursive: true, force: true }))
42
+ const pids = join(root, 'pids.txt')
43
+ const started = (): number[] => {
44
+ try {
45
+ return readFileSync(pids, 'utf8').trim().split('\n').filter(Boolean).map(Number)
46
+ } catch {
47
+ return []
48
+ }
49
+ }
50
+ return { root, pids, started }
51
+ }
52
+
53
+ function alive(pid: number): boolean {
54
+ try {
55
+ process.kill(pid, 0)
56
+ return true
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ async function until(check: () => boolean, ms = 10_000): Promise<void> {
63
+ for (const end = Date.now() + ms; Date.now() < end; ) {
64
+ if (check()) return
65
+ await sleep(20)
66
+ }
67
+ throw new Error('timed out waiting')
68
+ }
69
+
70
+ /** The fake agent as the plugin's only agent, mounted with a bare registry (no panel). */
71
+ async function boot(config: Partial<driverAcp.DriverAcpConfig> = {}) {
72
+ development()
73
+ const { root, pids, started } = folder()
74
+ const app = new Context()
75
+ await app.plugin(instance, pinnedInstance(join(root, '.acrylblends'), { root })).await()
76
+ const registry = createDrivers()
77
+ app.provide('drivers', registry)
78
+ const fiber = app.plugin(driverAcp, {
79
+ agents: { fake: { command: process.execPath, args: [FAKE], env: { FAKE_ACP_PIDS: pids } } },
80
+ ...config,
81
+ })
82
+ await fiber.await()
83
+ cleanup.push(() => fiber.dispose())
84
+ const driver = registry.get('acp:fake') as ChatDriver
85
+ return { app, registry, fiber, driver, root, started }
86
+ }
87
+
88
+ async function run(
89
+ driver: ChatDriver,
90
+ message: string,
91
+ signal = new AbortController().signal,
92
+ ): Promise<ChatEvent[]> {
93
+ const events: ChatEvent[] = []
94
+ for await (const event of driver.start({ message, signal })) events.push(event)
95
+ return events
96
+ }
97
+
98
+ test('a turn streams the agent message as text and each finished tool call as one tool event; thoughts stay out', async () => {
99
+ const { driver } = await boot()
100
+ assert.equal(driver.kind, 'chat')
101
+ assert.deepEqual(await run(driver, 'hello'), [
102
+ { event: 'text', data: { text: 'Hel' } },
103
+ { event: 'text', data: { text: 'lo' } },
104
+ {
105
+ event: 'tool',
106
+ data: { tool: 'Read README.md', input: { path: 'README.md' }, result: { lines: 3 } },
107
+ },
108
+ { event: 'tool', data: { tool: 'Run npm test', error: 'exit code 1' } },
109
+ ])
110
+ })
111
+
112
+ test('later messages continue the same session in the same process', async () => {
113
+ const { driver, started } = await boot()
114
+ assert.deepEqual(await run(driver, 'count'), [{ event: 'text', data: { text: 'prompts 1' } }])
115
+ assert.deepEqual(await run(driver, 'count'), [{ event: 'text', data: { text: 'prompts 2' } }])
116
+ assert.equal(started().length, 1)
117
+ })
118
+
119
+ test('aborting the signal cancels the turn through session/cancel, and the next message runs', async () => {
120
+ const { driver } = await boot()
121
+ const stop = new AbortController()
122
+ const events: ChatEvent[] = []
123
+ const reading = (async () => {
124
+ for await (const event of driver.start({ message: 'wait', signal: stop.signal })) {
125
+ events.push(event)
126
+ stop.abort()
127
+ }
128
+ })()
129
+ await reading
130
+ assert.deepEqual(
131
+ events,
132
+ [{ event: 'text', data: { text: 'working' } }],
133
+ 'a cancelled turn ends without an error',
134
+ )
135
+ assert.deepEqual(await run(driver, 'count'), [{ event: 'text', data: { text: 'prompts 2' } }])
136
+ })
137
+
138
+ test("a permission request gets the agent's reject option by default, and its allow option when configured", async () => {
139
+ const rejecting = await boot()
140
+ assert.deepEqual(await run(rejecting.driver, 'permission'), [
141
+ { event: 'text', data: { text: 'no' } },
142
+ ])
143
+ const allowing = await boot({ permissions: 'allow' })
144
+ assert.deepEqual(await run(allowing.driver, 'permission'), [
145
+ { event: 'text', data: { text: 'yes' } },
146
+ ])
147
+ })
148
+
149
+ test('a turn that stops short and an agent error are errors in the chat', async () => {
150
+ const { driver } = await boot()
151
+ assert.deepEqual(await run(driver, 'refuse'), [
152
+ { event: 'error', data: { message: 'acp:fake refused to continue' } },
153
+ ])
154
+ assert.deepEqual(await run(driver, 'nonsense'), [
155
+ { event: 'error', data: { message: 'the fake agent does not know "nonsense"' } },
156
+ ])
157
+ })
158
+
159
+ test('an agent that crashes is reported with its reason, and the next message starts a new one', async () => {
160
+ const { driver, started } = await boot()
161
+ const [crash] = await run(driver, 'crash')
162
+ assert.ok(crash?.event === 'error')
163
+ assert.match(crash.data.message, /exit code 3.*boom: the fake agent crashed/u)
164
+ assert.deepEqual(await run(driver, 'count'), [{ event: 'text', data: { text: 'prompts 1' } }])
165
+ assert.equal(started().length, 2)
166
+ })
167
+
168
+ test('an agent that cannot be started is an error of the turn, not of the app', async () => {
169
+ const { driver } = await boot({
170
+ agents: { fake: { command: process.execPath, args: ['--no-such-flag-for-node'] } },
171
+ })
172
+ const [failed] = await run(driver, 'hello')
173
+ assert.equal(failed?.event, 'error')
174
+ })
175
+
176
+ test('unloading the plugin ends the agent process it started, and its drivers leave', async () => {
177
+ const { driver, fiber, registry, started } = await boot()
178
+ await run(driver, 'count')
179
+ const [pid] = started()
180
+ assert.ok(pid !== undefined && alive(pid), 'the agent runs after a message')
181
+ await fiber.dispose()
182
+ await until(() => !alive(pid))
183
+ assert.deepEqual(registry.list(), [], 'the drivers leave with the plugin')
184
+ })
185
+
186
+ test('unloading the plugin also ends what the agent started (its tool processes), not only the agent', {
187
+ skip: process.platform === 'win32',
188
+ }, async () => {
189
+ const { driver, fiber, started } = await boot()
190
+ await run(driver, 'spawn')
191
+ const [agent, tool] = started()
192
+ assert.ok(
193
+ agent !== undefined && tool !== undefined && alive(agent) && alive(tool),
194
+ 'the agent and its tool process run',
195
+ )
196
+ await fiber.dispose()
197
+ await until(() => !alive(agent) && !alive(tool))
198
+ })
199
+
200
+ test('unloading in the middle of a turn ends the turn and the process', async () => {
201
+ const { driver, fiber, started } = await boot()
202
+ const events: ChatEvent[] = []
203
+ const reading = (async () => {
204
+ for await (const event of driver.start({
205
+ message: 'wait',
206
+ signal: new AbortController().signal,
207
+ }))
208
+ events.push(event)
209
+ })()
210
+ await until(() => events.length > 0)
211
+ const [pid] = started()
212
+ await fiber.dispose()
213
+ await reading
214
+ assert.equal(events.at(-1)?.event, 'error', 'the turn ends with the reason the agent is gone')
215
+ assert.ok(pid !== undefined && !alive(pid))
216
+ })
217
+
218
+ test('reloading three times leaves one driver and no process behind', async () => {
219
+ development()
220
+ const { root, pids, started } = folder()
221
+ const app = new Context()
222
+ await app.plugin(instance, pinnedInstance(join(root, '.acrylblends'), { root })).await()
223
+ const registry: Drivers = createDrivers()
224
+ app.provide('drivers', registry)
225
+ for (let round = 0; round < 3; round++) {
226
+ const fiber = app.plugin(driverAcp, {
227
+ agents: { fake: { command: process.execPath, args: [FAKE], env: { FAKE_ACP_PIDS: pids } } },
228
+ })
229
+ await fiber.await()
230
+ assert.deepEqual(
231
+ registry.list().map((d) => d.name),
232
+ ['acp:fake'],
233
+ )
234
+ await run(registry.get('acp:fake') as ChatDriver, 'count')
235
+ await fiber.dispose()
236
+ }
237
+ assert.equal(started().length, 3)
238
+ await until(() => started().every((pid) => !alive(pid)))
239
+ assert.deepEqual(registry.list(), [])
240
+ })
241
+
242
+ test('an agent whose command is not on the machine gets no driver and one line saying why', async () => {
243
+ const warnings: string[] = []
244
+ const warn = console.warn
245
+ console.warn = (line: string) => void warnings.push(line)
246
+ cleanup.push(() => {
247
+ console.warn = warn
248
+ })
249
+ const { registry } = await boot({
250
+ agents: { ghost: { command: 'acp-agent-that-is-not-installed', args: [] } },
251
+ })
252
+ assert.deepEqual(registry.list(), [])
253
+ assert.deepEqual(warnings, [
254
+ 'driver-acp: no acp:ghost driver, "acp-agent-that-is-not-installed" is not on the PATH',
255
+ ])
256
+ })
257
+
258
+ test('dsh is a preset: the command line of its ACP server, with no code of its own', () => {
259
+ assert.deepEqual(driverAcp.PRESETS.dsh, { command: 'dsh', args: ['--profile', 'acp'] })
260
+ })
261
+
262
+ test('without the panel the plugin is pending; in production it starts nothing', async () => {
263
+ development()
264
+ const { root } = folder()
265
+ const app = new Context()
266
+ await app.plugin(instance, pinnedInstance(join(root, '.acrylblends'), { root })).await()
267
+ const fiber = app.plugin(driverAcp, {
268
+ agents: { fake: { command: process.execPath, args: [FAKE] } },
269
+ })
270
+ await sleep(50)
271
+ assert.equal((app as unknown as { drivers?: unknown }).drivers, undefined)
272
+ const registry = createDrivers()
273
+ app.provide('drivers', registry)
274
+ await fiber.await()
275
+ assert.deepEqual(
276
+ registry.list().map((d) => d.name),
277
+ ['acp:fake'],
278
+ )
279
+ await fiber.dispose()
280
+
281
+ process.env.NODE_ENV = 'production'
282
+ const production = app.plugin(driverAcp, {
283
+ agents: { fake: { command: process.execPath, args: [FAKE] } },
284
+ })
285
+ await production.await()
286
+ assert.deepEqual(registry.list(), [])
287
+ await production.dispose()
288
+ })
289
+
290
+ test('through the real agent panel: the page asks acp:fake and gets its text, its tool lines and done', async () => {
291
+ development()
292
+ const { root, pids } = folder()
293
+ const app = new Context()
294
+ const fibers: Array<ReturnType<Context['plugin']>> = []
295
+ const mount = async (fiber: ReturnType<Context['plugin']>) => {
296
+ fibers.push(fiber)
297
+ await fiber.await()
298
+ }
299
+ await mount(app.plugin(instance, pinnedInstance(join(root, '.acrylblends'), { root })))
300
+ await mount(app.plugin(router))
301
+ await mount(app.plugin(state))
302
+ await mount(
303
+ app.plugin(extensions, { sources: [{ dir: join(root, 'plugins'), trust: 'install' }] }),
304
+ )
305
+ for (const plugin of [model, tools, memory, agent]) await mount(app.plugin(plugin))
306
+ await mount(app.plugin(builder, {}))
307
+ await mount(app.plugin(panel, { drivers: [] }))
308
+ await mount(
309
+ app.plugin(driverAcp, {
310
+ agents: { fake: { command: process.execPath, args: [FAKE], env: { FAKE_ACP_PIDS: pids } } },
311
+ }),
312
+ )
313
+ cleanup.push(async () => {
314
+ for (const fiber of [...fibers].reverse()) await fiber.dispose()
315
+ })
316
+ const own = { 'sec-fetch-site': 'same-origin' }
317
+ const session = (await (
318
+ await app.router.request('/api/agent-panel/session', { headers: own })
319
+ ).json()) as {
320
+ token: string
321
+ drivers: Array<{ name: string; kind: string }>
322
+ }
323
+ assert.ok(
324
+ session.drivers.some((d) => d.name === 'acp:fake' && d.kind === 'chat'),
325
+ 'the panel lists the driver',
326
+ )
327
+ const response = await app.router.request('/api/agent-panel/ask', {
328
+ method: 'POST',
329
+ headers: { 'content-type': 'application/json', ...own, 'x-agent-panel-token': session.token },
330
+ body: JSON.stringify({ message: 'hello', driver: 'acp:fake' }),
331
+ })
332
+ assert.equal(response.status, 200)
333
+ const events = (await response.text())
334
+ .split('\n\n')
335
+ .filter(Boolean)
336
+ .map((block) => block.match(/^event: (.+)$/mu)?.[1])
337
+ assert.deepEqual(events, ['text', 'text', 'tool', 'tool', 'done'])
338
+ })
@@ -0,0 +1,143 @@
1
+ // A small ACP agent for the tests: it speaks ACP v1 over stdio and does what the prompt says.
2
+ // hello two message chunks, a thought, one tool call that completes and one that fails, then end_turn
3
+ // permission asks for permission and answers with the option it was given (or "cancelled")
4
+ // wait holds the turn until session/cancel, then ends it as cancelled
5
+ // refuse ends the turn with stopReason refusal
6
+ // crash prints a reason on stderr and exits with code 3
7
+ // count answers how many prompts this session has had
8
+ // spawn starts a child of its own (a tool process), records its pid, and ends the turn
9
+ // It appends its pid to FAKE_ACP_PIDS and every message both ways to FAKE_ACP_WIRE (for the schema check), and ends when its stdin closes, as an ACP agent does.
10
+ import { spawn } from 'node:child_process'
11
+ import { appendFileSync } from 'node:fs'
12
+
13
+ if (process.env.FAKE_ACP_PIDS) appendFileSync(process.env.FAKE_ACP_PIDS, `${process.pid}\n`)
14
+ const record = (direction, message) => {
15
+ if (process.env.FAKE_ACP_WIRE)
16
+ appendFileSync(process.env.FAKE_ACP_WIRE, `${JSON.stringify({ direction, message })}\n`)
17
+ }
18
+
19
+ let nextId = 1
20
+ const waiting = new Map()
21
+ const send = (message) => {
22
+ const whole = { jsonrpc: '2.0', ...message }
23
+ record('toClient', whole)
24
+ process.stdout.write(`${JSON.stringify(whole)}\n`)
25
+ }
26
+ const ask = (method, params) =>
27
+ new Promise((resolve) => {
28
+ const id = `agent-${nextId++}`
29
+ waiting.set(id, resolve)
30
+ send({ id, method, params })
31
+ })
32
+ const update = (sessionId, value) =>
33
+ send({ method: 'session/update', params: { sessionId, update: value } })
34
+ const text = (sessionId, chunk) =>
35
+ update(sessionId, {
36
+ sessionUpdate: 'agent_message_chunk',
37
+ content: { type: 'text', text: chunk },
38
+ })
39
+
40
+ let prompts = 0
41
+ let held
42
+
43
+ async function prompt(id, { sessionId, prompt: blocks }) {
44
+ prompts += 1
45
+ const said = blocks.map((block) => block.text).join('')
46
+ switch (said) {
47
+ case 'hello':
48
+ text(sessionId, 'Hel')
49
+ update(sessionId, {
50
+ sessionUpdate: 'agent_thought_chunk',
51
+ content: { type: 'text', text: 'thinking' },
52
+ })
53
+ text(sessionId, 'lo')
54
+ update(sessionId, {
55
+ sessionUpdate: 'tool_call',
56
+ toolCallId: 't1',
57
+ title: 'Read README.md',
58
+ status: 'pending',
59
+ rawInput: { path: 'README.md' },
60
+ })
61
+ update(sessionId, {
62
+ sessionUpdate: 'tool_call_update',
63
+ toolCallId: 't1',
64
+ status: 'completed',
65
+ rawOutput: { lines: 3 },
66
+ })
67
+ update(sessionId, {
68
+ sessionUpdate: 'tool_call',
69
+ toolCallId: 't2',
70
+ title: 'Run npm test',
71
+ status: 'in_progress',
72
+ })
73
+ update(sessionId, {
74
+ sessionUpdate: 'tool_call_update',
75
+ toolCallId: 't2',
76
+ status: 'failed',
77
+ content: [{ type: 'content', content: { type: 'text', text: 'exit code 1' } }],
78
+ })
79
+ return send({ id, result: { stopReason: 'end_turn' } })
80
+ case 'permission': {
81
+ const answer = await ask('session/request_permission', {
82
+ sessionId,
83
+ toolCall: { toolCallId: 't3', title: 'Write index.ts' },
84
+ options: [
85
+ { optionId: 'yes', name: 'Allow', kind: 'allow_once' },
86
+ { optionId: 'no', name: 'Reject', kind: 'reject_once' },
87
+ ],
88
+ })
89
+ text(sessionId, answer.outcome.outcome === 'selected' ? answer.outcome.optionId : 'cancelled')
90
+ return send({ id, result: { stopReason: 'end_turn' } })
91
+ }
92
+ case 'wait':
93
+ text(sessionId, 'working')
94
+ held = () => send({ id, result: { stopReason: 'cancelled' } })
95
+ return
96
+ case 'refuse':
97
+ return send({ id, result: { stopReason: 'refusal' } })
98
+ case 'crash':
99
+ process.stderr.write('boom: the fake agent crashed\n')
100
+ return process.exit(3)
101
+ case 'spawn': {
102
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
103
+ stdio: 'ignore',
104
+ })
105
+ if (process.env.FAKE_ACP_PIDS) appendFileSync(process.env.FAKE_ACP_PIDS, `${child.pid}\n`)
106
+ text(sessionId, 'started')
107
+ return send({ id, result: { stopReason: 'end_turn' } })
108
+ }
109
+ case 'count':
110
+ text(sessionId, `prompts ${prompts}`)
111
+ return send({ id, result: { stopReason: 'end_turn' } })
112
+ default:
113
+ return send({
114
+ id,
115
+ error: { code: -32602, message: `the fake agent does not know "${said}"` },
116
+ })
117
+ }
118
+ }
119
+
120
+ let buffer = ''
121
+ process.stdin.setEncoding('utf8')
122
+ process.stdin.on('data', (chunk) => {
123
+ buffer += chunk
124
+ for (let end = buffer.indexOf('\n'); end !== -1; end = buffer.indexOf('\n')) {
125
+ const message = JSON.parse(buffer.slice(0, end))
126
+ buffer = buffer.slice(end + 1)
127
+ record('toAgent', message)
128
+ if (message.method === undefined) {
129
+ waiting.get(message.id)?.(message.result)
130
+ waiting.delete(message.id)
131
+ } else if (message.method === 'initialize')
132
+ send({ id: message.id, result: { protocolVersion: 1, agentCapabilities: {} } })
133
+ else if (message.method === 'session/new')
134
+ send({ id: message.id, result: { sessionId: `session-${process.pid}` } })
135
+ else if (message.method === 'session/prompt') void prompt(message.id, message.params)
136
+ else if (message.method === 'session/cancel') {
137
+ held?.()
138
+ held = undefined
139
+ } else if (message.id !== undefined)
140
+ send({ id: message.id, error: { code: -32601, message: 'unknown method' } })
141
+ }
142
+ })
143
+ process.stdin.on('end', () => process.exit(0))