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