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