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

protocol.ts

508 lines18.7 KB

1import * as Cause from "effect/Cause";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Option from "effect/Option";
6import * as Queue from "effect/Queue";
7import * as Ref from "effect/Ref";
8import * as Scope from "effect/Scope";
9import * as Schema from "effect/Schema";
10import * as Stdio from "effect/Stdio";
11import * as Stream from "effect/Stream";
12​
13import * as CodexError from "./errors.ts";
14import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
15const isJsonRpcId = Schema.is(JsonRpcId);
16const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
17const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
18const MAX_BUFFERED_RAW_MESSAGES = 32;
19// Bound JSONL lines before joining and parsing; the LF delimiter is excluded.
20const MAX_INCOMING_MESSAGE_BYTES = 128 * 1024 * 1024;
21const EXIT_STATUS_GRACE = "250 millis";
22​
23export interface CodexAppServerProtocolLogEvent {
24 readonly direction: "incoming" | "outgoing";
25 readonly stage: "raw" | "decoded" | "decode_failed";
26 readonly payload: unknown;
28​
29export interface CodexAppServerIncomingNotification {
30 readonly method: string;
31 readonly params?: unknown;
33​
34export interface CodexAppServerIncomingRequest {
35 readonly id: string | number;
36 readonly method: string;
37 readonly params?: unknown;
39​
40export interface CodexAppServerPatchedProtocolOptions {
41 readonly stdio: Stdio.Stdio;
42 readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
43 readonly logIncoming?: boolean;
44 readonly logOutgoing?: boolean;
45 // Test override; production uses MAX_INCOMING_MESSAGE_BYTES.
46 readonly maxIncomingMessageBytes?: number;
47 readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
48 readonly onNotification?: (
49 notification: CodexAppServerIncomingNotification,
50 ) => Effect.Effect<void, never>;
51 readonly onRequest?: (
52 request: CodexAppServerIncomingRequest,
53 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
54 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
56​
57export interface CodexAppServerPatchedProtocol {
58 readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
59 readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
60 readonly request: (
61 method: string,
62 payload?: unknown,
63 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
64 readonly notify: (
65 method: string,
66 payload?: unknown,
67 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
68 readonly respond: (
69 requestId: string | number,
70 result: unknown,
71 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
72 readonly respondError: (
73 requestId: string | number,
74 error: CodexError.CodexAppServerRequestError,
75 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
77​
78interface CodexAppServerPendingRequest {
79 readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;
80 readonly method: string;
82​
83function isObject(value: unknown): value is Record<string, unknown> {
84 return typeof value === "object" && value !== null;
86​
87function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
88 if (!isObject(value) || typeof value.method !== "string") {
89 return false;
90 }
91 return isJsonRpcId(value.id);
93​
94function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
95 return isObject(value) && typeof value.method === "string" && !("id" in value);
97​
98function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
99 return isJsonRpcResponseEnvelope(value);
101​
102const encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
103const decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
104​
105const encodeWireMessage = (
106 message: Record<string, unknown>,
107): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
108 encodeJsonString(message).pipe(
109 Effect.map((encoded) => `${encoded}\n`),
110 Effect.mapError((cause) => {
111 const method = typeof message.method === "string" ? message.method : undefined;
112 const requestId =
113 typeof message.id === "string" || typeof message.id === "number"
114 ? String(message.id)
115 : undefined;
116 return CodexError.CodexAppServerProtocolParseError.fromSchemaError(
117 "encode-wire-message",
118 cause,
119 {
120 ...(method === undefined ? {} : { method }),
121 ...(requestId === undefined ? {} : { requestId }),
122 },
123 );
124 }),
125 );
126​
127const decodeWireMessage = (
128 line: string,
129): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>
130 decodeJsonString(line).pipe(
131 Effect.mapError((cause) =>
132 CodexError.CodexAppServerProtocolParseError.fromSchemaError("decode-wire-message", cause),
133 ),
134 );
135​
136const normalizeIncomingError = (
137 error: unknown,
138 operation: CodexError.CodexAppServerTransportOperation,
139): CodexError.CodexAppServerError =>
140 isCodexAppServerError(error)
141 ? error
142 : new CodexError.CodexAppServerTransportError({
143 operation,
144 cause: error,
145 });
146​
147const toProtocolMessage = (
148 requestId: string | number,
149 fields: {
150 readonly result?: unknown;
151 readonly error?: CodexError.CodexAppServerProtocolErrorShape;
152 },
153): { readonly [key: string]: unknown } => ({
154 id: requestId,
155 ...(fields.result !== undefined ? { result: fields.result } : {}),
156 ...(fields.error !== undefined ? { error: fields.error } : {}),
157});
158​
159export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
160 function* (
161 options: CodexAppServerPatchedProtocolOptions,
162 ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
163 const protocolScope = yield* Scope.Scope;
164 const requestHandlerScope = yield* Scope.fork(protocolScope, "parallel");
165 const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
166 const incomingNotifications =
167 yield* Queue.sliding<CodexAppServerIncomingNotification>(MAX_BUFFERED_RAW_MESSAGES);
168 const incomingRequests =
169 yield* Queue.sliding<CodexAppServerIncomingRequest>(MAX_BUFFERED_RAW_MESSAGES);
170 const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
171 const nextRequestId = yield* Ref.make(1);
172 const maxIncomingMessageBytes = options.maxIncomingMessageBytes ?? MAX_INCOMING_MESSAGE_BYTES;
173 const remainder: Array<string> = [];
174 let remainderBytes = 0;
175 const terminationHandled = yield* Ref.make(false);
176 const terminationFailure = yield* Ref.make(Option.none<CodexError.CodexAppServerError>());
177 const terminationSignal = yield* Deferred.make<void>();
178 const activeRequestHandlers = yield* Ref.make(0);
179​
180 const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
181 if (event.direction === "incoming" && !options.logIncoming) {
182 return Effect.void;
183 }
184 if (event.direction === "outgoing" && !options.logOutgoing) {
185 return Effect.void;
186 }
187 return (
188 options.logger?.(event) ??
189 Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
190 );
191 };
192​
193 const failAllPending = (error: CodexError.CodexAppServerError) =>
194 Ref.get(pending).pipe(
195 Effect.flatMap((current) =>
196 Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {
197 discard: true,
198 }),
199 ),
200 Effect.andThen(Ref.set(pending, new Map())),
201 );
202​
203 const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
204 Ref.modify(terminationHandled, (handled) => {
205 if (handled) {
206 return [Effect.void, true] as const;
207 }
208 return [
209 Effect.gen(function* () {
210 const error = yield* classify();
211 yield* Ref.set(terminationFailure, Option.some(error));
212 yield* failAllPending(error);
213 yield* Queue.end(outgoing);
214 yield* Deferred.succeed(terminationSignal, undefined);
215 yield* Scope.close(requestHandlerScope, Exit.void).pipe(
216 Effect.forkIn(protocolScope, { startImmediately: true }),
217 Effect.asVoid,
218 );
219 if (options.onTermination) {
220 yield* options.onTermination(error);
221 }
222 }),
223 true,
224 ] as const;
225 }).pipe(Effect.flatten);
226​
227 const offerOutgoing =
228 /* Every protocol write reaches this helper; request spans cover the operation. */
229 Effect.fnUntraced(function* (message: Record<string, unknown>) {
230 const failure = yield* Ref.get(terminationFailure);
231 if (Option.isSome(failure)) return yield* failure.value;
232​
233 yield* logProtocol({
234 direction: "outgoing",
235 stage: "decoded",
236 payload: message,
237 });
238 const encoded = yield* encodeWireMessage(message);
239 yield* logProtocol({
240 direction: "outgoing",
241 stage: "raw",
242 payload: encoded,
243 });
244 const accepted = yield* Queue.offer(outgoing, encoded);
245 if (!accepted) {
246 const closed = yield* Ref.get(terminationFailure);
247 return yield* Option.getOrElse(
248 closed,
249 () => new CodexError.CodexAppServerInputStreamEndedError({}),
250 );
251 }
252 });
253​
254 const removePending = (requestId: string) =>
255 Ref.update(pending, (current) => {
256 if (!current.has(requestId)) {
257 return current;
258 }
259 const next = new Map(current);
260 next.delete(requestId);
261 return next;
262 });
263​
264 const resolvePending = (
265 requestId: string,
266 handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,
267 ) =>
268 Ref.modify(pending, (current) => {
269 const pendingRequest = current.get(requestId);
270 if (!pendingRequest) {
271 return [Effect.void, current] as const;
272 }
273 const next = new Map(current);
274 next.delete(requestId);
275 return [handler(pendingRequest), next] as const;
276 }).pipe(Effect.flatten);
277​
278 const respond = (requestId: string | number, result: unknown) =>
279 offerOutgoing(toProtocolMessage(requestId, { result }));
280​
281 const respondError = (
282 requestId: string | number,
283 error: CodexError.CodexAppServerRequestError,
284 ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
285​
286 const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
287 const requestId = String(response.id);
288 const protocolError = response.error;
289 if (protocolError !== undefined) {
290 return resolvePending(requestId, ({ deferred, method }) =>
291 Deferred.fail(
292 deferred,
293 CodexError.CodexAppServerRequestError.fromProtocolError(
294 protocolError,
295 method,
296 requestId,
297 ),
298 ),
299 );
300 }
301 return resolvePending(requestId, ({ deferred }) =>
302 Deferred.succeed(deferred, response.result),
303 );
304 };
305​
306 const handleRequest = (request: CodexAppServerIncomingRequest) =>
307 Queue.offer(incomingRequests, request).pipe(
308 Effect.flatMap(() => {
309 const handler = options.onRequest;
310 if (!handler) return Effect.void;
311​
312 return Ref.modify(activeRequestHandlers, (count) =>
313 count >= MAX_BUFFERED_RAW_MESSAGES ? [false, count] : [true, count + 1],
314 ).pipe(
315 Effect.flatMap((accepted) => {
316 if (!accepted) {
317 return respondError(
318 request.id,
319 CodexError.CodexAppServerRequestError.overloaded(
320 "Too many Codex requests are already active.",
321 ),
322 );
323 }
324​
325 return handler(request).pipe(
326 Effect.matchEffect({
327 onFailure: (error) =>
328 respondError(
329 request.id,
330 CodexError.CodexAppServerRequestError.fromAppServerError(
331 error,
332 request.method,
333 ),
334 ),
335 onSuccess: (result) => respond(request.id, result),
336 }),
337 Effect.ensuring(
338 Ref.update(activeRequestHandlers, (count) => Math.max(0, count - 1)),
339 ),
340 Effect.catch((error) =>
341 handleTermination(() => Effect.succeed(error)).pipe(
342 Effect.forkIn(protocolScope),
343 Effect.asVoid,
344 ),
345 ),
346 Effect.forkIn(requestHandlerScope, { startImmediately: true }),
347 Effect.asVoid,
348 );
349 }),
350 );
351 }),
352 Effect.asVoid,
353 );
354​
355 const handleNotification = (notification: CodexAppServerIncomingNotification) =>
356 Queue.offer(incomingNotifications, notification).pipe(
357 Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
358 Effect.asVoid,
359 );
360​
361 const routeMessage = Effect.fnUntraced(function* (message: unknown) {
362 if (Option.isSome(yield* Ref.get(terminationFailure))) return;
363 if (isIncomingRequest(message)) return yield* handleRequest(message);
364 if (isIncomingNotification(message)) return yield* handleNotification(message);
365 if (isIncomingResponse(message)) return yield* handleResponse(message);
366 return yield* CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message);
367 });
368​
369 const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
370 if (line.trim().length === 0) {
371 return Effect.void;
372 }
373 return logProtocol({
374 direction: "incoming",
375 stage: "raw",
376 payload: line,
377 }).pipe(
378 Effect.flatMap(() => decodeWireMessage(line)),
379 Effect.tap((decoded) =>
380 logProtocol({
381 direction: "incoming",
382 stage: "decoded",
383 payload: decoded,
384 }),
385 ),
386 Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
387 logProtocol({
388 direction: "incoming",
389 stage: "decode_failed",
390 payload: {
391 operation: error.operation,
392 ...(error.method === undefined ? {} : { method: error.method }),
393 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
394 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
395 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
396 ...(error.maximumPathDepth === undefined
397 ? {}
398 : { maximumPathDepth: error.maximumPathDepth }),
399 },
400 }),
401 ),
402 Effect.flatMap(routeMessage),
403 );
404 };
405​
406 yield* options.stdio.stdin.pipe(
407 Stream.interruptWhen(Deferred.await(terminationSignal)),
408 Stream.decodeText(),
409 Stream.runForEach(
410 Effect.fnUntraced(function* (chunk) {
411 let start = 0;
412 while (start < chunk.length) {
413 const newline = chunk.indexOf("\n", start);
414 const fragment = chunk.slice(start, newline === -1 ? chunk.length : newline);
415 // decodeText holds back split UTF-8 sequences, so fragment byte sums are exact.
416 remainderBytes += Buffer.byteLength(fragment, "utf8");
417 if (remainderBytes > maxIncomingMessageBytes) {
418 remainder.length = 0;
419 return yield* new CodexError.CodexAppServerTransportError({
420 operation: "read-input-stream",
421 cause: new Error(`Incoming message exceeded ${maxIncomingMessageBytes} bytes.`),
422 });
423 }
424 remainder.push(fragment);
425 if (newline === -1) break;
426 const line = remainder.join("").replace(/\r$/, "");
427 remainder.length = 0;
428 remainderBytes = 0;
429 yield* handleLine(line);
430 start = newline + 1;
431 }
432 }),
433 ),
434 Effect.matchEffect({
435 onFailure: (error) =>
436 handleTermination(() =>
437 Effect.succeed(normalizeIncomingError(error, "read-input-stream")),
438 ),
439 onSuccess: () =>
440 Effect.sync(() => {
441 const line = remainder.join("");
442 remainder.length = 0;
443 return line;
444 }).pipe(
445 Effect.flatMap(handleLine),
446 Effect.matchEffect({
447 onFailure: (error) => handleTermination(() => Effect.succeed(error)),
448 onSuccess: () =>
449 handleTermination(() => {
450 const ended = new CodexError.CodexAppServerInputStreamEndedError({});
451 // Node ends stdout before it reports the exit of a crashed process, so
452 // wait briefly for the exit status. stdout can also close while the
453 // process keeps running, so the wait must not hang pending requests.
454 return options.terminationError === undefined
455 ? Effect.succeed(ended)
456 : options.terminationError.pipe(
457 Effect.timeoutOrElse({
458 duration: EXIT_STATUS_GRACE,
459 orElse: () => Effect.succeed(ended),
460 }),
461 );
462 }),
463 }),
464 ),
465 }),
466 Effect.forkScoped,
467 );
468​
469 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
470​
471 const request = Effect.fn("CodexAppServerProtocol.request")(function* (
472 method: string,
473 payload?: unknown,
474 ) {
475 const requestId = yield* Ref.modify(
476 nextRequestId,
477 (current) => [current, current + 1] as const,
478 );
479 const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
480 yield* Ref.update(pending, (current) =>
481 new Map(current).set(String(requestId), { deferred, method }),
482 );
483 yield* offerOutgoing({
484 id: requestId,
485 method,
486 ...(payload !== undefined ? { params: payload } : {}),
487 }).pipe(Effect.tapError(() => removePending(String(requestId))));
488 return yield* Deferred.await(deferred).pipe(
489 Effect.onInterrupt(() => removePending(String(requestId))),
490 );
491 });
492​
493 const notify = (method: string, payload?: unknown) =>
494 offerOutgoing({
495 method,
496 ...(payload !== undefined ? { params: payload } : {}),
497 });
498​
499 return {
500 incomingNotifications: Stream.fromQueue(incomingNotifications),
501 incomingRequests: Stream.fromQueue(incomingRequests),
502 request,
503 notify,
504 respond,
505 respondError,
506 } satisfies CodexAppServerPatchedProtocol;
507 },
508);