Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Deferred from "effect/Deferred";
4import * as Exit from "effect/Exit";
5import * as Queue from "effect/Queue";
6import * as Ref from "effect/Ref";
7import type * as PlatformError from "effect/PlatformError";
8import * as Schema from "effect/Schema";
9import * as Scope from "effect/Scope";
10import * as Stream from "effect/Stream";
11import * as Stdio from "effect/Stdio";
12import * as RpcClient from "effect/unstable/rpc/RpcClient";
13import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
14import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
15import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
16import * as RpcServer from "effect/unstable/rpc/RpcServer";
17
18import * as AcpSchema from "./_generated/schema.gen.ts";
19import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
20import * as AcpError from "./errors.ts";
21const isAcpError = Schema.is(AcpError.AcpError);
22
23export interface AcpProtocolLogEvent {
24 readonly direction: "incoming" | "outgoing";
25 readonly stage: "raw" | "decoded" | "decode_failed";
26 readonly payload: unknown;
27}
28
29export type AcpIncomingNotification =
30 | {
31 readonly _tag: "SessionUpdate";
32 readonly method: typeof CLIENT_METHODS.session_update;
33 readonly params: AcpSchema.SessionNotification;
34 }
35 | {
36 readonly _tag: "ElicitationComplete";
37 readonly method: typeof CLIENT_METHODS.session_elicitation_complete | "elicitation/complete";
38 readonly params: AcpSchema.ElicitationCompleteNotification;
39 }
40 | {
41 readonly _tag: "ExtNotification";
42 readonly method: string;
43 readonly params: unknown;
44 };
45
46/** Standard I/O whose input can report provider-specific ACP failures. */
47export interface AcpStdio extends Omit<Stdio.Stdio, "stdin"> {
48 readonly stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpError.AcpError>;
49}
50
51export interface AcpPatchedProtocolOptions {
52 readonly stdio: AcpStdio;
53 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
54 readonly serverRequestMethods: ReadonlySet<string>;
55 readonly logIncoming?: boolean;
56 readonly logOutgoing?: boolean;
57 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
58 readonly transformSessionUpdate?: (
59 notification: AcpSchema.SessionNotification,
60 ) => AcpSchema.SessionNotification;
61 readonly onNotification?: (
62 notification: AcpIncomingNotification,
63 ) => Effect.Effect<void, AcpError.AcpError, never>;
64 readonly onExtRequest?: (
65 method: string,
66 params: unknown,
67 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
68 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
69}
70
71export interface AcpPatchedProtocol {
72 readonly clientProtocol: RpcClient.Protocol["Service"];
73 readonly serverProtocol: RpcServer.Protocol["Service"];
74 readonly incoming: Stream.Stream<AcpIncomingNotification>;
75 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
76 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
77}
78
79interface AcpPendingRequest {
80 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
81 readonly method: string;
82}
83
84const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
85const decodeElicitationComplete = Schema.decodeUnknownEffect(
86 AcpSchema.ElicitationCompleteNotification,
87);
88const parserFactory = RpcSerialization.ndJsonRpc();
89const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
90// Outbound JSON-RPC notification: no `id`, so peers never treat it as a request.
91const encodeJsonRpcNotification = Schema.encodeUnknownExit(
92 Schema.fromJsonString(
93 Schema.Struct({
94 jsonrpc: Schema.Literal("2.0"),
95 method: Schema.String,
96 params: Schema.Unknown,
97 }),
98 ),
99);
100
101export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
102 options: AcpPatchedProtocolOptions,
103): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
104 const parser = parserFactory.makeUnsafe();
105 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
106 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
107 const notificationQueue = yield* Queue.sliding<AcpIncomingNotification>(
108 MAX_BUFFERED_RAW_NOTIFICATIONS,
109 );
110 const disconnects = yield* Queue.unbounded<number>();
111 const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
112 const nextRequestId = yield* Ref.make(1);
113 const terminationHandled = yield* Ref.make(false);
114 const terminationFailure = yield* Deferred.make<never, AcpError.AcpError>();
115 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
116
117 const ensureActive = Ref.get(terminationHandled).pipe(
118 Effect.flatMap((terminated) => (terminated ? Deferred.await(terminationFailure) : Effect.void)),
119 );
120
121 const logProtocol = (event: AcpProtocolLogEvent) => {
122 if (event.direction === "incoming" && !options.logIncoming) {
123 return Effect.void;
124 }
125 if (event.direction === "outgoing" && !options.logOutgoing) {
126 return Effect.void;
127 }
128 return (
129 options.logger?.(event) ??
130 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
131 );
132 };
133
134 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
135 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
136 ) {
137 // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
138 // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
139 if (message._tag === "Interrupt") {
140 return;
141 }
142 yield* ensureActive;
143 yield* logProtocol({
144 direction: "outgoing",
145 stage: "decoded",
146 payload: message,
147 });
148
149 const method = message._tag === "Request" ? message.tag : undefined;
150 const encodedRequestId =
151 message._tag === "Request"
152 ? message.id
153 : "requestId" in message
154 ? message.requestId
155 : undefined;
156 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
157 const encoded = yield* Effect.try({
158 try: () => parser.encode(message),
159 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
160 });
161
162 if (encoded) {
163 yield* logProtocol({
164 direction: "outgoing",
165 stage: "raw",
166 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
167 });
168
169 yield* ensureActive;
170 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
171 }
172 });
173
174 const resolveExtPending = (
175 requestId: AcpError.AcpRequestId,
176 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
177 ) =>
178 Ref.modify(extPending, (pending) => {
179 const pendingKey = String(requestId);
180 const pendingRequest = pending.get(pendingKey);
181 if (!pendingRequest) {
182 return [Effect.void, pending] as const;
183 }
184 const next = new Map(pending);
185 next.delete(pendingKey);
186 return [onFound(pendingRequest), next] as const;
187 }).pipe(Effect.flatten);
188
189 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
190 Ref.update(extPending, (pending) => {
191 const pendingKey = String(requestId);
192 if (!pending.has(pendingKey)) {
193 return pending;
194 }
195 const next = new Map(pending);
196 next.delete(pendingKey);
197 return next;
198 });
199
200 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
201 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
202
203 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
204 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
205
206 const failAllExtPending = (error: AcpError.AcpError) =>
207 Ref.getAndSet(extPending, new Map()).pipe(
208 Effect.flatMap((pending) =>
209 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
210 discard: true,
211 }),
212 ),
213 );
214
215 const dispatchNotification = (notification: AcpIncomingNotification) =>
216 Queue.offer(notificationQueue, notification).pipe(
217 Effect.andThen(
218 options.onNotification
219 ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
220 : Effect.void,
221 ),
222 Effect.asVoid,
223 );
224
225 const emitClientProtocolError = (error: AcpError.AcpError) =>
226 Queue.offer(clientQueue, {
227 _tag: "ClientProtocolError",
228 error: new RpcClientError.RpcClientError({
229 reason: new RpcClientError.RpcClientDefect({
230 message: "ACP protocol terminated.",
231 cause: error,
232 }),
233 }),
234 }).pipe(Effect.asVoid);
235
236 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError>) =>
237 Ref.modify(terminationHandled, (handled) => {
238 if (handled) {
239 return [Effect.void, true] as const;
240 }
241 return [
242 Effect.gen(function* () {
243 yield* Queue.offer(disconnects, 0);
244 const error = yield* classify();
245 yield* Deferred.fail(terminationFailure, error);
246 yield* failAllExtPending(error);
247 yield* emitClientProtocolError(error);
248 if (options.onTermination) {
249 yield* options.onTermination(error);
250 }
251 }),
252 true,
253 ] as const;
254 }).pipe(Effect.flatten);
255
256 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
257 offerOutgoing({
258 _tag: "Exit",
259 requestId,
260 exit: {
261 _tag: "Success",
262 value,
263 },
264 });
265
266 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
267 offerOutgoing({
268 _tag: "Exit",
269 requestId,
270 exit: {
271 _tag: "Failure",
272 cause: [
273 {
274 _tag: "Fail",
275 error: error.toProtocolError(),
276 },
277 ],
278 },
279 });
280
281 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
282 if (!options.onExtRequest) {
283 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
284 }
285 return options.onExtRequest(message.tag, message.payload).pipe(
286 Effect.matchEffect({
287 onFailure: (error) =>
288 respondWithError(
289 message.id,
290 AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
291 ),
292 onSuccess: (value) => respondWithSuccess(message.id, value),
293 }),
294 );
295 };
296
297 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
298 if (message.id === "") {
299 if (message.tag === CLIENT_METHODS.session_update) {
300 return decodeSessionUpdate(message.payload).pipe(
301 Effect.map(
302 (params) =>
303 ({
304 _tag: "SessionUpdate",
305 method: CLIENT_METHODS.session_update,
306 params: options.transformSessionUpdate?.(params) ?? params,
307 }) satisfies AcpIncomingNotification,
308 ),
309 Effect.mapError((cause) =>
310 AcpError.AcpProtocolParseError.fromSchemaError(
311 "decode-notification-payload",
312 CLIENT_METHODS.session_update,
313 cause,
314 ),
315 ),
316 Effect.flatMap(dispatchNotification),
317 );
318 }
319 if (
320 message.tag === CLIENT_METHODS.session_elicitation_complete ||
321 message.tag === "elicitation/complete"
322 ) {
323 const method = message.tag;
324 return decodeElicitationComplete(message.payload).pipe(
325 Effect.map(
326 (params) =>
327 ({
328 _tag: "ElicitationComplete",
329 method,
330 params,
331 }) satisfies AcpIncomingNotification,
332 ),
333 Effect.mapError((cause) =>
334 AcpError.AcpProtocolParseError.fromSchemaError(
335 "decode-notification-payload",
336 method,
337 cause,
338 ),
339 ),
340 Effect.flatMap(dispatchNotification),
341 );
342 }
343 return dispatchNotification({
344 _tag: "ExtNotification",
345 method: message.tag,
346 params: message.payload,
347 });
348 }
349
350 if (!options.serverRequestMethods.has(message.tag)) {
351 return handleExtRequest(message).pipe(
352 Effect.catchTags({
353 AcpProtocolParseError: (error) =>
354 Effect.logWarning(error).pipe(
355 Effect.annotateLogs({
356 method: message.tag,
357 requestId: message.id,
358 operation: error.operation,
359 }),
360 Effect.andThen(
361 respondWithError(
362 message.id,
363 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
364 message.tag,
365 message.id,
366 error,
367 ),
368 ),
369 ),
370 ),
371 }),
372 Effect.asVoid,
373 );
374 }
375
376 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
377 };
378
379 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
380 Ref.get(extPending).pipe(
381 Effect.flatMap((pending) => {
382 const pendingRequest = pending.get(String(message.requestId));
383 if (!pendingRequest) {
384 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
385 }
386 if (message.exit._tag === "Success") {
387 return completeExtPendingSuccess(message.requestId, message.exit.value);
388 }
389 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
390 if (failure && isProtocolError(failure.error)) {
391 return completeExtPendingFailure(
392 message.requestId,
393 AcpError.AcpRequestError.fromProtocolError(failure.error, {
394 method: pendingRequest.method,
395 requestId: message.requestId,
396 cause: message.exit.cause,
397 }),
398 );
399 }
400 return completeExtPendingFailure(
401 message.requestId,
402 AcpError.AcpRequestError.fromExtensionResponseFailure(
403 pendingRequest.method,
404 message.requestId,
405 message.exit.cause,
406 ),
407 );
408 }),
409 );
410
411 const routeDecodedMessage = (
412 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
413 ): Effect.Effect<void, AcpError.AcpError> => {
414 switch (message._tag) {
415 case "Request":
416 return handleRequestEncoded(message);
417 case "Exit":
418 return handleExitEncoded(message);
419 case "Chunk":
420 return Ref.get(extPending).pipe(
421 Effect.flatMap((pending) => {
422 const pendingRequest = pending.get(String(message.requestId));
423 return pendingRequest
424 ? completeExtPendingFailure(
425 message.requestId,
426 AcpError.AcpRequestError.unsupportedStreamingResponse(
427 pendingRequest.method,
428 message.requestId,
429 ),
430 )
431 : Queue.offer(clientQueue, message).pipe(Effect.asVoid);
432 }),
433 );
434 case "Defect":
435 case "ClientProtocolError":
436 case "Pong":
437 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
438 case "Ack":
439 case "Interrupt":
440 case "Ping":
441 case "Eof":
442 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
443 }
444 };
445
446 yield* options.stdio.stdin.pipe(
447 Stream.runForEach((data) =>
448 (options.logIncoming
449 ? logProtocol({
450 direction: "incoming",
451 stage: "raw",
452 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
453 })
454 : Effect.void
455 ).pipe(
456 Effect.flatMap(() =>
457 Effect.try({
458 try: () =>
459 parser.decode(data) as ReadonlyArray<
460 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
461 >,
462 catch: (cause) =>
463 new AcpError.AcpProtocolParseError({
464 operation: "decode-wire-message",
465 cause,
466 }),
467 }),
468 ),
469 Effect.tap((messages) =>
470 logProtocol({
471 direction: "incoming",
472 stage: "decoded",
473 payload: messages,
474 }),
475 ),
476 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
477 logProtocol({
478 direction: "incoming",
479 stage: "decode_failed",
480 payload: {
481 operation: error.operation,
482 ...(error.method === undefined ? {} : { method: error.method }),
483 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
484 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
485 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
486 ...(error.maximumPathDepth === undefined
487 ? {}
488 : { maximumPathDepth: error.maximumPathDepth }),
489 },
490 }),
491 ),
492 Effect.flatMap((messages) =>
493 Effect.forEach(messages, routeDecodedMessage, {
494 discard: true,
495 }),
496 ),
497 ),
498 ),
499 Effect.matchEffect({
500 onFailure: (error) => {
501 const normalized: AcpError.AcpError = isAcpError(error)
502 ? error
503 : new AcpError.AcpTransportError({
504 operation: "read-input-stream",
505 cause: error,
506 });
507 return handleTermination(() => Effect.succeed(normalized));
508 },
509 onSuccess: () =>
510 handleTermination(
511 () =>
512 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
513 ),
514 }),
515 Effect.forkScoped,
516 );
517
518 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
519
520 const clientProtocol = RpcClient.Protocol.of({
521 run: (_clientId, f) =>
522 Stream.fromQueue(clientQueue).pipe(
523 Stream.runForEach((message) => f(message)),
524 Effect.forever,
525 ),
526 send: (_clientId, request) =>
527 offerOutgoing(request).pipe(
528 Effect.mapError(
529 (error) =>
530 new RpcClientError.RpcClientError({
531 reason: new RpcClientError.RpcClientDefect({
532 message: "Failed to send ACP protocol message.",
533 cause: error,
534 }),
535 }),
536 ),
537 ),
538 supportsAck: true,
539 supportsTransferables: false,
540 codecFor: parserFactory.codecFor,
541 });
542
543 const serverProtocol = RpcServer.Protocol.of({
544 run: (f) =>
545 Stream.fromQueue(serverQueue).pipe(
546 Stream.runForEach((message) => f(0, message)),
547 Effect.forever,
548 ),
549 disconnects,
550 send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
551 end: (_clientId) => Queue.end(outgoing),
552 clientIds: Effect.succeed(new Set([0])),
553 initialMessage: Effect.succeedNone,
554 supportsAck: true,
555 supportsTransferables: false,
556 codecFor: parserFactory.codecFor,
557 supportsSpanPropagation: true,
558 supportsNotifications: true,
559 });
560
561 // JSON-RPC notifications carry no `id`. Encoding a Request without `isNotification`
562 // emits an `id`, which real agents (Grok CLI) parse as a malformed request and silently drop.
563 // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
564 const sendNotification = Effect.fn("sendNotification")(function* (
565 method: string,
566 payload: unknown,
567 ) {
568 yield* ensureActive;
569 yield* logProtocol({
570 direction: "outgoing",
571 stage: "decoded",
572 payload: { _tag: "Notification", tag: method, payload },
573 });
574 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
575 if (Exit.isFailure(exit)) {
576 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
577 method,
578 undefined,
579 Cause.squash(exit.cause),
580 );
581 }
582 const encoded = `${exit.value}\n`;
583 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
584 yield* ensureActive;
585 yield* Queue.offer(outgoing, encoded);
586 });
587
588 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
589 yield* ensureActive;
590 const requestId = yield* Ref.modify(
591 nextRequestId,
592 (current) => [current, current + 1] as const,
593 );
594 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
595 yield* Ref.update(extPending, (pending) =>
596 new Map(pending).set(String(requestId), { deferred, method }),
597 );
598 yield* offerOutgoing({
599 _tag: "Request",
600 id: requestId,
601 tag: method,
602 payload,
603 headers: [],
604 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
605 return yield* Deferred.await(deferred).pipe(
606 Effect.onInterrupt(() => removeExtPending(requestId)),
607 );
608 });
609
610 return {
611 clientProtocol,
612 serverProtocol,
613 get incoming() {
614 return Stream.fromQueue(notificationQueue);
615 },
616 request: sendRequest,
617 notify: sendNotification,
618 } satisfies AcpPatchedProtocol;
619});
620
621function isProtocolError(
622 value: unknown,
623): value is { code: number; message: string; data?: unknown } {
624 return (
625 typeof value === "object" &&
626 value !== null &&
627 "code" in value &&
628 typeof value.code === "number" &&
629 "message" in value &&
630 typeof value.message === "string"
631 );
632}