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 decodeExtResponse = Schema.decodeEffect(Schema.fromJsonString(ExtResponse));
49const decodeRequestPermissionResponse = Schema.decodeEffect(
50 Schema.fromJsonString(RequestPermissionResponse),
51);
52const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
53const encoder = new TextEncoder();
54const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
55 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
56);
57const mockPeerArgs = (path: string) => [path];
58
59const makeHandle = (env?: Record<string, string>) =>
60 Effect.gen(function* () {
61 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
62 const path = yield* Path.Path;
63 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
64 cwd: path.join(import.meta.dirname, ".."),
65 ...(env ? { env: { ...process.env, ...env } } : {}),
66 });
67 return yield* spawner.spawn(command);
68 });
69
70it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
71 it.effect(
72 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
73 () =>
74 Effect.gen(function* () {
75 const { stdio, input, output } = yield* makeInMemoryStdio();
76 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
77 stdio,
78 serverRequestMethods: new Set(),
79 });
80
81 const notifications =
82 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
83 yield* transport.incoming.pipe(
84 Stream.take(2),
85 Stream.runCollect,
86 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
87 Effect.forkScoped,
88 );
89
90 yield* transport.notify("session/cancel", { sessionId: "session-1" });
91 const outbound = yield* Queue.take(output);
92 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
93 jsonrpc: "2.0",
94 method: "session/cancel",
95 params: {
96 sessionId: "session-1",
97 },
98 });
99
100 yield* Queue.offer(
101 input,
102 yield* encodeJsonl(SessionUpdateNotification, {
103 jsonrpc: "2.0",
104 method: "session/update",
105 params: {
106 sessionId: "session-1",
107 update: {
108 sessionUpdate: "plan",
109 entries: [
110 {
111 content: "Inspect repository",
112 priority: "high",
113 status: "in_progress",
114 },
115 ],
116 },
117 },
118 }),
119 );
120
121 yield* Queue.offer(
122 input,
123 yield* encodeJsonl(ElicitationCompleteNotification, {
124 jsonrpc: "2.0",
125 method: "session/elicitation/complete",
126 params: {
127 elicitationId: "elicitation-1",
128 },
129 }),
130 );
131
132 const [update, completion] = yield* Deferred.await(notifications);
133 assert.equal(update?._tag, "SessionUpdate");
134 assert.equal(completion?._tag, "ElicitationComplete");
135 }),
136 );
137
138 it.effect("keeps invalid core notification values only in the schema cause", () =>
139 Effect.gen(function* () {
140 const secret = "acp-core-notification-secret-sentinel";
141 const { stdio, input } = yield* makeInMemoryStdio();
142 const termination = yield* Deferred.make<AcpError.AcpError>();
143 yield* AcpProtocol.makeAcpPatchedProtocol({
144 stdio,
145 serverRequestMethods: new Set(),
146 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
147 });
148
149 yield* Queue.offer(
150 input,
151 encoder.encode(
152 `${encodeUnknownJsonString({
153 jsonrpc: "2.0",
154 method: "session/update",
155 params: {
156 sessionId: { secret },
157 update: {
158 sessionUpdate: "plan",
159 entries: [],
160 },
161 },
162 })}\n`,
163 ),
164 );
165
166 const error = yield* Deferred.await(termination);
167 assert.instanceOf(error, AcpError.AcpProtocolParseError);
168 const parseError = error as AcpError.AcpProtocolParseError;
169 const { cause, ...directDiagnostics } = parseError;
170 assert.equal(parseError.operation, "decode-notification-payload");
171 assert.equal(parseError.method, "session/update");
172 assert.isAbove(parseError.issueCount ?? 0, 0);
173 assert.include(parseError.issueKinds ?? [], "Pointer");
174 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
175 assert.isTrue(Schema.isSchemaError(cause));
176 assert.notInclude(parseError.message, secret);
177 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
178 }),
179 );
180
181 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
182 Effect.gen(function* () {
183 const { stdio } = yield* makeInMemoryStdio();
184 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
185 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
186 stdio,
187 serverRequestMethods: new Set(),
188 logOutgoing: true,
189 logger: (event) =>
190 Effect.sync(() => {
191 events.push(event);
192 }),
193 });
194
195 yield* transport.notify("session/cancel", { sessionId: "session-1" });
196
197 assert.deepEqual(events, [
198 {
199 direction: "outgoing",
200 stage: "decoded",
201 payload: {
202 _tag: "Request",
203 id: "",
204 tag: "session/cancel",
205 payload: {
206 sessionId: "session-1",
207 },
208 headers: [],
209 },
210 },
211 {
212 direction: "outgoing",
213 stage: "raw",
214 payload:
215 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
216 },
217 ]);
218 }),
219 );
220
221 it.effect("logs decode failures without copying the cause or wire payload", () =>
222 Effect.gen(function* () {
223 const secret = "acp-wire-secret-sentinel";
224 const { stdio, input } = yield* makeInMemoryStdio();
225 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
226 const termination = yield* Deferred.make<AcpError.AcpError>();
227 yield* AcpProtocol.makeAcpPatchedProtocol({
228 stdio,
229 serverRequestMethods: new Set(),
230 logIncoming: true,
231 logger: (event) =>
232 Effect.sync(() => {
233 events.push(event);
234 }),
235 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
236 });
237
238 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
239 yield* Deferred.await(termination);
240
241 const event = events.find(({ stage }) => stage === "decode_failed");
242 assert.deepEqual(event, {
243 direction: "incoming",
244 stage: "decode_failed",
245 payload: {
246 operation: "decode-wire-message",
247 },
248 });
249 assert.notInclude(encodeUnknownJsonString(event), secret);
250 }),
251 );
252
253 it.effect("fails notification encoding through the declared ACP error channel", () =>
254 Effect.gen(function* () {
255 const { stdio } = yield* makeInMemoryStdio();
256 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
257 stdio,
258 serverRequestMethods: new Set(),
259 });
260
261 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
262 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
263 assert.equal(bigintError.operation, "encode-message");
264 assert.equal(bigintError.method, "x/test");
265 assert.instanceOf(bigintError.cause, TypeError);
266 assert.equal(
267 bigintError.message,
268 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
269 );
270
271 const circular: Record<string, unknown> = {};
272 circular.self = circular;
273 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
274 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
275 assert.equal(circularError.operation, "encode-message");
276 assert.equal(circularError.method, "x/test");
277 assert.instanceOf(circularError.cause, TypeError);
278
279 const requestError = yield* transport.request("x/request", 1n).pipe(
280 Effect.match({
281 onFailure: (error) => error,
282 onSuccess: () => assert.fail("Expected request encoding to fail"),
283 }),
284 );
285 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
286 assert.deepInclude(requestError, {
287 operation: "encode-message",
288 method: "x/request",
289 requestId: 1,
290 });
291 }),
292 );
293
294 it.effect("supports generic extension requests over the patched transport", () =>
295 Effect.gen(function* () {
296 const { stdio, input, output } = yield* makeInMemoryStdio();
297 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
298 stdio,
299 serverRequestMethods: new Set(),
300 });
301
302 const response = yield* transport
303 .request("x/test", { hello: "world" })
304 .pipe(Effect.forkScoped);
305 const outbound = yield* Queue.take(output);
306 assert.deepEqual(yield* decodeExtRequest(outbound), {
307 jsonrpc: "2.0",
308 id: 1,
309 method: "x/test",
310 params: {
311 hello: "world",
312 },
313 headers: [],
314 });
315
316 yield* Queue.offer(
317 input,
318 yield* encodeJsonl(ExtResponse, {
319 jsonrpc: "2.0",
320 id: 1,
321 result: {
322 ok: true,
323 },
324 }),
325 );
326
327 const resolved = yield* Fiber.join(response);
328 assert.deepEqual(resolved, { ok: true });
329 }),
330 );
331
332 it.effect("correlates extension response errors with the originating request", () =>
333 Effect.gen(function* () {
334 const { stdio, input, output } = yield* makeInMemoryStdio();
335 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
336 stdio,
337 serverRequestMethods: new Set(),
338 });
339
340 const response = yield* transport
341 .request("x/private", { hello: "world" })
342 .pipe(Effect.forkScoped);
343 yield* Queue.take(output);
344 yield* Queue.offer(
345 input,
346 encoder.encode(
347 `${encodeUnknownJsonString({
348 jsonrpc: "2.0",
349 id: 1,
350 error: {
351 _tag: "Cause",
352 code: -32602,
353 message: "Invalid params",
354 data: [
355 {
356 _tag: "Fail",
357 error: {
358 code: -32602,
359 message: "Invalid params",
360 data: { field: "hello" },
361 },
362 },
363 ],
364 },
365 })}\n`,
366 ),
367 );
368
369 const error = yield* Fiber.join(response).pipe(
370 Effect.match({
371 onFailure: (error) => error,
372 onSuccess: () => assert.fail("Expected extension request to fail"),
373 }),
374 );
375 assert.instanceOf(error, AcpError.AcpRequestError);
376 assert.deepInclude(error, {
377 code: -32602,
378 errorMessage: "Invalid params",
379 method: "x/private",
380 requestId: 1,
381 operation: "receive-response",
382 });
383 }),
384 );
385
386 it.effect("preserves numeric ids for inbound extension requests", () =>
387 Effect.gen(function* () {
388 const { stdio, input, output } = yield* makeInMemoryStdio();
389 yield* AcpProtocol.makeAcpPatchedProtocol({
390 stdio,
391 serverRequestMethods: new Set(),
392 onExtRequest: () => Effect.succeed({ ok: true }),
393 });
394
395 yield* Queue.offer(
396 input,
397 yield* encodeJsonl(ExtRequest, {
398 jsonrpc: "2.0",
399 id: 7,
400 method: "x/test",
401 params: {
402 hello: "world",
403 },
404 headers: [],
405 }),
406 );
407
408 const outbound = yield* Queue.take(output);
409 assert.deepEqual(yield* decodeExtResponse(outbound), {
410 jsonrpc: "2.0",
411 id: 7,
412 result: {
413 ok: true,
414 },
415 });
416 }),
417 );
418
419 it.effect("preserves zero-valued ids for inbound core client requests", () =>
420 Effect.gen(function* () {
421 const { stdio, input, output } = yield* makeInMemoryStdio();
422 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
423 stdio,
424 serverRequestMethods: new Set(["session/request_permission"]),
425 });
426 const inboundRequest = yield* Deferred.make<unknown>();
427
428 yield* transport.serverProtocol
429 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
430 .pipe(Effect.forkScoped);
431
432 yield* Queue.offer(
433 input,
434 yield* encodeJsonl(RequestPermissionRequest, {
435 jsonrpc: "2.0",
436 id: 0,
437 method: "session/request_permission",
438 params: {
439 sessionId: "session-1",
440 toolCall: {
441 toolCallId: "tool-1",
442 title: "Allow mock action",
443 },
444 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
445 },
446 headers: [],
447 }),
448 );
449
450 const message = yield* Deferred.await(inboundRequest);
451 assert.deepEqual(message, {
452 _tag: "Request",
453 id: 0,
454 tag: "session/request_permission",
455 payload: {
456 sessionId: "session-1",
457 toolCall: {
458 toolCallId: "tool-1",
459 title: "Allow mock action",
460 },
461 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
462 },
463 headers: [],
464 });
465
466 yield* transport.serverProtocol.send(0, {
467 _tag: "Exit",
468 requestId: 0,
469 exit: {
470 _tag: "Success",
471 value: {
472 outcome: {
473 outcome: "selected",
474 optionId: "allow",
475 },
476 },
477 },
478 });
479
480 const outbound = yield* Queue.take(output);
481 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
482 jsonrpc: "2.0",
483 id: 0,
484 result: {
485 outcome: {
486 outcome: "selected",
487 optionId: "allow",
488 },
489 },
490 });
491 }),
492 );
493
494 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
495 Effect.gen(function* () {
496 const { stdio, input, output } = yield* makeInMemoryStdio();
497 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
498 stdio,
499 serverRequestMethods: new Set(),
500 });
501 const lateResponse = yield* Deferred.make<unknown>();
502
503 yield* transport.clientProtocol
504 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
505 .pipe(Effect.forkScoped);
506
507 const response = yield* transport
508 .request("x/test", { hello: "world" })
509 .pipe(Effect.forkScoped);
510 const outbound = yield* Queue.take(output);
511 assert.deepEqual(yield* decodeExtRequest(outbound), {
512 jsonrpc: "2.0",
513 id: 1,
514 method: "x/test",
515 params: {
516 hello: "world",
517 },
518 headers: [],
519 });
520
521 yield* Fiber.interrupt(response);
522 yield* Queue.offer(
523 input,
524 yield* encodeJsonl(ExtResponse, {
525 jsonrpc: "2.0",
526 id: 1,
527 result: {
528 ok: true,
529 },
530 }),
531 );
532
533 const message = yield* Deferred.await(lateResponse);
534 assert.deepEqual(message, {
535 _tag: "Exit",
536 requestId: 1,
537 exit: {
538 _tag: "Success",
539 value: {
540 ok: true,
541 },
542 },
543 });
544 }),
545 );
546
547 it.effect("propagates the real child exit code when the input stream ends", () =>
548 Effect.gen(function* () {
549 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
550 const firstMessage = yield* Deferred.make<unknown>();
551 const termination = yield* Deferred.make<AcpError.AcpError>();
552 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
553 stdio: makeChildStdio(handle),
554 terminationError: makeTerminationError(handle),
555 serverRequestMethods: new Set(),
556 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
557 });
558
559 yield* transport.clientProtocol
560 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
561 .pipe(Effect.forkScoped);
562
563 const message = yield* Deferred.await(firstMessage);
564 const exitError = yield* Deferred.await(termination);
565 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
566 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
567 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
568 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
569 readonly _tag: string;
570 readonly message: string;
571 readonly cause: unknown;
572 };
573 assert.equal(defect._tag, "RpcClientDefect");
574 assert.equal(defect.message, "ACP protocol terminated.");
575 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
576 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
577 }),
578 );
579
580 it.effect("classifies an input stream ending without inventing a cause", () =>
581 Effect.gen(function* () {
582 const { stdio, input } = yield* makeInMemoryStdio();
583 const termination = yield* Deferred.make<AcpError.AcpError>();
584 yield* AcpProtocol.makeAcpPatchedProtocol({
585 stdio,
586 serverRequestMethods: new Set(),
587 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
588 });
589
590 yield* Queue.end(input);
591
592 const error = yield* Deferred.await(termination);
593 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
594 assert.equal(error.message, "ACP input stream ended.");
595 assert.equal("cause" in error, false);
596 }),
597 );
598
599 it.effect("does not emit a second process-exit error after a decode failure", () =>
600 Effect.gen(function* () {
601 const handle = yield* makeHandle({
602 ACP_MOCK_MALFORMED_OUTPUT: "1",
603 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
604 });
605 const terminationCalls = yield* Ref.make(0);
606 const firstMessage = yield* Deferred.make<unknown>();
607 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
608 stdio: makeChildStdio(handle),
609 terminationError: makeTerminationError(handle),
610 serverRequestMethods: new Set(),
611 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
612 });
613
614 yield* transport.clientProtocol
615 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
616 .pipe(Effect.forkScoped);
617
618 const message = yield* Deferred.await(firstMessage);
619 assert.equal(yield* Ref.get(terminationCalls), 1);
620 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
621 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
622 readonly _tag: string;
623 readonly message: string;
624 readonly cause: unknown;
625 };
626 assert.equal(defect._tag, "RpcClientDefect");
627 assert.equal(defect.message, "ACP protocol terminated.");
628 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
629 }),
630 );
631
632 it.effect("keeps client send failure messages independent from the cause", () =>
633 Effect.gen(function* () {
634 const { stdio } = yield* makeInMemoryStdio();
635 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
636 stdio,
637 serverRequestMethods: new Set(),
638 });
639
640 const failure = yield* transport.clientProtocol
641 .send(0, {
642 _tag: "Request",
643 id: "request-1",
644 tag: "x/test",
645 payload: 1n,
646 headers: [],
647 })
648 .pipe(Effect.flip);
649 const defect = failure.reason as {
650 readonly _tag: string;
651 readonly message: string;
652 readonly cause: unknown;
653 };
654
655 assert.equal(defect._tag, "RpcClientDefect");
656 assert.equal(defect.message, "Failed to send ACP protocol message.");
657 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
658 }),
659 );
660
661 it.effect("fails pending extension requests with the propagated exit code", () =>
662 Effect.gen(function* () {
663 const { stdio, input, output } = yield* makeInMemoryStdio();
664 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
665 stdio,
666 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
667 serverRequestMethods: new Set(),
668 });
669
670 const response = yield* transport
671 .request("x/test", { hello: "world" })
672 .pipe(Effect.forkScoped);
673 yield* Queue.take(output);
674 yield* Queue.end(input);
675
676 const error = yield* Fiber.join(response).pipe(
677 Effect.match({
678 onFailure: (error) => error,
679 onSuccess: () => assert.fail("Expected request to fail after process exit"),
680 }),
681 );
682 assert.instanceOf(error, AcpError.AcpProcessExitedError);
683 assert.equal(error.code, 0);
684 }),
685 );
686});