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

client.ts

300 lines11.3 KB

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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8​
9import * as CodexRpc from "./_generated/meta.gen.ts";
10import * as CodexError from "./errors.ts";
11import * as CodexProtocol from "./protocol.ts";
12import {
13 decodeNotificationPayload,
14 decodeOptionalPayload,
15 encodeOptionalPayload,
16 runHandler,
17} from "./_internal/shared.ts";
18import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
19​
20const DEFAULT_APP_SERVER_FORCE_KILL_AFTER = "2 seconds" as const;
21​
22export interface CodexAppServerClientOptions {
23 readonly logIncoming?: boolean;
24 readonly logOutgoing?: boolean;
25 readonly logger?: (
26 event: CodexProtocol.CodexAppServerProtocolLogEvent,
27 ) => Effect.Effect<void, never>;
29​
30interface CodexAppServerClientRaw {
31 readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
32 readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
33 readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
34 readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
35 readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
36 readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
38​
39export interface CodexAppServerClientShape {
40 readonly raw: CodexAppServerClientRaw;
41 readonly request: <M extends CodexRpc.ClientRequestMethod>(
42 method: M,
43 payload: CodexRpc.ClientRequestParamsByMethod[M],
44 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
45 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
46 method: M,
47 payload: CodexRpc.ClientNotificationParamsByMethod[M],
48 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
49 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
50 method: M,
51 handler: (
52 payload: CodexRpc.ServerRequestParamsByMethod[M],
53 ) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
54 ) => Effect.Effect<void>;
55 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
56 method: M,
57 handler: (
58 payload: CodexRpc.ServerNotificationParamsByMethod[M],
59 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
60 ) => Effect.Effect<void>;
61 readonly handleUnknownServerRequest: (
62 handler: (
63 method: string,
64 params: unknown,
65 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
66 ) => Effect.Effect<void>;
67 readonly handleUnknownServerNotification: (
68 handler: (
69 method: string,
70 params: unknown,
71 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
72 ) => Effect.Effect<void>;
74​
75export class CodexAppServerClient extends Context.Service<
76 CodexAppServerClient,
77 CodexAppServerClientShape
78>()("effect-codex-app-server/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​
87export const 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<CodexAppServerClientShape, 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.catch(() => Effect.void),
157 );
158 }
159​
160 return unknownNotificationHandler
161 ? unknownNotificationHandler(notification.method, notification.params).pipe(
162 Effect.catch(() => Effect.void),
163 )
164 : Effect.void;
165 };
166​
167 const dispatchRequest = (
168 request: CodexProtocol.CodexAppServerIncomingRequest,
169 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
170 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
171 const method = request.method as CodexRpc.ServerRequestMethod;
172 const payloadSchema = getServerRequestParamSchema(method);
173 const responseSchema = getServerRequestResponseSchema(method);
174 const handler = requestHandlers.get(method);
175​
176 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
177 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
178 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
179 );
180 }
181​
182 return unknownRequestHandler
183 ? unknownRequestHandler(request.method, request.params)
184 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
185 };
186​
187 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
188 stdio,
189 ...(terminationError ? { terminationError } : {}),
190 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
191 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
192 ...(options.logger ? { logger: options.logger } : {}),
193 onNotification: dispatchNotification,
194 onRequest: dispatchRequest,
195 });
196​
197 const request = <M extends CodexRpc.ClientRequestMethod>(
198 method: M,
199 payload: CodexRpc.ClientRequestParamsByMethod[M],
200 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
201 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
202 Effect.flatMap((encoded) => transport.request(method, encoded)),
203 Effect.flatMap(
204 (
205 raw,
206 ): Effect.Effect<
207 CodexRpc.ClientRequestResponsesByMethod[M],
208 CodexError.CodexAppServerError
209 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
210 ),
211 );
212​
213 const notify = <M extends CodexRpc.ClientNotificationMethod>(
214 method: M,
215 payload: CodexRpc.ClientNotificationParamsByMethod[M],
216 ) =>
217 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
218 Effect.flatMap((encoded) => transport.notify(method, encoded)),
219 );
220​
221 return CodexAppServerClient.of({
222 raw: {
223 notifications: transport.incomingNotifications,
224 requests: transport.incomingRequests,
225 request: transport.request,
226 notify: transport.notify,
227 respond: transport.respond,
228 respondError: transport.respondError,
229 },
230 request,
231 notify,
232 handleServerRequest: (method, handler) =>
233 Effect.sync(() => {
234 requestHandlers.set(method, handler as ServerRequestHandler);
235 }),
236 handleServerNotification: (method, handler) =>
237 Effect.sync(() => {
238 const current = notificationHandlers.get(method) ?? [];
239 current.push(handler as ServerNotificationHandler);
240 notificationHandlers.set(method, current);
241 }),
242 handleUnknownServerRequest: (handler) =>
243 Effect.sync(() => {
244 unknownRequestHandler = handler;
245 }),
246 handleUnknownServerNotification: (handler) =>
247 Effect.sync(() => {
248 unknownNotificationHandler = handler;
249 }),
250 });
251});
252​
253export const layerChildProcess = (
254 handle: ChildProcessSpawner.ChildProcessHandle,
255 options: CodexAppServerClientOptions = {},
256): Layer.Layer<CodexAppServerClient> => {
257 const stdio = makeChildStdio(handle);
258 const terminationError = makeTerminationError(handle);
259 return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
260};
261​
262export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
263 readonly command: string;
264 readonly args?: ReadonlyArray<string>;
265 readonly cwd?: string;
266 readonly env?: Record<string, string>;
268​
269export const layerCommand = (
270 options: CodexAppServerCommandLayerOptions,
271): Layer.Layer<
272 CodexAppServerClient,
273 CodexError.CodexAppServerSpawnError,
274 ChildProcessSpawner.ChildProcessSpawner
275> =>
276 Layer.effect(
277 CodexAppServerClient,
278 Effect.gen(function* () {
279 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
280 const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
281 ...(options.cwd ? { cwd: options.cwd } : {}),
282 ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
283 forceKillAfter: DEFAULT_APP_SERVER_FORCE_KILL_AFTER,
284 shell: process.platform === "win32",
285 });
286 return yield* spawner.spawn(command).pipe(
287 Effect.mapError(
288 (cause) =>
289 new CodexError.CodexAppServerSpawnError({
290 command: [options.command, ...(options.args ?? [])].join(" "),
291 cause,
292 }),
293 ),
294 );
295 }).pipe(
296 Effect.flatMap((handle) =>
297 make(makeChildStdio(handle), options, makeTerminationError(handle)),
298 ),
299 ),
300 );