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