Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Deferred from "effect/Deferred";
4import * as Queue from "effect/Queue";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Scope from "effect/Scope";
8import * as Stream from "effect/Stream";
9import * as Stdio from "effect/Stdio";
10import * as RpcClient from "effect/unstable/rpc/RpcClient";
11import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
12import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
13import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
14import * as RpcServer from "effect/unstable/rpc/RpcServer";
15
16import * as AcpSchema from "./_generated/schema.gen.ts";
17import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
18import * as AcpError from "./errors.ts";
19
20export interface AcpProtocolLogEvent {
21 readonly direction: "incoming" | "outgoing";
22 readonly stage: "raw" | "decoded" | "decode_failed";
23 readonly payload: unknown;
24}
25
26export type AcpIncomingNotification =
27 | {
28 readonly _tag: "SessionUpdate";
29 readonly method: typeof CLIENT_METHODS.session_update;
30 readonly params: typeof AcpSchema.SessionNotification.Type;
31 }
32 | {
33 readonly _tag: "ElicitationComplete";
34 readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
35 readonly params: typeof AcpSchema.ElicitationCompleteNotification.Type;
36 }
37 | {
38 readonly _tag: "ExtNotification";
39 readonly method: string;
40 readonly params: unknown;
41 };
42
43export interface AcpPatchedProtocolOptions {
44 readonly stdio: Stdio.Stdio;
45 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
46 readonly serverRequestMethods: ReadonlySet<string>;
47 readonly logIncoming?: boolean;
48 readonly logOutgoing?: boolean;
49 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
50 readonly onNotification?: (
51 notification: AcpIncomingNotification,
52 ) => Effect.Effect<void, AcpError.AcpError, never>;
53 readonly onExtRequest?: (
54 method: string,
55 params: unknown,
56 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
57 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
58}
59
60export interface AcpPatchedProtocol {
61 readonly clientProtocol: RpcClient.Protocol["Service"];
62 readonly serverProtocol: RpcServer.Protocol["Service"];
63 readonly incoming: Stream.Stream<AcpIncomingNotification>;
64 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
65 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
66}
67
68const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
69const decodeElicitationComplete = Schema.decodeUnknownEffect(
70 AcpSchema.ElicitationCompleteNotification,
71);
72const parserFactory = RpcSerialization.ndJsonRpc();
73
74export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
75 options: AcpPatchedProtocolOptions,
76): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
77 const parser = parserFactory.makeUnsafe();
78 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
79 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
80 const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();
81 const disconnects = yield* Queue.unbounded<number>();
82 const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
83 const nextRequestId = yield* Ref.make(1n);
84 const terminationHandled = yield* Ref.make(false);
85 const extPending = yield* Ref.make(
86 new Map<string, Deferred.Deferred<unknown, AcpError.AcpError>>(),
87 );
88
89 const logProtocol = (event: AcpProtocolLogEvent) => {
90 if (event.direction === "incoming" && !options.logIncoming) {
91 return Effect.void;
92 }
93 if (event.direction === "outgoing" && !options.logOutgoing) {
94 return Effect.void;
95 }
96 return (
97 options.logger?.(event) ??
98 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
99 );
100 };
101
102 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
103 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
104 ) {
105 yield* logProtocol({
106 direction: "outgoing",
107 stage: "decoded",
108 payload: message,
109 });
110
111 const encoded = yield* Effect.try({
112 try: () => parser.encode(message),
113 catch: (cause) =>
114 new AcpError.AcpProtocolParseError({
115 detail: "Failed to encode ACP message",
116 cause,
117 }),
118 });
119
120 if (encoded) {
121 yield* logProtocol({
122 direction: "outgoing",
123 stage: "raw",
124 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
125 });
126
127 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
128 }
129 });
130
131 const resolveExtPending = (
132 requestId: string,
133 onFound: (deferred: Deferred.Deferred<unknown, AcpError.AcpError>) => Effect.Effect<void>,
134 ) =>
135 Ref.modify(extPending, (pending) => {
136 const deferred = pending.get(requestId);
137 if (!deferred) {
138 return [Effect.void, pending] as const;
139 }
140 const next = new Map(pending);
141 next.delete(requestId);
142 return [onFound(deferred), next] as const;
143 }).pipe(Effect.flatten);
144
145 const removeExtPending = (requestId: string) =>
146 Ref.update(extPending, (pending) => {
147 if (!pending.has(requestId)) {
148 return pending;
149 }
150 const next = new Map(pending);
151 next.delete(requestId);
152 return next;
153 });
154
155 const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) =>
156 resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error));
157
158 const completeExtPendingSuccess = (requestId: string, value: unknown) =>
159 resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value));
160
161 const failAllExtPending = (error: AcpError.AcpError) =>
162 Ref.getAndSet(extPending, new Map()).pipe(
163 Effect.flatMap((pending) =>
164 Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), {
165 discard: true,
166 }),
167 ),
168 );
169
170 const dispatchNotification = (notification: AcpIncomingNotification) =>
171 Queue.offer(notificationQueue, notification).pipe(
172 Effect.andThen(
173 options.onNotification
174 ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
175 : Effect.void,
176 ),
177 Effect.asVoid,
178 );
179
180 const emitClientProtocolError = (error: AcpError.AcpError) =>
181 Queue.offer(clientQueue, {
182 _tag: "ClientProtocolError",
183 error: new RpcClientError.RpcClientError({
184 reason: new RpcClientError.RpcClientDefect({
185 message: error.message,
186 cause: error,
187 }),
188 }),
189 }).pipe(Effect.asVoid);
190
191 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>
192 Ref.modify(terminationHandled, (handled) => {
193 if (handled) {
194 return [Effect.void, true] as const;
195 }
196 return [
197 Effect.gen(function* () {
198 yield* Queue.offer(disconnects, 0);
199 const error = yield* classify();
200 if (!error) {
201 return;
202 }
203 yield* failAllExtPending(error);
204 yield* emitClientProtocolError(error);
205 if (options.onTermination) {
206 yield* options.onTermination(error);
207 }
208 }),
209 true,
210 ] as const;
211 }).pipe(Effect.flatten);
212
213 const respondWithSuccess = (requestId: string, value: unknown) =>
214 offerOutgoing({
215 _tag: "Exit",
216 requestId,
217 exit: {
218 _tag: "Success",
219 value,
220 },
221 });
222
223 const respondWithError = (requestId: string, error: AcpError.AcpRequestError) =>
224 offerOutgoing({
225 _tag: "Exit",
226 requestId,
227 exit: {
228 _tag: "Failure",
229 cause: [
230 {
231 _tag: "Fail",
232 error: error.toProtocolError(),
233 },
234 ],
235 },
236 });
237
238 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
239 if (!options.onExtRequest) {
240 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
241 }
242 return options.onExtRequest(message.tag, message.payload).pipe(
243 Effect.matchEffect({
244 onFailure: (error) => respondWithError(message.id, normalizeToRequestError(error)),
245 onSuccess: (value) => respondWithSuccess(message.id, value),
246 }),
247 );
248 };
249
250 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
251 if (message.id === "") {
252 if (message.tag === CLIENT_METHODS.session_update) {
253 return decodeSessionUpdate(message.payload).pipe(
254 Effect.map(
255 (params) =>
256 ({
257 _tag: "SessionUpdate",
258 method: CLIENT_METHODS.session_update,
259 params,
260 }) satisfies AcpIncomingNotification,
261 ),
262 Effect.mapError(
263 (cause) =>
264 new AcpError.AcpProtocolParseError({
265 detail: `Invalid ${CLIENT_METHODS.session_update} notification payload`,
266 cause,
267 }),
268 ),
269 Effect.flatMap(dispatchNotification),
270 );
271 }
272 if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
273 return decodeElicitationComplete(message.payload).pipe(
274 Effect.map(
275 (params) =>
276 ({
277 _tag: "ElicitationComplete",
278 method: CLIENT_METHODS.session_elicitation_complete,
279 params,
280 }) satisfies AcpIncomingNotification,
281 ),
282 Effect.mapError(
283 (cause) =>
284 new AcpError.AcpProtocolParseError({
285 detail: `Invalid ${CLIENT_METHODS.session_elicitation_complete} notification payload`,
286 cause,
287 }),
288 ),
289 Effect.flatMap(dispatchNotification),
290 );
291 }
292 return dispatchNotification({
293 _tag: "ExtNotification",
294 method: message.tag,
295 params: message.payload,
296 });
297 }
298
299 if (!options.serverRequestMethods.has(message.tag)) {
300 return handleExtRequest(message).pipe(
301 Effect.catch(() => respondWithError(message.id, AcpError.AcpRequestError.internalError())),
302 Effect.asVoid,
303 );
304 }
305
306 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
307 };
308
309 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
310 Ref.get(extPending).pipe(
311 Effect.flatMap((pending) => {
312 if (!pending.has(message.requestId)) {
313 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
314 }
315 if (message.exit._tag === "Success") {
316 return completeExtPendingSuccess(message.requestId, message.exit.value);
317 }
318 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
319 if (failure && isProtocolError(failure.error)) {
320 return completeExtPendingFailure(
321 message.requestId,
322 AcpError.AcpRequestError.fromProtocolError(failure.error),
323 );
324 }
325 return completeExtPendingFailure(
326 message.requestId,
327 AcpError.AcpRequestError.internalError("Extension request failed"),
328 );
329 }),
330 );
331
332 const routeDecodedMessage = (
333 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
334 ): Effect.Effect<void, AcpError.AcpError> => {
335 switch (message._tag) {
336 case "Request":
337 return handleRequestEncoded(message);
338 case "Exit":
339 return handleExitEncoded(message);
340 case "Chunk":
341 return Ref.get(extPending).pipe(
342 Effect.flatMap((pending) =>
343 pending.has(message.requestId)
344 ? completeExtPendingFailure(
345 message.requestId,
346 AcpError.AcpRequestError.internalError(
347 "Streaming extension responses are not supported",
348 ),
349 )
350 : Queue.offer(clientQueue, message).pipe(Effect.asVoid),
351 ),
352 );
353 case "Defect":
354 case "ClientProtocolError":
355 case "Pong":
356 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
357 case "Ack":
358 case "Interrupt":
359 case "Ping":
360 case "Eof":
361 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
362 }
363 };
364
365 yield* options.stdio.stdin.pipe(
366 Stream.runForEach((data) =>
367 logProtocol({
368 direction: "incoming",
369 stage: "raw",
370 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
371 }).pipe(
372 Effect.flatMap(() =>
373 Effect.try({
374 try: () =>
375 parser.decode(data) as ReadonlyArray<
376 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
377 >,
378 catch: (cause) =>
379 new AcpError.AcpProtocolParseError({
380 detail: "Failed to decode ACP wire message",
381 cause,
382 }),
383 }),
384 ),
385 Effect.tap((messages) =>
386 logProtocol({
387 direction: "incoming",
388 stage: "decoded",
389 payload: messages,
390 }),
391 ),
392 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
393 logProtocol({
394 direction: "incoming",
395 stage: "decode_failed",
396 payload: {
397 detail: error.detail,
398 cause: error.cause,
399 },
400 }),
401 ),
402 Effect.flatMap((messages) =>
403 Effect.forEach(messages, routeDecodedMessage, {
404 discard: true,
405 }),
406 ),
407 ),
408 ),
409 Effect.matchEffect({
410 onFailure: (error) => {
411 const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
412 ? error
413 : new AcpError.AcpTransportError({
414 detail: error instanceof Error ? error.message : String(error),
415 cause: error,
416 });
417 return handleTermination(() => Effect.succeed(normalized));
418 },
419 onSuccess: () =>
420 handleTermination(
421 () =>
422 options.terminationError ??
423 Effect.succeed(
424 new AcpError.AcpTransportError({
425 detail: "ACP input stream ended",
426 cause: new Error("ACP input stream ended"),
427 }),
428 ),
429 ),
430 }),
431 Effect.forkScoped,
432 );
433
434 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
435
436 const clientProtocol = RpcClient.Protocol.of({
437 run: (_clientId, f) =>
438 Stream.fromQueue(clientQueue).pipe(
439 Stream.runForEach((message) => f(message)),
440 Effect.forever,
441 ),
442 send: (_clientId, request) => offerOutgoing(request).pipe(Effect.mapError(toRpcClientError)),
443 supportsAck: true,
444 supportsTransferables: false,
445 });
446
447 const serverProtocol = RpcServer.Protocol.of({
448 run: (f) =>
449 Stream.fromQueue(serverQueue).pipe(
450 Stream.runForEach((message) => f(0, message)),
451 Effect.forever,
452 ),
453 disconnects,
454 send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
455 end: (_clientId) => Queue.end(outgoing),
456 clientIds: Effect.succeed(new Set([0])),
457 initialMessage: Effect.succeedNone,
458 supportsAck: true,
459 supportsTransferables: false,
460 supportsSpanPropagation: true,
461 });
462
463 const sendNotification = Effect.fn("sendNotification")(function* (
464 method: string,
465 payload: unknown,
466 ) {
467 yield* offerOutgoing({
468 _tag: "Request",
469 id: "",
470 tag: method,
471 payload,
472 headers: [],
473 });
474 });
475
476 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
477 const requestId = yield* Ref.modify(
478 nextRequestId,
479 (current) => [current, current + 1n] as const,
480 );
481 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
482 yield* Ref.update(extPending, (pending) => new Map(pending).set(String(requestId), deferred));
483 yield* offerOutgoing({
484 _tag: "Request",
485 id: String(requestId),
486 tag: method,
487 payload,
488 headers: [],
489 }).pipe(
490 Effect.catch((error) =>
491 removeExtPending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
492 ),
493 );
494 return yield* Deferred.await(deferred).pipe(
495 Effect.onInterrupt(() => removeExtPending(String(requestId))),
496 );
497 });
498
499 return {
500 clientProtocol,
501 serverProtocol,
502 get incoming() {
503 return Stream.fromQueue(notificationQueue);
504 },
505 request: sendRequest,
506 notify: sendNotification,
507 } satisfies AcpPatchedProtocol;
508});
509
510function isProtocolError(
511 value: unknown,
512): value is { code: number; message: string; data?: unknown } {
513 return (
514 typeof value === "object" &&
515 value !== null &&
516 "code" in value &&
517 typeof value.code === "number" &&
518 "message" in value &&
519 typeof value.message === "string"
520 );
521}
522
523function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError {
524 return Schema.is(AcpError.AcpRequestError)(error)
525 ? error
526 : AcpError.AcpRequestError.internalError(error.message);
527}
528
529function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError {
530 return new RpcClientError.RpcClientError({
531 reason: new RpcClientError.RpcClientDefect({
532 message: error.message,
533 cause: error,
534 }),
535 });
536}