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 Logger from "effect/Logger";
8import * as Queue from "effect/Queue";
9import * as References from "effect/References";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import * as Sink from "effect/Sink";
13import * as Stdio from "effect/Stdio";
14import * as Stream from "effect/Stream";
15import * as Ref from "effect/Ref";
16import * as TestClock from "effect/testing/TestClock";
17import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
19import { it, assert, expect } from "@effect/vitest";
20import * as NodeServices from "@effect/platform-node/NodeServices";
21
22import * as AcpSchema from "./schema.ts";
23import * as AcpProtocol from "./protocol.ts";
24import {
25 encodeJsonl,
26 jsonRpcNotification,
27 jsonRpcRequest,
28 jsonRpcResponse,
29} from "./_internal/shared.ts";
30import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
31
32const SessionCancelNotification = jsonRpcNotification(
33 "session/cancel",
34 AcpSchema.CancelNotification,
35);
36const SessionUpdateNotification = jsonRpcNotification(
37 "session/update",
38 AcpSchema.SessionNotification,
39);
40const ElicitationCompleteNotification = jsonRpcNotification(
41 "elicitation/complete",
42 AcpSchema.CompleteElicitationNotification,
43);
44const RequestPermissionRequest = jsonRpcRequest(
45 "session/request_permission",
46 AcpSchema.RequestPermissionRequest,
47);
48const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
49const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
50const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
51const decodeSessionCancelNotification = Schema.decodeEffect(
52 Schema.fromJsonString(SessionCancelNotification),
53);
54const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
55const decodeRequestPermissionResponse = Schema.decodeEffect(
56 Schema.fromJsonString(RequestPermissionResponse),
57);
58const JsonRpcErrorResponse = Schema.Struct({
59 jsonrpc: Schema.Literal("2.0"),
60 id: Schema.Number,
61 error: Schema.Struct({ code: Schema.Number, message: Schema.String }),
62});
63const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
64const encoder = new TextEncoder();
65const MIB = 1024 * 1024;
66const decodeIndex = Schema.decodeUnknownSync(Schema.Struct({ index: Schema.Number }));
67const largeNotification = (index: number, textLength: number) =>
68 encoder.encode(
69 `${encodeUnknownJsonString({
70 jsonrpc: "2.0",
71 method: "x/large",
72 params: { index, text: "x".repeat(textLength) },
73 })}\n`,
74 );
75const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
76 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
77);
78const mockPeerArgs = (path: string) => [path];
79
80const makeHandle = (env?: Record<string, string>) =>
81 Effect.gen(function* () {
82 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
83 const path = yield* Path.Path;
84 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
85 cwd: path.join(import.meta.dirname, ".."),
86 ...(env ? { env: { ...process.env, ...env } } : {}),
87 });
88 return yield* spawner.spawn(command);
89 });
90
91it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
92 it.effect(
93 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
94 () =>
95 Effect.gen(function* () {
96 const { stdio, input, output } = yield* makeInMemoryStdio();
97 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
98 stdio,
99 serverRequestMethods: new Set(),
100 });
101
102 const notifications =
103 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
104 yield* transport.incoming.pipe(
105 Stream.take(2),
106 Stream.runCollect,
107 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
108 Effect.forkScoped,
109 );
110
111 yield* transport.notify("session/cancel", { sessionId: "session-1" });
112 const outbound = yield* Queue.take(output);
113 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
114 jsonrpc: "2.0",
115 method: "session/cancel",
116 params: {
117 sessionId: "session-1",
118 },
119 });
120
121 const updateFrame = yield* encodeJsonl(SessionUpdateNotification, {
122 jsonrpc: "2.0",
123 method: "session/update",
124 params: {
125 sessionId: "session-1",
126 update: {
127 sessionUpdate: "plan",
128 entries: [
129 {
130 content: "Inspect repository",
131 priority: "high",
132 status: "in_progress",
133 },
134 ],
135 },
136 },
137 });
138 const completionFrame = yield* encodeJsonl(ElicitationCompleteNotification, {
139 jsonrpc: "2.0",
140 method: "elicitation/complete",
141 params: {
142 elicitationId: "elicitation-1",
143 },
144 });
145
146 // Frames split across reads, with one read ending one frame and starting the next.
147 const wire = new Uint8Array([...updateFrame, ...completionFrame]);
148 const splits = [10, updateFrame.length + 10, wire.length];
149 let start = 0;
150 for (const end of splits) {
151 yield* Queue.offer(input, wire.subarray(start, end));
152 start = end;
153 }
154
155 const [update, completion] = yield* Deferred.await(notifications);
156 assert.equal(update?._tag, "SessionUpdate");
157 assert.equal(completion?._tag, "ElicitationComplete");
158 }),
159 );
160
161 it.effect("keeps only recent raw notifications after their callbacks run", () =>
162 Effect.gen(function* () {
163 const { stdio, input } = yield* makeInMemoryStdio();
164 const handled = yield* Deferred.make<void>();
165 let handledCount = 0;
166 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
167 stdio,
168 serverRequestMethods: new Set(),
169 onNotification: () =>
170 Effect.sync(() => ++handledCount).pipe(
171 Effect.flatMap((count) =>
172 count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
173 ),
174 ),
175 });
176
177 const messages = Array.from({ length: 64 }, (_, index) =>
178 encodeUnknownJsonString({
179 jsonrpc: "2.0",
180 method: "x/performance",
181 params: { index },
182 }),
183 );
184 yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
185 yield* Deferred.await(handled);
186
187 const retained = yield* transport.incoming.pipe(Stream.take(32), Stream.runCollect);
188
189 assert.equal(handledCount, 64);
190 assert.equal(retained.length, 32);
191 assert.deepEqual(retained[0]?.params, { index: 32 });
192 assert.deepEqual(retained[31]?.params, { index: 63 });
193 }),
194 );
195
196 it.effect("keeps the newest unread raw notifications whose JSON fits in 16Mi characters", () =>
197 Effect.gen(function* () {
198 const { stdio, input } = yield* makeInMemoryStdio();
199 const handled = yield* Queue.unbounded<number>();
200 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
201 stdio,
202 serverRequestMethods: new Set(),
203 onNotification: (notification) =>
204 Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
205 });
206
207 // Ten 3 MiB notifications: only the newest five fit in the budget.
208 for (let index = 0; index < 10; index++) {
209 yield* Queue.offer(input, largeNotification(index, 3 * MIB));
210 assert.equal(yield* Queue.take(handled), index);
211 }
212
213 const retained = yield* transport.incoming.pipe(Stream.take(5), Stream.runCollect);
214 assert.deepEqual(
215 retained.map((notification) => decodeIndex(notification.params).index),
216 [5, 6, 7, 8, 9],
217 );
218 }),
219 );
220
221 it.effect("keeps a single unread raw notification that alone exceeds the budget", () =>
222 Effect.gen(function* () {
223 const { stdio, input } = yield* makeInMemoryStdio();
224 const handled = yield* Queue.unbounded<number>();
225 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
226 stdio,
227 serverRequestMethods: new Set(),
228 onNotification: (notification) =>
229 Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
230 });
231
232 yield* Queue.offer(input, largeNotification(0, 1));
233 yield* Queue.take(handled);
234 yield* Queue.offer(input, largeNotification(1, 17 * MIB));
235 yield* Queue.take(handled);
236
237 const [retained] = yield* transport.incoming.pipe(Stream.take(1), Stream.runCollect);
238 assert.equal(decodeIndex(retained?.params).index, 1);
239 }),
240 );
241
242 it.effect("evicts unread raw notifications while a slow reader handles an earlier one", () =>
243 Effect.gen(function* () {
244 const { stdio, input } = yield* makeInMemoryStdio();
245 const handled = yield* Queue.unbounded<number>();
246 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
247 stdio,
248 serverRequestMethods: new Set(),
249 onNotification: (notification) =>
250 Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
251 });
252 const send = (index: number, textLength: number) =>
253 Queue.offer(input, largeNotification(index, textLength)).pipe(
254 Effect.andThen(Queue.take(handled)),
255 );
256
257 yield* send(1, 6 * MIB);
258 yield* send(2, 6 * MIB);
259 const entered = yield* Deferred.make<void>();
260 const release = yield* Deferred.make<void>();
261 const reader = yield* transport.incoming.pipe(
262 Stream.map((notification) => decodeIndex(notification.params).index),
263 Stream.tap((index) =>
264 index === 1
265 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release)))
266 : Effect.void,
267 ),
268 Stream.take(4),
269 Stream.runCollect,
270 Effect.forkScoped,
271 );
272 yield* Deferred.await(entered);
273
274 // Notification 2 is still unread, so 3 and 4 push it past the budget.
275 yield* send(3, 6 * MIB);
276 yield* send(4, 6 * MIB);
277 yield* send(5, 1);
278 yield* Deferred.succeed(release, undefined);
279
280 assert.deepEqual(yield* Fiber.join(reader), [1, 3, 4, 5]);
281 }),
282 );
283
284 it.effect("delivers every raw notification to a reader that keeps up, then ends", () =>
285 Effect.gen(function* () {
286 const { stdio, input } = yield* makeInMemoryStdio();
287 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
288 stdio,
289 serverRequestMethods: new Set(),
290 });
291 const received = yield* Queue.unbounded<number>();
292 const reader = yield* transport.incoming.pipe(
293 Stream.map((notification) => decodeIndex(notification.params).index),
294 Stream.tap((index) => Queue.offer(received, index)),
295 Stream.runCollect,
296 Effect.forkScoped,
297 );
298
299 // 30 MiB in total, well past the unread budget.
300 for (let index = 0; index < 10; index++) {
301 yield* Queue.offer(input, largeNotification(index, 3 * MIB));
302 assert.equal(yield* Queue.take(received), index);
303 }
304 yield* Queue.end(input);
305
306 assert.deepEqual(yield* Fiber.join(reader), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
307 }),
308 );
309
310 it.effect("ends the raw notification stream when the connection scope closes", () =>
311 Effect.gen(function* () {
312 const { stdio } = yield* makeInMemoryStdio();
313 const connection = yield* Scope.make();
314 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
315 stdio,
316 serverRequestMethods: new Set(),
317 }).pipe(Scope.provide(connection));
318 const reader = yield* transport.incoming.pipe(Stream.runCollect, Effect.forkScoped);
319
320 yield* Scope.close(connection, Exit.void);
321
322 assert.deepEqual(yield* Fiber.join(reader), []);
323 }),
324 );
325
326 it.effect("keeps the ended raw backlog intact when notifications arrive after termination", () =>
327 Effect.gen(function* () {
328 const { stdio, input } = yield* makeInMemoryStdio();
329 const handled = yield* Queue.unbounded<number>();
330 const terminated = yield* Deferred.make<void>();
331 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
332 stdio: Stdio.make({
333 args: stdio.args,
334 stdin: stdio.stdin,
335 stdout: () => Sink.forEach(() => Effect.die("stdout failed")),
336 stderr: () => Sink.drain,
337 }),
338 serverRequestMethods: new Set(),
339 onNotification: (notification) =>
340 Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
341 onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
342 });
343 const deliver = (index: number) =>
344 Queue.offer(
345 input,
346 encoder.encode(
347 `${encodeUnknownJsonString({ jsonrpc: "2.0", method: "x/late", params: { index } })}\n`,
348 ),
349 ).pipe(Effect.andThen(Queue.take(handled)));
350
351 for (let index = 0; index < 32; index++) {
352 assert.equal(yield* deliver(index), index);
353 }
354 // A failed write terminates the connection while the reader keeps running.
355 yield* transport.notify("x/fail", {}).pipe(Effect.exit);
356 yield* Deferred.await(terminated);
357 assert.equal(yield* deliver(32), 32);
358
359 const retained = yield* transport.incoming.pipe(
360 Stream.map((notification) => decodeIndex(notification.params).index),
361 Stream.runCollect,
362 );
363 assert.deepEqual(
364 retained,
365 Array.from({ length: 32 }, (_, index) => index),
366 );
367 }),
368 );
369
370 // clanka once sent a usage_update without `used` and `size`. One bad update
371 // must not end a session whose later updates are fine.
372 it.effect("drops a session/update that fails to decode and keeps reading", () =>
373 Effect.gen(function* () {
374 const secret = "acp-core-notification-secret-sentinel";
375 const { stdio, input } = yield* makeInMemoryStdio();
376 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
377 const warnings: Array<unknown> = [];
378 let terminated = false;
379 let transformCalls = 0;
380 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
381 stdio,
382 serverRequestMethods: new Set(),
383 logIncoming: true,
384 logger: (event) =>
385 Effect.sync(() => {
386 events.push(event);
387 }),
388 transformSessionUpdate: (notification) => {
389 transformCalls += 1;
390 return notification;
391 },
392 onTermination: () =>
393 Effect.sync(() => {
394 terminated = true;
395 }),
396 }).pipe(
397 Effect.provide(
398 Logger.layer([
399 Logger.make(({ logLevel, fiber }) => {
400 if (logLevel === "Warn")
401 warnings.push(fiber.getRef(References.CurrentLogAnnotations));
402 }),
403 ]),
404 ),
405 );
406 const received = yield* Deferred.make<AcpProtocol.AcpIncomingNotification>();
407 yield* transport.incoming.pipe(
408 Stream.runForEach((notification) => Deferred.succeed(received, notification)),
409 Effect.forkScoped,
410 );
411
412 const send = (params: unknown) =>
413 Queue.offer(
414 input,
415 encoder.encode(
416 `${encodeUnknownJsonString({ jsonrpc: "2.0", method: "session/update", params })}\n`,
417 ),
418 );
419 const malformed = {
420 sessionId: "session-1",
421 update: { sessionUpdate: "usage_update", cost: { amount: 1, currency: secret } },
422 };
423 yield* send(malformed);
424 yield* send(malformed);
425 yield* send({
426 sessionId: "session-1",
427 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
428 });
429
430 const notification = yield* TestClock.withLive(
431 Deferred.await(received).pipe(Effect.timeout("2 seconds")),
432 );
433 assert.equal(notification._tag, "SessionUpdate");
434 assert.deepEqual(notification.params, {
435 sessionId: "session-1",
436 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
437 });
438 assert.isFalse(terminated);
439 assert.equal(transformCalls, 1);
440
441 const decodeFailed = events.find(({ stage }) => stage === "decode_failed");
442 expect(decodeFailed?.payload).toMatchObject({
443 operation: "decode-notification-payload",
444 method: "session/update",
445 issueSummary: expect.stringContaining("update.used missing"),
446 });
447 assert.lengthOf(
448 events.filter(({ stage }) => stage === "decode_failed"),
449 2,
450 );
451 assert.lengthOf(warnings, 1);
452 expect(warnings[0]).toMatchObject({
453 issueSummary: expect.stringContaining("update.used missing"),
454 });
455 assert.notInclude(encodeUnknownJsonString({ decodeFailed, warnings }), secret);
456 }),
457 );
458
459 it.effect("terminates when a callback on the reader dies", () =>
460 Effect.gen(function* () {
461 const { stdio, input } = yield* makeInMemoryStdio();
462 const termination = yield* Deferred.make<AcpError.AcpError>();
463 yield* AcpProtocol.makeAcpPatchedProtocol({
464 stdio,
465 serverRequestMethods: new Set(),
466 transformSessionUpdate: () => {
467 throw new Error("normalizer bug");
468 },
469 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
470 });
471
472 yield* Queue.offer(
473 input,
474 encoder.encode(
475 `${encodeUnknownJsonString({
476 jsonrpc: "2.0",
477 method: "session/update",
478 params: {
479 sessionId: "session-1",
480 update: { sessionUpdate: "plan", entries: [] },
481 },
482 })}\n`,
483 ),
484 );
485
486 const error = yield* TestClock.withLive(
487 Deferred.await(termination).pipe(Effect.timeout("2 seconds")),
488 );
489 assert.instanceOf(error, AcpError.AcpTransportError);
490 assert.equal((error as AcpError.AcpTransportError).operation, "read-input-stream");
491 }),
492 );
493
494 // regression: #9154 notifications went out with `id` and `headers`, which Grok CLI drops
495 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
496 Effect.gen(function* () {
497 const { stdio } = yield* makeInMemoryStdio();
498 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
499 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
500 stdio,
501 serverRequestMethods: new Set(),
502 logOutgoing: true,
503 logger: (event) =>
504 Effect.sync(() => {
505 events.push(event);
506 }),
507 });
508
509 yield* transport.notify("session/cancel", { sessionId: "session-1" });
510
511 // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
512 assert.deepEqual(events, [
513 {
514 direction: "outgoing",
515 stage: "decoded",
516 payload: {
517 _tag: "Notification",
518 tag: "session/cancel",
519 payload: {
520 sessionId: "session-1",
521 },
522 },
523 },
524 {
525 direction: "outgoing",
526 stage: "raw",
527 payload:
528 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
529 },
530 ]);
531 }),
532 );
533
534 it.effect("logs decode failures without copying the cause or wire payload", () =>
535 Effect.gen(function* () {
536 const secret = "acp-wire-secret-sentinel";
537 const { stdio, input } = yield* makeInMemoryStdio();
538 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
539 const termination = yield* Deferred.make<AcpError.AcpError>();
540 yield* AcpProtocol.makeAcpPatchedProtocol({
541 stdio,
542 serverRequestMethods: new Set(),
543 logIncoming: true,
544 logger: (event) =>
545 Effect.sync(() => {
546 events.push(event);
547 }),
548 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
549 });
550
551 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
552 yield* Deferred.await(termination);
553
554 const event = events.find(({ stage }) => stage === "decode_failed");
555 assert.deepEqual(event, {
556 direction: "incoming",
557 stage: "decode_failed",
558 payload: {
559 operation: "decode-wire-message",
560 },
561 });
562 assert.notInclude(encodeUnknownJsonString(event), secret);
563 }),
564 );
565
566 it.effect("fails notification encoding through the declared ACP error channel", () =>
567 Effect.gen(function* () {
568 const { stdio } = yield* makeInMemoryStdio();
569 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
570 stdio,
571 serverRequestMethods: new Set(),
572 });
573
574 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
575 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
576 assert.equal(bigintError.operation, "encode-message");
577 assert.equal(bigintError.method, "x/test");
578 assert.isDefined(bigintError.cause);
579 assert.equal(
580 bigintError.message,
581 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
582 );
583
584 const circular: Record<string, unknown> = {};
585 circular.self = circular;
586 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
587 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
588 assert.equal(circularError.operation, "encode-message");
589 assert.equal(circularError.method, "x/test");
590 assert.isDefined(circularError.cause);
591
592 const requestError = yield* transport.request("x/request", 1n).pipe(
593 Effect.match({
594 onFailure: (error) => error,
595 onSuccess: () => assert.fail("Expected request encoding to fail"),
596 }),
597 );
598 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
599 assert.deepInclude(requestError, {
600 operation: "encode-message",
601 method: "x/request",
602 requestId: 1,
603 });
604 }),
605 );
606
607 it.effect("does not correlate a string response id with a numeric extension request id", () =>
608 Effect.gen(function* () {
609 const { stdio, input, output } = yield* makeInMemoryStdio();
610 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
611 stdio,
612 serverRequestMethods: new Set(),
613 });
614
615 const response = yield* transport
616 .request("x/test", { hello: "world" })
617 .pipe(Effect.forkScoped);
618 yield* Queue.take(output);
619 yield* Queue.offer(
620 input,
621 encoder.encode(
622 `${encodeUnknownJsonString({
623 jsonrpc: "2.0",
624 id: "1",
625 result: { ok: false },
626 })}\n`,
627 ),
628 );
629 yield* Effect.yieldNow;
630 assert.isUndefined(response.pollUnsafe());
631
632 yield* Queue.offer(
633 input,
634 yield* encodeJsonl(ExtResponse, {
635 jsonrpc: "2.0",
636 id: 1,
637 result: { ok: true },
638 }),
639 );
640 assert.deepEqual(yield* Fiber.join(response), { ok: true });
641 }),
642 );
643
644 it.effect("correlates extension response errors with the originating request", () =>
645 Effect.gen(function* () {
646 const { stdio, input, output } = yield* makeInMemoryStdio();
647 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
648 stdio,
649 serverRequestMethods: new Set(),
650 });
651
652 const response = yield* transport
653 .request("x/private", { hello: "world" })
654 .pipe(Effect.forkScoped);
655 yield* Queue.take(output);
656 yield* Queue.offer(
657 input,
658 encoder.encode(
659 `${encodeUnknownJsonString({
660 jsonrpc: "2.0",
661 id: 1,
662 error: {
663 _tag: "Cause",
664 code: -32602,
665 message: "Invalid params",
666 data: [
667 {
668 _tag: "Fail",
669 error: {
670 code: -32602,
671 message: "Invalid params",
672 data: { field: "hello" },
673 },
674 },
675 ],
676 },
677 })}\n`,
678 ),
679 );
680
681 const error = yield* Fiber.join(response).pipe(
682 Effect.match({
683 onFailure: (error) => error,
684 onSuccess: () => assert.fail("Expected extension request to fail"),
685 }),
686 );
687 assert.instanceOf(error, AcpError.AcpRequestError);
688 assert.deepInclude(error, {
689 code: -32602,
690 errorMessage: "Invalid params",
691 method: "x/private",
692 requestId: 1,
693 operation: "receive-response",
694 });
695 }),
696 );
697
698 it.effect("preserves application error data in outgoing extension responses", () =>
699 Effect.gen(function* () {
700 const { stdio, input, output } = yield* makeInMemoryStdio();
701 const acknowledged = yield* Deferred.make<string>();
702 yield* AcpProtocol.makeAcpPatchedProtocol({
703 stdio,
704 serverRequestMethods: new Set(),
705 onExtRequest: () =>
706 Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
707 onOutgoingResponse: (requestId) =>
708 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
709 });
710
711 yield* Queue.offer(
712 input,
713 encoder.encode(
714 encodeUnknownJsonString({
715 jsonrpc: "2.0",
716 id: "peer-1",
717 method: "x/test",
718 params: {},
719 }) + "\n",
720 ),
721 );
722
723 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
724 jsonrpc: "2.0",
725 id: "peer-1",
726 error: { code: -32602, message: "bad input", data: { field: "name" } },
727 });
728 assert.equal(yield* Deferred.await(acknowledged), "peer-1");
729 }),
730 );
731
732 it.effect("completes a batch with successful and failed extension responses", () =>
733 Effect.gen(function* () {
734 const { stdio, input, output } = yield* makeInMemoryStdio();
735 const acknowledgements = yield* Queue.unbounded<string>();
736 yield* AcpProtocol.makeAcpPatchedProtocol({
737 stdio,
738 serverRequestMethods: new Set(),
739 onExtRequest: (method) =>
740 method === "x/success"
741 ? Effect.succeed({ ok: true })
742 : Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
743 onOutgoingResponse: (requestId) => Queue.offer(acknowledgements, requestId),
744 });
745
746 yield* Queue.offer(
747 input,
748 encoder.encode(
749 encodeUnknownJsonString([
750 { jsonrpc: "2.0", id: 0, method: "x/success", params: {} },
751 { jsonrpc: "2.0", id: "peer-1", method: "x/failure", params: {} },
752 ]) + "\n",
753 ),
754 );
755
756 assert.deepEqual(JSON.parse(yield* Queue.take(output)), [
757 { jsonrpc: "2.0", id: 0, result: { ok: true } },
758 {
759 jsonrpc: "2.0",
760 id: "peer-1",
761 error: { code: -32602, message: "bad input", data: { field: "name" } },
762 },
763 ]);
764 assert.equal(yield* Queue.take(acknowledgements), "peer-1");
765 }),
766 );
767
768 it.effect.each([
769 {
770 name: "typed failure",
771 cause: [{ _tag: "Fail", error: { code: -32602, message: "bad input", data: null } }],
772 error: { code: -32602, message: "bad input", data: null },
773 },
774 {
775 name: "typed failure with interruption",
776 cause: [
777 { _tag: "Fail", error: { code: -32602, message: "bad input", data: { field: "name" } } },
778 { _tag: "Interrupt", fiberId: null },
779 ],
780 error: { code: -32602, message: "bad input", data: { field: "name" } },
781 },
782 {
783 name: "defect",
784 cause: [{ _tag: "Die", defect: "private defect" }],
785 error: { code: -32603, message: "Internal error" },
786 },
787 {
788 name: "failure with a defect",
789 cause: [
790 { _tag: "Fail", error: { code: -32602, message: "bad input" } },
791 { _tag: "Die", defect: "private defect" },
792 ],
793 error: { code: -32603, message: "Internal error" },
794 },
795 ] as const)("emits a standard ACP error for a core $name", ({ cause, error }) =>
796 Effect.gen(function* () {
797 const { stdio, output } = yield* makeInMemoryStdio();
798 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
799 stdio,
800 serverRequestMethods: new Set(),
801 });
802
803 yield* transport.serverProtocol.send(0, {
804 _tag: "Exit",
805 requestId: 0,
806 exit: { _tag: "Failure", cause },
807 });
808
809 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
810 jsonrpc: "2.0",
811 id: 0,
812 error,
813 });
814 }),
815 );
816
817 it.effect("answers an extension request whose handler also dies as an internal error", () =>
818 Effect.gen(function* () {
819 const { stdio, input, output } = yield* makeInMemoryStdio();
820 yield* AcpProtocol.makeAcpPatchedProtocol({
821 stdio,
822 serverRequestMethods: new Set(),
823 onExtRequest: () =>
824 Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
825 Effect.ensuring(Effect.die(new Error("cleanup bug"))),
826 ),
827 });
828
829 yield* Queue.offer(
830 input,
831 yield* encodeJsonl(ExtRequest, {
832 jsonrpc: "2.0",
833 id: 9,
834 method: "x/test",
835 params: { hello: "world" },
836 headers: [],
837 }),
838 );
839 const decodeJsonRpcErrorResponse = Schema.decodeEffect(
840 Schema.fromJsonString(JsonRpcErrorResponse),
841 );
842
843 const response = yield* decodeJsonRpcErrorResponse(yield* Queue.take(output));
844 assert.equal(response.id, 9);
845 assert.equal(response.error.code, -32603);
846 }),
847 );
848
849 it.effect("preserves zero-valued ids for inbound core client requests", () =>
850 Effect.gen(function* () {
851 const { stdio, input, output } = yield* makeInMemoryStdio();
852 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
853 stdio,
854 serverRequestMethods: new Set(["session/request_permission"]),
855 });
856 const inboundRequest = yield* Deferred.make<unknown>();
857
858 yield* transport.serverProtocol
859 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
860 .pipe(Effect.forkScoped);
861
862 yield* Queue.offer(
863 input,
864 yield* encodeJsonl(RequestPermissionRequest, {
865 jsonrpc: "2.0",
866 id: 0,
867 method: "session/request_permission",
868 params: {
869 sessionId: "session-1",
870 title: "Allow mock action",
871 subject: {
872 type: "tool_call",
873 toolCall: {
874 toolCallId: "tool-1",
875 title: "Allow mock action",
876 },
877 },
878 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
879 },
880 headers: [],
881 }),
882 );
883
884 const message = yield* Deferred.await(inboundRequest);
885 assert.deepEqual(message, {
886 _tag: "Request",
887 id: 0,
888 tag: "session/request_permission",
889 payload: {
890 sessionId: "session-1",
891 title: "Allow mock action",
892 subject: {
893 type: "tool_call",
894 toolCall: {
895 toolCallId: "tool-1",
896 title: "Allow mock action",
897 },
898 },
899 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
900 },
901 headers: [],
902 });
903
904 yield* transport.serverProtocol.send(0, {
905 _tag: "Exit",
906 requestId: 0,
907 exit: {
908 _tag: "Success",
909 value: {
910 outcome: {
911 outcome: "selected",
912 optionId: "allow",
913 },
914 },
915 },
916 });
917
918 const outbound = yield* Queue.take(output);
919 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
920 jsonrpc: "2.0",
921 id: 0,
922 result: {
923 outcome: {
924 outcome: "selected",
925 optionId: "allow",
926 },
927 },
928 });
929 }),
930 );
931
932 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
933 Effect.gen(function* () {
934 const { stdio } = yield* makeInMemoryStdio();
935 const acknowledged = yield* Deferred.make<string>();
936 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
937 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
938 stdio,
939 serverRequestMethods: new Set(),
940 onOutgoingResponse: (requestId) =>
941 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
942 onOutgoingResponseFailure: (requestId, error) =>
943 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
944 });
945
946 yield* transport.serverProtocol.send(0, {
947 _tag: "Exit",
948 requestId: "success-1",
949 exit: { _tag: "Success", value: { ok: true } },
950 });
951 assert.equal(yield* Deferred.await(acknowledged), "success-1");
952
953 const circular: { self?: unknown } = {};
954 circular.self = circular;
955 yield* transport.serverProtocol
956 .send(0, {
957 _tag: "Exit",
958 requestId: "failure-1",
959 exit: { _tag: "Success", value: circular },
960 })
961 .pipe(Effect.exit);
962 const [requestId, error] = yield* Deferred.await(failed);
963 assert.equal(requestId, "failure-1");
964 assert.instanceOf(error, AcpError.AcpProtocolParseError);
965 }),
966 );
967
968 it.effect("acknowledges a response only after the stdout write completes", () =>
969 Effect.gen(function* () {
970 const writeStarted = yield* Deferred.make<void>();
971 const releaseWrite = yield* Deferred.make<void>();
972 const acknowledged = yield* Deferred.make<string>();
973 const stdio = Stdio.make({
974 args: Effect.succeed([]),
975 stdin: Stream.never,
976 stdout: () =>
977 Sink.forEach(() =>
978 Deferred.succeed(writeStarted, undefined).pipe(
979 Effect.andThen(Deferred.await(releaseWrite)),
980 ),
981 ),
982 stderr: () => Sink.drain,
983 });
984 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
985 stdio,
986 serverRequestMethods: new Set(),
987 onOutgoingResponse: (requestId) =>
988 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
989 });
990 const sendFiber = yield* transport.serverProtocol
991 .send(0, {
992 _tag: "Exit",
993 requestId: "held-write",
994 exit: { _tag: "Success", value: { ok: true } },
995 })
996 .pipe(Effect.forkScoped);
997
998 yield* Deferred.await(writeStarted);
999 assert.isUndefined(sendFiber.pollUnsafe());
1000 assert.isFalse(yield* Deferred.isDone(acknowledged));
1001 yield* Deferred.succeed(releaseWrite, undefined);
1002 yield* Fiber.join(sendFiber);
1003 assert.equal(yield* Deferred.await(acknowledged), "held-write");
1004 }),
1005 );
1006
1007 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
1008 Effect.gen(function* () {
1009 const writeStarted = yield* Deferred.make<void>();
1010 const releaseFailure = yield* Deferred.make<void>();
1011 const failures = yield* Queue.unbounded<string>();
1012 const terminated = yield* Deferred.make<AcpError.AcpError>();
1013 const stdio = Stdio.make({
1014 args: Effect.succeed([]),
1015 stdin: Stream.never,
1016 stdout: () =>
1017 Sink.forEach(() =>
1018 Deferred.succeed(writeStarted, undefined).pipe(
1019 Effect.andThen(Deferred.await(releaseFailure)),
1020 Effect.andThen(Effect.die("stdout failed")),
1021 ),
1022 ),
1023 stderr: () => Sink.drain,
1024 });
1025 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1026 stdio,
1027 serverRequestMethods: new Set(),
1028 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1029 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1030 });
1031 const send = (requestId: string) =>
1032 transport.serverProtocol
1033 .send(0, {
1034 _tag: "Exit",
1035 requestId,
1036 exit: { _tag: "Success", value: { ok: true } },
1037 })
1038 .pipe(Effect.exit);
1039 const current = yield* send("current").pipe(Effect.forkScoped);
1040 yield* Deferred.await(writeStarted);
1041 const queued = yield* send("queued").pipe(Effect.forkScoped);
1042 yield* Effect.yieldNow;
1043 assert.isUndefined(current.pollUnsafe());
1044 assert.isUndefined(queued.pollUnsafe());
1045 yield* Deferred.succeed(releaseFailure, undefined);
1046 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
1047 yield* Fiber.join(current);
1048 yield* Fiber.join(queued);
1049 yield* send("future");
1050
1051 assert.deepEqual(
1052 new Set(yield* Queue.takeN(failures, 3)),
1053 new Set(["current", "queued", "future"]),
1054 );
1055 }),
1056 );
1057
1058 it.effect(
1059 "atomically rejects an admitted response when the writer closes before queue offer",
1060 () =>
1061 Effect.gen(function* () {
1062 const admitted = yield* Deferred.make<void>();
1063 const releaseAdmission = yield* Deferred.make<void>();
1064 const failures = yield* Queue.unbounded<string>();
1065 const protocolScope = yield* Scope.make();
1066 const stdio = Stdio.make({
1067 args: Effect.succeed([]),
1068 stdin: Stream.never,
1069 stdout: () => Sink.drain,
1070 stderr: () => Sink.drain,
1071 });
1072 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1073 stdio,
1074 serverRequestMethods: new Set(),
1075 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1076 testHooks: {
1077 onOutgoingWriteAdmitted: () =>
1078 Deferred.succeed(admitted, undefined).pipe(
1079 Effect.andThen(Deferred.await(releaseAdmission)),
1080 ),
1081 },
1082 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
1083 const send = (requestId: string) =>
1084 transport.serverProtocol
1085 .send(0, {
1086 _tag: "Exit",
1087 requestId,
1088 exit: { _tag: "Success", value: { ok: true } },
1089 })
1090 .pipe(Effect.exit);
1091 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
1092
1093 yield* Deferred.await(admitted);
1094 yield* Scope.close(protocolScope, Exit.void);
1095 yield* Deferred.succeed(releaseAdmission, undefined);
1096 yield* Fiber.join(admittedSend);
1097 yield* send("future");
1098
1099 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
1100 }),
1101 );
1102
1103 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
1104 Effect.gen(function* () {
1105 const { stdio, input } = yield* makeInMemoryStdio();
1106 const notifications =
1107 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
1108 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1109 stdio,
1110 serverRequestMethods: new Set(),
1111 });
1112
1113 yield* transport.incoming.pipe(
1114 Stream.take(1),
1115 Stream.runCollect,
1116 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
1117 Effect.forkScoped,
1118 );
1119
1120 yield* Queue.offer(
1121 input,
1122 encoder.encode(
1123 `${encodeUnknownJsonString({
1124 jsonrpc: "2.0",
1125 id: "skills-reload",
1126 result: {
1127 reloaded: true,
1128 },
1129 })}\n`,
1130 ),
1131 );
1132 yield* Queue.offer(
1133 input,
1134 yield* encodeJsonl(SessionUpdateNotification, {
1135 jsonrpc: "2.0",
1136 method: "session/update",
1137 params: {
1138 sessionId: "session-1",
1139 update: {
1140 sessionUpdate: "plan",
1141 entries: [
1142 {
1143 content: "Reload skills",
1144 priority: "high",
1145 status: "in_progress",
1146 },
1147 ],
1148 },
1149 },
1150 }),
1151 );
1152
1153 const [update] = yield* Deferred.await(notifications);
1154 assert.equal(update?._tag, "SessionUpdate");
1155 }),
1156 );
1157
1158 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
1159 Effect.gen(function* () {
1160 const { stdio, input, output } = yield* makeInMemoryStdio();
1161 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1162 stdio,
1163 serverRequestMethods: new Set(),
1164 });
1165 const lateResponse = yield* Deferred.make<unknown>();
1166
1167 yield* transport.clientProtocol
1168 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
1169 .pipe(Effect.forkScoped);
1170
1171 const response = yield* transport
1172 .request("x/test", { hello: "world" })
1173 .pipe(Effect.forkScoped);
1174 const outbound = yield* Queue.take(output);
1175 assert.deepEqual(yield* decodeExtRequest(outbound), {
1176 jsonrpc: "2.0",
1177 id: 1,
1178 method: "x/test",
1179 params: {
1180 hello: "world",
1181 },
1182 headers: [],
1183 });
1184
1185 yield* Fiber.interrupt(response);
1186 yield* Queue.offer(
1187 input,
1188 yield* encodeJsonl(ExtResponse, {
1189 jsonrpc: "2.0",
1190 id: 1,
1191 result: {
1192 ok: true,
1193 },
1194 }),
1195 );
1196
1197 const message = yield* Deferred.await(lateResponse);
1198 assert.deepEqual(message, {
1199 _tag: "Exit",
1200 requestId: 1,
1201 exit: {
1202 _tag: "Success",
1203 value: {
1204 ok: true,
1205 },
1206 },
1207 });
1208 }),
1209 );
1210
1211 it.effect("fails pending and later requests when input ends before the process exits", () =>
1212 Effect.gen(function* () {
1213 const { stdio, input, output } = yield* makeInMemoryStdio();
1214 const termination = yield* Deferred.make<AcpError.AcpError>();
1215 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1216 stdio,
1217 terminationError: Effect.never,
1218 serverRequestMethods: new Set(),
1219 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1220 });
1221 const pending = yield* transport
1222 .request("x/test", { hello: "world" })
1223 .pipe(Effect.flip, Effect.orDie, Effect.forkScoped);
1224 yield* Queue.take(output);
1225 yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","id":1,"result":'));
1226 yield* Queue.end(input);
1227
1228 const error = yield* Deferred.await(termination);
1229 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
1230 assert.strictEqual(yield* Fiber.join(pending), error);
1231 assert.strictEqual(
1232 yield* transport.request("x/test", { hello: "later" }).pipe(Effect.flip, Effect.orDie),
1233 error,
1234 );
1235 assert.strictEqual(
1236 yield* transport.notify("session/cancel", { sessionId: "session-1" }).pipe(Effect.flip),
1237 error,
1238 );
1239 }),
1240 );
1241
1242 it.effect("answers a pending request from a final response without a trailing newline", () =>
1243 Effect.gen(function* () {
1244 const { stdio, input, output } = yield* makeInMemoryStdio();
1245 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1246 stdio,
1247 serverRequestMethods: new Set(),
1248 });
1249 const pending = yield* transport
1250 .request("x/test", { hello: "world" })
1251 .pipe(Effect.forkScoped);
1252 yield* Queue.take(output);
1253 yield* Queue.offer(
1254 input,
1255 encoder.encode(encodeUnknownJsonString({ jsonrpc: "2.0", id: 1, result: { ok: true } })),
1256 );
1257 yield* Queue.end(input);
1258
1259 assert.deepEqual(yield* Fiber.join(pending), { ok: true });
1260 }),
1261 );
1262
1263 it.effect("propagates the real child exit code when the input stream ends", () =>
1264 Effect.gen(function* () {
1265 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
1266 const firstMessage = yield* Deferred.make<unknown>();
1267 const termination = yield* Deferred.make<AcpError.AcpError>();
1268 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1269 stdio: makeChildStdio(handle),
1270 terminationError: makeTerminationError(handle),
1271 serverRequestMethods: new Set(),
1272 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1273 });
1274
1275 yield* transport.clientProtocol
1276 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1277 .pipe(Effect.forkScoped);
1278
1279 const message = yield* Deferred.await(firstMessage);
1280 const exitError = yield* Deferred.await(termination);
1281 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
1282 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
1283 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1284 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1285 readonly _tag: string;
1286 readonly message: string;
1287 readonly cause: unknown;
1288 };
1289 assert.equal(defect._tag, "RpcClientDefect");
1290 assert.equal(defect.message, "ACP protocol terminated.");
1291 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
1292 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
1293 }),
1294 );
1295
1296 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
1297 Effect.gen(function* () {
1298 const { stdio, input } = yield* makeInMemoryStdio();
1299 const terminations = yield* Ref.make(0);
1300 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
1301 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1302 stdio,
1303 serverRequestMethods: new Set(),
1304 onTermination: () => Ref.update(terminations, (count) => count + 1),
1305 testHooks: {
1306 onOutgoingWriterExit: (detail) =>
1307 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
1308 },
1309 });
1310
1311 yield* transport.serverProtocol.end(0);
1312 const exitDetail = yield* Deferred.await(writerExit);
1313 assert.isTrue(exitDetail.intentionalEnd);
1314 assert.equal(yield* Ref.get(terminations), 0);
1315
1316 yield* Queue.end(input);
1317 }),
1318 );
1319
1320 it.effect("does not emit a second process-exit error after a decode failure", () =>
1321 Effect.gen(function* () {
1322 const handle = yield* makeHandle({
1323 ACP_MOCK_MALFORMED_OUTPUT: "1",
1324 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
1325 });
1326 const terminationCalls = yield* Ref.make(0);
1327 const firstMessage = yield* Deferred.make<unknown>();
1328 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1329 stdio: makeChildStdio(handle),
1330 terminationError: makeTerminationError(handle),
1331 serverRequestMethods: new Set(),
1332 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
1333 });
1334
1335 yield* transport.clientProtocol
1336 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1337 .pipe(Effect.forkScoped);
1338
1339 const message = yield* Deferred.await(firstMessage);
1340 assert.equal(yield* Ref.get(terminationCalls), 1);
1341 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1342 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1343 readonly _tag: string;
1344 readonly message: string;
1345 readonly cause: unknown;
1346 };
1347 assert.equal(defect._tag, "RpcClientDefect");
1348 assert.equal(defect.message, "ACP protocol terminated.");
1349 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1350 }),
1351 );
1352
1353 it.effect.each(["request", "notification"] as const)(
1354 "rejects a %s if the connection ends while its logger is running",
1355 (operation) =>
1356 Effect.gen(function* () {
1357 const { stdio, input, output } = yield* makeInMemoryStdio();
1358 const writeStarted = yield* Deferred.make<void>();
1359 const releaseWrite = yield* Deferred.make<void>();
1360 const terminated = yield* Deferred.make<AcpError.AcpError>();
1361 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1362 stdio,
1363 serverRequestMethods: new Set(),
1364 logOutgoing: true,
1365 logger: (event) =>
1366 event.stage === "raw"
1367 ? Deferred.succeed(writeStarted, undefined).pipe(
1368 Effect.andThen(Deferred.await(releaseWrite)),
1369 )
1370 : Effect.void,
1371 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1372 });
1373 const send = yield* (
1374 operation === "request"
1375 ? transport.request("x/test", { hello: "world" })
1376 : transport.notify("session/cancel", { sessionId: "session-1" })
1377 ).pipe(Effect.forkScoped);
1378
1379 yield* Deferred.await(writeStarted);
1380 yield* Queue.end(input);
1381 const error = yield* Deferred.await(terminated);
1382 yield* Deferred.succeed(releaseWrite, undefined);
1383
1384 const failure = yield* Fiber.join(send).pipe(
1385 Effect.match({
1386 onFailure: (failure) => failure,
1387 onSuccess: () => assert.fail("Expected the send to fail after termination"),
1388 }),
1389 );
1390 assert.strictEqual(failure, error);
1391 assert.equal(yield* Queue.size(output), 0);
1392 }),
1393 );
1394});