import type * as AcpCompat from "./compat.ts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import type * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Stdio from "effect/Stdio"; import * as RpcClient from "effect/rpc/RpcClient"; import * as RpcClientError from "effect/rpc/RpcClientError"; import * as RpcMessage from "effect/rpc/RpcMessage"; import * as RpcSerialization from "effect/rpc/RpcSerialization"; import * as RpcServer from "effect/rpc/RpcServer"; import * as AcpSchema from "./schema.ts"; import * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts"; import { CLIENT_METHODS } from "./_generated/meta.gen.ts"; import * as AcpError from "./errors.ts"; import { isolateNotificationHandler } from "./_internal/shared.ts"; const isAcpError = Schema.is(AcpError.AcpError); export interface AcpProtocolLogEvent { readonly direction: "incoming" | "outgoing"; readonly stage: "raw" | "decoded" | "decode_failed"; readonly payload: unknown; } export interface AcpRequestContext { readonly requestId: string; readonly method: string; } export function acpRequestIdentity(requestId: AcpError.AcpRequestId): string { const prefix = "$t3:jsonrpc:"; if (typeof requestId === "number") return `${prefix}number:${requestId}`; return requestId.startsWith(prefix) ? `${prefix}string:${requestId}` : requestId; } export type AcpRequestHandler = ( request: Request, context: AcpRequestContext, ) => Effect.Effect; export type AcpIncomingNotification = | { readonly _tag: "SessionUpdate"; readonly method: typeof CLIENT_METHODS.session_update; readonly params: | AcpSchema.UpdateSessionNotification | AcpSchemaV1.SessionNotification | AcpCompat.SessionNotification; } | { readonly _tag: "ElicitationComplete"; readonly method: typeof CLIENT_METHODS.elicitation_complete | "session/elicitation/complete"; readonly params: AcpSchema.CompleteElicitationNotification; } | { readonly _tag: "ExtNotification"; readonly method: string; readonly params: unknown; }; export interface AcpStdio extends Omit { readonly stdin: Stream.Stream; } export interface AcpPatchedProtocolOptions { readonly stdio: AcpStdio; readonly terminationError?: Effect.Effect; readonly serverRequestMethods: ReadonlySet; readonly logIncoming?: boolean; readonly logOutgoing?: boolean; readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect; readonly onIncomingRequest?: ( requestId: string, method: string, payload: unknown, ) => Effect.Effect; readonly transformSessionUpdate?: ( notification: | AcpSchema.UpdateSessionNotification | AcpSchemaV1.SessionNotification | AcpCompat.SessionNotification, ) => | AcpSchema.UpdateSessionNotification | AcpSchemaV1.SessionNotification | AcpCompat.SessionNotification; readonly onNotification?: ( notification: AcpIncomingNotification, ) => Effect.Effect; readonly onExtRequest?: ( method: string, params: unknown, context: AcpRequestContext, ) => Effect.Effect; readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect; readonly onOutgoingResponseFailure?: ( requestId: string, error: AcpError.AcpError, ) => Effect.Effect; readonly onOutgoingResponse?: (requestId: string) => Effect.Effect; readonly testHooks?: { readonly onOutgoingWriteAdmitted?: () => Effect.Effect; readonly onOutgoingWriterExit?: (input: { readonly intentionalEnd: boolean; }) => Effect.Effect; }; } /** * Provided to a request call, settles once that request is queued for writing. Messages queued * later are written after it; the call itself returns only with the reply. */ export const AcpOutgoingQueued = Context.Reference | undefined>( "effect-acp/protocol/AcpOutgoingQueued", { defaultValue: () => undefined }, ); export interface AcpPatchedProtocol { readonly clientProtocol: RpcClient.Protocol["Service"]; readonly serverProtocol: RpcServer.Protocol["Service"]; readonly incoming: Stream.Stream; readonly request: (method: string, payload: unknown) => Effect.Effect; readonly notify: (method: string, payload: unknown) => Effect.Effect; } interface AcpPendingRequest { readonly deferred: Deferred.Deferred; readonly method: string; } /** A decoded wire message and the length of the JSON line it arrived on. */ interface AcpDecodedWireMessage { readonly message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded; readonly lineLength: number; } interface AcpBufferedRawNotification { readonly notification: AcpIncomingNotification; readonly lineLength: number; } interface AcpOutgoingWrite { readonly acknowledgement?: Deferred.Deferred; readonly payload: string | Uint8Array; } interface AcpOutgoingWriterState { readonly outstandingAcknowledgements: ReadonlySet>; readonly intentionalEnd: boolean; readonly terminalError?: AcpError.AcpError; } const decodeSessionUpdate = Schema.decodeUnknownEffect( Schema.Union([ // Claude ACP v2 reports prompt failures on idle; alpha.3 omits that field. Schema.Struct({ ...AcpSchema.UpdateSessionNotification.fields, update: Schema.Struct({ sessionUpdate: Schema.Literal("state_update"), state: Schema.Literal("idle"), stopReason: Schema.optionalKey(Schema.NullOr(AcpSchema.StopReason)), usage: Schema.optionalKey(Schema.NullOr(AcpSchema.Usage)), error: Schema.optionalKey(Schema.NullOr(AcpSchema.Error)), _meta: AcpSchema.UpdateSessionNotification.fields._meta, }), }), // fx reports command cancellation outside ACP's standard tool fields. Schema.Struct({ ...AcpSchemaV1.SessionNotification.fields, update: Schema.Struct({ ...AcpSchemaV1.ToolCallUpdate.fields, sessionUpdate: Schema.Literals(["tool_call", "tool_call_update"]), command_result: Schema.Json, }), }), AcpSchema.UpdateSessionNotification, AcpSchemaV1.SessionNotification, ]), ); const decodeElicitationComplete = Schema.decodeUnknownEffect( AcpSchema.CompleteElicitationNotification, ); const parserFactory = RpcSerialization.ndJsonRpc(); // ndJsonRpc skips lines that are not JSON. A malformed agent line has to end the // session, so frames are split here and each nonblank one goes through the strict codec. const makeStrictNdJsonRpcParser = () => { const codec = RpcSerialization.jsonRpc().makeUnsafe(); const decoder = new TextDecoder(); let buffer = ""; const decodeLine = (line: string): ReadonlyArray => codec.decode(line).map((message) => ({ message: normalizeAcpJsonRpcError( message as RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, ), lineLength: line.length, })); return { // Every message in a batch line is charged the whole line. decode: (bytes: Uint8Array | string): ReadonlyArray => { const chunk = typeof bytes === "string" ? bytes : decoder.decode(bytes, { stream: true }); const lastNewline = chunk.lastIndexOf("\n"); // Splitting the whole buffer per chunk is quadratic for multi-megabyte lines. if (lastNewline === -1) { buffer += chunk; return []; } const lines = (buffer + chunk.slice(0, lastNewline)).split("\n"); buffer = chunk.slice(lastNewline + 1); return lines.flatMap((line) => (line.trim() === "" ? [] : decodeLine(line))); }, // A truncated final line is left to the exit status, which explains a crash better. end: (): ReadonlyArray => { const line = buffer + decoder.decode(); buffer = ""; try { return line.trim() === "" ? [] : decodeLine(line); } catch { return []; } }, encode: (response: Parameters[0]) => { const encoded = codec.encode(response); if (encoded === undefined) return undefined; const json = typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded); if (!json.includes('"_tag":"Cause"')) return `${json}\n`; return `${JSON.stringify(normalizeOutgoingFrame(JSON.parse(json)))}\n`; }, }; }; const isCauseResponse = Schema.is( Schema.Struct({ error: Schema.TaggedStruct("Cause", { data: Schema.Array(Schema.Unknown) }), }), ); const isProtocolFailure = Schema.is(Schema.TaggedStruct("Fail", { error: AcpSchema.Error })); const isInterruptReason = Schema.is(Schema.TaggedStruct("Interrupt", {})); // Normalize only Effect's error envelope after the codec has completed batch tracking. function normalizeOutgoingFrame(frame: unknown): unknown { if (Array.isArray(frame)) return frame.map(normalizeOutgoingFrame); if (!isCauseResponse(frame)) return frame; const reasons = frame.error.data.filter((reason) => !isInterruptReason(reason)); const [failure] = reasons; const error = reasons.length === 1 && isProtocolFailure(failure) ? failure.error : AcpError.AcpRequestError.internalError().toProtocolError(); return { ...frame, error: { code: error.code, message: error.message, ...(error.data === undefined ? {} : { data: error.data }), }, }; } // Unread raw notifications are best-effort. The newest is always kept; older // ones are dropped once the backlog passes either limit. The length limit counts // JSON line characters (UTF-16 code units), not bytes or heap size. const MAX_BUFFERED_RAW_NOTIFICATIONS = 32; const MAX_BUFFERED_RAW_NOTIFICATION_JSON_LENGTH = 16 * 1024 * 1024; const decodeFailureDiagnostics = (error: AcpError.AcpProtocolParseError) => ({ operation: error.operation, ...(error.method === undefined ? {} : { method: error.method }), ...(error.requestId === undefined ? {} : { requestId: error.requestId }), ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }), ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }), ...(error.maximumPathDepth === undefined ? {} : { maximumPathDepth: error.maximumPathDepth }), ...(error.issueSummary === undefined ? {} : { issueSummary: error.issueSummary }), }); const encodeJsonRpcNotification = Schema.encodeUnknownExit( Schema.fromJsonString( Schema.Struct({ jsonrpc: Schema.Literal("2.0"), method: Schema.String, params: Schema.Unknown, }), ), ); /** * First id for typed Effect RPC requests. Starts within signed int32 for SDKs that reject * larger numeric ids (e.g. the Kotlin ACP SDK decodes ids as `Int`), while staying far * above extension ids, which count up from 1. */ export const RPC_REQUEST_ID_START = 2 ** 30; const isEffectRpcRequestId = (requestId: AcpError.AcpRequestId): boolean => typeof requestId === "number" && Number.isSafeInteger(requestId); /** * Effect RPC's JSON-RPC codec treats a standard JSON-RPC error object as a * defect unless it carries Effect's private `_tag: "Cause"` envelope. */ function normalizeAcpJsonRpcError( message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, ): RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded { if (message._tag !== "Exit" || message.exit._tag !== "Failure") return message; const [failure] = message.exit.cause; if ( message.exit.cause.length !== 1 || failure?._tag !== "Die" || !isProtocolError(failure.defect) ) { return message; } return { ...message, exit: { _tag: "Failure", cause: [{ _tag: "Fail", error: failure.defect }], }, }; } export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* ( options: AcpPatchedProtocolOptions, ): Effect.fn.Return { const parser = makeStrictNdJsonRpcParser(); const serverQueue = yield* Queue.unbounded(); const clientQueue = yield* Queue.unbounded(); const rawNotifications = yield* Queue.unbounded>(); // JSON length of the notifications still in the queue. `incoming` takes one // at a time, so a slow reader holds at most one outside this budget. let rawNotificationsJsonLength = 0; // Raw readers finish with the connection: termination ends the queue, and so // does closing the scope, which interrupts the reader before it terminates. yield* Effect.addFinalizer(() => Queue.end(rawNotifications)); const disconnects = yield* Queue.unbounded(); const outgoing = yield* Queue.unbounded>(); const outgoingWriterState = yield* Ref.make({ intentionalEnd: false, outstandingAcknowledgements: new Set(), }); const nextRequestId = yield* Ref.make(1); const warnedDecodeFailures = new Set(); const terminationHandled = yield* Ref.make(false); const terminationFailure = yield* Deferred.make(); const extPending = yield* Ref.make(new Map()); const ensureActive = Ref.get(terminationHandled).pipe( Effect.flatMap((terminated) => (terminated ? Deferred.await(terminationFailure) : Effect.void)), ); const logProtocol = (event: AcpProtocolLogEvent) => { if (event.direction === "incoming" && !options.logIncoming) { return Effect.void; } if (event.direction === "outgoing" && !options.logOutgoing) { return Effect.void; } return ( options.logger?.(event) ?? Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event })) ); }; const offerOutgoing = Effect.fn("offerOutgoing")(function* ( message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, ) { // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted. // ACP has no such method; agents log it as an error and cannot act on it, so drop it. if (message._tag === "Interrupt") { return; } yield* ensureActive; yield* logProtocol({ direction: "outgoing", stage: "decoded", payload: message, }); const method = message._tag === "Request" ? message.tag : undefined; const encodedRequestId = message._tag === "Request" ? message.id : "requestId" in message ? message.requestId : undefined; const requestId = encodedRequestId === "" ? undefined : encodedRequestId; const encoded = yield* Effect.try({ try: () => parser.encode(message), catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause), }); if (encoded) { yield* logProtocol({ direction: "outgoing", stage: "raw", payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), }); yield* ensureActive; const acknowledgement = message._tag === "Exit" ? yield* Deferred.make() : undefined; const admissionError = yield* Ref.modify(outgoingWriterState, (state) => { if (state.terminalError !== undefined) { return [state.terminalError, state] as const; } if (acknowledgement === undefined) { return [undefined, state] as const; } return [ undefined, { ...state, outstandingAcknowledgements: new Set(state.outstandingAcknowledgements).add( acknowledgement, ), }, ] as const; }); if (admissionError !== undefined) { return yield* admissionError; } if (options.testHooks?.onOutgoingWriteAdmitted !== undefined) { yield* options.testHooks.onOutgoingWriteAdmitted(); } yield* Queue.offer(outgoing, { payload: encoded, ...(acknowledgement === undefined ? {} : { acknowledgement }), }).pipe( Effect.mapError( (cause) => new AcpError.AcpTransportError({ detail: "Failed to queue an outgoing ACP message", cause, }), ), Effect.filterOrFail( (accepted) => accepted, () => new AcpError.AcpTransportError({ detail: "The ACP output queue was closed before accepting a message", cause: "Output queue closed", }), ), Effect.tapError((error) => acknowledgement === undefined ? Effect.void : Ref.update(outgoingWriterState, (state) => { const updated = new Set(state.outstandingAcknowledgements); updated.delete(acknowledgement); return { ...state, outstandingAcknowledgements: updated }; }).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid), ), ); const queued = yield* AcpOutgoingQueued; if (queued !== undefined) { yield* Deferred.succeed(queued, undefined); } if (acknowledgement !== undefined) { yield* Deferred.await(acknowledgement); } if (message._tag === "Exit" && options.onOutgoingResponse !== undefined) { yield* options.onOutgoingResponse(acpRequestIdentity(message.requestId)); } } }); const resolveExtPending = ( requestId: AcpError.AcpRequestId, onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect, ) => Ref.modify(extPending, (pending) => { const pendingKey = acpRequestIdentity(requestId); const pendingRequest = pending.get(pendingKey); if (!pendingRequest) { return [Effect.void, pending] as const; } const next = new Map(pending); next.delete(pendingKey); return [onFound(pendingRequest), next] as const; }).pipe(Effect.flatten); const removeExtPending = (requestId: AcpError.AcpRequestId) => Ref.update(extPending, (pending) => { const pendingKey = acpRequestIdentity(requestId); if (!pending.has(pendingKey)) { return pending; } const next = new Map(pending); next.delete(pendingKey); return next; }); const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) => resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error)); const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) => resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value)); const failAllExtPending = (error: AcpError.AcpError) => Ref.getAndSet(extPending, new Map()).pipe( Effect.flatMap((pending) => Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), { discard: true, }), ), ); // Offer first so an ended queue rejects the notification without evicting the // backlog readers are still draining. Offer and eviction share one sync block, // so readers never see more than the limits allow. const bufferRawNotification = (notification: AcpIncomingNotification, lineLength: number) => Effect.sync(() => { if (!Queue.offerUnsafe(rawNotifications, { notification, lineLength })) return; rawNotificationsJsonLength += lineLength; while ( Queue.sizeUnsafe(rawNotifications) > MAX_BUFFERED_RAW_NOTIFICATIONS || (Queue.sizeUnsafe(rawNotifications) > 1 && rawNotificationsJsonLength > MAX_BUFFERED_RAW_NOTIFICATION_JSON_LENGTH) ) { const dropped = Queue.takeUnsafe(rawNotifications); if (dropped === undefined || Exit.isFailure(dropped)) break; rawNotificationsJsonLength -= dropped.value.lineLength; } }); const dispatchNotification = (notification: AcpIncomingNotification, lineLength: number) => bufferRawNotification(notification, lineLength).pipe( Effect.andThen( // A failing or dying handler must not stop the reader, or every later // message on the connection goes unanswered. options.onNotification ? isolateNotificationHandler(options.onNotification(notification)) : Effect.void, ), Effect.asVoid, ); const emitClientProtocolError = (error: AcpError.AcpError) => Queue.offer(clientQueue, { _tag: "ClientProtocolError", error: new RpcClientError.RpcClientError({ reason: new RpcClientError.RpcClientDefect({ message: "ACP protocol terminated.", cause: error, }), }), }).pipe(Effect.asVoid); // A broken pipe can win the race against the exit that explains it; wait briefly on the live clock. const preferProcessExit = (error: AcpError.AcpError) => options.terminationError ? options.terminationError.pipe( Effect.timeoutOption("250 millis"), Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()), Effect.map(Option.getOrElse(() => error)), ) : Effect.succeed(error); const handleTermination = (classify: Effect.Effect) => Ref.modify(terminationHandled, (handled) => { if (handled) { return [Effect.void, true] as const; } return [ Effect.gen(function* () { yield* Queue.offer(disconnects, 0); yield* Queue.end(rawNotifications); const error = yield* classify; yield* Deferred.fail(terminationFailure, error); yield* failAllExtPending(error); yield* emitClientProtocolError(error); if (options.onTermination) { yield* options.onTermination(error); } }), true, ] as const; }).pipe(Effect.flatten); const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) => offerOutgoing({ _tag: "Exit", requestId, exit: { _tag: "Success", value, }, }); const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) => offerOutgoing({ _tag: "Exit", requestId, exit: { _tag: "Failure", cause: [ { _tag: "Fail", error: error.toProtocolError(), }, ], }, }); const handleExtRequest = (message: RpcMessage.RequestEncoded) => { if (!options.onExtRequest) { return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag)); } return options .onExtRequest(message.tag, message.payload, { requestId: acpRequestIdentity(message.id), method: message.tag, }) .pipe( Effect.matchCauseEffect({ onFailure: (cause) => { const failure = Cause.hasDies(cause) ? Option.none() : Cause.findErrorOption(cause); if (Option.isSome(failure)) { return respondWithError( message.id, AcpError.AcpRequestError.fromExtensionHandlerError(failure.value, message.tag), ); } return Effect.logError( `ACP extension request handler failed for '${message.tag}'`, cause, ).pipe( Effect.andThen( respondWithError( message.id, AcpError.AcpRequestError.internalError( `ACP extension request handler failed for method '${message.tag}'`, undefined, { method: message.tag, operation: "handle-extension-request", cause: Cause.squash(cause), }, ), ), ), ); }, onSuccess: (value) => respondWithSuccess(message.id, value), }), ); }; // Drop undecodable notifications without ending working sessions; newer specs may add unknown shapes. // Warn once per distinct failure per connection because agents repeat bad payloads. const dropUndecodableNotification = (method: string) => (cause: Schema.SchemaError) => { const error = AcpError.AcpProtocolParseError.fromSchemaError( "decode-notification-payload", method, cause, ); const diagnostics = decodeFailureDiagnostics(error); const key = `${method}\n${error.issueSummary}`; const firstOfItsKind = !warnedDecodeFailures.has(key); warnedDecodeFailures.add(key); return logProtocol({ direction: "incoming", stage: "decode_failed", payload: diagnostics, }).pipe( Effect.andThen( firstOfItsKind ? Effect.logWarning("Dropped an ACP notification that failed to decode").pipe( Effect.annotateLogs(diagnostics), ) : Effect.void, ), ); }; const handleRequestEncoded = (message: RpcMessage.RequestEncoded, lineLength: number) => { if (message.id === "") { if (message.tag === CLIENT_METHODS.session_update) { return decodeSessionUpdate(message.payload).pipe( Effect.matchEffect({ onFailure: dropUndecodableNotification(CLIENT_METHODS.session_update), onSuccess: (params) => dispatchNotification( { _tag: "SessionUpdate", method: CLIENT_METHODS.session_update, params: options.transformSessionUpdate?.(params) ?? params, }, lineLength, ), }), ); } if ( message.tag === CLIENT_METHODS.elicitation_complete || message.tag === "session/elicitation/complete" ) { const method = message.tag; return decodeElicitationComplete(message.payload).pipe( Effect.matchEffect({ onFailure: dropUndecodableNotification(method), onSuccess: (params) => dispatchNotification({ _tag: "ElicitationComplete", method, params }, lineLength), }), ); } return dispatchNotification( { _tag: "ExtNotification", method: message.tag, params: message.payload }, lineLength, ); } const observeIncoming = options.onIncomingRequest?.(acpRequestIdentity(message.id), message.tag, message.payload) ?? Effect.void; if (!options.serverRequestMethods.has(message.tag)) { return observeIncoming.pipe( Effect.andThen(handleExtRequest(message)), Effect.catchTags({ AcpProtocolParseError: (error) => Effect.logWarning(error).pipe( Effect.annotateLogs({ method: message.tag, requestId: message.id, operation: error.operation, }), Effect.andThen( respondWithError( message.id, AcpError.AcpRequestError.fromExtensionResponseEncodingError( message.tag, message.id, error, ), ), ), ), }), Effect.asVoid, ); } return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid); }; const forwardToRpcClient = ( message: RpcMessage.ResponseChunkEncoded | RpcMessage.ResponseExitEncoded, ) => isEffectRpcRequestId(message.requestId) ? Queue.offer(clientQueue, message).pipe(Effect.asVoid) : Effect.void; const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) => Ref.get(extPending).pipe( Effect.flatMap((pending) => { const pendingRequest = pending.get(acpRequestIdentity(message.requestId)); if (!pendingRequest) { return forwardToRpcClient(message); } if (message.exit._tag === "Success") { return completeExtPendingSuccess(message.requestId, message.exit.value); } const failure = message.exit.cause.find((entry) => entry._tag === "Fail"); if (failure && isProtocolError(failure.error)) { return completeExtPendingFailure( message.requestId, AcpError.AcpRequestError.fromProtocolError(failure.error, { method: pendingRequest.method, requestId: message.requestId, cause: message.exit.cause, }), ); } return completeExtPendingFailure( message.requestId, AcpError.AcpRequestError.fromExtensionResponseFailure( pendingRequest.method, message.requestId, message.exit.cause, ), ); }), ); const routeDecodedMessage = ({ message, lineLength, }: AcpDecodedWireMessage): Effect.Effect => { switch (message._tag) { case "Request": return handleRequestEncoded(message, lineLength); case "Exit": return handleExitEncoded(message); case "Chunk": return Ref.get(extPending).pipe( Effect.flatMap((pending) => { const pendingRequest = pending.get(acpRequestIdentity(message.requestId)); return pendingRequest ? completeExtPendingFailure( message.requestId, AcpError.AcpRequestError.unsupportedStreamingResponse( pendingRequest.method, message.requestId, ), ) : forwardToRpcClient(message); }), ); case "Defect": case "ClientProtocolError": case "Pong": return Queue.offer(clientQueue, message).pipe(Effect.asVoid); case "Ack": case "Interrupt": case "Ping": case "Eof": return Queue.offer(serverQueue, message).pipe(Effect.asVoid); } }; yield* options.stdio.stdin.pipe( Stream.runForEach((data) => (options.logIncoming ? logProtocol({ direction: "incoming", stage: "raw", payload: typeof data === "string" ? data : new TextDecoder().decode(data), }) : Effect.void ).pipe( Effect.flatMap(() => Effect.try({ try: () => parser.decode(data), catch: (cause) => new AcpError.AcpProtocolParseError({ operation: "decode-wire-message", cause, }), }), ), Effect.tap((decoded) => options.logIncoming ? logProtocol({ direction: "incoming", stage: "decoded", payload: decoded.map(({ message }) => message), }) : Effect.void, ), Effect.tapErrorTag("AcpProtocolParseError", (error) => logProtocol({ direction: "incoming", stage: "decode_failed", payload: decodeFailureDiagnostics(error), }), ), Effect.flatMap((decoded) => Effect.forEach(decoded, routeDecodedMessage, { discard: true, }), ), ), ), Effect.andThen( Effect.suspend(() => Effect.forEach(parser.end(), routeDecodedMessage, { discard: true })), ), // Anything that ends the reader, including a defect in a callback it runs, // terminates the connection so pending requests fail instead of hanging. Effect.matchCauseEffect({ onFailure: (cause) => { const failure = Cause.findErrorOption(cause); const error = Option.isSome(failure) ? failure.value : Cause.squash(cause); const normalized: AcpError.AcpError = isAcpError(error) ? error : new AcpError.AcpTransportError({ operation: "read-input-stream", cause: error, }); // A failed read may be the exit's echo; an ACP error or a defect is the cause itself. return handleTermination( Option.isSome(failure) && !isAcpError(failure.value) ? preferProcessExit(normalized) : Effect.succeed(normalized), ); }, onSuccess: () => handleTermination(preferProcessExit(new AcpError.AcpInputStreamEndedError({}))), }), Effect.forkScoped, ); const failOutgoingWrites = (error: AcpError.AcpError) => Ref.modify(outgoingWriterState, (state) => { const terminalError = state.terminalError ?? error; return [ [terminalError, state.outstandingAcknowledgements] as const, { ...state, terminalError, outstandingAcknowledgements: new Set>(), }, ] as const; }).pipe( Effect.flatMap((acknowledgements) => Effect.forEach( acknowledgements[1], (acknowledgement) => Deferred.fail(acknowledgement, acknowledgements[0]), { concurrency: "unbounded", discard: true }, ), ), Effect.andThen(Queue.fail(outgoing, error)), Effect.asVoid, ); const completeOutgoingWrites = () => Ref.modify(outgoingWriterState, (state) => { return [ state.outstandingAcknowledgements, { ...state, outstandingAcknowledgements: new Set>(), }, ] as const; }).pipe( Effect.flatMap((acknowledgements) => Effect.forEach( acknowledgements, (acknowledgement) => Deferred.succeed(acknowledgement, undefined), { concurrency: "unbounded", discard: true }, ), ), Effect.asVoid, ); const acknowledgeOutgoingWrite = (acknowledgement: Deferred.Deferred) => Ref.update(outgoingWriterState, (state) => { const updated = new Set(state.outstandingAcknowledgements); updated.delete(acknowledgement); return { ...state, outstandingAcknowledgements: updated }; }).pipe(Effect.andThen(Deferred.succeed(acknowledgement, undefined)), Effect.asVoid); yield* Stream.fromQueue(outgoing).pipe( Stream.flatMap((write) => { const acknowledgement = write.acknowledgement; const completion = acknowledgement === undefined ? Stream.empty : Stream.fromEffect(acknowledgeOutgoingWrite(acknowledgement)).pipe(Stream.drain); return Stream.make(write.payload).pipe(Stream.concat(completion)); }), Stream.run(options.stdio.stdout()), Effect.onExit((exit) => Exit.match(exit, { onFailure: (cause) => { const error = new AcpError.AcpTransportError({ detail: Cause.hasInterruptsOnly(cause) ? "The ACP output writer was interrupted while closing" : "Failed to write an outgoing ACP message", cause, }); return failOutgoingWrites(error).pipe( Effect.andThen( Cause.hasInterruptsOnly(cause) ? Effect.void : handleTermination(preferProcessExit(error)), ), ); }, onSuccess: () => Ref.get(outgoingWriterState).pipe( Effect.flatMap((state) => { const handled = state.intentionalEnd ? completeOutgoingWrites() : (() => { const error = new AcpError.AcpTransportError({ detail: "ACP output writer ended before the protocol closed", cause: "Output writer ended", }); return failOutgoingWrites(error).pipe( Effect.andThen(handleTermination(preferProcessExit(error))), ); })(); return handled.pipe( Effect.andThen( options.testHooks?.onOutgoingWriterExit === undefined ? Effect.void : options.testHooks.onOutgoingWriterExit({ intentionalEnd: state.intentionalEnd, }), ), ); }), ), }), ), Effect.forkScoped, ); // Protocol loops and per-message sends share the caller's operation span. const clientProtocol = RpcClient.Protocol.of({ run: Effect.fnUntraced(function* (_clientId, f) { return yield* Stream.fromQueue(clientQueue).pipe( Stream.runForEach((message) => f(message)), Effect.forever, ); }), send: Effect.fnUntraced(function* (_clientId, request) { return yield* offerOutgoing(request).pipe( Effect.mapError( (error) => new RpcClientError.RpcClientError({ reason: new RpcClientError.RpcClientDefect({ message: "Failed to send ACP protocol message.", cause: error, }), }), ), ); }), supportsAck: true, supportsTransferables: false, codecFor: parserFactory.codecFor, }); const serverProtocol = RpcServer.Protocol.of({ run: Effect.fnUntraced(function* (f) { return yield* Stream.fromQueue(serverQueue).pipe( Stream.runForEach((message) => f(0, message)), Effect.forever, ); }), disconnects, send: Effect.fnUntraced(function* (_clientId, response) { return yield* offerOutgoing(response).pipe( Effect.tapError((error) => response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined ? options.onOutgoingResponseFailure(acpRequestIdentity(response.requestId), error) : Effect.void, ), Effect.orDie, ); }), end: Effect.fn("RpcServer.Protocol.end")(function (_clientId) { return Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe( Effect.andThen(Queue.end(outgoing)), ); }), clientIds: Effect.succeed(new Set([0])), initialMessage: Effect.succeedNone, supportsAck: true, supportsTransferables: false, codecFor: parserFactory.codecFor, supportsSpanPropagation: true, supportsNotifications: true, }); // JSON-RPC notifications carry no `id`. Encoding a Request without `isNotification` // emits an `id`, which real agents (Grok CLI) parse as a malformed request and silently drop. const sendNotification = Effect.fn("sendNotification")(function* ( method: string, payload: unknown, ) { yield* ensureActive; yield* logProtocol({ direction: "outgoing", stage: "decoded", payload: { _tag: "Notification", tag: method, payload }, }); const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload }); if (Exit.isFailure(exit)) { return yield* AcpError.AcpProtocolParseError.fromEncodingError( method, undefined, Cause.squash(exit.cause), ); } const encoded = `${exit.value}\n`; yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded }); yield* ensureActive; // FIFO queue admission preserves wire ordering against later requests // (a session/prompt sent after session/cancel cannot overtake it). yield* Queue.offer(outgoing, { payload: encoded }).pipe( Effect.mapError( (cause) => new AcpError.AcpTransportError({ detail: "Failed to queue an outgoing ACP notification", cause, }), ), Effect.filterOrFail( (accepted) => accepted, () => new AcpError.AcpTransportError({ detail: "The ACP output queue was closed before accepting a notification", cause: "Output queue closed", }), ), ); }); const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) { yield* ensureActive; const requestId = yield* Ref.modify( nextRequestId, (current) => [current, current + 1] as const, ); const deferred = yield* Deferred.make(); yield* Ref.update(extPending, (pending) => new Map(pending).set(acpRequestIdentity(requestId), { deferred, method }), ); yield* offerOutgoing({ _tag: "Request", id: requestId, tag: method, payload, headers: [], }).pipe(Effect.tapError(() => removeExtPending(requestId))); return yield* Deferred.await(deferred).pipe( Effect.onInterrupt(() => removeExtPending(requestId)), ); }); return { clientProtocol, serverProtocol, get incoming() { return Stream.fromPull( Effect.succeed( Queue.take(rawNotifications).pipe( Effect.map(({ notification, lineLength }) => { rawNotificationsJsonLength -= lineLength; return [notification] as const; }), ), ), ); }, request: sendRequest, notify: sendNotification, } satisfies AcpPatchedProtocol; }); const isProtocolError = Schema.is(AcpSchema.Error);