The best way to control Claude Code, Codex and more from any computer or phone

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