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