Open History to see the last commit
1import * as Path from "effect/Path";
2import * as AcpError from "./errors.ts";
3import * as Effect from "effect/Effect";
4import * as Deferred from "effect/Deferred";
5import * as Fiber from "effect/Fiber";
6import * as Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as Ref from "effect/Ref";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11
12import { it, assert } from "@effect/vitest";
13import * as NodeServices from "@effect/platform-node/NodeServices";
14
15import * as AcpSchema from "./_generated/schema.gen.ts";
16import * as AcpProtocol from "./protocol.ts";
17import {
18 encodeJsonl,
19 jsonRpcNotification,
20 jsonRpcRequest,
21 jsonRpcResponse,
22} from "./_internal/shared.ts";
23import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
24
25const SessionCancelNotification = jsonRpcNotification(
26 "session/cancel",
27 AcpSchema.CancelNotification,
28);
29const SessionUpdateNotification = jsonRpcNotification(
30 "session/update",
31 AcpSchema.SessionNotification,
32);
33const ElicitationCompleteNotification = jsonRpcNotification(
34 "session/elicitation/complete",
35 AcpSchema.ElicitationCompleteNotification,
36);
37const RequestPermissionRequest = jsonRpcRequest(
38 "session/request_permission",
39 AcpSchema.RequestPermissionRequest,
40);
41const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
42const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
43const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
44const decodeSessionCancelNotification = Schema.decodeEffect(
45 Schema.fromJsonString(SessionCancelNotification),
46);
47const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
48const decodeRequestPermissionResponse = Schema.decodeEffect(
49 Schema.fromJsonString(RequestPermissionResponse),
50);
51const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
52 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
53);
54
55const makeHandle = (env?: Record<string, string>) =>
56 Effect.gen(function* () {
57 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
58 const path = yield* Path.Path;
59 const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
60 cwd: path.join(import.meta.dirname, ".."),
61 shell: process.platform === "win32",
62 ...(env ? { env: { ...process.env, ...env } } : {}),
63 });
64 return yield* spawner.spawn(command);
65 });
66
67it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
68 it.effect(
69 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
70 () =>
71 Effect.gen(function* () {
72 const { stdio, input, output } = yield* makeInMemoryStdio();
73 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
74 stdio,
75 serverRequestMethods: new Set(),
76 });
77
78 const notifications =
79 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
80 yield* transport.incoming.pipe(
81 Stream.take(2),
82 Stream.runCollect,
83 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
84 Effect.forkScoped,
85 );
86
87 yield* transport.notify("session/cancel", { sessionId: "session-1" });
88 const outbound = yield* Queue.take(output);
89 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
90 jsonrpc: "2.0",
91 method: "session/cancel",
92 params: {
93 sessionId: "session-1",
94 },
95 });
96
97 yield* Queue.offer(
98 input,
99 yield* encodeJsonl(SessionUpdateNotification, {
100 jsonrpc: "2.0",
101 method: "session/update",
102 params: {
103 sessionId: "session-1",
104 update: {
105 sessionUpdate: "plan",
106 entries: [
107 {
108 content: "Inspect repository",
109 priority: "high",
110 status: "in_progress",
111 },
112 ],
113 },
114 },
115 }),
116 );
117
118 yield* Queue.offer(
119 input,
120 yield* encodeJsonl(ElicitationCompleteNotification, {
121 jsonrpc: "2.0",
122 method: "session/elicitation/complete",
123 params: {
124 elicitationId: "elicitation-1",
125 },
126 }),
127 );
128
129 const [update, completion] = yield* Deferred.await(notifications);
130 assert.equal(update?._tag, "SessionUpdate");
131 assert.equal(completion?._tag, "ElicitationComplete");
132 }),
133 );
134
135 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
136 Effect.gen(function* () {
137 const { stdio } = yield* makeInMemoryStdio();
138 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
139 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
140 stdio,
141 serverRequestMethods: new Set(),
142 logOutgoing: true,
143 logger: (event) =>
144 Effect.sync(() => {
145 events.push(event);
146 }),
147 });
148
149 yield* transport.notify("session/cancel", { sessionId: "session-1" });
150
151 assert.deepEqual(events, [
152 {
153 direction: "outgoing",
154 stage: "decoded",
155 payload: {
156 _tag: "Request",
157 id: "",
158 tag: "session/cancel",
159 payload: {
160 sessionId: "session-1",
161 },
162 headers: [],
163 },
164 },
165 {
166 direction: "outgoing",
167 stage: "raw",
168 payload:
169 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
170 },
171 ]);
172 }),
173 );
174
175 it.effect("fails notification encoding through the declared ACP error channel", () =>
176 Effect.gen(function* () {
177 const { stdio } = yield* makeInMemoryStdio();
178 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
179 stdio,
180 serverRequestMethods: new Set(),
181 });
182
183 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
184 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
185 assert.equal(bigintError.detail, "Failed to encode ACP message");
186
187 const circular: Record<string, unknown> = {};
188 circular.self = circular;
189 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
190 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
191 assert.equal(circularError.detail, "Failed to encode ACP message");
192 }),
193 );
194
195 it.effect("supports generic extension requests over the patched transport", () =>
196 Effect.gen(function* () {
197 const { stdio, input, output } = yield* makeInMemoryStdio();
198 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
199 stdio,
200 serverRequestMethods: new Set(),
201 });
202
203 const response = yield* transport
204 .request("x/test", { hello: "world" })
205 .pipe(Effect.forkScoped);
206 const outbound = yield* Queue.take(output);
207 assert.deepEqual(yield* decodeExtRequest(outbound), {
208 jsonrpc: "2.0",
209 id: 1,
210 method: "x/test",
211 params: {
212 hello: "world",
213 },
214 headers: [],
215 });
216
217 yield* Queue.offer(
218 input,
219 yield* encodeJsonl(ExtResponse, {
220 jsonrpc: "2.0",
221 id: 1,
222 result: {
223 ok: true,
224 },
225 }),
226 );
227
228 const resolved = yield* Fiber.join(response);
229 assert.deepEqual(resolved, { ok: true });
230 }),
231 );
232
233 it.effect("preserves zero-valued ids for inbound core client requests", () =>
234 Effect.gen(function* () {
235 const { stdio, input, output } = yield* makeInMemoryStdio();
236 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
237 stdio,
238 serverRequestMethods: new Set(["session/request_permission"]),
239 });
240 const inboundRequest = yield* Deferred.make<unknown>();
241
242 yield* transport.serverProtocol
243 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
244 .pipe(Effect.forkScoped);
245
246 yield* Queue.offer(
247 input,
248 yield* encodeJsonl(RequestPermissionRequest, {
249 jsonrpc: "2.0",
250 id: 0,
251 method: "session/request_permission",
252 params: {
253 sessionId: "session-1",
254 toolCall: {
255 toolCallId: "tool-1",
256 title: "Allow mock action",
257 },
258 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
259 },
260 headers: [],
261 }),
262 );
263
264 const message = yield* Deferred.await(inboundRequest);
265 assert.deepEqual(message, {
266 _tag: "Request",
267 id: "0",
268 tag: "session/request_permission",
269 payload: {
270 sessionId: "session-1",
271 toolCall: {
272 toolCallId: "tool-1",
273 title: "Allow mock action",
274 },
275 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
276 },
277 headers: [],
278 });
279
280 yield* transport.serverProtocol.send(0, {
281 _tag: "Exit",
282 requestId: "0",
283 exit: {
284 _tag: "Success",
285 value: {
286 outcome: {
287 outcome: "selected",
288 optionId: "allow",
289 },
290 },
291 },
292 });
293
294 const outbound = yield* Queue.take(output);
295 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
296 jsonrpc: "2.0",
297 id: 0,
298 result: {
299 outcome: {
300 outcome: "selected",
301 optionId: "allow",
302 },
303 },
304 });
305 }),
306 );
307
308 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
309 Effect.gen(function* () {
310 const { stdio, input, output } = yield* makeInMemoryStdio();
311 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
312 stdio,
313 serverRequestMethods: new Set(),
314 });
315 const lateResponse = yield* Deferred.make<unknown>();
316
317 yield* transport.clientProtocol
318 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
319 .pipe(Effect.forkScoped);
320
321 const response = yield* transport
322 .request("x/test", { hello: "world" })
323 .pipe(Effect.forkScoped);
324 const outbound = yield* Queue.take(output);
325 assert.deepEqual(yield* decodeExtRequest(outbound), {
326 jsonrpc: "2.0",
327 id: 1,
328 method: "x/test",
329 params: {
330 hello: "world",
331 },
332 headers: [],
333 });
334
335 yield* Fiber.interrupt(response);
336 yield* Queue.offer(
337 input,
338 yield* encodeJsonl(ExtResponse, {
339 jsonrpc: "2.0",
340 id: 1,
341 result: {
342 ok: true,
343 },
344 }),
345 );
346
347 const message = yield* Deferred.await(lateResponse);
348 assert.deepEqual(message, {
349 _tag: "Exit",
350 requestId: "1",
351 exit: {
352 _tag: "Success",
353 value: {
354 ok: true,
355 },
356 },
357 });
358 }),
359 );
360
361 it.effect("propagates the real child exit code when the input stream ends", () =>
362 Effect.gen(function* () {
363 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
364 const firstMessage = yield* Deferred.make<unknown>();
365 const termination = yield* Deferred.make<AcpError.AcpError>();
366 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
367 stdio: makeChildStdio(handle),
368 terminationError: makeTerminationError(handle),
369 serverRequestMethods: new Set(),
370 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
371 });
372
373 yield* transport.clientProtocol
374 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
375 .pipe(Effect.forkScoped);
376
377 const message = yield* Deferred.await(firstMessage);
378 const exitError = yield* Deferred.await(termination);
379 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
380 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
381 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
382 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
383 readonly _tag: string;
384 readonly cause: unknown;
385 };
386 assert.equal(defect._tag, "RpcClientDefect");
387 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
388 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
389 }),
390 );
391
392 it.effect("does not emit a second process-exit error after a decode failure", () =>
393 Effect.gen(function* () {
394 const handle = yield* makeHandle({
395 ACP_MOCK_MALFORMED_OUTPUT: "1",
396 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
397 });
398 const terminationCalls = yield* Ref.make(0);
399 const firstMessage = yield* Deferred.make<unknown>();
400 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
401 stdio: makeChildStdio(handle),
402 terminationError: makeTerminationError(handle),
403 serverRequestMethods: new Set(),
404 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
405 });
406
407 yield* transport.clientProtocol
408 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
409 .pipe(Effect.forkScoped);
410
411 const message = yield* Deferred.await(firstMessage);
412 assert.equal(yield* Ref.get(terminationCalls), 1);
413 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
414 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
415 readonly _tag: string;
416 readonly cause: unknown;
417 };
418 assert.equal(defect._tag, "RpcClientDefect");
419 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
420 }),
421 );
422
423 it.effect("fails pending extension requests with the propagated exit code", () =>
424 Effect.gen(function* () {
425 const { stdio, input, output } = yield* makeInMemoryStdio();
426 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
427 stdio,
428 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
429 serverRequestMethods: new Set(),
430 });
431
432 const response = yield* transport
433 .request("x/test", { hello: "world" })
434 .pipe(Effect.forkScoped);
435 yield* Queue.take(output);
436 yield* Queue.end(input);
437
438 const error = yield* Fiber.join(response).pipe(
439 Effect.match({
440 onFailure: (error) => error,
441 onSuccess: () => assert.fail("Expected request to fail after process exit"),
442 }),
443 );
444 assert.instanceOf(error, AcpError.AcpProcessExitedError);
445 assert.equal(error.code, 0);
446 }),
447 );
448});