Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6import * as Stdio from "effect/Stdio";
7import * as Stream from "effect/Stream";
8import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
9
10import * as CodexRpc from "./_generated/meta.gen.ts";
11import * as CodexError from "./errors.ts";
12import * as CodexProtocol from "./protocol.ts";
13import {
14 decodeNotificationPayload,
15 decodeOptionalPayload,
16 encodeOptionalPayload,
17 runHandler,
18} from "./_internal/shared.ts";
19import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
20
21export interface CodexAppServerClientOptions {
22 readonly logIncoming?: boolean;
23 readonly logOutgoing?: boolean;
24 readonly logger?: (
25 event: CodexProtocol.CodexAppServerProtocolLogEvent,
26 ) => Effect.Effect<void, never>;
27}
28
29interface CodexAppServerClientRaw {
30 readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
31 readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
32 readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
33 readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
34 readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
35 readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
36}
37
38export class CodexAppServerClient extends Context.Service<
39 CodexAppServerClient,
40 {
41 readonly raw: CodexAppServerClientRaw;
42 readonly request: <M extends CodexRpc.ClientRequestMethod>(
43 method: M,
44 payload: CodexRpc.ClientRequestParamsByMethod[M],
45 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
46 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
47 method: M,
48 payload: CodexRpc.ClientNotificationParamsByMethod[M],
49 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
50 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
51 method: M,
52 handler: (
53 payload: CodexRpc.ServerRequestParamsByMethod[M],
54 ) => Effect.Effect<
55 CodexRpc.ServerRequestResponsesByMethod[M],
56 CodexError.CodexAppServerError
57 >,
58 ) => Effect.Effect<void>;
59 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
60 method: M,
61 handler: (
62 payload: CodexRpc.ServerNotificationParamsByMethod[M],
63 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
64 ) => Effect.Effect<void>;
65 readonly handleUnknownServerRequest: (
66 handler: (
67 method: string,
68 params: unknown,
69 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
70 ) => Effect.Effect<void>;
71 readonly handleUnknownServerNotification: (
72 handler: (
73 method: string,
74 params: unknown,
75 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
76 ) => Effect.Effect<void>;
77 }
78>()("effect-codex-app-server/client/CodexAppServerClient") {}
79
80type ServerRequestHandler = (
81 payload: unknown,
82) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
83type ServerNotificationHandler = (
84 payload: unknown,
85) => Effect.Effect<void, CodexError.CodexAppServerError>;
86
87const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
88 stdio: Stdio.Stdio,
89 options: CodexAppServerClientOptions = {},
90 terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
91): Effect.fn.Return<CodexAppServerClient["Service"], never, Scope.Scope> {
92 const requestHandlers = new Map<string, ServerRequestHandler>();
93 const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
94 let unknownRequestHandler:
95 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
96 | undefined;
97 let unknownNotificationHandler:
98 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
99 | undefined;
100
101 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
102 method: M,
103 ):
104 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
105 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
106
107 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
108 method: M,
109 ):
110 | Schema.Codec<
111 CodexRpc.ServerRequestResponsesByMethod[M],
112 CodexRpc.ServerRequestResponsesByMethod[M]
113 >
114 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
115
116 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
117 method: M,
118 ):
119 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
120 | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;
121
122 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
123 method: M,
124 ):
125 | Schema.Codec<
126 CodexRpc.ClientRequestResponsesByMethod[M],
127 CodexRpc.ClientRequestResponsesByMethod[M]
128 >
129 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
130
131 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
132 method: M,
133 ):
134 | Schema.Codec<
135 CodexRpc.ClientNotificationParamsByMethod[M],
136 CodexRpc.ClientNotificationParamsByMethod[M]
137 >
138 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
139
140 const dispatchNotification = (
141 notification: CodexProtocol.CodexAppServerIncomingNotification,
142 ): Effect.Effect<void, never> => {
143 const schema =
144 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
145 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
146 notification.method as CodexRpc.ServerNotificationMethod
147 ]
148 : undefined;
149 const handlers = notificationHandlers.get(notification.method) ?? [];
150
151 if (schema) {
152 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
153 Effect.flatMap((decoded) =>
154 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
155 ),
156 Effect.ignore,
157 );
158 }
159
160 return unknownNotificationHandler
161 ? unknownNotificationHandler(notification.method, notification.params).pipe(Effect.ignore)
162 : Effect.void;
163 };
164
165 const dispatchRequest = (
166 request: CodexProtocol.CodexAppServerIncomingRequest,
167 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
168 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
169 const method = request.method as CodexRpc.ServerRequestMethod;
170 const payloadSchema = getServerRequestParamSchema(method);
171 const responseSchema = getServerRequestResponseSchema(method);
172 const handler = requestHandlers.get(method);
173
174 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
175 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
176 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
177 );
178 }
179
180 return unknownRequestHandler
181 ? unknownRequestHandler(request.method, request.params)
182 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
183 };
184
185 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
186 stdio,
187 ...(terminationError ? { terminationError } : {}),
188 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
189 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
190 ...(options.logger ? { logger: options.logger } : {}),
191 onNotification: dispatchNotification,
192 onRequest: dispatchRequest,
193 });
194
195 const request = <M extends CodexRpc.ClientRequestMethod>(
196 method: M,
197 payload: CodexRpc.ClientRequestParamsByMethod[M],
198 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
199 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
200 Effect.flatMap((encoded) => transport.request(method, encoded)),
201 Effect.flatMap(
202 (
203 raw,
204 ): Effect.Effect<
205 CodexRpc.ClientRequestResponsesByMethod[M],
206 CodexError.CodexAppServerError
207 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
208 ),
209 );
210
211 const notify = <M extends CodexRpc.ClientNotificationMethod>(
212 method: M,
213 payload: CodexRpc.ClientNotificationParamsByMethod[M],
214 ) =>
215 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
216 Effect.flatMap((encoded) => transport.notify(method, encoded)),
217 );
218
219 return CodexAppServerClient.of({
220 raw: {
221 notifications: transport.incomingNotifications,
222 requests: transport.incomingRequests,
223 request: transport.request,
224 notify: transport.notify,
225 respond: transport.respond,
226 respondError: transport.respondError,
227 },
228 request,
229 notify,
230 handleServerRequest: (method, handler) =>
231 Effect.sync(() => {
232 requestHandlers.set(method, handler as ServerRequestHandler);
233 }),
234 handleServerNotification: (method, handler) =>
235 Effect.sync(() => {
236 const current = notificationHandlers.get(method) ?? [];
237 current.push(handler as ServerNotificationHandler);
238 notificationHandlers.set(method, current);
239 }),
240 handleUnknownServerRequest: (handler) =>
241 Effect.sync(() => {
242 unknownRequestHandler = handler;
243 }),
244 handleUnknownServerNotification: (handler) =>
245 Effect.sync(() => {
246 unknownNotificationHandler = handler;
247 }),
248 });
249});
250
251export const layerChildProcess = (
252 handle: ChildProcessSpawner.ChildProcessHandle,
253 options: CodexAppServerClientOptions = {},
254): Layer.Layer<CodexAppServerClient> =>
255 Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
256
257const makeChildProcessClient = Effect.fn(
258 "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
259)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
260 yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
261 return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
262});