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;
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 (message.tag === CLIENT_METHODS.session_elicitation_complete) {
320 return decodeElicitationComplete(message.payload).pipe(
321 Effect.map(
322 (params) =>
323 ({
324 _tag: "ElicitationComplete",
325 method: CLIENT_METHODS.session_elicitation_complete,
326 params,
327 }) satisfies AcpIncomingNotification,
328 ),
329 Effect.mapError((cause) =>
330 AcpError.AcpProtocolParseError.fromSchemaError(
331 "decode-notification-payload",
332 CLIENT_METHODS.session_elicitation_complete,
333 cause,
334 ),
335 ),
336 Effect.flatMap(dispatchNotification),
337 );
338 }
339 return dispatchNotification({
340 _tag: "ExtNotification",
341 method: message.tag,
342 params: message.payload,
343 });
344 }
345
346 if (!options.serverRequestMethods.has(message.tag)) {
347 return handleExtRequest(message).pipe(
348 Effect.catchTags({
349 AcpProtocolParseError: (error) =>
350 Effect.logWarning(error).pipe(
351 Effect.annotateLogs({
352 method: message.tag,
353 requestId: message.id,
354 operation: error.operation,
355 }),
356 Effect.andThen(
357 respondWithError(
358 message.id,
359 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
360 message.tag,
361 message.id,
362 error,
363 ),
364 ),
365 ),
366 ),
367 }),
368 Effect.asVoid,
369 );
370 }
371
372 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
373 };
374
375 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
376 Ref.get(extPending).pipe(
377 Effect.flatMap((pending) => {
378 const pendingRequest = pending.get(String(message.requestId));
379 if (!pendingRequest) {
380 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
381 }
382 if (message.exit._tag === "Success") {
383 return completeExtPendingSuccess(message.requestId, message.exit.value);
384 }
385 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
386 if (failure && isProtocolError(failure.error)) {
387 return completeExtPendingFailure(
388 message.requestId,
389 AcpError.AcpRequestError.fromProtocolError(failure.error, {
390 method: pendingRequest.method,
391 requestId: message.requestId,
392 cause: message.exit.cause,
393 }),
394 );
395 }
396 return completeExtPendingFailure(
397 message.requestId,
398 AcpError.AcpRequestError.fromExtensionResponseFailure(
399 pendingRequest.method,
400 message.requestId,
401 message.exit.cause,
402 ),
403 );
404 }),
405 );
406
407 const routeDecodedMessage = (
408 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
409 ): Effect.Effect<void, AcpError.AcpError> => {
410 switch (message._tag) {
411 case "Request":
412 return handleRequestEncoded(message);
413 case "Exit":
414 return handleExitEncoded(message);
415 case "Chunk":
416 return Ref.get(extPending).pipe(
417 Effect.flatMap((pending) => {
418 const pendingRequest = pending.get(String(message.requestId));
419 return pendingRequest
420 ? completeExtPendingFailure(
421 message.requestId,
422 AcpError.AcpRequestError.unsupportedStreamingResponse(
423 pendingRequest.method,
424 message.requestId,
425 ),
426 )
427 : Queue.offer(clientQueue, message).pipe(Effect.asVoid);
428 }),
429 );
430 case "Defect":
431 case "ClientProtocolError":
432 case "Pong":
433 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
434 case "Ack":
435 case "Interrupt":
436 case "Ping":
437 case "Eof":
438 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
439 }
440 };
441
442 yield* options.stdio.stdin.pipe(
443 Stream.runForEach((data) =>
444 (options.logIncoming
445 ? logProtocol({
446 direction: "incoming",
447 stage: "raw",
448 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
449 })
450 : Effect.void
451 ).pipe(
452 Effect.flatMap(() =>
453 Effect.try({
454 try: () =>
455 parser.decode(data) as ReadonlyArray<
456 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
457 >,
458 catch: (cause) =>
459 new AcpError.AcpProtocolParseError({
460 operation: "decode-wire-message",
461 cause,
462 }),
463 }),
464 ),
465 Effect.tap((messages) =>
466 logProtocol({
467 direction: "incoming",
468 stage: "decoded",
469 payload: messages,
470 }),
471 ),
472 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
473 logProtocol({
474 direction: "incoming",
475 stage: "decode_failed",
476 payload: {
477 operation: error.operation,
478 ...(error.method === undefined ? {} : { method: error.method }),
479 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
480 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
481 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
482 ...(error.maximumPathDepth === undefined
483 ? {}
484 : { maximumPathDepth: error.maximumPathDepth }),
485 },
486 }),
487 ),
488 Effect.flatMap((messages) =>
489 Effect.forEach(messages, routeDecodedMessage, {
490 discard: true,
491 }),
492 ),
493 ),
494 ),
495 Effect.matchEffect({
496 onFailure: (error) => {
497 const normalized: AcpError.AcpError = isAcpError(error)
498 ? error
499 : new AcpError.AcpTransportError({
500 operation: "read-input-stream",
501 cause: error,
502 });
503 return handleTermination(() => Effect.succeed(normalized));
504 },
505 onSuccess: () =>
506 handleTermination(
507 () =>
508 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
509 ),
510 }),
511 Effect.forkScoped,
512 );
513
514 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
515
516 const clientProtocol = RpcClient.Protocol.of({
517 run: (_clientId, f) =>
518 Stream.fromQueue(clientQueue).pipe(
519 Stream.runForEach((message) => f(message)),
520 Effect.forever,
521 ),
522 send: (_clientId, request) =>
523 offerOutgoing(request).pipe(
524 Effect.mapError(
525 (error) =>
526 new RpcClientError.RpcClientError({
527 reason: new RpcClientError.RpcClientDefect({
528 message: "Failed to send ACP protocol message.",
529 cause: error,
530 }),
531 }),
532 ),
533 ),
534 supportsAck: true,
535 supportsTransferables: false,
536 });
537
538 const serverProtocol = RpcServer.Protocol.of({
539 run: (f) =>
540 Stream.fromQueue(serverQueue).pipe(
541 Stream.runForEach((message) => f(0, message)),
542 Effect.forever,
543 ),
544 disconnects,
545 send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
546 end: (_clientId) => Queue.end(outgoing),
547 clientIds: Effect.succeed(new Set([0])),
548 initialMessage: Effect.succeedNone,
549 supportsAck: true,
550 supportsTransferables: false,
551 supportsSpanPropagation: true,
552 });
553
554 // JSON-RPC notifications carry no `id`. The generic Request encoder emits `id: ""` plus
555 // `headers`, which real agents (Grok CLI) parse as a malformed request and silently drop.
556 // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
557 const sendNotification = Effect.fn("sendNotification")(function* (
558 method: string,
559 payload: unknown,
560 ) {
561 yield* ensureActive;
562 yield* logProtocol({
563 direction: "outgoing",
564 stage: "decoded",
565 payload: { _tag: "Notification", tag: method, payload },
566 });
567 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
568 if (Exit.isFailure(exit)) {
569 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
570 method,
571 undefined,
572 Cause.squash(exit.cause),
573 );
574 }
575 const encoded = `${exit.value}\n`;
576 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
577 yield* ensureActive;
578 yield* Queue.offer(outgoing, encoded);
579 });
580
581 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
582 yield* ensureActive;
583 const requestId = yield* Ref.modify(
584 nextRequestId,
585 (current) => [current, current + 1] as const,
586 );
587 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
588 yield* Ref.update(extPending, (pending) =>
589 new Map(pending).set(String(requestId), { deferred, method }),
590 );
591 yield* offerOutgoing({
592 _tag: "Request",
593 id: requestId,
594 tag: method,
595 payload,
596 headers: [],
597 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
598 return yield* Deferred.await(deferred).pipe(
599 Effect.onInterrupt(() => removeExtPending(requestId)),
600 );
601 });
602
603 return {
604 clientProtocol,
605 serverProtocol,
606 get incoming() {
607 return Stream.fromQueue(notificationQueue);
608 },
609 request: sendRequest,
610 notify: sendNotification,
611 } satisfies AcpPatchedProtocol;
612});
613
614function isProtocolError(
615 value: unknown,
616): value is { code: number; message: string; data?: unknown } {
617 return (
618 typeof value === "object" &&
619 value !== null &&
620 "code" in value &&
621 typeof value.code === "number" &&
622 "message" in value &&
623 typeof value.message === "string"
624 );
625}