Open History to see the last commit
1import type * as AcpCompat from "./compat.ts";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Deferred from "effect/Deferred";
5import * as Exit from "effect/Exit";
6import * as Option from "effect/Option";
7import * as Queue from "effect/Queue";
8import * as Ref from "effect/Ref";
9import type * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import * as Stdio from "effect/Stdio";
14import * as RpcClient from "effect/rpc/RpcClient";
15import * as RpcClientError from "effect/rpc/RpcClientError";
16import * as RpcMessage from "effect/rpc/RpcMessage";
17import * as RpcSerialization from "effect/rpc/RpcSerialization";
18import * as RpcServer from "effect/rpc/RpcServer";
19
20import * as AcpSchema from "./schema.ts";
21import * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts";
22import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
23import * as AcpError from "./errors.ts";
24import { isolateNotificationHandler } from "./_internal/shared.ts";
25const isAcpError = Schema.is(AcpError.AcpError);
26
27export interface AcpProtocolLogEvent {
28 readonly direction: "incoming" | "outgoing";
29 readonly stage: "raw" | "decoded" | "decode_failed";
30 readonly payload: unknown;
31}
32
33export interface AcpRequestContext {
34 readonly requestId: string;
35 readonly method: string;
36}
37
38export function acpRequestIdentity(requestId: AcpError.AcpRequestId): string {
39 const prefix = "$t3:jsonrpc:";
40 if (typeof requestId === "number") return `${prefix}number:${requestId}`;
41 return requestId.startsWith(prefix) ? `${prefix}string:${requestId}` : requestId;
42}
43
44export type AcpRequestHandler<Request, Response> = (
45 request: Request,
46 context: AcpRequestContext,
47) => Effect.Effect<Response, AcpError.AcpError>;
48
49export type AcpIncomingNotification =
50 | {
51 readonly _tag: "SessionUpdate";
52 readonly method: typeof CLIENT_METHODS.session_update;
53 readonly params:
54 | AcpSchema.UpdateSessionNotification
55 | AcpSchemaV1.SessionNotification
56 | AcpCompat.SessionNotification;
57 }
58 | {
59 readonly _tag: "ElicitationComplete";
60 readonly method: typeof CLIENT_METHODS.elicitation_complete | "session/elicitation/complete";
61 readonly params: AcpSchema.CompleteElicitationNotification;
62 }
63 | {
64 readonly _tag: "ExtNotification";
65 readonly method: string;
66 readonly params: unknown;
67 };
68
69export interface AcpStdio extends Omit<Stdio.Stdio, "stdin"> {
70 readonly stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpError.AcpError>;
71}
72
73export interface AcpPatchedProtocolOptions {
74 readonly stdio: AcpStdio;
75 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
76 readonly serverRequestMethods: ReadonlySet<string>;
77 readonly logIncoming?: boolean;
78 readonly logOutgoing?: boolean;
79 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
80 readonly onIncomingRequest?: (
81 requestId: string,
82 method: string,
83 payload: unknown,
84 ) => Effect.Effect<void, never>;
85
86 readonly transformSessionUpdate?: (
87 notification:
88 | AcpSchema.UpdateSessionNotification
89 | AcpSchemaV1.SessionNotification
90 | AcpCompat.SessionNotification,
91 ) =>
92 | AcpSchema.UpdateSessionNotification
93 | AcpSchemaV1.SessionNotification
94 | AcpCompat.SessionNotification;
95 readonly onNotification?: (
96 notification: AcpIncomingNotification,
97 ) => Effect.Effect<void, AcpError.AcpError, never>;
98 readonly onExtRequest?: (
99 method: string,
100 params: unknown,
101 context: AcpRequestContext,
102 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
103 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
104 readonly onOutgoingResponseFailure?: (
105 requestId: string,
106 error: AcpError.AcpError,
107 ) => Effect.Effect<void, never>;
108 readonly onOutgoingResponse?: (requestId: string) => Effect.Effect<void, never>;
109 readonly testHooks?: {
110 readonly onOutgoingWriteAdmitted?: () => Effect.Effect<void>;
111 readonly onOutgoingWriterExit?: (input: {
112 readonly intentionalEnd: boolean;
113 }) => Effect.Effect<void>;
114 };
115}
116
117export interface AcpPatchedProtocol {
118 readonly clientProtocol: RpcClient.Protocol["Service"];
119 readonly serverProtocol: RpcServer.Protocol["Service"];
120 readonly incoming: Stream.Stream<AcpIncomingNotification>;
121 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
122 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
123}
124
125interface AcpPendingRequest {
126 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
127 readonly method: string;
128}
129
130interface AcpOutgoingWrite {
131 readonly acknowledgement?: Deferred.Deferred<void, AcpError.AcpError>;
132 readonly payload: string | Uint8Array;
133}
134
135interface AcpOutgoingWriterState {
136 readonly outstandingAcknowledgements: ReadonlySet<Deferred.Deferred<void, AcpError.AcpError>>;
137 readonly intentionalEnd: boolean;
138 readonly terminalError?: AcpError.AcpError;
139}
140
141const decodeSessionUpdate = Schema.decodeUnknownEffect(
142 Schema.Union([
143 // Claude ACP v2 reports prompt failures on idle; alpha.3 omits that field.
144 Schema.Struct({
145 ...AcpSchema.UpdateSessionNotification.fields,
146 update: Schema.Struct({
147 sessionUpdate: Schema.Literal("state_update"),
148 state: Schema.Literal("idle"),
149 stopReason: Schema.optionalKey(Schema.NullOr(AcpSchema.StopReason)),
150 usage: Schema.optionalKey(Schema.NullOr(AcpSchema.Usage)),
151 error: Schema.optionalKey(Schema.NullOr(AcpSchema.Error)),
152 _meta: AcpSchema.UpdateSessionNotification.fields._meta,
153 }),
154 }),
155 AcpSchema.UpdateSessionNotification,
156 AcpSchemaV1.SessionNotification,
157 ]),
158);
159const decodeElicitationComplete = Schema.decodeUnknownEffect(
160 AcpSchema.CompleteElicitationNotification,
161);
162const parserFactory = RpcSerialization.ndJsonRpc();
163// ndJsonRpc skips lines that are not JSON. A malformed agent line has to end the
164// session, so frames are split here and each one goes through the strict codec.
165const makeStrictNdJsonRpcParser = () => {
166 const codec = RpcSerialization.jsonRpc().makeUnsafe();
167 const decoder = new TextDecoder();
168 let buffer = "";
169 return {
170 decode: (bytes: Uint8Array | string): ReadonlyArray<unknown> => {
171 buffer += typeof bytes === "string" ? bytes : decoder.decode(bytes, { stream: true });
172 const lines = buffer.split("\n");
173 buffer = lines.pop() ?? "";
174 return lines.flatMap((line) => codec.decode(line));
175 },
176 encode: (response: Parameters<typeof codec.encode>[0]) => {
177 const encoded = codec.encode(response);
178 return encoded === undefined ? undefined : `${encoded}\n`;
179 },
180 };
181};
182const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
183
184const decodeFailureDiagnostics = (error: AcpError.AcpProtocolParseError) => ({
185 operation: error.operation,
186 ...(error.method === undefined ? {} : { method: error.method }),
187 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
188 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
189 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
190 ...(error.maximumPathDepth === undefined ? {} : { maximumPathDepth: error.maximumPathDepth }),
191 ...(error.issueSummary === undefined ? {} : { issueSummary: error.issueSummary }),
192});
193const encodeJsonRpcNotification = Schema.encodeUnknownExit(
194 Schema.fromJsonString(
195 Schema.Struct({
196 jsonrpc: Schema.Literal("2.0"),
197 method: Schema.String,
198 params: Schema.Unknown,
199 }),
200 ),
201);
202
203/**
204 * First id for typed Effect RPC requests. Starts within signed int32 for SDKs that reject
205 * larger numeric ids (e.g. the Kotlin ACP SDK decodes ids as `Int`), while staying far
206 * above extension ids, which count up from 1.
207 */
208export const RPC_REQUEST_ID_START = 2 ** 30;
209
210const isEffectRpcRequestId = (requestId: AcpError.AcpRequestId): boolean =>
211 typeof requestId === "number" && Number.isSafeInteger(requestId);
212
213/**
214 * Effect RPC's JSON-RPC codec treats a standard JSON-RPC error object as a
215 * defect unless it carries Effect's private `_tag: "Cause"` envelope.
216 */
217function normalizeAcpJsonRpcError(
218 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
219): RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded {
220 if (message._tag !== "Exit" || message.exit._tag !== "Failure") return message;
221 const [failure] = message.exit.cause;
222 if (
223 message.exit.cause.length !== 1 ||
224 failure?._tag !== "Die" ||
225 !isProtocolError(failure.defect)
226 ) {
227 return message;
228 }
229 return {
230 ...message,
231 exit: {
232 _tag: "Failure",
233 cause: [{ _tag: "Fail", error: failure.defect }],
234 },
235 };
236}
237
238export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
239 options: AcpPatchedProtocolOptions,
240): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
241 const parser = makeStrictNdJsonRpcParser();
242 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
243 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
244 const notificationQueue = yield* Queue.sliding<AcpIncomingNotification>(
245 MAX_BUFFERED_RAW_NOTIFICATIONS,
246 );
247 const disconnects = yield* Queue.unbounded<number>();
248 const outgoing = yield* Queue.unbounded<AcpOutgoingWrite, AcpError.AcpError | Cause.Done<void>>();
249 const outgoingWriterState = yield* Ref.make<AcpOutgoingWriterState>({
250 intentionalEnd: false,
251 outstandingAcknowledgements: new Set(),
252 });
253 const nextRequestId = yield* Ref.make(1);
254 const warnedDecodeFailures = new Set<string>();
255 const terminationHandled = yield* Ref.make(false);
256 const terminationFailure = yield* Deferred.make<never, AcpError.AcpError>();
257 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
258
259 const ensureActive = Ref.get(terminationHandled).pipe(
260 Effect.flatMap((terminated) => (terminated ? Deferred.await(terminationFailure) : Effect.void)),
261 );
262
263 const logProtocol = (event: AcpProtocolLogEvent) => {
264 if (event.direction === "incoming" && !options.logIncoming) {
265 return Effect.void;
266 }
267 if (event.direction === "outgoing" && !options.logOutgoing) {
268 return Effect.void;
269 }
270 return (
271 options.logger?.(event) ??
272 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
273 );
274 };
275
276 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
277 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
278 ) {
279 // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
280 // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
281 if (message._tag === "Interrupt") {
282 return;
283 }
284 yield* ensureActive;
285 yield* logProtocol({
286 direction: "outgoing",
287 stage: "decoded",
288 payload: message,
289 });
290
291 const method = message._tag === "Request" ? message.tag : undefined;
292 const encodedRequestId =
293 message._tag === "Request"
294 ? message.id
295 : "requestId" in message
296 ? message.requestId
297 : undefined;
298 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
299 const encoded = yield* Effect.try({
300 try: () => parser.encode(message),
301 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
302 });
303
304 if (encoded) {
305 yield* logProtocol({
306 direction: "outgoing",
307 stage: "raw",
308 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
309 });
310
311 yield* ensureActive;
312 const acknowledgement =
313 message._tag === "Exit" ? yield* Deferred.make<void, AcpError.AcpError>() : undefined;
314 const admissionError = yield* Ref.modify(outgoingWriterState, (state) => {
315 if (state.terminalError !== undefined) {
316 return [state.terminalError, state] as const;
317 }
318 if (acknowledgement === undefined) {
319 return [undefined, state] as const;
320 }
321 return [
322 undefined,
323 {
324 ...state,
325 outstandingAcknowledgements: new Set(state.outstandingAcknowledgements).add(
326 acknowledgement,
327 ),
328 },
329 ] as const;
330 });
331 if (admissionError !== undefined) {
332 return yield* admissionError;
333 }
334 if (options.testHooks?.onOutgoingWriteAdmitted !== undefined) {
335 yield* options.testHooks.onOutgoingWriteAdmitted();
336 }
337 yield* Queue.offer(outgoing, {
338 payload: encoded,
339 ...(acknowledgement === undefined ? {} : { acknowledgement }),
340 }).pipe(
341 Effect.mapError(
342 (cause) =>
343 new AcpError.AcpTransportError({
344 detail: "Failed to queue an outgoing ACP message",
345 cause,
346 }),
347 ),
348 Effect.filterOrFail(
349 (accepted) => accepted,
350 () =>
351 new AcpError.AcpTransportError({
352 detail: "The ACP output queue was closed before accepting a message",
353 cause: "Output queue closed",
354 }),
355 ),
356 Effect.tapError((error) =>
357 acknowledgement === undefined
358 ? Effect.void
359 : Ref.update(outgoingWriterState, (state) => {
360 const updated = new Set(state.outstandingAcknowledgements);
361 updated.delete(acknowledgement);
362 return { ...state, outstandingAcknowledgements: updated };
363 }).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid),
364 ),
365 );
366 if (acknowledgement !== undefined) {
367 yield* Deferred.await(acknowledgement);
368 }
369 if (message._tag === "Exit" && options.onOutgoingResponse !== undefined) {
370 yield* options.onOutgoingResponse(acpRequestIdentity(message.requestId));
371 }
372 }
373 });
374
375 const resolveExtPending = (
376 requestId: AcpError.AcpRequestId,
377 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
378 ) =>
379 Ref.modify(extPending, (pending) => {
380 const pendingKey = acpRequestIdentity(requestId);
381 const pendingRequest = pending.get(pendingKey);
382 if (!pendingRequest) {
383 return [Effect.void, pending] as const;
384 }
385 const next = new Map(pending);
386 next.delete(pendingKey);
387 return [onFound(pendingRequest), next] as const;
388 }).pipe(Effect.flatten);
389
390 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
391 Ref.update(extPending, (pending) => {
392 const pendingKey = acpRequestIdentity(requestId);
393 if (!pending.has(pendingKey)) {
394 return pending;
395 }
396 const next = new Map(pending);
397 next.delete(pendingKey);
398 return next;
399 });
400
401 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
402 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
403
404 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
405 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
406
407 const failAllExtPending = (error: AcpError.AcpError) =>
408 Ref.getAndSet(extPending, new Map()).pipe(
409 Effect.flatMap((pending) =>
410 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
411 discard: true,
412 }),
413 ),
414 );
415
416 const dispatchNotification = (notification: AcpIncomingNotification) =>
417 Queue.offer(notificationQueue, notification).pipe(
418 Effect.andThen(
419 // A failing or dying handler must not stop the reader, or every later
420 // message on the connection goes unanswered.
421 options.onNotification
422 ? isolateNotificationHandler(options.onNotification(notification))
423 : Effect.void,
424 ),
425 Effect.asVoid,
426 );
427
428 const emitClientProtocolError = (error: AcpError.AcpError) =>
429 Queue.offer(clientQueue, {
430 _tag: "ClientProtocolError",
431 error: new RpcClientError.RpcClientError({
432 reason: new RpcClientError.RpcClientDefect({
433 message: "ACP protocol terminated.",
434 cause: error,
435 }),
436 }),
437 }).pipe(Effect.asVoid);
438
439 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError>) =>
440 Ref.modify(terminationHandled, (handled) => {
441 if (handled) {
442 return [Effect.void, true] as const;
443 }
444 return [
445 Effect.gen(function* () {
446 yield* Queue.offer(disconnects, 0);
447 const error = yield* classify();
448 yield* Deferred.fail(terminationFailure, error);
449 yield* failAllExtPending(error);
450 yield* emitClientProtocolError(error);
451 if (options.onTermination) {
452 yield* options.onTermination(error);
453 }
454 }),
455 true,
456 ] as const;
457 }).pipe(Effect.flatten);
458
459 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
460 offerOutgoing({
461 _tag: "Exit",
462 requestId,
463 exit: {
464 _tag: "Success",
465 value,
466 },
467 });
468
469 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
470 offerOutgoing({
471 _tag: "Exit",
472 requestId,
473 exit: {
474 _tag: "Failure",
475 cause: [
476 {
477 _tag: "Fail",
478 error: error.toProtocolError(),
479 },
480 ],
481 },
482 });
483
484 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
485 if (!options.onExtRequest) {
486 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
487 }
488 return options
489 .onExtRequest(message.tag, message.payload, {
490 requestId: acpRequestIdentity(message.id),
491 method: message.tag,
492 })
493 .pipe(
494 Effect.matchCauseEffect({
495 onFailure: (cause) => {
496 const failure = Cause.hasDies(cause) ? Option.none() : Cause.findErrorOption(cause);
497 if (Option.isSome(failure)) {
498 return respondWithError(
499 message.id,
500 AcpError.AcpRequestError.fromExtensionHandlerError(failure.value, message.tag),
501 );
502 }
503 return Effect.logError(
504 `ACP extension request handler failed for '${message.tag}'`,
505 cause,
506 ).pipe(
507 Effect.andThen(
508 respondWithError(
509 message.id,
510 AcpError.AcpRequestError.internalError(
511 `ACP extension request handler failed for method '${message.tag}'`,
512 undefined,
513 {
514 method: message.tag,
515 operation: "handle-extension-request",
516 cause: Cause.squash(cause),
517 },
518 ),
519 ),
520 ),
521 );
522 },
523 onSuccess: (value) => respondWithSuccess(message.id, value),
524 }),
525 );
526 };
527
528 // Drop undecodable notifications without ending working sessions; newer specs may add unknown shapes.
529 // Warn once per distinct failure per connection because agents repeat bad payloads.
530 const dropUndecodableNotification = (method: string) => (cause: Schema.SchemaError) => {
531 const error = AcpError.AcpProtocolParseError.fromSchemaError(
532 "decode-notification-payload",
533 method,
534 cause,
535 );
536 const diagnostics = decodeFailureDiagnostics(error);
537 const key = `${method}\n${error.issueSummary}`;
538 const firstOfItsKind = !warnedDecodeFailures.has(key);
539 warnedDecodeFailures.add(key);
540 return logProtocol({
541 direction: "incoming",
542 stage: "decode_failed",
543 payload: diagnostics,
544 }).pipe(
545 Effect.andThen(
546 firstOfItsKind
547 ? Effect.logWarning("Dropped an ACP notification that failed to decode").pipe(
548 Effect.annotateLogs(diagnostics),
549 )
550 : Effect.void,
551 ),
552 );
553 };
554
555 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
556 if (message.id === "") {
557 if (message.tag === CLIENT_METHODS.session_update) {
558 return decodeSessionUpdate(message.payload).pipe(
559 Effect.matchEffect({
560 onFailure: dropUndecodableNotification(CLIENT_METHODS.session_update),
561 onSuccess: (params) =>
562 dispatchNotification({
563 _tag: "SessionUpdate",
564 method: CLIENT_METHODS.session_update,
565 params: options.transformSessionUpdate?.(params) ?? params,
566 }),
567 }),
568 );
569 }
570 if (
571 message.tag === CLIENT_METHODS.elicitation_complete ||
572 message.tag === "session/elicitation/complete"
573 ) {
574 const method = message.tag;
575 return decodeElicitationComplete(message.payload).pipe(
576 Effect.matchEffect({
577 onFailure: dropUndecodableNotification(method),
578 onSuccess: (params) =>
579 dispatchNotification({ _tag: "ElicitationComplete", method, params }),
580 }),
581 );
582 }
583 return dispatchNotification({
584 _tag: "ExtNotification",
585 method: message.tag,
586 params: message.payload,
587 });
588 }
589
590 const observeIncoming =
591 options.onIncomingRequest?.(acpRequestIdentity(message.id), message.tag, message.payload) ??
592 Effect.void;
593
594 if (!options.serverRequestMethods.has(message.tag)) {
595 return observeIncoming.pipe(
596 Effect.andThen(handleExtRequest(message)),
597 Effect.catchTags({
598 AcpProtocolParseError: (error) =>
599 Effect.logWarning(error).pipe(
600 Effect.annotateLogs({
601 method: message.tag,
602 requestId: message.id,
603 operation: error.operation,
604 }),
605 Effect.andThen(
606 respondWithError(
607 message.id,
608 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
609 message.tag,
610 message.id,
611 error,
612 ),
613 ),
614 ),
615 ),
616 }),
617 Effect.asVoid,
618 );
619 }
620
621 return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid);
622 };
623
624 const forwardToRpcClient = (
625 message: RpcMessage.ResponseChunkEncoded | RpcMessage.ResponseExitEncoded,
626 ) =>
627 isEffectRpcRequestId(message.requestId)
628 ? Queue.offer(clientQueue, message).pipe(Effect.asVoid)
629 : Effect.void;
630
631 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
632 Ref.get(extPending).pipe(
633 Effect.flatMap((pending) => {
634 const pendingRequest = pending.get(acpRequestIdentity(message.requestId));
635 if (!pendingRequest) {
636 return forwardToRpcClient(message);
637 }
638 if (message.exit._tag === "Success") {
639 return completeExtPendingSuccess(message.requestId, message.exit.value);
640 }
641 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
642 if (failure && isProtocolError(failure.error)) {
643 return completeExtPendingFailure(
644 message.requestId,
645 AcpError.AcpRequestError.fromProtocolError(failure.error, {
646 method: pendingRequest.method,
647 requestId: message.requestId,
648 cause: message.exit.cause,
649 }),
650 );
651 }
652 return completeExtPendingFailure(
653 message.requestId,
654 AcpError.AcpRequestError.fromExtensionResponseFailure(
655 pendingRequest.method,
656 message.requestId,
657 message.exit.cause,
658 ),
659 );
660 }),
661 );
662
663 const routeDecodedMessage = (
664 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
665 ): Effect.Effect<void, AcpError.AcpError> => {
666 switch (message._tag) {
667 case "Request":
668 return handleRequestEncoded(message);
669 case "Exit":
670 return handleExitEncoded(message);
671 case "Chunk":
672 return Ref.get(extPending).pipe(
673 Effect.flatMap((pending) => {
674 const pendingRequest = pending.get(acpRequestIdentity(message.requestId));
675 return pendingRequest
676 ? completeExtPendingFailure(
677 message.requestId,
678 AcpError.AcpRequestError.unsupportedStreamingResponse(
679 pendingRequest.method,
680 message.requestId,
681 ),
682 )
683 : forwardToRpcClient(message);
684 }),
685 );
686 case "Defect":
687 case "ClientProtocolError":
688 case "Pong":
689 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
690 case "Ack":
691 case "Interrupt":
692 case "Ping":
693 case "Eof":
694 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
695 }
696 };
697
698 yield* options.stdio.stdin.pipe(
699 Stream.runForEach((data) =>
700 (options.logIncoming
701 ? logProtocol({
702 direction: "incoming",
703 stage: "raw",
704 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
705 })
706 : Effect.void
707 ).pipe(
708 Effect.flatMap(() =>
709 Effect.try({
710 try: () =>
711 (
712 parser.decode(data) as ReadonlyArray<
713 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
714 >
715 ).map(normalizeAcpJsonRpcError),
716 catch: (cause) =>
717 new AcpError.AcpProtocolParseError({
718 operation: "decode-wire-message",
719 cause,
720 }),
721 }),
722 ),
723 Effect.tap((messages) =>
724 logProtocol({
725 direction: "incoming",
726 stage: "decoded",
727 payload: messages,
728 }),
729 ),
730 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
731 logProtocol({
732 direction: "incoming",
733 stage: "decode_failed",
734 payload: decodeFailureDiagnostics(error),
735 }),
736 ),
737 Effect.flatMap((messages) =>
738 Effect.forEach(messages, routeDecodedMessage, {
739 discard: true,
740 }),
741 ),
742 ),
743 ),
744 // Anything that ends the reader, including a defect in a callback it runs,
745 // terminates the connection so pending requests fail instead of hanging.
746 Effect.matchCauseEffect({
747 onFailure: (cause) => {
748 const failure = Cause.findErrorOption(cause);
749 const error = Option.isSome(failure) ? failure.value : Cause.squash(cause);
750 const normalized: AcpError.AcpError = isAcpError(error)
751 ? error
752 : new AcpError.AcpTransportError({
753 operation: "read-input-stream",
754 cause: error,
755 });
756 return handleTermination(() => Effect.succeed(normalized));
757 },
758 onSuccess: () =>
759 handleTermination(
760 () =>
761 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
762 ),
763 }),
764 Effect.forkScoped,
765 );
766
767 const failOutgoingWrites = (error: AcpError.AcpError) =>
768 Ref.modify(outgoingWriterState, (state) => {
769 const terminalError = state.terminalError ?? error;
770 return [
771 [terminalError, state.outstandingAcknowledgements] as const,
772 {
773 ...state,
774 terminalError,
775 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
776 },
777 ] as const;
778 }).pipe(
779 Effect.flatMap((acknowledgements) =>
780 Effect.forEach(
781 acknowledgements[1],
782 (acknowledgement) => Deferred.fail(acknowledgement, acknowledgements[0]),
783 { concurrency: "unbounded", discard: true },
784 ),
785 ),
786 Effect.andThen(Queue.fail(outgoing, error)),
787 Effect.asVoid,
788 );
789 const completeOutgoingWrites = () =>
790 Ref.modify(outgoingWriterState, (state) => {
791 return [
792 state.outstandingAcknowledgements,
793 {
794 ...state,
795 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
796 },
797 ] as const;
798 }).pipe(
799 Effect.flatMap((acknowledgements) =>
800 Effect.forEach(
801 acknowledgements,
802 (acknowledgement) => Deferred.succeed(acknowledgement, undefined),
803 { concurrency: "unbounded", discard: true },
804 ),
805 ),
806 Effect.asVoid,
807 );
808 const acknowledgeOutgoingWrite = (acknowledgement: Deferred.Deferred<void, AcpError.AcpError>) =>
809 Ref.update(outgoingWriterState, (state) => {
810 const updated = new Set(state.outstandingAcknowledgements);
811 updated.delete(acknowledgement);
812 return { ...state, outstandingAcknowledgements: updated };
813 }).pipe(Effect.andThen(Deferred.succeed(acknowledgement, undefined)), Effect.asVoid);
814 yield* Stream.fromQueue(outgoing).pipe(
815 Stream.flatMap((write) => {
816 const acknowledgement = write.acknowledgement;
817 const completion =
818 acknowledgement === undefined
819 ? Stream.empty
820 : Stream.fromEffect(acknowledgeOutgoingWrite(acknowledgement)).pipe(Stream.drain);
821 return Stream.make(write.payload).pipe(Stream.concat(completion));
822 }),
823 Stream.run(options.stdio.stdout()),
824 Effect.onExit((exit) =>
825 Exit.match(exit, {
826 onFailure: (cause) => {
827 const error = new AcpError.AcpTransportError({
828 detail: Cause.hasInterruptsOnly(cause)
829 ? "The ACP output writer was interrupted while closing"
830 : "Failed to write an outgoing ACP message",
831 cause,
832 });
833 return failOutgoingWrites(error).pipe(
834 Effect.andThen(
835 Cause.hasInterruptsOnly(cause)
836 ? Effect.void
837 : handleTermination(() => Effect.succeed(error)),
838 ),
839 );
840 },
841 onSuccess: () =>
842 Ref.get(outgoingWriterState).pipe(
843 Effect.flatMap((state) => {
844 const handled = state.intentionalEnd
845 ? completeOutgoingWrites()
846 : (() => {
847 const error = new AcpError.AcpTransportError({
848 detail: "ACP output writer ended before the protocol closed",
849 cause: "Output writer ended",
850 });
851 return failOutgoingWrites(error).pipe(
852 Effect.andThen(handleTermination(() => Effect.succeed(error))),
853 );
854 })();
855 return handled.pipe(
856 Effect.andThen(
857 options.testHooks?.onOutgoingWriterExit === undefined
858 ? Effect.void
859 : options.testHooks.onOutgoingWriterExit({
860 intentionalEnd: state.intentionalEnd,
861 }),
862 ),
863 );
864 }),
865 ),
866 }),
867 ),
868 Effect.forkScoped,
869 );
870
871 // Protocol loops and per-message sends share the caller's operation span.
872 const clientProtocol = RpcClient.Protocol.of({
873 run: Effect.fnUntraced(function* (_clientId, f) {
874 return yield* Stream.fromQueue(clientQueue).pipe(
875 Stream.runForEach((message) => f(message)),
876 Effect.forever,
877 );
878 }),
879 send: Effect.fnUntraced(function* (_clientId, request) {
880 return yield* offerOutgoing(request).pipe(
881 Effect.mapError(
882 (error) =>
883 new RpcClientError.RpcClientError({
884 reason: new RpcClientError.RpcClientDefect({
885 message: "Failed to send ACP protocol message.",
886 cause: error,
887 }),
888 }),
889 ),
890 );
891 }),
892 supportsAck: true,
893 supportsTransferables: false,
894 codecFor: parserFactory.codecFor,
895 });
896
897 const serverProtocol = RpcServer.Protocol.of({
898 run: Effect.fnUntraced(function* (f) {
899 return yield* Stream.fromQueue(serverQueue).pipe(
900 Stream.runForEach((message) => f(0, message)),
901 Effect.forever,
902 );
903 }),
904 disconnects,
905 send: Effect.fnUntraced(function* (_clientId, response) {
906 return yield* offerOutgoing(response).pipe(
907 Effect.tapError((error) =>
908 response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined
909 ? options.onOutgoingResponseFailure(acpRequestIdentity(response.requestId), error)
910 : Effect.void,
911 ),
912 Effect.orDie,
913 );
914 }),
915 end: Effect.fn("RpcServer.Protocol.end")(function (_clientId) {
916 return Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
917 Effect.andThen(Queue.end(outgoing)),
918 );
919 }),
920 clientIds: Effect.succeed(new Set([0])),
921 initialMessage: Effect.succeedNone,
922 supportsAck: true,
923 supportsTransferables: false,
924 codecFor: parserFactory.codecFor,
925 supportsSpanPropagation: true,
926 supportsNotifications: true,
927 });
928
929 // JSON-RPC notifications carry no `id`. Encoding a Request without `isNotification`
930 // emits an `id`, which real agents (Grok CLI) parse as a malformed request and silently drop.
931 const sendNotification = Effect.fn("sendNotification")(function* (
932 method: string,
933 payload: unknown,
934 ) {
935 yield* ensureActive;
936 yield* logProtocol({
937 direction: "outgoing",
938 stage: "decoded",
939 payload: { _tag: "Notification", tag: method, payload },
940 });
941 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
942 if (Exit.isFailure(exit)) {
943 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
944 method,
945 undefined,
946 Cause.squash(exit.cause),
947 );
948 }
949 const encoded = `${exit.value}\n`;
950 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
951 yield* ensureActive;
952 // FIFO queue admission preserves wire ordering against later requests
953 // (a session/prompt sent after session/cancel cannot overtake it).
954 yield* Queue.offer(outgoing, { payload: encoded }).pipe(
955 Effect.mapError(
956 (cause) =>
957 new AcpError.AcpTransportError({
958 detail: "Failed to queue an outgoing ACP notification",
959 cause,
960 }),
961 ),
962 Effect.filterOrFail(
963 (accepted) => accepted,
964 () =>
965 new AcpError.AcpTransportError({
966 detail: "The ACP output queue was closed before accepting a notification",
967 cause: "Output queue closed",
968 }),
969 ),
970 );
971 });
972
973 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
974 yield* ensureActive;
975 const requestId = yield* Ref.modify(
976 nextRequestId,
977 (current) => [current, current + 1] as const,
978 );
979 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
980 yield* Ref.update(extPending, (pending) =>
981 new Map(pending).set(acpRequestIdentity(requestId), { deferred, method }),
982 );
983 yield* offerOutgoing({
984 _tag: "Request",
985 id: requestId,
986 tag: method,
987 payload,
988 headers: [],
989 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
990 return yield* Deferred.await(deferred).pipe(
991 Effect.onInterrupt(() => removeExtPending(requestId)),
992 );
993 });
994
995 return {
996 clientProtocol,
997 serverProtocol,
998 get incoming() {
999 return Stream.fromQueue(notificationQueue);
1000 },
1001 request: sendRequest,
1002 notify: sendNotification,
1003 } satisfies AcpPatchedProtocol;
1004});
1005
1006const isProtocolError = Schema.is(AcpSchema.Error);