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

protocol.ts

403 lines13.7 KB

1import * as Cause from "effect/Cause";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Queue from "effect/Queue";
5import * as Ref from "effect/Ref";
6import * as Scope from "effect/Scope";
7import * as Schema from "effect/Schema";
8import * as Stdio from "effect/Stdio";
9import * as Stream from "effect/Stream";
10​
11import * as CodexError from "./errors.ts";
12import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
13​
14export interface CodexAppServerProtocolLogEvent {
15 readonly direction: "incoming" | "outgoing";
16 readonly stage: "raw" | "decoded" | "decode_failed";
17 readonly payload: unknown;
19​
20export interface CodexAppServerIncomingNotification {
21 readonly method: string;
22 readonly params?: unknown;
24​
25export interface CodexAppServerIncomingRequest {
26 readonly id: string | number;
27 readonly method: string;
28 readonly params?: unknown;
30​
31export interface CodexAppServerPatchedProtocolOptions {
32 readonly stdio: Stdio.Stdio;
33 readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
34 readonly logIncoming?: boolean;
35 readonly logOutgoing?: boolean;
36 readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
37 readonly onNotification?: (
38 notification: CodexAppServerIncomingNotification,
39 ) => Effect.Effect<void, never>;
40 readonly onRequest?: (
41 request: CodexAppServerIncomingRequest,
42 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
43 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
45​
46export interface CodexAppServerPatchedProtocol {
47 readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
48 readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
49 readonly request: (
50 method: string,
51 payload?: unknown,
52 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
53 readonly notify: (
54 method: string,
55 payload?: unknown,
56 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
57 readonly respond: (
58 requestId: string | number,
59 result: unknown,
60 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
61 readonly respondError: (
62 requestId: string | number,
63 error: CodexError.CodexAppServerRequestError,
64 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
66​
67function isObject(value: unknown): value is Record<string, unknown> {
68 return typeof value === "object" && value !== null;
70​
71function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
72 if (!isObject(value) || typeof value.method !== "string") {
73 return false;
74 }
75 return Schema.is(JsonRpcId)(value.id);
77​
78function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
79 return isObject(value) && typeof value.method === "string" && !("id" in value);
81​
82function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
83 return Schema.is(JsonRpcResponseEnvelope)(value);
85​
86const encodeJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
87const decodeJsonString = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
88​
89const encodeWireMessage = (
90 message: Record<string, unknown>,
91): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
92 encodeJsonString(message).pipe(
93 Effect.map((encoded) => `${encoded}\n`),
94 Effect.mapError(
95 (cause) =>
96 new CodexError.CodexAppServerProtocolParseError({
97 detail: "Failed to encode Codex App Server message",
98 cause,
99 }),
100 ),
101 );
102​
103const decodeWireMessage = (
104 line: string,
105): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>
106 decodeJsonString(line).pipe(
107 Effect.mapError(
108 (cause) =>
109 new CodexError.CodexAppServerProtocolParseError({
110 detail: "Failed to decode Codex App Server wire message",
111 cause,
112 }),
113 ),
114 );
115​
116const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
117 Schema.is(CodexError.CodexAppServerError)(error)
118 ? error
119 : new CodexError.CodexAppServerTransportError({
120 detail,
121 cause: error,
122 });
123​
124const toProtocolMessage = (
125 requestId: string | number,
126 fields: {
127 readonly result?: unknown;
128 readonly error?: CodexError.CodexAppServerProtocolErrorShape;
129 },
130): { readonly [key: string]: unknown } => ({
131 id: requestId,
132 ...(fields.result !== undefined ? { result: fields.result } : {}),
133 ...(fields.error !== undefined ? { error: fields.error } : {}),
134});
135​
136export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
137 function* (
138 options: CodexAppServerPatchedProtocolOptions,
139 ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
140 const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
141 const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
142 const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
143 const pending = yield* Ref.make(
144 new Map<string, Deferred.Deferred<unknown, CodexError.CodexAppServerError>>(),
145 );
146 const nextRequestId = yield* Ref.make(1);
147 const remainder = yield* Ref.make("");
148 const terminationHandled = yield* Ref.make(false);
149​
150 const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
151 if (event.direction === "incoming" && !options.logIncoming) {
152 return Effect.void;
153 }
154 if (event.direction === "outgoing" && !options.logOutgoing) {
155 return Effect.void;
156 }
157 return (
158 options.logger?.(event) ??
159 Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
160 );
161 };
162​
163 const failAllPending = (error: CodexError.CodexAppServerError) =>
164 Ref.get(pending).pipe(
165 Effect.flatMap((current) =>
166 Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {
167 discard: true,
168 }),
169 ),
170 Effect.andThen(Ref.set(pending, new Map())),
171 );
172​
173 const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
174 Ref.modify(terminationHandled, (handled) => {
175 if (handled) {
176 return [Effect.void, true] as const;
177 }
178 return [
179 Effect.gen(function* () {
180 const error = yield* classify();
181 yield* failAllPending(error);
182 yield* Queue.end(outgoing);
183 if (options.onTermination) {
184 yield* options.onTermination(error);
185 }
186 }),
187 true,
188 ] as const;
189 }).pipe(Effect.flatten);
190​
191 const offerOutgoing = (message: Record<string, unknown>) =>
192 Effect.gen(function* () {
193 yield* logProtocol({
194 direction: "outgoing",
195 stage: "decoded",
196 payload: message,
197 });
198 const encoded = yield* encodeWireMessage(message);
199 yield* logProtocol({
200 direction: "outgoing",
201 stage: "raw",
202 payload: encoded,
203 });
204 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
205 });
206​
207 const removePending = (requestId: string) =>
208 Ref.update(pending, (current) => {
209 if (!current.has(requestId)) {
210 return current;
211 }
212 const next = new Map(current);
213 next.delete(requestId);
214 return next;
215 });
216​
217 const resolvePending = (
218 requestId: string,
219 handler: (
220 deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>,
221 ) => Effect.Effect<void>,
222 ) =>
223 Ref.modify(pending, (current) => {
224 const deferred = current.get(requestId);
225 if (!deferred) {
226 return [Effect.void, current] as const;
227 }
228 const next = new Map(current);
229 next.delete(requestId);
230 return [handler(deferred), next] as const;
231 }).pipe(Effect.flatten);
232​
233 const respond = (requestId: string | number, result: unknown) =>
234 offerOutgoing(toProtocolMessage(requestId, { result }));
235​
236 const respondError = (
237 requestId: string | number,
238 error: CodexError.CodexAppServerRequestError,
239 ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
240​
241 const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
242 const requestId = String(response.id);
243 const protocolError = response.error;
244 if (protocolError !== undefined) {
245 return resolvePending(requestId, (deferred) =>
246 Deferred.fail(
247 deferred,
248 CodexError.CodexAppServerRequestError.fromProtocolError(protocolError),
249 ),
250 );
251 }
252 return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result));
253 };
254​
255 const handleRequest = (request: CodexAppServerIncomingRequest) =>
256 Queue.offer(incomingRequests, request).pipe(
257 Effect.andThen(
258 options.onRequest
259 ? options.onRequest(request).pipe(
260 Effect.matchEffect({
261 onFailure: (error) =>
262 respondError(request.id, CodexError.normalizeToRequestError(error)),
263 onSuccess: (result) => respond(request.id, result),
264 }),
265 )
266 : Effect.void,
267 ),
268 Effect.asVoid,
269 );
270​
271 const handleNotification = (notification: CodexAppServerIncomingNotification) =>
272 Queue.offer(incomingNotifications, notification).pipe(
273 Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
274 Effect.asVoid,
275 );
276​
277 const routeMessage = (
278 message: unknown,
279 ): Effect.Effect<void, CodexError.CodexAppServerError> => {
280 if (isIncomingRequest(message)) {
281 return handleRequest(message);
282 }
283 if (isIncomingNotification(message)) {
284 return handleNotification(message);
285 }
286 if (isIncomingResponse(message)) {
287 return handleResponse(message);
288 }
289 return Effect.fail(
290 new CodexError.CodexAppServerProtocolParseError({
291 detail: "Received protocol message in an unknown shape",
292 }),
293 );
294 };
295​
296 const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
297 if (line.trim().length === 0) {
298 return Effect.void;
299 }
300 return logProtocol({
301 direction: "incoming",
302 stage: "raw",
303 payload: line,
304 }).pipe(
305 Effect.flatMap(() => decodeWireMessage(line)),
306 Effect.tap((decoded) =>
307 logProtocol({
308 direction: "incoming",
309 stage: "decoded",
310 payload: decoded,
311 }),
312 ),
313 Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
314 logProtocol({
315 direction: "incoming",
316 stage: "decode_failed",
317 payload: {
318 detail: error.detail,
319 cause: error.cause,
320 },
321 }),
322 ),
323 Effect.flatMap(routeMessage),
324 );
325 };
326​
327 yield* options.stdio.stdin.pipe(
328 Stream.decodeText(),
329 Stream.runForEach((chunk) =>
330 Ref.modify(remainder, (current) => {
331 const combined = current + chunk;
332 const lines = combined.split("\n");
333 const nextRemainder = lines.pop() ?? "";
334 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
335 }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
336 ),
337 Effect.matchEffect({
338 onFailure: (error) =>
339 handleTermination(() =>
340 Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")),
341 ),
342 onSuccess: () =>
343 Ref.get(remainder).pipe(
344 Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),
345 Effect.matchEffect({
346 onFailure: (error) => handleTermination(() => Effect.succeed(error)),
347 onSuccess: () =>
348 handleTermination(
349 () =>
350 options.terminationError ??
351 Effect.succeed(
352 new CodexError.CodexAppServerTransportError({
353 detail: "Codex App Server input stream ended",
354 cause: new Error("Codex App Server input stream ended"),
355 }),
356 ),
357 ),
358 }),
359 ),
360 }),
361 Effect.forkScoped,
362 );
363​
364 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
365​
366 const request = (method: string, payload?: unknown) =>
367 Effect.gen(function* () {
368 const requestId = yield* Ref.modify(
369 nextRequestId,
370 (current) => [current, current + 1] as const,
371 );
372 const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
373 yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred));
374 yield* offerOutgoing({
375 id: requestId,
376 method,
377 ...(payload !== undefined ? { params: payload } : {}),
378 }).pipe(
379 Effect.catch((error) =>
380 removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
381 ),
382 );
383 return yield* Deferred.await(deferred).pipe(
384 Effect.onInterrupt(() => removePending(String(requestId))),
385 );
386 });
387​
388 const notify = (method: string, payload?: unknown) =>
389 offerOutgoing({
390 method,
391 ...(payload !== undefined ? { params: payload } : {}),
392 });
393​
394 return {
395 incomingNotifications: Stream.fromQueue(incomingNotifications),
396 incomingRequests: Stream.fromQueue(incomingRequests),
397 request,
398 notify,
399 respond,
400 respondError,
401 } satisfies CodexAppServerPatchedProtocol;
402 },
403);