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

protocol.ts

536 lines17.3 KB

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