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 Exit from "effect/Exit";
7import * as Queue from "effect/Queue";
8import * as Schema from "effect/Schema";
9import * as Scope from "effect/Scope";
10import * as Sink from "effect/Sink";
11import * as Stdio from "effect/Stdio";
12import * as Stream from "effect/Stream";
13import * as Ref from "effect/Ref";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15
16import { it, assert } from "@effect/vitest";
17import * as NodeServices from "@effect/platform-node/NodeServices";
18
19import * as AcpSchema from "./_generated/schema.gen.ts";
20import * as AcpProtocol from "./protocol.ts";
21import {
22 encodeJsonl,
23 jsonRpcNotification,
24 jsonRpcRequest,
25 jsonRpcResponse,
26} from "./_internal/shared.ts";
27import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
28
29const SessionCancelNotification = jsonRpcNotification(
30 "session/cancel",
31 AcpSchema.CancelNotification,
32);
33const SessionUpdateNotification = jsonRpcNotification(
34 "session/update",
35 AcpSchema.SessionNotification,
36);
37const ElicitationCompleteNotification = jsonRpcNotification(
38 "session/elicitation/complete",
39 AcpSchema.ElicitationCompleteNotification,
40);
41const RequestPermissionRequest = jsonRpcRequest(
42 "session/request_permission",
43 AcpSchema.RequestPermissionRequest,
44);
45const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
46const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
47const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
48const decodeSessionCancelNotification = Schema.decodeEffect(
49 Schema.fromJsonString(SessionCancelNotification),
50);
51const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
52const decodeExtResponse = Schema.decodeEffect(Schema.fromJsonString(ExtResponse));
53const decodeRequestPermissionResponse = Schema.decodeEffect(
54 Schema.fromJsonString(RequestPermissionResponse),
55);
56const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
57const encoder = new TextEncoder();
58const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
59 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
60);
61const mockPeerArgs = (path: string) => [path];
62
63const makeHandle = (env?: Record<string, string>) =>
64 Effect.gen(function* () {
65 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
66 const path = yield* Path.Path;
67 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
68 cwd: path.join(import.meta.dirname, ".."),
69 ...(env ? { env: { ...process.env, ...env } } : {}),
70 });
71 return yield* spawner.spawn(command);
72 });
73
74it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
75 it.effect(
76 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
77 () =>
78 Effect.gen(function* () {
79 const { stdio, input, output } = yield* makeInMemoryStdio();
80 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
81 stdio,
82 serverRequestMethods: new Set(),
83 });
84
85 const notifications =
86 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
87 yield* transport.incoming.pipe(
88 Stream.take(2),
89 Stream.runCollect,
90 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
91 Effect.forkScoped,
92 );
93
94 yield* transport.notify("session/cancel", { sessionId: "session-1" });
95 const outbound = yield* Queue.take(output);
96 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
97 jsonrpc: "2.0",
98 method: "session/cancel",
99 params: {
100 sessionId: "session-1",
101 },
102 });
103
104 yield* Queue.offer(
105 input,
106 yield* encodeJsonl(SessionUpdateNotification, {
107 jsonrpc: "2.0",
108 method: "session/update",
109 params: {
110 sessionId: "session-1",
111 update: {
112 sessionUpdate: "plan",
113 entries: [
114 {
115 content: "Inspect repository",
116 priority: "high",
117 status: "in_progress",
118 },
119 ],
120 },
121 },
122 }),
123 );
124
125 yield* Queue.offer(
126 input,
127 yield* encodeJsonl(ElicitationCompleteNotification, {
128 jsonrpc: "2.0",
129 method: "session/elicitation/complete",
130 params: {
131 elicitationId: "elicitation-1",
132 },
133 }),
134 );
135
136 const [update, completion] = yield* Deferred.await(notifications);
137 assert.equal(update?._tag, "SessionUpdate");
138 assert.equal(completion?._tag, "ElicitationComplete");
139 }),
140 );
141
142 it.effect("keeps invalid core notification values only in the schema cause", () =>
143 Effect.gen(function* () {
144 const secret = "acp-core-notification-secret-sentinel";
145 const { stdio, input } = yield* makeInMemoryStdio();
146 const termination = yield* Deferred.make<AcpError.AcpError>();
147 yield* AcpProtocol.makeAcpPatchedProtocol({
148 stdio,
149 serverRequestMethods: new Set(),
150 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
151 });
152
153 yield* Queue.offer(
154 input,
155 encoder.encode(
156 `${encodeUnknownJsonString({
157 jsonrpc: "2.0",
158 method: "session/update",
159 params: {
160 sessionId: { secret },
161 update: {
162 sessionUpdate: "plan",
163 entries: [],
164 },
165 },
166 })}\n`,
167 ),
168 );
169
170 const error = yield* Deferred.await(termination);
171 assert.instanceOf(error, AcpError.AcpProtocolParseError);
172 const parseError = error as AcpError.AcpProtocolParseError;
173 const { cause, ...directDiagnostics } = parseError;
174 assert.equal(parseError.operation, "decode-notification-payload");
175 assert.equal(parseError.method, "session/update");
176 assert.isAbove(parseError.issueCount ?? 0, 0);
177 assert.include(parseError.issueKinds ?? [], "Pointer");
178 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
179 assert.isTrue(Schema.isSchemaError(cause));
180 assert.notInclude(parseError.message, secret);
181 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
182 }),
183 );
184
185 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
186 Effect.gen(function* () {
187 const { stdio } = yield* makeInMemoryStdio();
188 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
189 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
190 stdio,
191 serverRequestMethods: new Set(),
192 logOutgoing: true,
193 logger: (event) =>
194 Effect.sync(() => {
195 events.push(event);
196 }),
197 });
198
199 yield* transport.notify("session/cancel", { sessionId: "session-1" });
200
201 assert.deepEqual(events, [
202 {
203 direction: "outgoing",
204 stage: "decoded",
205 payload: {
206 _tag: "Request",
207 id: "",
208 tag: "session/cancel",
209 payload: {
210 sessionId: "session-1",
211 },
212 headers: [],
213 },
214 },
215 {
216 direction: "outgoing",
217 stage: "raw",
218 payload:
219 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
220 },
221 ]);
222 }),
223 );
224
225 it.effect("logs decode failures without copying the cause or wire payload", () =>
226 Effect.gen(function* () {
227 const secret = "acp-wire-secret-sentinel";
228 const { stdio, input } = yield* makeInMemoryStdio();
229 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
230 const termination = yield* Deferred.make<AcpError.AcpError>();
231 yield* AcpProtocol.makeAcpPatchedProtocol({
232 stdio,
233 serverRequestMethods: new Set(),
234 logIncoming: true,
235 logger: (event) =>
236 Effect.sync(() => {
237 events.push(event);
238 }),
239 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
240 });
241
242 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
243 yield* Deferred.await(termination);
244
245 const event = events.find(({ stage }) => stage === "decode_failed");
246 assert.deepEqual(event, {
247 direction: "incoming",
248 stage: "decode_failed",
249 payload: {
250 operation: "decode-wire-message",
251 },
252 });
253 assert.notInclude(encodeUnknownJsonString(event), secret);
254 }),
255 );
256
257 it.effect("fails notification encoding through the declared ACP error channel", () =>
258 Effect.gen(function* () {
259 const { stdio } = yield* makeInMemoryStdio();
260 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
261 stdio,
262 serverRequestMethods: new Set(),
263 });
264
265 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
266 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
267 assert.equal(bigintError.operation, "encode-message");
268 assert.equal(bigintError.method, "x/test");
269 assert.instanceOf(bigintError.cause, TypeError);
270 assert.equal(
271 bigintError.message,
272 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
273 );
274
275 const circular: Record<string, unknown> = {};
276 circular.self = circular;
277 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
278 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
279 assert.equal(circularError.operation, "encode-message");
280 assert.equal(circularError.method, "x/test");
281 assert.instanceOf(circularError.cause, TypeError);
282
283 const requestError = yield* transport.request("x/request", 1n).pipe(
284 Effect.match({
285 onFailure: (error) => error,
286 onSuccess: () => assert.fail("Expected request encoding to fail"),
287 }),
288 );
289 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
290 assert.deepInclude(requestError, {
291 operation: "encode-message",
292 method: "x/request",
293 requestId: 1,
294 });
295 }),
296 );
297
298 it.effect("supports generic extension requests over the patched transport", () =>
299 Effect.gen(function* () {
300 const { stdio, input, output } = yield* makeInMemoryStdio();
301 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
302 stdio,
303 serverRequestMethods: new Set(),
304 });
305
306 const response = yield* transport
307 .request("x/test", { hello: "world" })
308 .pipe(Effect.forkScoped);
309 const outbound = yield* Queue.take(output);
310 assert.deepEqual(yield* decodeExtRequest(outbound), {
311 jsonrpc: "2.0",
312 id: 1,
313 method: "x/test",
314 params: {
315 hello: "world",
316 },
317 headers: [],
318 });
319
320 yield* Queue.offer(
321 input,
322 yield* encodeJsonl(ExtResponse, {
323 jsonrpc: "2.0",
324 id: 1,
325 result: {
326 ok: true,
327 },
328 }),
329 );
330
331 const resolved = yield* Fiber.join(response);
332 assert.deepEqual(resolved, { ok: true });
333 }),
334 );
335
336 it.effect("correlates extension response errors with the originating request", () =>
337 Effect.gen(function* () {
338 const { stdio, input, output } = yield* makeInMemoryStdio();
339 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
340 stdio,
341 serverRequestMethods: new Set(),
342 });
343
344 const response = yield* transport
345 .request("x/private", { hello: "world" })
346 .pipe(Effect.forkScoped);
347 yield* Queue.take(output);
348 yield* Queue.offer(
349 input,
350 encoder.encode(
351 `${encodeUnknownJsonString({
352 jsonrpc: "2.0",
353 id: 1,
354 error: {
355 _tag: "Cause",
356 code: -32602,
357 message: "Invalid params",
358 data: [
359 {
360 _tag: "Fail",
361 error: {
362 code: -32602,
363 message: "Invalid params",
364 data: { field: "hello" },
365 },
366 },
367 ],
368 },
369 })}\n`,
370 ),
371 );
372
373 const error = yield* Fiber.join(response).pipe(
374 Effect.match({
375 onFailure: (error) => error,
376 onSuccess: () => assert.fail("Expected extension request to fail"),
377 }),
378 );
379 assert.instanceOf(error, AcpError.AcpRequestError);
380 assert.deepInclude(error, {
381 code: -32602,
382 errorMessage: "Invalid params",
383 method: "x/private",
384 requestId: 1,
385 operation: "receive-response",
386 });
387 }),
388 );
389
390 it.effect("preserves numeric ids for inbound extension requests", () =>
391 Effect.gen(function* () {
392 const { stdio, input, output } = yield* makeInMemoryStdio();
393 yield* AcpProtocol.makeAcpPatchedProtocol({
394 stdio,
395 serverRequestMethods: new Set(),
396 onExtRequest: () => Effect.succeed({ ok: true }),
397 });
398
399 yield* Queue.offer(
400 input,
401 yield* encodeJsonl(ExtRequest, {
402 jsonrpc: "2.0",
403 id: 7,
404 method: "x/test",
405 params: {
406 hello: "world",
407 },
408 headers: [],
409 }),
410 );
411
412 const outbound = yield* Queue.take(output);
413 assert.deepEqual(yield* decodeExtResponse(outbound), {
414 jsonrpc: "2.0",
415 id: 7,
416 result: {
417 ok: true,
418 },
419 });
420 }),
421 );
422
423 it.effect("preserves zero-valued ids for inbound core client requests", () =>
424 Effect.gen(function* () {
425 const { stdio, input, output } = yield* makeInMemoryStdio();
426 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
427 stdio,
428 serverRequestMethods: new Set(["session/request_permission"]),
429 });
430 const inboundRequest = yield* Deferred.make<unknown>();
431
432 yield* transport.serverProtocol
433 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
434 .pipe(Effect.forkScoped);
435
436 yield* Queue.offer(
437 input,
438 yield* encodeJsonl(RequestPermissionRequest, {
439 jsonrpc: "2.0",
440 id: 0,
441 method: "session/request_permission",
442 params: {
443 sessionId: "session-1",
444 toolCall: {
445 toolCallId: "tool-1",
446 title: "Allow mock action",
447 },
448 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
449 },
450 headers: [],
451 }),
452 );
453
454 const message = yield* Deferred.await(inboundRequest);
455 assert.deepEqual(message, {
456 _tag: "Request",
457 id: 0,
458 tag: "session/request_permission",
459 payload: {
460 sessionId: "session-1",
461 toolCall: {
462 toolCallId: "tool-1",
463 title: "Allow mock action",
464 },
465 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
466 },
467 headers: [],
468 });
469
470 yield* transport.serverProtocol.send(0, {
471 _tag: "Exit",
472 requestId: 0,
473 exit: {
474 _tag: "Success",
475 value: {
476 outcome: {
477 outcome: "selected",
478 optionId: "allow",
479 },
480 },
481 },
482 });
483
484 const outbound = yield* Queue.take(output);
485 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
486 jsonrpc: "2.0",
487 id: 0,
488 result: {
489 outcome: {
490 outcome: "selected",
491 optionId: "allow",
492 },
493 },
494 });
495 }),
496 );
497
498 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
499 Effect.gen(function* () {
500 const { stdio } = yield* makeInMemoryStdio();
501 const acknowledged = yield* Deferred.make<string>();
502 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
503 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
504 stdio,
505 serverRequestMethods: new Set(),
506 onOutgoingResponse: (requestId) =>
507 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
508 onOutgoingResponseFailure: (requestId, error) =>
509 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
510 });
511
512 yield* transport.serverProtocol.send(0, {
513 _tag: "Exit",
514 requestId: "success-1",
515 exit: { _tag: "Success", value: { ok: true } },
516 });
517 assert.equal(yield* Deferred.await(acknowledged), "success-1");
518
519 const circular: { self?: unknown } = {};
520 circular.self = circular;
521 yield* transport.serverProtocol
522 .send(0, {
523 _tag: "Exit",
524 requestId: "failure-1",
525 exit: { _tag: "Success", value: circular },
526 })
527 .pipe(Effect.exit);
528 const [requestId, error] = yield* Deferred.await(failed);
529 assert.equal(requestId, "failure-1");
530 assert.instanceOf(error, AcpError.AcpProtocolParseError);
531 }),
532 );
533
534 it.effect("acknowledges a response only after the stdout write completes", () =>
535 Effect.gen(function* () {
536 const writeStarted = yield* Deferred.make<void>();
537 const releaseWrite = yield* Deferred.make<void>();
538 const acknowledged = yield* Deferred.make<string>();
539 const stdio = Stdio.make({
540 args: Effect.succeed([]),
541 stdin: Stream.never,
542 stdout: () =>
543 Sink.forEach(() =>
544 Deferred.succeed(writeStarted, undefined).pipe(
545 Effect.andThen(Deferred.await(releaseWrite)),
546 ),
547 ),
548 stderr: () => Sink.drain,
549 });
550 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
551 stdio,
552 serverRequestMethods: new Set(),
553 onOutgoingResponse: (requestId) =>
554 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
555 });
556 const sendFiber = yield* transport.serverProtocol
557 .send(0, {
558 _tag: "Exit",
559 requestId: "held-write",
560 exit: { _tag: "Success", value: { ok: true } },
561 })
562 .pipe(Effect.forkScoped);
563
564 yield* Deferred.await(writeStarted);
565 assert.isUndefined(sendFiber.pollUnsafe());
566 assert.isFalse(yield* Deferred.isDone(acknowledged));
567 yield* Deferred.succeed(releaseWrite, undefined);
568 yield* Fiber.join(sendFiber);
569 assert.equal(yield* Deferred.await(acknowledged), "held-write");
570 }),
571 );
572
573 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
574 Effect.gen(function* () {
575 const writeStarted = yield* Deferred.make<void>();
576 const releaseFailure = yield* Deferred.make<void>();
577 const failures = yield* Queue.unbounded<string>();
578 const terminated = yield* Deferred.make<AcpError.AcpError>();
579 const stdio = Stdio.make({
580 args: Effect.succeed([]),
581 stdin: Stream.never,
582 stdout: () =>
583 Sink.forEach(() =>
584 Deferred.succeed(writeStarted, undefined).pipe(
585 Effect.andThen(Deferred.await(releaseFailure)),
586 Effect.andThen(Effect.die("stdout failed")),
587 ),
588 ),
589 stderr: () => Sink.drain,
590 });
591 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
592 stdio,
593 serverRequestMethods: new Set(),
594 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
595 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
596 });
597 const send = (requestId: string) =>
598 transport.serverProtocol
599 .send(0, {
600 _tag: "Exit",
601 requestId,
602 exit: { _tag: "Success", value: { ok: true } },
603 })
604 .pipe(Effect.exit);
605 const current = yield* send("current").pipe(Effect.forkScoped);
606 yield* Deferred.await(writeStarted);
607 const queued = yield* send("queued").pipe(Effect.forkScoped);
608 yield* Effect.yieldNow;
609 assert.isUndefined(current.pollUnsafe());
610 assert.isUndefined(queued.pollUnsafe());
611 yield* Deferred.succeed(releaseFailure, undefined);
612 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
613 yield* Fiber.join(current);
614 yield* Fiber.join(queued);
615 yield* send("future");
616
617 assert.deepEqual(
618 new Set(yield* Queue.takeN(failures, 3)),
619 new Set(["current", "queued", "future"]),
620 );
621 }),
622 );
623
624 it.effect(
625 "atomically rejects an admitted response when the writer closes before queue offer",
626 () =>
627 Effect.gen(function* () {
628 const admitted = yield* Deferred.make<void>();
629 const releaseAdmission = yield* Deferred.make<void>();
630 const failures = yield* Queue.unbounded<string>();
631 const protocolScope = yield* Scope.make();
632 const stdio = Stdio.make({
633 args: Effect.succeed([]),
634 stdin: Stream.never,
635 stdout: () => Sink.drain,
636 stderr: () => Sink.drain,
637 });
638 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
639 stdio,
640 serverRequestMethods: new Set(),
641 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
642 testHooks: {
643 onOutgoingWriteAdmitted: () =>
644 Deferred.succeed(admitted, undefined).pipe(
645 Effect.andThen(Deferred.await(releaseAdmission)),
646 ),
647 },
648 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
649 const send = (requestId: string) =>
650 transport.serverProtocol
651 .send(0, {
652 _tag: "Exit",
653 requestId,
654 exit: { _tag: "Success", value: { ok: true } },
655 })
656 .pipe(Effect.exit);
657 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
658
659 yield* Deferred.await(admitted);
660 yield* Scope.close(protocolScope, Exit.void);
661 yield* Deferred.succeed(releaseAdmission, undefined);
662 yield* Fiber.join(admittedSend);
663 yield* send("future");
664
665 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
666 }),
667 );
668
669 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
670 Effect.gen(function* () {
671 const { stdio, input } = yield* makeInMemoryStdio();
672 const notifications =
673 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
674 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
675 stdio,
676 serverRequestMethods: new Set(),
677 });
678
679 yield* transport.incoming.pipe(
680 Stream.take(1),
681 Stream.runCollect,
682 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
683 Effect.forkScoped,
684 );
685
686 yield* Queue.offer(
687 input,
688 encoder.encode(
689 `${encodeUnknownJsonString({
690 jsonrpc: "2.0",
691 id: "skills-reload",
692 result: {
693 reloaded: true,
694 },
695 })}\n`,
696 ),
697 );
698 yield* Queue.offer(
699 input,
700 yield* encodeJsonl(SessionUpdateNotification, {
701 jsonrpc: "2.0",
702 method: "session/update",
703 params: {
704 sessionId: "session-1",
705 update: {
706 sessionUpdate: "plan",
707 entries: [
708 {
709 content: "Reload skills",
710 priority: "high",
711 status: "in_progress",
712 },
713 ],
714 },
715 },
716 }),
717 );
718
719 const [update] = yield* Deferred.await(notifications);
720 assert.equal(update?._tag, "SessionUpdate");
721 }),
722 );
723
724 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
725 Effect.gen(function* () {
726 const { stdio, input, output } = yield* makeInMemoryStdio();
727 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
728 stdio,
729 serverRequestMethods: new Set(),
730 });
731 const lateResponse = yield* Deferred.make<unknown>();
732
733 yield* transport.clientProtocol
734 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
735 .pipe(Effect.forkScoped);
736
737 const response = yield* transport
738 .request("x/test", { hello: "world" })
739 .pipe(Effect.forkScoped);
740 const outbound = yield* Queue.take(output);
741 assert.deepEqual(yield* decodeExtRequest(outbound), {
742 jsonrpc: "2.0",
743 id: 1,
744 method: "x/test",
745 params: {
746 hello: "world",
747 },
748 headers: [],
749 });
750
751 yield* Fiber.interrupt(response);
752 yield* Queue.offer(
753 input,
754 yield* encodeJsonl(ExtResponse, {
755 jsonrpc: "2.0",
756 id: 1,
757 result: {
758 ok: true,
759 },
760 }),
761 );
762
763 const message = yield* Deferred.await(lateResponse);
764 assert.deepEqual(message, {
765 _tag: "Exit",
766 requestId: 1,
767 exit: {
768 _tag: "Success",
769 value: {
770 ok: true,
771 },
772 },
773 });
774 }),
775 );
776
777 it.effect("propagates the real child exit code when the input stream ends", () =>
778 Effect.gen(function* () {
779 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
780 const firstMessage = yield* Deferred.make<unknown>();
781 const termination = yield* Deferred.make<AcpError.AcpError>();
782 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
783 stdio: makeChildStdio(handle),
784 terminationError: makeTerminationError(handle),
785 serverRequestMethods: new Set(),
786 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
787 });
788
789 yield* transport.clientProtocol
790 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
791 .pipe(Effect.forkScoped);
792
793 const message = yield* Deferred.await(firstMessage);
794 const exitError = yield* Deferred.await(termination);
795 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
796 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
797 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
798 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
799 readonly _tag: string;
800 readonly message: string;
801 readonly cause: unknown;
802 };
803 assert.equal(defect._tag, "RpcClientDefect");
804 assert.equal(defect.message, "ACP protocol terminated.");
805 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
806 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
807 }),
808 );
809
810 it.effect("classifies an input stream ending without inventing a cause", () =>
811 Effect.gen(function* () {
812 const { stdio, input } = yield* makeInMemoryStdio();
813 const termination = yield* Deferred.make<AcpError.AcpError>();
814 yield* AcpProtocol.makeAcpPatchedProtocol({
815 stdio,
816 serverRequestMethods: new Set(),
817 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
818 });
819
820 yield* Queue.end(input);
821
822 const error = yield* Deferred.await(termination);
823 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
824 assert.equal(error.message, "ACP input stream ended.");
825 assert.equal("cause" in error, false);
826 }),
827 );
828
829 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
830 Effect.gen(function* () {
831 const { stdio, input } = yield* makeInMemoryStdio();
832 const terminations = yield* Ref.make(0);
833 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
834 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
835 stdio,
836 serverRequestMethods: new Set(),
837 onTermination: () => Ref.update(terminations, (count) => count + 1),
838 testHooks: {
839 onOutgoingWriterExit: (detail) =>
840 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
841 },
842 });
843
844 yield* transport.serverProtocol.end(0);
845 const exitDetail = yield* Deferred.await(writerExit);
846 assert.isTrue(exitDetail.intentionalEnd);
847 assert.equal(yield* Ref.get(terminations), 0);
848
849 // Tear down the forever input reader so the scoped test can finish.
850 yield* Queue.end(input);
851 }),
852 );
853
854 it.effect("does not emit a second process-exit error after a decode failure", () =>
855 Effect.gen(function* () {
856 const handle = yield* makeHandle({
857 ACP_MOCK_MALFORMED_OUTPUT: "1",
858 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
859 });
860 const terminationCalls = yield* Ref.make(0);
861 const firstMessage = yield* Deferred.make<unknown>();
862 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
863 stdio: makeChildStdio(handle),
864 terminationError: makeTerminationError(handle),
865 serverRequestMethods: new Set(),
866 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
867 });
868
869 yield* transport.clientProtocol
870 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
871 .pipe(Effect.forkScoped);
872
873 const message = yield* Deferred.await(firstMessage);
874 assert.equal(yield* Ref.get(terminationCalls), 1);
875 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
876 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
877 readonly _tag: string;
878 readonly message: string;
879 readonly cause: unknown;
880 };
881 assert.equal(defect._tag, "RpcClientDefect");
882 assert.equal(defect.message, "ACP protocol terminated.");
883 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
884 }),
885 );
886
887 it.effect("keeps client send failure messages independent from the cause", () =>
888 Effect.gen(function* () {
889 const { stdio } = yield* makeInMemoryStdio();
890 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
891 stdio,
892 serverRequestMethods: new Set(),
893 });
894
895 const failure = yield* transport.clientProtocol
896 .send(0, {
897 _tag: "Request",
898 id: "request-1",
899 tag: "x/test",
900 payload: 1n,
901 headers: [],
902 })
903 .pipe(Effect.flip);
904 const defect = failure.reason as {
905 readonly _tag: string;
906 readonly message: string;
907 readonly cause: unknown;
908 };
909
910 assert.equal(defect._tag, "RpcClientDefect");
911 assert.equal(defect.message, "Failed to send ACP protocol message.");
912 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
913 }),
914 );
915
916 it.effect("fails pending extension requests with the propagated exit code", () =>
917 Effect.gen(function* () {
918 const { stdio, input, output } = yield* makeInMemoryStdio();
919 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
920 stdio,
921 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
922 serverRequestMethods: new Set(),
923 });
924
925 const response = yield* transport
926 .request("x/test", { hello: "world" })
927 .pipe(Effect.forkScoped);
928 yield* Queue.take(output);
929 yield* Queue.end(input);
930
931 const error = yield* Fiber.join(response).pipe(
932 Effect.match({
933 onFailure: (error) => error,
934 onSuccess: () => assert.fail("Expected request to fail after process exit"),
935 }),
936 );
937 assert.instanceOf(error, AcpError.AcpProcessExitedError);
938 assert.equal(error.code, 0);
939 }),
940 );
941});