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​
20export interface CodexAppServerClientOptions {
21 readonly logIncoming?: boolean;
22 readonly logOutgoing?: boolean;
23 readonly logger?: (
24 event: CodexProtocol.CodexAppServerProtocolLogEvent,
25 ) => Effect.Effect<void, never>;
27​
28interface CodexAppServerClientRaw {
29 readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
30 readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
31 readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
32 readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
33 readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
34 readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
36​
37export interface CodexAppServerClientShape {
38 readonly raw: CodexAppServerClientRaw;
39 readonly request: <M extends CodexRpc.ClientRequestMethod>(
40 method: M,
41 payload: CodexRpc.ClientRequestParamsByMethod[M],
42 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
43 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
44 method: M,
45 payload: CodexRpc.ClientNotificationParamsByMethod[M],
46 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
47 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
48 method: M,
49 handler: (
50 payload: CodexRpc.ServerRequestParamsByMethod[M],
51 ) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
52 ) => Effect.Effect<void>;
53 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
54 method: M,
55 handler: (
56 payload: CodexRpc.ServerNotificationParamsByMethod[M],
57 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
58 ) => Effect.Effect<void>;
59 readonly handleUnknownServerRequest: (
60 handler: (
61 method: string,
62 params: unknown,
63 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
64 ) => Effect.Effect<void>;
65 readonly handleUnknownServerNotification: (
66 handler: (
67 method: string,
68 params: unknown,
69 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
70 ) => Effect.Effect<void>;
72​
73export class CodexAppServerClient extends Context.Service<
74 CodexAppServerClient,
75 CodexAppServerClientShape
76>()("effect-codex-app-server/CodexAppServerClient") {}
77​
78type ServerRequestHandler = (
79 payload: unknown,
80) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
81type ServerNotificationHandler = (
82 payload: unknown,
83) => Effect.Effect<void, CodexError.CodexAppServerError>;
84​
85export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
86 stdio: Stdio.Stdio,
87 options: CodexAppServerClientOptions = {},
88 terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
89): Effect.fn.Return<CodexAppServerClientShape, never, Scope.Scope> {
90 const requestHandlers = new Map<string, ServerRequestHandler>();
91 const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
92 let unknownRequestHandler:
93 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
94 | undefined;
95 let unknownNotificationHandler:
96 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
97 | undefined;
98​
99 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
100 method: M,
101 ):
102 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
103 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
104​
105 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
106 method: M,
107 ):
108 | Schema.Codec<
109 CodexRpc.ServerRequestResponsesByMethod[M],
110 CodexRpc.ServerRequestResponsesByMethod[M]
111 >
112 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
113​
114 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
115 method: M,
116 ):
117 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
118 | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;
119​
120 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
121 method: M,
122 ):
123 | Schema.Codec<
124 CodexRpc.ClientRequestResponsesByMethod[M],
125 CodexRpc.ClientRequestResponsesByMethod[M]
126 >
127 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
128​
129 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
130 method: M,
131 ):
132 | Schema.Codec<
133 CodexRpc.ClientNotificationParamsByMethod[M],
134 CodexRpc.ClientNotificationParamsByMethod[M]
135 >
136 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
137​
138 const dispatchNotification = (
139 notification: CodexProtocol.CodexAppServerIncomingNotification,
140 ): Effect.Effect<void, never> => {
141 const schema =
142 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
143 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
144 notification.method as CodexRpc.ServerNotificationMethod
145 ]
146 : undefined;
147 const handlers = notificationHandlers.get(notification.method) ?? [];
148​
149 if (schema) {
150 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
151 Effect.flatMap((decoded) =>
152 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
153 ),
154 Effect.catch(() => Effect.void),
155 );
156 }
157​
158 return unknownNotificationHandler
159 ? unknownNotificationHandler(notification.method, notification.params).pipe(
160 Effect.catch(() => Effect.void),
161 )
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 const stdio = makeChildStdio(handle);
256 const terminationError = makeTerminationError(handle);
257 return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
258};
259​
260export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
261 readonly command: string;
262 readonly args?: ReadonlyArray<string>;
263 readonly cwd?: string;
264 readonly env?: Record<string, string>;
266​
267export const layerCommand = (
268 options: CodexAppServerCommandLayerOptions,
269): Layer.Layer<
270 CodexAppServerClient,
271 CodexError.CodexAppServerSpawnError,
272 ChildProcessSpawner.ChildProcessSpawner
273> =>
274 Layer.effect(
275 CodexAppServerClient,
276 Effect.acquireRelease(
277 Effect.gen(function* () {
278 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
279 const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
280 ...(options.cwd ? { cwd: options.cwd } : {}),
281 ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
282 shell: process.platform === "win32",
283 });
284 return yield* spawner.spawn(command).pipe(
285 Effect.mapError(
286 (cause) =>
287 new CodexError.CodexAppServerSpawnError({
288 command: [options.command, ...(options.args ?? [])].join(" "),
289 cause,
290 }),
291 ),
292 );
293 }),
294 (handle) => handle.kill().pipe(Effect.orDie),
295 ).pipe(
296 Effect.flatMap((handle) =>
297 make(makeChildStdio(handle), options, makeTerminationError(handle)),
298 ),
299 ),
300 );