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

protocol.ts

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