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