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