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 Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as Ref from "effect/Ref";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11
12import { it, assert } from "@effect/vitest";
13import * as NodeServices from "@effect/platform-node/NodeServices";
14
15import * as AcpSchema from "./_generated/schema.gen.ts";
16import * as AcpProtocol from "./protocol.ts";
17import {
18 encodeJsonl,
19 jsonRpcNotification,
20 jsonRpcRequest,
21 jsonRpcResponse,
22} from "./_internal/shared.ts";
23import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
24
25const SessionCancelNotification = jsonRpcNotification(
26 "session/cancel",
27 AcpSchema.CancelNotification,
28);
29const SessionUpdateNotification = jsonRpcNotification(
30 "session/update",
31 AcpSchema.SessionNotification,
32);
33const ElicitationCompleteNotification = jsonRpcNotification(
34 "session/elicitation/complete",
35 AcpSchema.ElicitationCompleteNotification,
36);
37const RequestPermissionRequest = jsonRpcRequest(
38 "session/request_permission",
39 AcpSchema.RequestPermissionRequest,
40);
41const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
42const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
43const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
44const decodeSessionCancelNotification = Schema.decodeEffect(
45 Schema.fromJsonString(SessionCancelNotification),
46);
47const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
48const decodeRequestPermissionResponse = Schema.decodeEffect(
49 Schema.fromJsonString(RequestPermissionResponse),
50);
51const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
52const encoder = new TextEncoder();
53const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
54 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
55);
56const mockPeerArgs = (path: string) => [path];
57
58const makeHandle = (env?: Record<string, string>) =>
59 Effect.gen(function* () {
60 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
61 const path = yield* Path.Path;
62 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
63 cwd: path.join(import.meta.dirname, ".."),
64 ...(env ? { env: { ...process.env, ...env } } : {}),
65 });
66 return yield* spawner.spawn(command);
67 });
68
69it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
70 it.effect(
71 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
72 () =>
73 Effect.gen(function* () {
74 const { stdio, input, output } = yield* makeInMemoryStdio();
75 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
76 stdio,
77 serverRequestMethods: new Set(),
78 });
79
80 const notifications =
81 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
82 yield* transport.incoming.pipe(
83 Stream.take(2),
84 Stream.runCollect,
85 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
86 Effect.forkScoped,
87 );
88
89 yield* transport.notify("session/cancel", { sessionId: "session-1" });
90 const outbound = yield* Queue.take(output);
91 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
92 jsonrpc: "2.0",
93 method: "session/cancel",
94 params: {
95 sessionId: "session-1",
96 },
97 });
98
99 yield* Queue.offer(
100 input,
101 yield* encodeJsonl(SessionUpdateNotification, {
102 jsonrpc: "2.0",
103 method: "session/update",
104 params: {
105 sessionId: "session-1",
106 update: {
107 sessionUpdate: "plan",
108 entries: [
109 {
110 content: "Inspect repository",
111 priority: "high",
112 status: "in_progress",
113 },
114 ],
115 },
116 },
117 }),
118 );
119
120 yield* Queue.offer(
121 input,
122 yield* encodeJsonl(ElicitationCompleteNotification, {
123 jsonrpc: "2.0",
124 method: "session/elicitation/complete",
125 params: {
126 elicitationId: "elicitation-1",
127 },
128 }),
129 );
130
131 const [update, completion] = yield* Deferred.await(notifications);
132 assert.equal(update?._tag, "SessionUpdate");
133 assert.equal(completion?._tag, "ElicitationComplete");
134 }),
135 );
136
137 it.effect("keeps invalid core notification values only in the schema cause", () =>
138 Effect.gen(function* () {
139 const secret = "acp-core-notification-secret-sentinel";
140 const { stdio, input } = yield* makeInMemoryStdio();
141 const termination = yield* Deferred.make<AcpError.AcpError>();
142 yield* AcpProtocol.makeAcpPatchedProtocol({
143 stdio,
144 serverRequestMethods: new Set(),
145 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
146 });
147
148 yield* Queue.offer(
149 input,
150 encoder.encode(
151 `${encodeUnknownJsonString({
152 jsonrpc: "2.0",
153 method: "session/update",
154 params: {
155 sessionId: { secret },
156 update: {
157 sessionUpdate: "plan",
158 entries: [],
159 },
160 },
161 })}\n`,
162 ),
163 );
164
165 const error = yield* Deferred.await(termination);
166 assert.instanceOf(error, AcpError.AcpProtocolParseError);
167 const parseError = error as AcpError.AcpProtocolParseError;
168 const { cause, ...directDiagnostics } = parseError;
169 assert.equal(parseError.operation, "decode-notification-payload");
170 assert.equal(parseError.method, "session/update");
171 assert.isAbove(parseError.issueCount ?? 0, 0);
172 assert.include(parseError.issueKinds ?? [], "Pointer");
173 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
174 assert.isTrue(Schema.isSchemaError(cause));
175 assert.notInclude(parseError.message, secret);
176 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
177 }),
178 );
179
180 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
181 Effect.gen(function* () {
182 const { stdio } = yield* makeInMemoryStdio();
183 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
184 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
185 stdio,
186 serverRequestMethods: new Set(),
187 logOutgoing: true,
188 logger: (event) =>
189 Effect.sync(() => {
190 events.push(event);
191 }),
192 });
193
194 yield* transport.notify("session/cancel", { sessionId: "session-1" });
195
196 assert.deepEqual(events, [
197 {
198 direction: "outgoing",
199 stage: "decoded",
200 payload: {
201 _tag: "Request",
202 id: "",
203 tag: "session/cancel",
204 payload: {
205 sessionId: "session-1",
206 },
207 headers: [],
208 },
209 },
210 {
211 direction: "outgoing",
212 stage: "raw",
213 payload:
214 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
215 },
216 ]);
217 }),
218 );
219
220 it.effect("logs decode failures without copying the cause or wire payload", () =>
221 Effect.gen(function* () {
222 const secret = "acp-wire-secret-sentinel";
223 const { stdio, input } = yield* makeInMemoryStdio();
224 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
225 const termination = yield* Deferred.make<AcpError.AcpError>();
226 yield* AcpProtocol.makeAcpPatchedProtocol({
227 stdio,
228 serverRequestMethods: new Set(),
229 logIncoming: true,
230 logger: (event) =>
231 Effect.sync(() => {
232 events.push(event);
233 }),
234 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
235 });
236
237 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
238 yield* Deferred.await(termination);
239
240 const event = events.find(({ stage }) => stage === "decode_failed");
241 assert.deepEqual(event, {
242 direction: "incoming",
243 stage: "decode_failed",
244 payload: {
245 operation: "decode-wire-message",
246 },
247 });
248 assert.notInclude(encodeUnknownJsonString(event), secret);
249 }),
250 );
251
252 it.effect("fails notification encoding through the declared ACP error channel", () =>
253 Effect.gen(function* () {
254 const { stdio } = yield* makeInMemoryStdio();
255 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
256 stdio,
257 serverRequestMethods: new Set(),
258 });
259
260 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
261 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
262 assert.equal(bigintError.operation, "encode-message");
263 assert.equal(bigintError.method, "x/test");
264 assert.instanceOf(bigintError.cause, TypeError);
265 assert.equal(
266 bigintError.message,
267 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
268 );
269
270 const circular: Record<string, unknown> = {};
271 circular.self = circular;
272 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
273 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
274 assert.equal(circularError.operation, "encode-message");
275 assert.equal(circularError.method, "x/test");
276 assert.instanceOf(circularError.cause, TypeError);
277
278 const requestError = yield* transport.request("x/request", 1n).pipe(
279 Effect.match({
280 onFailure: (error) => error,
281 onSuccess: () => assert.fail("Expected request encoding to fail"),
282 }),
283 );
284 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
285 assert.deepInclude(requestError, {
286 operation: "encode-message",
287 method: "x/request",
288 requestId: "1",
289 });
290 }),
291 );
292
293 it.effect("supports generic extension requests over the patched transport", () =>
294 Effect.gen(function* () {
295 const { stdio, input, output } = yield* makeInMemoryStdio();
296 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
297 stdio,
298 serverRequestMethods: new Set(),
299 });
300
301 const response = yield* transport
302 .request("x/test", { hello: "world" })
303 .pipe(Effect.forkScoped);
304 const outbound = yield* Queue.take(output);
305 assert.deepEqual(yield* decodeExtRequest(outbound), {
306 jsonrpc: "2.0",
307 id: 1,
308 method: "x/test",
309 params: {
310 hello: "world",
311 },
312 headers: [],
313 });
314
315 yield* Queue.offer(
316 input,
317 yield* encodeJsonl(ExtResponse, {
318 jsonrpc: "2.0",
319 id: 1,
320 result: {
321 ok: true,
322 },
323 }),
324 );
325
326 const resolved = yield* Fiber.join(response);
327 assert.deepEqual(resolved, { ok: true });
328 }),
329 );
330
331 it.effect("correlates extension response errors with the originating request", () =>
332 Effect.gen(function* () {
333 const { stdio, input, output } = yield* makeInMemoryStdio();
334 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
335 stdio,
336 serverRequestMethods: new Set(),
337 });
338
339 const response = yield* transport
340 .request("x/private", { hello: "world" })
341 .pipe(Effect.forkScoped);
342 yield* Queue.take(output);
343 yield* Queue.offer(
344 input,
345 encoder.encode(
346 `${encodeUnknownJsonString({
347 jsonrpc: "2.0",
348 id: 1,
349 error: {
350 _tag: "Cause",
351 code: -32602,
352 message: "Invalid params",
353 data: [
354 {
355 _tag: "Fail",
356 error: {
357 code: -32602,
358 message: "Invalid params",
359 data: { field: "hello" },
360 },
361 },
362 ],
363 },
364 })}\n`,
365 ),
366 );
367
368 const error = yield* Fiber.join(response).pipe(
369 Effect.match({
370 onFailure: (error) => error,
371 onSuccess: () => assert.fail("Expected extension request to fail"),
372 }),
373 );
374 assert.instanceOf(error, AcpError.AcpRequestError);
375 assert.deepInclude(error, {
376 code: -32602,
377 errorMessage: "Invalid params",
378 method: "x/private",
379 requestId: "1",
380 operation: "receive-response",
381 });
382 }),
383 );
384
385 it.effect("preserves zero-valued ids for inbound core client requests", () =>
386 Effect.gen(function* () {
387 const { stdio, input, output } = yield* makeInMemoryStdio();
388 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
389 stdio,
390 serverRequestMethods: new Set(["session/request_permission"]),
391 });
392 const inboundRequest = yield* Deferred.make<unknown>();
393
394 yield* transport.serverProtocol
395 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
396 .pipe(Effect.forkScoped);
397
398 yield* Queue.offer(
399 input,
400 yield* encodeJsonl(RequestPermissionRequest, {
401 jsonrpc: "2.0",
402 id: 0,
403 method: "session/request_permission",
404 params: {
405 sessionId: "session-1",
406 toolCall: {
407 toolCallId: "tool-1",
408 title: "Allow mock action",
409 },
410 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
411 },
412 headers: [],
413 }),
414 );
415
416 const message = yield* Deferred.await(inboundRequest);
417 assert.deepEqual(message, {
418 _tag: "Request",
419 id: "0",
420 tag: "session/request_permission",
421 payload: {
422 sessionId: "session-1",
423 toolCall: {
424 toolCallId: "tool-1",
425 title: "Allow mock action",
426 },
427 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
428 },
429 headers: [],
430 });
431
432 yield* transport.serverProtocol.send(0, {
433 _tag: "Exit",
434 requestId: "0",
435 exit: {
436 _tag: "Success",
437 value: {
438 outcome: {
439 outcome: "selected",
440 optionId: "allow",
441 },
442 },
443 },
444 });
445
446 const outbound = yield* Queue.take(output);
447 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
448 jsonrpc: "2.0",
449 id: 0,
450 result: {
451 outcome: {
452 outcome: "selected",
453 optionId: "allow",
454 },
455 },
456 });
457 }),
458 );
459
460 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
461 Effect.gen(function* () {
462 const { stdio, input, output } = yield* makeInMemoryStdio();
463 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
464 stdio,
465 serverRequestMethods: new Set(),
466 });
467 const lateResponse = yield* Deferred.make<unknown>();
468
469 yield* transport.clientProtocol
470 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
471 .pipe(Effect.forkScoped);
472
473 const response = yield* transport
474 .request("x/test", { hello: "world" })
475 .pipe(Effect.forkScoped);
476 const outbound = yield* Queue.take(output);
477 assert.deepEqual(yield* decodeExtRequest(outbound), {
478 jsonrpc: "2.0",
479 id: 1,
480 method: "x/test",
481 params: {
482 hello: "world",
483 },
484 headers: [],
485 });
486
487 yield* Fiber.interrupt(response);
488 yield* Queue.offer(
489 input,
490 yield* encodeJsonl(ExtResponse, {
491 jsonrpc: "2.0",
492 id: 1,
493 result: {
494 ok: true,
495 },
496 }),
497 );
498
499 const message = yield* Deferred.await(lateResponse);
500 assert.deepEqual(message, {
501 _tag: "Exit",
502 requestId: "1",
503 exit: {
504 _tag: "Success",
505 value: {
506 ok: true,
507 },
508 },
509 });
510 }),
511 );
512
513 it.effect("propagates the real child exit code when the input stream ends", () =>
514 Effect.gen(function* () {
515 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
516 const firstMessage = yield* Deferred.make<unknown>();
517 const termination = yield* Deferred.make<AcpError.AcpError>();
518 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
519 stdio: makeChildStdio(handle),
520 terminationError: makeTerminationError(handle),
521 serverRequestMethods: new Set(),
522 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
523 });
524
525 yield* transport.clientProtocol
526 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
527 .pipe(Effect.forkScoped);
528
529 const message = yield* Deferred.await(firstMessage);
530 const exitError = yield* Deferred.await(termination);
531 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
532 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
533 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
534 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
535 readonly _tag: string;
536 readonly message: string;
537 readonly cause: unknown;
538 };
539 assert.equal(defect._tag, "RpcClientDefect");
540 assert.equal(defect.message, "ACP protocol terminated.");
541 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
542 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
543 }),
544 );
545
546 it.effect("classifies an input stream ending without inventing a cause", () =>
547 Effect.gen(function* () {
548 const { stdio, input } = yield* makeInMemoryStdio();
549 const termination = yield* Deferred.make<AcpError.AcpError>();
550 yield* AcpProtocol.makeAcpPatchedProtocol({
551 stdio,
552 serverRequestMethods: new Set(),
553 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
554 });
555
556 yield* Queue.end(input);
557
558 const error = yield* Deferred.await(termination);
559 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
560 assert.equal(error.message, "ACP input stream ended.");
561 assert.equal("cause" in error, false);
562 }),
563 );
564
565 it.effect("does not emit a second process-exit error after a decode failure", () =>
566 Effect.gen(function* () {
567 const handle = yield* makeHandle({
568 ACP_MOCK_MALFORMED_OUTPUT: "1",
569 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
570 });
571 const terminationCalls = yield* Ref.make(0);
572 const firstMessage = yield* Deferred.make<unknown>();
573 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
574 stdio: makeChildStdio(handle),
575 terminationError: makeTerminationError(handle),
576 serverRequestMethods: new Set(),
577 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
578 });
579
580 yield* transport.clientProtocol
581 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
582 .pipe(Effect.forkScoped);
583
584 const message = yield* Deferred.await(firstMessage);
585 assert.equal(yield* Ref.get(terminationCalls), 1);
586 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
587 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
588 readonly _tag: string;
589 readonly message: string;
590 readonly cause: unknown;
591 };
592 assert.equal(defect._tag, "RpcClientDefect");
593 assert.equal(defect.message, "ACP protocol terminated.");
594 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
595 }),
596 );
597
598 it.effect("keeps client send failure messages independent from the cause", () =>
599 Effect.gen(function* () {
600 const { stdio } = yield* makeInMemoryStdio();
601 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
602 stdio,
603 serverRequestMethods: new Set(),
604 });
605
606 const failure = yield* transport.clientProtocol
607 .send(0, {
608 _tag: "Request",
609 id: "request-1",
610 tag: "x/test",
611 payload: 1n,
612 headers: [],
613 })
614 .pipe(Effect.flip);
615 const defect = failure.reason as {
616 readonly _tag: string;
617 readonly message: string;
618 readonly cause: unknown;
619 };
620
621 assert.equal(defect._tag, "RpcClientDefect");
622 assert.equal(defect.message, "Failed to send ACP protocol message.");
623 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
624 }),
625 );
626
627 it.effect("fails pending extension requests with the propagated exit code", () =>
628 Effect.gen(function* () {
629 const { stdio, input, output } = yield* makeInMemoryStdio();
630 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
631 stdio,
632 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
633 serverRequestMethods: new Set(),
634 });
635
636 const response = yield* transport
637 .request("x/test", { hello: "world" })
638 .pipe(Effect.forkScoped);
639 yield* Queue.take(output);
640 yield* Queue.end(input);
641
642 const error = yield* Fiber.join(response).pipe(
643 Effect.match({
644 onFailure: (error) => error,
645 onSuccess: () => assert.fail("Expected request to fail after process exit"),
646 }),
647 );
648 assert.instanceOf(error, AcpError.AcpProcessExitedError);
649 assert.equal(error.code, 0);
650 }),
651 );
652});