Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

protocol.ts

1,155 lines41.5 KB

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