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