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