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

protocol.ts

1,118 lines40.0 KB

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