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