The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,449 lines 50.6 KB
Raw
1 import * as Path from "effect/Path";
2 import * as AcpError from "./errors.ts";
3 import * as Effect from "effect/Effect";
4 import * as Deferred from "effect/Deferred";
5 import * as Fiber from "effect/Fiber";
6 import * as Exit from "effect/Exit";
7 import * as Logger from "effect/Logger";
8 import * as Queue from "effect/Queue";
9 import * as References from "effect/References";
10 import * as Schema from "effect/Schema";
11 import * as Scope from "effect/Scope";
12 import * as Sink from "effect/Sink";
13 import * as Stdio from "effect/Stdio";
14 import * as Stream from "effect/Stream";
15 import * as Ref from "effect/Ref";
16 import * as TestClock from "effect/testing/TestClock";
17 import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
19 import { it, assert, expect } from "@effect/vitest";
20 import * as NodeServices from "@effect/platform-node/NodeServices";
21
22 import * as AcpSchema from "./schema.ts";
23 import * as AcpProtocol from "./protocol.ts";
24 import {
25 encodeJsonl,
26 jsonRpcNotification,
27 jsonRpcRequest,
28 jsonRpcResponse,
29 } from "./_internal/shared.ts";
30 import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
31
32 const SessionCancelNotification = jsonRpcNotification(
33 "session/cancel",
34 AcpSchema.CancelNotification,
35 );
36 const SessionUpdateNotification = jsonRpcNotification(
37 "session/update",
38 AcpSchema.SessionNotification,
39 );
40 const ElicitationCompleteNotification = jsonRpcNotification(
41 "elicitation/complete",
42 AcpSchema.CompleteElicitationNotification,
43 );
44 const RequestPermissionRequest = jsonRpcRequest(
45 "session/request_permission",
46 AcpSchema.RequestPermissionRequest,
47 );
48 const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
49 const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
50 const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
51 const decodeSessionCancelNotification = Schema.decodeEffect(
52 Schema.fromJsonString(SessionCancelNotification),
53 );
54 const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
55 const decodeRequestPermissionResponse = Schema.decodeEffect(
56 Schema.fromJsonString(RequestPermissionResponse),
57 );
58 const JsonRpcErrorResponse = Schema.Struct({
59 jsonrpc: Schema.Literal("2.0"),
60 id: Schema.Number,
61 error: Schema.Struct({ code: Schema.Number, message: Schema.String }),
62 });
63 const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
64 const encoder = new TextEncoder();
65 const MIB = 1024 * 1024;
66 const decodeIndex = Schema.decodeUnknownSync(Schema.Struct({ index: Schema.Number }));
67 const 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 );
75 const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
76 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
77 );
78 const mockPeerArgs = (path: string) => [path];
79
80 const 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
91 it.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 // clanka once sent a usage_update without `used` and `size`. One bad update
401 // must not end a session whose later updates are fine.
402 it.effect("drops a session/update that fails to decode and keeps reading", () =>
403 Effect.gen(function* () {
404 const secret = "acp-core-notification-secret-sentinel";
405 const { stdio, input } = yield* makeInMemoryStdio();
406 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
407 const warnings: Array<unknown> = [];
408 let terminated = false;
409 let transformCalls = 0;
410 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
411 stdio,
412 serverRequestMethods: new Set(),
413 logIncoming: true,
414 logger: (event) =>
415 Effect.sync(() => {
416 events.push(event);
417 }),
418 transformSessionUpdate: (notification) => {
419 transformCalls += 1;
420 return notification;
421 },
422 onTermination: () =>
423 Effect.sync(() => {
424 terminated = true;
425 }),
426 }).pipe(
427 Effect.provide(
428 Logger.layer([
429 Logger.make(({ logLevel, fiber }) => {
430 if (logLevel === "Warn")
431 warnings.push(fiber.getRef(References.CurrentLogAnnotations));
432 }),
433 ]),
434 ),
435 );
436 const received = yield* Deferred.make<AcpProtocol.AcpIncomingNotification>();
437 yield* transport.incoming.pipe(
438 Stream.runForEach((notification) => Deferred.succeed(received, notification)),
439 Effect.forkScoped,
440 );
441
442 const send = (params: unknown) =>
443 Queue.offer(
444 input,
445 encoder.encode(
446 `${encodeUnknownJsonString({ jsonrpc: "2.0", method: "session/update", params })}\n`,
447 ),
448 );
449 const malformed = {
450 sessionId: "session-1",
451 update: { sessionUpdate: "usage_update", cost: { amount: 1, currency: secret } },
452 };
453 yield* send(malformed);
454 yield* send(malformed);
455 yield* send({
456 sessionId: "session-1",
457 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
458 });
459
460 const notification = yield* TestClock.withLive(
461 Deferred.await(received).pipe(Effect.timeout("2 seconds")),
462 );
463 assert.equal(notification._tag, "SessionUpdate");
464 assert.deepEqual(notification.params, {
465 sessionId: "session-1",
466 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
467 });
468 assert.isFalse(terminated);
469 assert.equal(transformCalls, 1);
470
471 const decodeFailed = events.find(({ stage }) => stage === "decode_failed");
472 expect(decodeFailed?.payload).toMatchObject({
473 operation: "decode-notification-payload",
474 method: "session/update",
475 issueSummary: expect.stringContaining("update.used missing"),
476 });
477 assert.lengthOf(
478 events.filter(({ stage }) => stage === "decode_failed"),
479 2,
480 );
481 assert.lengthOf(warnings, 1);
482 expect(warnings[0]).toMatchObject({
483 issueSummary: expect.stringContaining("update.used missing"),
484 });
485 assert.notInclude(encodeUnknownJsonString({ decodeFailed, warnings }), secret);
486 }),
487 );
488
489 it.effect("terminates when a callback on the reader dies", () =>
490 Effect.gen(function* () {
491 const { stdio, input } = yield* makeInMemoryStdio();
492 const termination = yield* Deferred.make<AcpError.AcpError>();
493 yield* AcpProtocol.makeAcpPatchedProtocol({
494 stdio,
495 serverRequestMethods: new Set(),
496 transformSessionUpdate: () => {
497 throw new Error("normalizer bug");
498 },
499 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
500 });
501
502 yield* Queue.offer(
503 input,
504 encoder.encode(
505 `${encodeUnknownJsonString({
506 jsonrpc: "2.0",
507 method: "session/update",
508 params: {
509 sessionId: "session-1",
510 update: { sessionUpdate: "plan", entries: [] },
511 },
512 })}\n`,
513 ),
514 );
515
516 const error = yield* TestClock.withLive(
517 Deferred.await(termination).pipe(Effect.timeout("2 seconds")),
518 );
519 assert.instanceOf(error, AcpError.AcpTransportError);
520 assert.equal((error as AcpError.AcpTransportError).operation, "read-input-stream");
521 }),
522 );
523
524 // regression: #9154 notifications went out with `id` and `headers`, which Grok CLI drops
525 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
526 Effect.gen(function* () {
527 const { stdio } = yield* makeInMemoryStdio();
528 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
529 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
530 stdio,
531 serverRequestMethods: new Set(),
532 logOutgoing: true,
533 logger: (event) =>
534 Effect.sync(() => {
535 events.push(event);
536 }),
537 });
538
539 yield* transport.notify("session/cancel", { sessionId: "session-1" });
540
541 // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
542 assert.deepEqual(events, [
543 {
544 direction: "outgoing",
545 stage: "decoded",
546 payload: {
547 _tag: "Notification",
548 tag: "session/cancel",
549 payload: {
550 sessionId: "session-1",
551 },
552 },
553 },
554 {
555 direction: "outgoing",
556 stage: "raw",
557 payload:
558 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
559 },
560 ]);
561 }),
562 );
563
564 it.effect("skips blank lines between agent messages", () =>
565 Effect.gen(function* () {
566 const { stdio, input } = yield* makeInMemoryStdio();
567 const outcome = yield* Deferred.make<string>();
568 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
569 stdio,
570 serverRequestMethods: new Set(),
571 onTermination: (error) => Deferred.succeed(outcome, error._tag).pipe(Effect.asVoid),
572 });
573 yield* transport.incoming.pipe(
574 Stream.runForEach((notification) => Deferred.succeed(outcome, notification._tag)),
575 Effect.forkScoped,
576 );
577
578 const update = encodeUnknownJsonString({
579 jsonrpc: "2.0",
580 method: "session/update",
581 params: { sessionId: "session-1", update: { sessionUpdate: "plan", entries: [] } },
582 });
583 yield* Queue.offer(input, encoder.encode(`\n\r\n \t\n${update}\n\n`));
584
585 assert.equal(yield* Deferred.await(outcome), "SessionUpdate");
586 }),
587 );
588
589 it.effect("logs decode failures without copying the cause or wire payload", () =>
590 Effect.gen(function* () {
591 const secret = "acp-wire-secret-sentinel";
592 const { stdio, input } = yield* makeInMemoryStdio();
593 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
594 const termination = yield* Deferred.make<AcpError.AcpError>();
595 yield* AcpProtocol.makeAcpPatchedProtocol({
596 stdio,
597 serverRequestMethods: new Set(),
598 logIncoming: true,
599 logger: (event) =>
600 Effect.sync(() => {
601 events.push(event);
602 }),
603 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
604 });
605
606 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
607 yield* Deferred.await(termination);
608
609 const event = events.find(({ stage }) => stage === "decode_failed");
610 assert.deepEqual(event, {
611 direction: "incoming",
612 stage: "decode_failed",
613 payload: {
614 operation: "decode-wire-message",
615 },
616 });
617 assert.notInclude(encodeUnknownJsonString(event), secret);
618 }),
619 );
620
621 it.effect("fails notification encoding through the declared ACP error channel", () =>
622 Effect.gen(function* () {
623 const { stdio } = yield* makeInMemoryStdio();
624 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
625 stdio,
626 serverRequestMethods: new Set(),
627 });
628
629 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
630 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
631 assert.equal(bigintError.operation, "encode-message");
632 assert.equal(bigintError.method, "x/test");
633 assert.isDefined(bigintError.cause);
634 assert.equal(
635 bigintError.message,
636 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
637 );
638
639 const circular: Record<string, unknown> = {};
640 circular.self = circular;
641 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
642 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
643 assert.equal(circularError.operation, "encode-message");
644 assert.equal(circularError.method, "x/test");
645 assert.isDefined(circularError.cause);
646
647 const requestError = yield* transport.request("x/request", 1n).pipe(
648 Effect.match({
649 onFailure: (error) => error,
650 onSuccess: () => assert.fail("Expected request encoding to fail"),
651 }),
652 );
653 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
654 assert.deepInclude(requestError, {
655 operation: "encode-message",
656 method: "x/request",
657 requestId: 1,
658 });
659 }),
660 );
661
662 it.effect("does not correlate a string response id with a numeric extension request id", () =>
663 Effect.gen(function* () {
664 const { stdio, input, output } = yield* makeInMemoryStdio();
665 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
666 stdio,
667 serverRequestMethods: new Set(),
668 });
669
670 const response = yield* transport
671 .request("x/test", { hello: "world" })
672 .pipe(Effect.forkScoped);
673 yield* Queue.take(output);
674 yield* Queue.offer(
675 input,
676 encoder.encode(
677 `${encodeUnknownJsonString({
678 jsonrpc: "2.0",
679 id: "1",
680 result: { ok: false },
681 })}\n`,
682 ),
683 );
684 yield* Effect.yieldNow;
685 assert.isUndefined(response.pollUnsafe());
686
687 yield* Queue.offer(
688 input,
689 yield* encodeJsonl(ExtResponse, {
690 jsonrpc: "2.0",
691 id: 1,
692 result: { ok: true },
693 }),
694 );
695 assert.deepEqual(yield* Fiber.join(response), { ok: true });
696 }),
697 );
698
699 it.effect("correlates extension response errors with the originating request", () =>
700 Effect.gen(function* () {
701 const { stdio, input, output } = yield* makeInMemoryStdio();
702 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
703 stdio,
704 serverRequestMethods: new Set(),
705 });
706
707 const response = yield* transport
708 .request("x/private", { hello: "world" })
709 .pipe(Effect.forkScoped);
710 yield* Queue.take(output);
711 yield* Queue.offer(
712 input,
713 encoder.encode(
714 `${encodeUnknownJsonString({
715 jsonrpc: "2.0",
716 id: 1,
717 error: {
718 _tag: "Cause",
719 code: -32602,
720 message: "Invalid params",
721 data: [
722 {
723 _tag: "Fail",
724 error: {
725 code: -32602,
726 message: "Invalid params",
727 data: { field: "hello" },
728 },
729 },
730 ],
731 },
732 })}\n`,
733 ),
734 );
735
736 const error = yield* Fiber.join(response).pipe(
737 Effect.match({
738 onFailure: (error) => error,
739 onSuccess: () => assert.fail("Expected extension request to fail"),
740 }),
741 );
742 assert.instanceOf(error, AcpError.AcpRequestError);
743 assert.deepInclude(error, {
744 code: -32602,
745 errorMessage: "Invalid params",
746 method: "x/private",
747 requestId: 1,
748 operation: "receive-response",
749 });
750 }),
751 );
752
753 it.effect("preserves application error data in outgoing extension responses", () =>
754 Effect.gen(function* () {
755 const { stdio, input, output } = yield* makeInMemoryStdio();
756 const acknowledged = yield* Deferred.make<string>();
757 yield* AcpProtocol.makeAcpPatchedProtocol({
758 stdio,
759 serverRequestMethods: new Set(),
760 onExtRequest: () =>
761 Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
762 onOutgoingResponse: (requestId) =>
763 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
764 });
765
766 yield* Queue.offer(
767 input,
768 encoder.encode(
769 encodeUnknownJsonString({
770 jsonrpc: "2.0",
771 id: "peer-1",
772 method: "x/test",
773 params: {},
774 }) + "\n",
775 ),
776 );
777
778 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
779 jsonrpc: "2.0",
780 id: "peer-1",
781 error: { code: -32602, message: "bad input", data: { field: "name" } },
782 });
783 assert.equal(yield* Deferred.await(acknowledged), "peer-1");
784 }),
785 );
786
787 it.effect("completes a batch with successful and failed extension responses", () =>
788 Effect.gen(function* () {
789 const { stdio, input, output } = yield* makeInMemoryStdio();
790 const acknowledgements = yield* Queue.unbounded<string>();
791 yield* AcpProtocol.makeAcpPatchedProtocol({
792 stdio,
793 serverRequestMethods: new Set(),
794 onExtRequest: (method) =>
795 method === "x/success"
796 ? Effect.succeed({ ok: true })
797 : Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
798 onOutgoingResponse: (requestId) => Queue.offer(acknowledgements, requestId),
799 });
800
801 yield* Queue.offer(
802 input,
803 encoder.encode(
804 encodeUnknownJsonString([
805 { jsonrpc: "2.0", id: 0, method: "x/success", params: {} },
806 { jsonrpc: "2.0", id: "peer-1", method: "x/failure", params: {} },
807 ]) + "\n",
808 ),
809 );
810
811 assert.deepEqual(JSON.parse(yield* Queue.take(output)), [
812 { jsonrpc: "2.0", id: 0, result: { ok: true } },
813 {
814 jsonrpc: "2.0",
815 id: "peer-1",
816 error: { code: -32602, message: "bad input", data: { field: "name" } },
817 },
818 ]);
819 assert.equal(yield* Queue.take(acknowledgements), "peer-1");
820 }),
821 );
822
823 it.effect.each([
824 {
825 name: "typed failure",
826 cause: [{ _tag: "Fail", error: { code: -32602, message: "bad input", data: null } }],
827 error: { code: -32602, message: "bad input", data: null },
828 },
829 {
830 name: "typed failure with interruption",
831 cause: [
832 { _tag: "Fail", error: { code: -32602, message: "bad input", data: { field: "name" } } },
833 { _tag: "Interrupt", fiberId: null },
834 ],
835 error: { code: -32602, message: "bad input", data: { field: "name" } },
836 },
837 {
838 name: "defect",
839 cause: [{ _tag: "Die", defect: "private defect" }],
840 error: { code: -32603, message: "Internal error" },
841 },
842 {
843 name: "failure with a defect",
844 cause: [
845 { _tag: "Fail", error: { code: -32602, message: "bad input" } },
846 { _tag: "Die", defect: "private defect" },
847 ],
848 error: { code: -32603, message: "Internal error" },
849 },
850 ] as const)("emits a standard ACP error for a core $name", ({ cause, error }) =>
851 Effect.gen(function* () {
852 const { stdio, output } = yield* makeInMemoryStdio();
853 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
854 stdio,
855 serverRequestMethods: new Set(),
856 });
857
858 yield* transport.serverProtocol.send(0, {
859 _tag: "Exit",
860 requestId: 0,
861 exit: { _tag: "Failure", cause },
862 });
863
864 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
865 jsonrpc: "2.0",
866 id: 0,
867 error,
868 });
869 }),
870 );
871
872 it.effect("answers an extension request whose handler also dies as an internal error", () =>
873 Effect.gen(function* () {
874 const { stdio, input, output } = yield* makeInMemoryStdio();
875 yield* AcpProtocol.makeAcpPatchedProtocol({
876 stdio,
877 serverRequestMethods: new Set(),
878 onExtRequest: () =>
879 Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
880 Effect.ensuring(Effect.die(new Error("cleanup bug"))),
881 ),
882 });
883
884 yield* Queue.offer(
885 input,
886 yield* encodeJsonl(ExtRequest, {
887 jsonrpc: "2.0",
888 id: 9,
889 method: "x/test",
890 params: { hello: "world" },
891 headers: [],
892 }),
893 );
894 const decodeJsonRpcErrorResponse = Schema.decodeEffect(
895 Schema.fromJsonString(JsonRpcErrorResponse),
896 );
897
898 const response = yield* decodeJsonRpcErrorResponse(yield* Queue.take(output));
899 assert.equal(response.id, 9);
900 assert.equal(response.error.code, -32603);
901 }),
902 );
903
904 it.effect("preserves zero-valued ids for inbound core client requests", () =>
905 Effect.gen(function* () {
906 const { stdio, input, output } = yield* makeInMemoryStdio();
907 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
908 stdio,
909 serverRequestMethods: new Set(["session/request_permission"]),
910 });
911 const inboundRequest = yield* Deferred.make<unknown>();
912
913 yield* transport.serverProtocol
914 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
915 .pipe(Effect.forkScoped);
916
917 yield* Queue.offer(
918 input,
919 yield* encodeJsonl(RequestPermissionRequest, {
920 jsonrpc: "2.0",
921 id: 0,
922 method: "session/request_permission",
923 params: {
924 sessionId: "session-1",
925 title: "Allow mock action",
926 subject: {
927 type: "tool_call",
928 toolCall: {
929 toolCallId: "tool-1",
930 title: "Allow mock action",
931 },
932 },
933 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
934 },
935 headers: [],
936 }),
937 );
938
939 const message = yield* Deferred.await(inboundRequest);
940 assert.deepEqual(message, {
941 _tag: "Request",
942 id: 0,
943 tag: "session/request_permission",
944 payload: {
945 sessionId: "session-1",
946 title: "Allow mock action",
947 subject: {
948 type: "tool_call",
949 toolCall: {
950 toolCallId: "tool-1",
951 title: "Allow mock action",
952 },
953 },
954 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
955 },
956 headers: [],
957 });
958
959 yield* transport.serverProtocol.send(0, {
960 _tag: "Exit",
961 requestId: 0,
962 exit: {
963 _tag: "Success",
964 value: {
965 outcome: {
966 outcome: "selected",
967 optionId: "allow",
968 },
969 },
970 },
971 });
972
973 const outbound = yield* Queue.take(output);
974 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
975 jsonrpc: "2.0",
976 id: 0,
977 result: {
978 outcome: {
979 outcome: "selected",
980 optionId: "allow",
981 },
982 },
983 });
984 }),
985 );
986
987 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
988 Effect.gen(function* () {
989 const { stdio } = yield* makeInMemoryStdio();
990 const acknowledged = yield* Deferred.make<string>();
991 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
992 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
993 stdio,
994 serverRequestMethods: new Set(),
995 onOutgoingResponse: (requestId) =>
996 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
997 onOutgoingResponseFailure: (requestId, error) =>
998 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
999 });
1000
1001 yield* transport.serverProtocol.send(0, {
1002 _tag: "Exit",
1003 requestId: "success-1",
1004 exit: { _tag: "Success", value: { ok: true } },
1005 });
1006 assert.equal(yield* Deferred.await(acknowledged), "success-1");
1007
1008 const circular: { self?: unknown } = {};
1009 circular.self = circular;
1010 yield* transport.serverProtocol
1011 .send(0, {
1012 _tag: "Exit",
1013 requestId: "failure-1",
1014 exit: { _tag: "Success", value: circular },
1015 })
1016 .pipe(Effect.exit);
1017 const [requestId, error] = yield* Deferred.await(failed);
1018 assert.equal(requestId, "failure-1");
1019 assert.instanceOf(error, AcpError.AcpProtocolParseError);
1020 }),
1021 );
1022
1023 it.effect("acknowledges a response only after the stdout write completes", () =>
1024 Effect.gen(function* () {
1025 const writeStarted = yield* Deferred.make<void>();
1026 const releaseWrite = yield* Deferred.make<void>();
1027 const acknowledged = yield* Deferred.make<string>();
1028 const stdio = Stdio.make({
1029 args: Effect.succeed([]),
1030 stdin: Stream.never,
1031 stdout: () =>
1032 Sink.forEach(() =>
1033 Deferred.succeed(writeStarted, undefined).pipe(
1034 Effect.andThen(Deferred.await(releaseWrite)),
1035 ),
1036 ),
1037 stderr: () => Sink.drain,
1038 });
1039 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1040 stdio,
1041 serverRequestMethods: new Set(),
1042 onOutgoingResponse: (requestId) =>
1043 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
1044 });
1045 const sendFiber = yield* transport.serverProtocol
1046 .send(0, {
1047 _tag: "Exit",
1048 requestId: "held-write",
1049 exit: { _tag: "Success", value: { ok: true } },
1050 })
1051 .pipe(Effect.forkScoped);
1052
1053 yield* Deferred.await(writeStarted);
1054 assert.isUndefined(sendFiber.pollUnsafe());
1055 assert.isFalse(yield* Deferred.isDone(acknowledged));
1056 yield* Deferred.succeed(releaseWrite, undefined);
1057 yield* Fiber.join(sendFiber);
1058 assert.equal(yield* Deferred.await(acknowledged), "held-write");
1059 }),
1060 );
1061
1062 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
1063 Effect.gen(function* () {
1064 const writeStarted = yield* Deferred.make<void>();
1065 const releaseFailure = yield* Deferred.make<void>();
1066 const failures = yield* Queue.unbounded<string>();
1067 const terminated = yield* Deferred.make<AcpError.AcpError>();
1068 const stdio = Stdio.make({
1069 args: Effect.succeed([]),
1070 stdin: Stream.never,
1071 stdout: () =>
1072 Sink.forEach(() =>
1073 Deferred.succeed(writeStarted, undefined).pipe(
1074 Effect.andThen(Deferred.await(releaseFailure)),
1075 Effect.andThen(Effect.die("stdout failed")),
1076 ),
1077 ),
1078 stderr: () => Sink.drain,
1079 });
1080 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1081 stdio,
1082 serverRequestMethods: new Set(),
1083 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1084 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1085 });
1086 const send = (requestId: string) =>
1087 transport.serverProtocol
1088 .send(0, {
1089 _tag: "Exit",
1090 requestId,
1091 exit: { _tag: "Success", value: { ok: true } },
1092 })
1093 .pipe(Effect.exit);
1094 const current = yield* send("current").pipe(Effect.forkScoped);
1095 yield* Deferred.await(writeStarted);
1096 const queued = yield* send("queued").pipe(Effect.forkScoped);
1097 yield* Effect.yieldNow;
1098 assert.isUndefined(current.pollUnsafe());
1099 assert.isUndefined(queued.pollUnsafe());
1100 yield* Deferred.succeed(releaseFailure, undefined);
1101 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
1102 yield* Fiber.join(current);
1103 yield* Fiber.join(queued);
1104 yield* send("future");
1105
1106 assert.deepEqual(
1107 new Set(yield* Queue.takeN(failures, 3)),
1108 new Set(["current", "queued", "future"]),
1109 );
1110 }),
1111 );
1112
1113 it.effect(
1114 "atomically rejects an admitted response when the writer closes before queue offer",
1115 () =>
1116 Effect.gen(function* () {
1117 const admitted = yield* Deferred.make<void>();
1118 const releaseAdmission = yield* Deferred.make<void>();
1119 const failures = yield* Queue.unbounded<string>();
1120 const protocolScope = yield* Scope.make();
1121 const stdio = Stdio.make({
1122 args: Effect.succeed([]),
1123 stdin: Stream.never,
1124 stdout: () => Sink.drain,
1125 stderr: () => Sink.drain,
1126 });
1127 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1128 stdio,
1129 serverRequestMethods: new Set(),
1130 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
1131 testHooks: {
1132 onOutgoingWriteAdmitted: () =>
1133 Deferred.succeed(admitted, undefined).pipe(
1134 Effect.andThen(Deferred.await(releaseAdmission)),
1135 ),
1136 },
1137 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
1138 const send = (requestId: string) =>
1139 transport.serverProtocol
1140 .send(0, {
1141 _tag: "Exit",
1142 requestId,
1143 exit: { _tag: "Success", value: { ok: true } },
1144 })
1145 .pipe(Effect.exit);
1146 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
1147
1148 yield* Deferred.await(admitted);
1149 yield* Scope.close(protocolScope, Exit.void);
1150 yield* Deferred.succeed(releaseAdmission, undefined);
1151 yield* Fiber.join(admittedSend);
1152 yield* send("future");
1153
1154 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
1155 }),
1156 );
1157
1158 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
1159 Effect.gen(function* () {
1160 const { stdio, input } = yield* makeInMemoryStdio();
1161 const notifications =
1162 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
1163 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1164 stdio,
1165 serverRequestMethods: new Set(),
1166 });
1167
1168 yield* transport.incoming.pipe(
1169 Stream.take(1),
1170 Stream.runCollect,
1171 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
1172 Effect.forkScoped,
1173 );
1174
1175 yield* Queue.offer(
1176 input,
1177 encoder.encode(
1178 `${encodeUnknownJsonString({
1179 jsonrpc: "2.0",
1180 id: "skills-reload",
1181 result: {
1182 reloaded: true,
1183 },
1184 })}\n`,
1185 ),
1186 );
1187 yield* Queue.offer(
1188 input,
1189 yield* encodeJsonl(SessionUpdateNotification, {
1190 jsonrpc: "2.0",
1191 method: "session/update",
1192 params: {
1193 sessionId: "session-1",
1194 update: {
1195 sessionUpdate: "plan",
1196 entries: [
1197 {
1198 content: "Reload skills",
1199 priority: "high",
1200 status: "in_progress",
1201 },
1202 ],
1203 },
1204 },
1205 }),
1206 );
1207
1208 const [update] = yield* Deferred.await(notifications);
1209 assert.equal(update?._tag, "SessionUpdate");
1210 }),
1211 );
1212
1213 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
1214 Effect.gen(function* () {
1215 const { stdio, input, output } = yield* makeInMemoryStdio();
1216 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1217 stdio,
1218 serverRequestMethods: new Set(),
1219 });
1220 const lateResponse = yield* Deferred.make<unknown>();
1221
1222 yield* transport.clientProtocol
1223 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
1224 .pipe(Effect.forkScoped);
1225
1226 const response = yield* transport
1227 .request("x/test", { hello: "world" })
1228 .pipe(Effect.forkScoped);
1229 const outbound = yield* Queue.take(output);
1230 assert.deepEqual(yield* decodeExtRequest(outbound), {
1231 jsonrpc: "2.0",
1232 id: 1,
1233 method: "x/test",
1234 params: {
1235 hello: "world",
1236 },
1237 headers: [],
1238 });
1239
1240 yield* Fiber.interrupt(response);
1241 yield* Queue.offer(
1242 input,
1243 yield* encodeJsonl(ExtResponse, {
1244 jsonrpc: "2.0",
1245 id: 1,
1246 result: {
1247 ok: true,
1248 },
1249 }),
1250 );
1251
1252 const message = yield* Deferred.await(lateResponse);
1253 assert.deepEqual(message, {
1254 _tag: "Exit",
1255 requestId: 1,
1256 exit: {
1257 _tag: "Success",
1258 value: {
1259 ok: true,
1260 },
1261 },
1262 });
1263 }),
1264 );
1265
1266 it.effect("fails pending and later requests when input ends before the process exits", () =>
1267 Effect.gen(function* () {
1268 const { stdio, input, output } = yield* makeInMemoryStdio();
1269 const termination = yield* Deferred.make<AcpError.AcpError>();
1270 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1271 stdio,
1272 terminationError: Effect.never,
1273 serverRequestMethods: new Set(),
1274 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1275 });
1276 const pending = yield* transport
1277 .request("x/test", { hello: "world" })
1278 .pipe(Effect.flip, Effect.orDie, Effect.forkScoped);
1279 yield* Queue.take(output);
1280 yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","id":1,"result":'));
1281 yield* Queue.end(input);
1282
1283 const error = yield* Deferred.await(termination);
1284 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
1285 assert.strictEqual(yield* Fiber.join(pending), error);
1286 assert.strictEqual(
1287 yield* transport.request("x/test", { hello: "later" }).pipe(Effect.flip, Effect.orDie),
1288 error,
1289 );
1290 assert.strictEqual(
1291 yield* transport.notify("session/cancel", { sessionId: "session-1" }).pipe(Effect.flip),
1292 error,
1293 );
1294 }),
1295 );
1296
1297 it.effect("answers a pending request from a final response without a trailing newline", () =>
1298 Effect.gen(function* () {
1299 const { stdio, input, output } = yield* makeInMemoryStdio();
1300 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1301 stdio,
1302 serverRequestMethods: new Set(),
1303 });
1304 const pending = yield* transport
1305 .request("x/test", { hello: "world" })
1306 .pipe(Effect.forkScoped);
1307 yield* Queue.take(output);
1308 yield* Queue.offer(
1309 input,
1310 encoder.encode(encodeUnknownJsonString({ jsonrpc: "2.0", id: 1, result: { ok: true } })),
1311 );
1312 yield* Queue.end(input);
1313
1314 assert.deepEqual(yield* Fiber.join(pending), { ok: true });
1315 }),
1316 );
1317
1318 it.effect("propagates the real child exit code when the input stream ends", () =>
1319 Effect.gen(function* () {
1320 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
1321 const firstMessage = yield* Deferred.make<unknown>();
1322 const termination = yield* Deferred.make<AcpError.AcpError>();
1323 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1324 stdio: makeChildStdio(handle),
1325 terminationError: makeTerminationError(handle),
1326 serverRequestMethods: new Set(),
1327 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1328 });
1329
1330 yield* transport.clientProtocol
1331 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1332 .pipe(Effect.forkScoped);
1333
1334 const message = yield* Deferred.await(firstMessage);
1335 const exitError = yield* Deferred.await(termination);
1336 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
1337 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
1338 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1339 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1340 readonly _tag: string;
1341 readonly message: string;
1342 readonly cause: unknown;
1343 };
1344 assert.equal(defect._tag, "RpcClientDefect");
1345 assert.equal(defect.message, "ACP protocol terminated.");
1346 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
1347 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
1348 }),
1349 );
1350
1351 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
1352 Effect.gen(function* () {
1353 const { stdio, input } = yield* makeInMemoryStdio();
1354 const terminations = yield* Ref.make(0);
1355 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
1356 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1357 stdio,
1358 serverRequestMethods: new Set(),
1359 onTermination: () => Ref.update(terminations, (count) => count + 1),
1360 testHooks: {
1361 onOutgoingWriterExit: (detail) =>
1362 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
1363 },
1364 });
1365
1366 yield* transport.serverProtocol.end(0);
1367 const exitDetail = yield* Deferred.await(writerExit);
1368 assert.isTrue(exitDetail.intentionalEnd);
1369 assert.equal(yield* Ref.get(terminations), 0);
1370
1371 yield* Queue.end(input);
1372 }),
1373 );
1374
1375 it.effect("does not emit a second process-exit error after a decode failure", () =>
1376 Effect.gen(function* () {
1377 const handle = yield* makeHandle({
1378 ACP_MOCK_MALFORMED_OUTPUT: "1",
1379 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
1380 });
1381 const terminationCalls = yield* Ref.make(0);
1382 const firstMessage = yield* Deferred.make<unknown>();
1383 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1384 stdio: makeChildStdio(handle),
1385 terminationError: makeTerminationError(handle),
1386 serverRequestMethods: new Set(),
1387 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
1388 });
1389
1390 yield* transport.clientProtocol
1391 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1392 .pipe(Effect.forkScoped);
1393
1394 const message = yield* Deferred.await(firstMessage);
1395 assert.equal(yield* Ref.get(terminationCalls), 1);
1396 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1397 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1398 readonly _tag: string;
1399 readonly message: string;
1400 readonly cause: unknown;
1401 };
1402 assert.equal(defect._tag, "RpcClientDefect");
1403 assert.equal(defect.message, "ACP protocol terminated.");
1404 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1405 }),
1406 );
1407
1408 it.effect.each(["request", "notification"] as const)(
1409 "rejects a %s if the connection ends while its logger is running",
1410 (operation) =>
1411 Effect.gen(function* () {
1412 const { stdio, input, output } = yield* makeInMemoryStdio();
1413 const writeStarted = yield* Deferred.make<void>();
1414 const releaseWrite = yield* Deferred.make<void>();
1415 const terminated = yield* Deferred.make<AcpError.AcpError>();
1416 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1417 stdio,
1418 serverRequestMethods: new Set(),
1419 logOutgoing: true,
1420 logger: (event) =>
1421 event.stage === "raw"
1422 ? Deferred.succeed(writeStarted, undefined).pipe(
1423 Effect.andThen(Deferred.await(releaseWrite)),
1424 )
1425 : Effect.void,
1426 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1427 });
1428 const send = yield* (
1429 operation === "request"
1430 ? transport.request("x/test", { hello: "world" })
1431 : transport.notify("session/cancel", { sessionId: "session-1" })
1432 ).pipe(Effect.forkScoped);
1433
1434 yield* Deferred.await(writeStarted);
1435 yield* Queue.end(input);
1436 const error = yield* Deferred.await(terminated);
1437 yield* Deferred.succeed(releaseWrite, undefined);
1438
1439 const failure = yield* Fiber.join(send).pipe(
1440 Effect.match({
1441 onFailure: (failure) => failure,
1442 onSuccess: () => assert.fail("Expected the send to fail after termination"),
1443 }),
1444 );
1445 assert.strictEqual(failure, error);
1446 assert.equal(yield* Queue.size(output), 0);
1447 }),
1448 );
1449 });