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("skips blank lines between agent messages", () =>
535 Effect.gen(function* () {
536 const { stdio, input } = yield* makeInMemoryStdio();
537 const outcome = yield* Deferred.make<string>();
538 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
539 stdio,
540 serverRequestMethods: new Set(),
541 onTermination: (error) => Deferred.succeed(outcome, error._tag).pipe(Effect.asVoid),
542 });
543 yield* transport.incoming.pipe(
544 Stream.runForEach((notification) => Deferred.succeed(outcome, notification._tag)),
545 Effect.forkScoped,
546 );
547
548 const update = encodeUnknownJsonString({
549 jsonrpc: "2.0",
550 method: "session/update",
551 params: { sessionId: "session-1", update: { sessionUpdate: "plan", entries: [] } },
552 });
553 yield* Queue.offer(input, encoder.encode(`\n\r\n \t\n${update}\n\n`));
554
555 assert.equal(yield* Deferred.await(outcome), "SessionUpdate");
556 }),
557 );
558
559 it.effect("logs decode failures without copying the cause or wire payload", () =>
560 Effect.gen(function* () {
561 const secret = "acp-wire-secret-sentinel";
562 const { stdio, input } = yield* makeInMemoryStdio();
563 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
564 const termination = yield* Deferred.make<AcpError.AcpError>();
565 yield* AcpProtocol.makeAcpPatchedProtocol({
566 stdio,
567 serverRequestMethods: new Set(),
568 logIncoming: true,
569 logger: (event) =>
570 Effect.sync(() => {
571 events.push(event);
572 }),
573 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
574 });
575
576 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
577 yield* Deferred.await(termination);
578
579 const event = events.find(({ stage }) => stage === "decode_failed");
580 assert.deepEqual(event, {
581 direction: "incoming",
582 stage: "decode_failed",
583 payload: {
584 operation: "decode-wire-message",
585 },
586 });
587 assert.notInclude(encodeUnknownJsonString(event), secret);
588 }),
589 );
590
591 it.effect("fails notification encoding through the declared ACP error channel", () =>
592 Effect.gen(function* () {
593 const { stdio } = yield* makeInMemoryStdio();
594 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
595 stdio,
596 serverRequestMethods: new Set(),
597 });
598
599 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
600 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
601 assert.equal(bigintError.operation, "encode-message");
602 assert.equal(bigintError.method, "x/test");
603 assert.isDefined(bigintError.cause);
604 assert.equal(
605 bigintError.message,
606 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
607 );
608
609 const circular: Record<string, unknown> = {};
610 circular.self = circular;
611 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
612 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
613 assert.equal(circularError.operation, "encode-message");
614 assert.equal(circularError.method, "x/test");
615 assert.isDefined(circularError.cause);
616
617 const requestError = yield* transport.request("x/request", 1n).pipe(
618 Effect.match({
619 onFailure: (error) => error,
620 onSuccess: () => assert.fail("Expected request encoding to fail"),
621 }),
622 );
623 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
624 assert.deepInclude(requestError, {
625 operation: "encode-message",
626 method: "x/request",
627 requestId: 1,
628 });
629 }),
630 );
631
632 it.effect("does not correlate a string response id with a numeric extension request id", () =>
633 Effect.gen(function* () {
634 const { stdio, input, output } = yield* makeInMemoryStdio();
635 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
636 stdio,
637 serverRequestMethods: new Set(),
638 });
639
640 const response = yield* transport
641 .request("x/test", { hello: "world" })
642 .pipe(Effect.forkScoped);
643 yield* Queue.take(output);
644 yield* Queue.offer(
645 input,
646 encoder.encode(
647 `${encodeUnknownJsonString({
648 jsonrpc: "2.0",
649 id: "1",
650 result: { ok: false },
651 })}\n`,
652 ),
653 );
654 yield* Effect.yieldNow;
655 assert.isUndefined(response.pollUnsafe());
656
657 yield* Queue.offer(
658 input,
659 yield* encodeJsonl(ExtResponse, {
660 jsonrpc: "2.0",
661 id: 1,
662 result: { ok: true },
663 }),
664 );
665 assert.deepEqual(yield* Fiber.join(response), { ok: true });
666 }),
667 );
668
669 it.effect("correlates extension response errors with the originating request", () =>
670 Effect.gen(function* () {
671 const { stdio, input, output } = yield* makeInMemoryStdio();
672 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
673 stdio,
674 serverRequestMethods: new Set(),
675 });
676
677 const response = yield* transport
678 .request("x/private", { hello: "world" })
679 .pipe(Effect.forkScoped);
680 yield* Queue.take(output);
681 yield* Queue.offer(
682 input,
683 encoder.encode(
684 `${encodeUnknownJsonString({
685 jsonrpc: "2.0",
686 id: 1,
687 error: {
688 _tag: "Cause",
689 code: -32602,
690 message: "Invalid params",
691 data: [
692 {
693 _tag: "Fail",
694 error: {
695 code: -32602,
696 message: "Invalid params",
697 data: { field: "hello" },
698 },
699 },
700 ],
701 },
702 })}\n`,
703 ),
704 );
705
706 const error = yield* Fiber.join(response).pipe(
707 Effect.match({
708 onFailure: (error) => error,
709 onSuccess: () => assert.fail("Expected extension request to fail"),
710 }),
711 );
712 assert.instanceOf(error, AcpError.AcpRequestError);
713 assert.deepInclude(error, {
714 code: -32602,
715 errorMessage: "Invalid params",
716 method: "x/private",
717 requestId: 1,
718 operation: "receive-response",
719 });
720 }),
721 );
722
723 it.effect("preserves application error data in outgoing extension responses", () =>
724 Effect.gen(function* () {
725 const { stdio, input, output } = yield* makeInMemoryStdio();
726 const acknowledged = yield* Deferred.make<string>();
727 yield* AcpProtocol.makeAcpPatchedProtocol({
728 stdio,
729 serverRequestMethods: new Set(),
730 onExtRequest: () =>
731 Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
732 onOutgoingResponse: (requestId) =>
733 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
734 });
735
736 yield* Queue.offer(
737 input,
738 encoder.encode(
739 encodeUnknownJsonString({
740 jsonrpc: "2.0",
741 id: "peer-1",
742 method: "x/test",
743 params: {},
744 }) + "\n",
745 ),
746 );
747
748 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
749 jsonrpc: "2.0",
750 id: "peer-1",
751 error: { code: -32602, message: "bad input", data: { field: "name" } },
752 });
753 assert.equal(yield* Deferred.await(acknowledged), "peer-1");
754 }),
755 );
756
757 it.effect("completes a batch with successful and failed extension responses", () =>
758 Effect.gen(function* () {
759 const { stdio, input, output } = yield* makeInMemoryStdio();
760 const acknowledgements = yield* Queue.unbounded<string>();
761 yield* AcpProtocol.makeAcpPatchedProtocol({
762 stdio,
763 serverRequestMethods: new Set(),
764 onExtRequest: (method) =>
765 method === "x/success"
766 ? Effect.succeed({ ok: true })
767 : Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
768 onOutgoingResponse: (requestId) => Queue.offer(acknowledgements, requestId),
769 });
770
771 yield* Queue.offer(
772 input,
773 encoder.encode(
774 encodeUnknownJsonString([
775 { jsonrpc: "2.0", id: 0, method: "x/success", params: {} },
776 { jsonrpc: "2.0", id: "peer-1", method: "x/failure", params: {} },
777 ]) + "\n",
778 ),
779 );
780
781 assert.deepEqual(JSON.parse(yield* Queue.take(output)), [
782 { jsonrpc: "2.0", id: 0, result: { ok: true } },
783 {
784 jsonrpc: "2.0",
785 id: "peer-1",
786 error: { code: -32602, message: "bad input", data: { field: "name" } },
787 },
788 ]);
789 assert.equal(yield* Queue.take(acknowledgements), "peer-1");
790 }),
791 );
792
793 it.effect.each([
794 {
795 name: "typed failure",
796 cause: [{ _tag: "Fail", error: { code: -32602, message: "bad input", data: null } }],
797 error: { code: -32602, message: "bad input", data: null },
798 },
799 {
800 name: "typed failure with interruption",
801 cause: [
802 { _tag: "Fail", error: { code: -32602, message: "bad input", data: { field: "name" } } },
803 { _tag: "Interrupt", fiberId: null },
804 ],
805 error: { code: -32602, message: "bad input", data: { field: "name" } },
806 },
807 {
808 name: "defect",
809 cause: [{ _tag: "Die", defect: "private defect" }],
810 error: { code: -32603, message: "Internal error" },
811 },
812 {
813 name: "failure with a defect",
814 cause: [
815 { _tag: "Fail", error: { code: -32602, message: "bad input" } },
816 { _tag: "Die", defect: "private defect" },
817 ],
818 error: { code: -32603, message: "Internal error" },
819 },
820 ] as const)("emits a standard ACP error for a core $name", ({ cause, error }) =>
821 Effect.gen(function* () {
822 const { stdio, output } = yield* makeInMemoryStdio();
823 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
824 stdio,
825 serverRequestMethods: new Set(),
826 });
827
828 yield* transport.serverProtocol.send(0, {
829 _tag: "Exit",
830 requestId: 0,
831 exit: { _tag: "Failure", cause },
832 });
833
834 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
835 jsonrpc: "2.0",
836 id: 0,
837 error,
838 });
839 }),
840 );
841
842 it.effect("answers an extension request whose handler also dies as an internal error", () =>
843 Effect.gen(function* () {
844 const { stdio, input, output } = yield* makeInMemoryStdio();
845 yield* AcpProtocol.makeAcpPatchedProtocol({
846 stdio,
847 serverRequestMethods: new Set(),
848 onExtRequest: () =>
849 Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
850 Effect.ensuring(Effect.die(new Error("cleanup bug"))),
851 ),
852 });
853
854 yield* Queue.offer(
855 input,
856 yield* encodeJsonl(ExtRequest, {
857 jsonrpc: "2.0",
858 id: 9,
859 method: "x/test",
860 params: { hello: "world" },
861 headers: [],
862 }),
863 );
864 const decodeJsonRpcErrorResponse = Schema.decodeEffect(
865 Schema.fromJsonString(JsonRpcErrorResponse),
866 );
867
868 const response = yield* decodeJsonRpcErrorResponse(yield* Queue.take(output));
869 assert.equal(response.id, 9);
870 assert.equal(response.error.code, -32603);
871 }),
872 );
873
874 it.effect("preserves zero-valued ids for inbound core client requests", () =>
875 Effect.gen(function* () {
876 const { stdio, input, output } = yield* makeInMemoryStdio();
877 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
878 stdio,
879 serverRequestMethods: new Set(["session/request_permission"]),
880 });
881 const inboundRequest = yield* Deferred.make<unknown>();
882
883 yield* transport.serverProtocol
884 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
885 .pipe(Effect.forkScoped);
886
887 yield* Queue.offer(
888 input,
889 yield* encodeJsonl(RequestPermissionRequest, {
890 jsonrpc: "2.0",
891 id: 0,
892 method: "session/request_permission",
893 params: {
894 sessionId: "session-1",
895 title: "Allow mock action",
896 subject: {
897 type: "tool_call",
898 toolCall: {
899 toolCallId: "tool-1",
900 title: "Allow mock action",
901 },
902 },
903 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
904 },
905 headers: [],
906 }),
907 );
908
909 const message = yield* Deferred.await(inboundRequest);
910 assert.deepEqual(message, {
911 _tag: "Request",
912 id: 0,
913 tag: "session/request_permission",
914 payload: {
915 sessionId: "session-1",
916 title: "Allow mock action",
917 subject: {
918 type: "tool_call",
919 toolCall: {
920 toolCallId: "tool-1",
921 title: "Allow mock action",
922 },
923 },
924 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
925 },
926 headers: [],
927 });
928
929 yield* transport.serverProtocol.send(0, {
930 _tag: "Exit",
931 requestId: 0,
932 exit: {
933 _tag: "Success",
934 value: {
935 outcome: {
936 outcome: "selected",
937 optionId: "allow",
938 },
939 },
940 },
941 });
942
943 const outbound = yield* Queue.take(output);
944 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
945 jsonrpc: "2.0",
946 id: 0,
947 result: {
948 outcome: {
949 outcome: "selected",
950 optionId: "allow",
951 },
952 },
953 });
954 }),
955 );
956
957 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
958 Effect.gen(function* () {
959 const { stdio } = yield* makeInMemoryStdio();
960 const acknowledged = yield* Deferred.make<string>();
961 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
962 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
963 stdio,
964 serverRequestMethods: new Set(),
965 onOutgoingResponse: (requestId) =>
966 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
967 onOutgoingResponseFailure: (requestId, error) =>
968 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
969 });
970
971 yield* transport.serverProtocol.send(0, {
972 _tag: "Exit",
973 requestId: "success-1",
974 exit: { _tag: "Success", value: { ok: true } },
975 });
976 assert.equal(yield* Deferred.await(acknowledged), "success-1");
977
978 const circular: { self?: unknown } = {};
979 circular.self = circular;
980 yield* transport.serverProtocol
981 .send(0, {
982 _tag: "Exit",
983 requestId: "failure-1",
984 exit: { _tag: "Success", value: circular },
985 })
986 .pipe(Effect.exit);
987 const [requestId, error] = yield* Deferred.await(failed);
988 assert.equal(requestId, "failure-1");
989 assert.instanceOf(error, AcpError.AcpProtocolParseError);
990 }),
991 );
992
993 it.effect("acknowledges a response only after the stdout write completes", () =>
994 Effect.gen(function* () {
995 const writeStarted = yield* Deferred.make<void>();
996 const releaseWrite = yield* Deferred.make<void>();
997 const acknowledged = yield* Deferred.make<string>();
998 const stdio = Stdio.make({
999 args: Effect.succeed([]),
1000 stdin: Stream.never,
1001 stdout: () =>
1002 Sink.forEach(() =>
1003 Deferred.succeed(writeStarted, undefined).pipe(
1004 Effect.andThen(Deferred.await(releaseWrite)),
1005 ),
1006 ),
1007 stderr: () => Sink.drain,
1008 });
1009 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1010 stdio,
1011 serverRequestMethods: new Set(),
1012 onOutgoingResponse: (requestId) =>
1013 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
1014 });
1015 const sendFiber = yield* transport.serverProtocol
1016 .send(0, {
1017 _tag: "Exit",
1018 requestId: "held-write",
1019 exit: { _tag: "Success", value: { ok: true } },
1020 })
1021 .pipe(Effect.forkScoped);
1022
1023 yield* Deferred.await(writeStarted);
1024 assert.isUndefined(sendFiber.pollUnsafe());
1025 assert.isFalse(yield* Deferred.isDone(acknowledged));
1026 yield* Deferred.succeed(releaseWrite, undefined);
1027 yield* Fiber.join(sendFiber);
1028 assert.equal(yield* Deferred.await(acknowledged), "held-write");
1029 }),
1030 );
1031
1032 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
1033 Effect.gen(function* () {
1034 const writeStarted = yield* Deferred.make<void>();
1035 const releaseFailure = yield* Deferred.make<void>();
1036 const failures = yield* Queue.unbounded<string>();
1037 const terminated = yield* Deferred.make<AcpError.AcpError>();
1038 const stdio = Stdio.make({
1039 args: Effect.succeed([]),
1040 stdin: Stream.never,
1041 stdout: () =>
1042 Sink.forEach(() =>
1043 Deferred.succeed(writeStarted, undefined).pipe(
1044 Effect.andThen(Deferred.await(releaseFailure)),
1045 Effect.andThen(Effect.die("stdout failed")),
1046 ),
1047 ),
1048 stderr: () => Sink.drain,
1049 });
1050 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1051 stdio,
1052 serverRequestMethods: new Set(),
1053 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1054 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1055 });
1056 const send = (requestId: string) =>
1057 transport.serverProtocol
1058 .send(0, {
1059 _tag: "Exit",
1060 requestId,
1061 exit: { _tag: "Success", value: { ok: true } },
1062 })
1063 .pipe(Effect.exit);
1064 const current = yield* send("current").pipe(Effect.forkScoped);
1065 yield* Deferred.await(writeStarted);
1066 const queued = yield* send("queued").pipe(Effect.forkScoped);
1067 yield* Effect.yieldNow;
1068 assert.isUndefined(current.pollUnsafe());
1069 assert.isUndefined(queued.pollUnsafe());
1070 yield* Deferred.succeed(releaseFailure, undefined);
1071 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
1072 yield* Fiber.join(current);
1073 yield* Fiber.join(queued);
1074 yield* send("future");
1075
1076 assert.deepEqual(
1077 new Set(yield* Queue.takeN(failures, 3)),
1078 new Set(["current", "queued", "future"]),
1079 );
1080 }),
1081 );
1082
1083 it.effect(
1084 "atomically rejects an admitted response when the writer closes before queue offer",
1085 () =>
1086 Effect.gen(function* () {
1087 const admitted = yield* Deferred.make<void>();
1088 const releaseAdmission = yield* Deferred.make<void>();
1089 const failures = yield* Queue.unbounded<string>();
1090 const protocolScope = yield* Scope.make();
1091 const stdio = Stdio.make({
1092 args: Effect.succeed([]),
1093 stdin: Stream.never,
1094 stdout: () => Sink.drain,
1095 stderr: () => Sink.drain,
1096 });
1097 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1098 stdio,
1099 serverRequestMethods: new Set(),
1100 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1101 testHooks: {
1102 onOutgoingWriteAdmitted: () =>
1103 Deferred.succeed(admitted, undefined).pipe(
1104 Effect.andThen(Deferred.await(releaseAdmission)),
1105 ),
1106 },
1107 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
1108 const send = (requestId: string) =>
1109 transport.serverProtocol
1110 .send(0, {
1111 _tag: "Exit",
1112 requestId,
1113 exit: { _tag: "Success", value: { ok: true } },
1114 })
1115 .pipe(Effect.exit);
1116 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
1117
1118 yield* Deferred.await(admitted);
1119 yield* Scope.close(protocolScope, Exit.void);
1120 yield* Deferred.succeed(releaseAdmission, undefined);
1121 yield* Fiber.join(admittedSend);
1122 yield* send("future");
1123
1124 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
1125 }),
1126 );
1127
1128 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
1129 Effect.gen(function* () {
1130 const { stdio, input } = yield* makeInMemoryStdio();
1131 const notifications =
1132 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
1133 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1134 stdio,
1135 serverRequestMethods: new Set(),
1136 });
1137
1138 yield* transport.incoming.pipe(
1139 Stream.take(1),
1140 Stream.runCollect,
1141 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
1142 Effect.forkScoped,
1143 );
1144
1145 yield* Queue.offer(
1146 input,
1147 encoder.encode(
1148 `${encodeUnknownJsonString({
1149 jsonrpc: "2.0",
1150 id: "skills-reload",
1151 result: {
1152 reloaded: true,
1153 },
1154 })}\n`,
1155 ),
1156 );
1157 yield* Queue.offer(
1158 input,
1159 yield* encodeJsonl(SessionUpdateNotification, {
1160 jsonrpc: "2.0",
1161 method: "session/update",
1162 params: {
1163 sessionId: "session-1",
1164 update: {
1165 sessionUpdate: "plan",
1166 entries: [
1167 {
1168 content: "Reload skills",
1169 priority: "high",
1170 status: "in_progress",
1171 },
1172 ],
1173 },
1174 },
1175 }),
1176 );
1177
1178 const [update] = yield* Deferred.await(notifications);
1179 assert.equal(update?._tag, "SessionUpdate");
1180 }),
1181 );
1182
1183 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
1184 Effect.gen(function* () {
1185 const { stdio, input, output } = yield* makeInMemoryStdio();
1186 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1187 stdio,
1188 serverRequestMethods: new Set(),
1189 });
1190 const lateResponse = yield* Deferred.make<unknown>();
1191
1192 yield* transport.clientProtocol
1193 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
1194 .pipe(Effect.forkScoped);
1195
1196 const response = yield* transport
1197 .request("x/test", { hello: "world" })
1198 .pipe(Effect.forkScoped);
1199 const outbound = yield* Queue.take(output);
1200 assert.deepEqual(yield* decodeExtRequest(outbound), {
1201 jsonrpc: "2.0",
1202 id: 1,
1203 method: "x/test",
1204 params: {
1205 hello: "world",
1206 },
1207 headers: [],
1208 });
1209
1210 yield* Fiber.interrupt(response);
1211 yield* Queue.offer(
1212 input,
1213 yield* encodeJsonl(ExtResponse, {
1214 jsonrpc: "2.0",
1215 id: 1,
1216 result: {
1217 ok: true,
1218 },
1219 }),
1220 );
1221
1222 const message = yield* Deferred.await(lateResponse);
1223 assert.deepEqual(message, {
1224 _tag: "Exit",
1225 requestId: 1,
1226 exit: {
1227 _tag: "Success",
1228 value: {
1229 ok: true,
1230 },
1231 },
1232 });
1233 }),
1234 );
1235
1236 it.effect("fails pending and later requests when input ends before the process exits", () =>
1237 Effect.gen(function* () {
1238 const { stdio, input, output } = yield* makeInMemoryStdio();
1239 const termination = yield* Deferred.make<AcpError.AcpError>();
1240 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1241 stdio,
1242 terminationError: Effect.never,
1243 serverRequestMethods: new Set(),
1244 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1245 });
1246 const pending = yield* transport
1247 .request("x/test", { hello: "world" })
1248 .pipe(Effect.flip, Effect.orDie, Effect.forkScoped);
1249 yield* Queue.take(output);
1250 yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","id":1,"result":'));
1251 yield* Queue.end(input);
1252
1253 const error = yield* Deferred.await(termination);
1254 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
1255 assert.strictEqual(yield* Fiber.join(pending), error);
1256 assert.strictEqual(
1257 yield* transport.request("x/test", { hello: "later" }).pipe(Effect.flip, Effect.orDie),
1258 error,
1259 );
1260 assert.strictEqual(
1261 yield* transport.notify("session/cancel", { sessionId: "session-1" }).pipe(Effect.flip),
1262 error,
1263 );
1264 }),
1265 );
1266
1267 it.effect("answers a pending request from a final response without a trailing newline", () =>
1268 Effect.gen(function* () {
1269 const { stdio, input, output } = yield* makeInMemoryStdio();
1270 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1271 stdio,
1272 serverRequestMethods: new Set(),
1273 });
1274 const pending = yield* transport
1275 .request("x/test", { hello: "world" })
1276 .pipe(Effect.forkScoped);
1277 yield* Queue.take(output);
1278 yield* Queue.offer(
1279 input,
1280 encoder.encode(encodeUnknownJsonString({ jsonrpc: "2.0", id: 1, result: { ok: true } })),
1281 );
1282 yield* Queue.end(input);
1283
1284 assert.deepEqual(yield* Fiber.join(pending), { ok: true });
1285 }),
1286 );
1287
1288 it.effect("propagates the real child exit code when the input stream ends", () =>
1289 Effect.gen(function* () {
1290 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
1291 const firstMessage = yield* Deferred.make<unknown>();
1292 const termination = yield* Deferred.make<AcpError.AcpError>();
1293 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1294 stdio: makeChildStdio(handle),
1295 terminationError: makeTerminationError(handle),
1296 serverRequestMethods: new Set(),
1297 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1298 });
1299
1300 yield* transport.clientProtocol
1301 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1302 .pipe(Effect.forkScoped);
1303
1304 const message = yield* Deferred.await(firstMessage);
1305 const exitError = yield* Deferred.await(termination);
1306 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
1307 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
1308 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1309 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1310 readonly _tag: string;
1311 readonly message: string;
1312 readonly cause: unknown;
1313 };
1314 assert.equal(defect._tag, "RpcClientDefect");
1315 assert.equal(defect.message, "ACP protocol terminated.");
1316 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
1317 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
1318 }),
1319 );
1320
1321 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
1322 Effect.gen(function* () {
1323 const { stdio, input } = yield* makeInMemoryStdio();
1324 const terminations = yield* Ref.make(0);
1325 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
1326 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1327 stdio,
1328 serverRequestMethods: new Set(),
1329 onTermination: () => Ref.update(terminations, (count) => count + 1),
1330 testHooks: {
1331 onOutgoingWriterExit: (detail) =>
1332 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
1333 },
1334 });
1335
1336 yield* transport.serverProtocol.end(0);
1337 const exitDetail = yield* Deferred.await(writerExit);
1338 assert.isTrue(exitDetail.intentionalEnd);
1339 assert.equal(yield* Ref.get(terminations), 0);
1340
1341 yield* Queue.end(input);
1342 }),
1343 );
1344
1345 it.effect("does not emit a second process-exit error after a decode failure", () =>
1346 Effect.gen(function* () {
1347 const handle = yield* makeHandle({
1348 ACP_MOCK_MALFORMED_OUTPUT: "1",
1349 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
1350 });
1351 const terminationCalls = yield* Ref.make(0);
1352 const firstMessage = yield* Deferred.make<unknown>();
1353 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1354 stdio: makeChildStdio(handle),
1355 terminationError: makeTerminationError(handle),
1356 serverRequestMethods: new Set(),
1357 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
1358 });
1359
1360 yield* transport.clientProtocol
1361 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1362 .pipe(Effect.forkScoped);
1363
1364 const message = yield* Deferred.await(firstMessage);
1365 assert.equal(yield* Ref.get(terminationCalls), 1);
1366 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1367 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1368 readonly _tag: string;
1369 readonly message: string;
1370 readonly cause: unknown;
1371 };
1372 assert.equal(defect._tag, "RpcClientDefect");
1373 assert.equal(defect.message, "ACP protocol terminated.");
1374 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1375 }),
1376 );
1377
1378 it.effect.each(["request", "notification"] as const)(
1379 "rejects a %s if the connection ends while its logger is running",
1380 (operation) =>
1381 Effect.gen(function* () {
1382 const { stdio, input, output } = yield* makeInMemoryStdio();
1383 const writeStarted = yield* Deferred.make<void>();
1384 const releaseWrite = yield* Deferred.make<void>();
1385 const terminated = yield* Deferred.make<AcpError.AcpError>();
1386 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1387 stdio,
1388 serverRequestMethods: new Set(),
1389 logOutgoing: true,
1390 logger: (event) =>
1391 event.stage === "raw"
1392 ? Deferred.succeed(writeStarted, undefined).pipe(
1393 Effect.andThen(Deferred.await(releaseWrite)),
1394 )
1395 : Effect.void,
1396 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1397 });
1398 const send = yield* (
1399 operation === "request"
1400 ? transport.request("x/test", { hello: "world" })
1401 : transport.notify("session/cancel", { sessionId: "session-1" })
1402 ).pipe(Effect.forkScoped);
1403
1404 yield* Deferred.await(writeStarted);
1405 yield* Queue.end(input);
1406 const error = yield* Deferred.await(terminated);
1407 yield* Deferred.succeed(releaseWrite, undefined);
1408
1409 const failure = yield* Fiber.join(send).pipe(
1410 Effect.match({
1411 onFailure: (failure) => failure,
1412 onSuccess: () => assert.fail("Expected the send to fail after termination"),
1413 }),
1414 );
1415 assert.strictEqual(failure, error);
1416 assert.equal(yield* Queue.size(output), 0);
1417 }),
1418 );
1419});