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