Open History to see the last commit
1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Queue from "effect/Queue";
5import * as Schema from "effect/Schema";
6import * as Stream from "effect/Stream";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10
11import * as CodexError from "./errors.ts";
12import * as CodexProtocol from "./protocol.ts";
13import * as CodexRpc from "./rpc.ts";
14import * as CodexSchema from "./schema.ts";
15import { makeInMemoryStdio } from "./_internal/stdio.ts";
16const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
17
18const encoder = new TextEncoder();
19
20const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
21
22const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
23const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
24 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
25);
26const decodeAccountRateLimitsResponse = Schema.decodeUnknownEffect(
27 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
28);
29const decodeConsumeRateLimitResetCreditParams = Schema.decodeUnknownEffect(
30 CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
31);
32const decodeConsumeRateLimitResetCreditResponse = Schema.decodeUnknownEffect(
33 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
34);
35
36it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
37 it.effect("maps account usage responses to the upstream token usage schema", () =>
38 Effect.gen(function* () {
39 assert.strictEqual(
40 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
41 CodexSchema.V2GetAccountTokenUsageResponse,
42 );
43 const decoded = yield* decodeAccountTokenUsageResponse({
44 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
45 summary: { lifetimeTokens: 42 },
46 });
47 assert.deepEqual(decoded, {
48 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
49 summary: { lifetimeTokens: 42 },
50 });
51 }),
52 );
53
54 it.effect("maps earned rate-limit reset credits from account rate-limit snapshots", () =>
55 Effect.gen(function* () {
56 assert.strictEqual(
57 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
58 CodexSchema.V2GetAccountRateLimitsResponse,
59 );
60
61 const response = {
62 rateLimits: {},
63 rateLimitResetCredits: {
64 availableCount: 2,
65 credits: [
66 {
67 id: "RateLimitResetCredit_1",
68 resetType: "codexRateLimits",
69 status: "available",
70 grantedAt: 1_781_654_400,
71 expiresAt: 1_784_246_400,
72 title: "Full reset",
73 description: "Ready to redeem",
74 },
75 {
76 id: "RateLimitResetCredit_2",
77 resetType: "unknown",
78 status: "unknown",
79 grantedAt: 1_781_654_401,
80 expiresAt: null,
81 },
82 ],
83 },
84 } as const;
85
86 assert.deepEqual(yield* decodeAccountRateLimitsResponse(response), response);
87 assert.deepEqual(
88 yield* decodeAccountRateLimitsResponse({
89 rateLimits: {},
90 rateLimitResetCredits: { availableCount: 2, credits: null },
91 }),
92 {
93 rateLimits: {},
94 rateLimitResetCredits: { availableCount: 2, credits: null },
95 },
96 );
97 }),
98 );
99
100 it.effect("maps the earned rate-limit reset consume request and response", () =>
101 Effect.gen(function* () {
102 assert.equal(
103 CodexRpc.CLIENT_REQUEST_METHODS["account/rateLimitResetCredit/consume"],
104 "account/rateLimitResetCredit/consume",
105 );
106 assert.strictEqual(
107 CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
108 CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,
109 );
110 assert.strictEqual(
111 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
112 CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,
113 );
114
115 assert.deepEqual(
116 yield* decodeConsumeRateLimitResetCreditParams({
117 idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
118 creditId: "RateLimitResetCredit_1",
119 }),
120 {
121 idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
122 creditId: "RateLimitResetCredit_1",
123 },
124 );
125 assert.deepEqual(yield* decodeConsumeRateLimitResetCreditResponse({ outcome: "reset" }), {
126 outcome: "reset",
127 });
128 }),
129 );
130
131 it.effect(
132 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
133 () =>
134 Effect.gen(function* () {
135 const { stdio, input, output } = yield* makeInMemoryStdio();
136 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
137
138 const notificationDeferred =
139 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
140 const requestDeferred =
141 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
142
143 yield* transport.incomingNotifications.pipe(
144 Stream.take(1),
145 Stream.runCollect,
146 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
147 Effect.forkScoped,
148 );
149
150 yield* transport.incomingRequests.pipe(
151 Stream.take(1),
152 Stream.runCollect,
153 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
154 Effect.forkScoped,
155 );
156
157 yield* transport.notify("initialized");
158 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
159
160 const initializeParams = {
161 clientInfo: {
162 name: "effect-codex-app-server-test",
163 title: "Effect Codex App Server Test",
164 version: "0.0.0",
165 },
166 capabilities: {
167 experimentalApi: true,
168 optOutNotificationMethods: null,
169 },
170 };
171
172 const pendingInitialize = yield* transport
173 .request("initialize", initializeParams)
174 .pipe(Effect.forkScoped);
175 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
176 id: 1,
177 method: "initialize",
178 params: initializeParams,
179 });
180
181 yield* Queue.offer(
182 input,
183 encodeJsonl({
184 method: "item/agentMessage/delta",
185 params: {
186 delta: "Hello from the mock peer.",
187 itemId: "item-1",
188 threadId: "thread-1",
189 turnId: "turn-1",
190 },
191 }),
192 );
193 yield* Queue.offer(
194 input,
195 encodeJsonl({
196 id: 77,
197 method: "item/tool/requestUserInput",
198 params: {
199 itemId: "item-approval-1",
200 threadId: "thread-1",
201 turnId: "turn-1",
202 questions: [
203 {
204 id: "approved",
205 header: "Approve",
206 question: "Continue?",
207 },
208 ],
209 },
210 }),
211 );
212 yield* Queue.offer(
213 input,
214 encodeJsonl({
215 id: 1,
216 result: {
217 userAgent: "mock-codex-app-server",
218 codexHome: "/tmp/codex-home",
219 platformFamily: "unix",
220 platformOs: "macos",
221 },
222 }),
223 );
224
225 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
226 userAgent: "mock-codex-app-server",
227 codexHome: "/tmp/codex-home",
228 platformFamily: "unix",
229 platformOs: "macos",
230 });
231 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
232 {
233 method: "item/agentMessage/delta",
234 params: {
235 delta: "Hello from the mock peer.",
236 itemId: "item-1",
237 threadId: "thread-1",
238 turnId: "turn-1",
239 },
240 },
241 ]);
242 assert.deepEqual(yield* Deferred.await(requestDeferred), [
243 {
244 id: 77,
245 method: "item/tool/requestUserInput",
246 params: {
247 itemId: "item-approval-1",
248 threadId: "thread-1",
249 turnId: "turn-1",
250 questions: [
251 {
252 id: "approved",
253 header: "Approve",
254 question: "Continue?",
255 },
256 ],
257 },
258 },
259 ]);
260
261 yield* transport.respond(77, {
262 answers: {
263 approved: {
264 answers: ["yes"],
265 },
266 },
267 });
268 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
269 id: 77,
270 result: {
271 answers: {
272 approved: {
273 answers: ["yes"],
274 },
275 },
276 },
277 });
278
279 yield* transport.respondError(
280 78,
281 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
282 );
283 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
284 id: 78,
285 error: {
286 code: -32601,
287 message: "Method not found: x/test",
288 },
289 });
290 }),
291 );
292
293 it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
294 Effect.gen(function* () {
295 const { stdio } = yield* makeInMemoryStdio();
296 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
297
298 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
299 assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
300 assert.equal(bigintError.operation, "encode-wire-message");
301 assert.equal(bigintError.method, "x/test");
302 assert.exists(bigintError.cause);
303 assert.equal(
304 bigintError.message,
305 "Codex App Server protocol operation 'encode-wire-message' failed for method 'x/test'.",
306 );
307
308 const circular: Record<string, unknown> = {};
309 circular.self = circular;
310 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
311 assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
312 assert.equal(circularError.operation, "encode-wire-message");
313 assert.equal(circularError.method, "x/test");
314 assert.exists(circularError.cause);
315
316 const requestError = yield* transport.request("x/request", 1n).pipe(
317 Effect.match({
318 onFailure: (error) => error,
319 onSuccess: () => assert.fail("Expected request encoding to fail"),
320 }),
321 );
322 assert.instanceOf(requestError, CodexError.CodexAppServerProtocolParseError);
323 assert.deepInclude(requestError, {
324 operation: "encode-wire-message",
325 method: "x/request",
326 requestId: "1",
327 });
328 }),
329 );
330
331 it.effect("correlates response errors with the originating request", () =>
332 Effect.gen(function* () {
333 const { stdio, input, output } = yield* makeInMemoryStdio();
334 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
335
336 const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
337 yield* Queue.take(output);
338 yield* Queue.offer(
339 input,
340 encodeJsonl({
341 id: 1,
342 error: {
343 code: -32602,
344 message: "Invalid params",
345 data: { field: "cwd" },
346 },
347 }),
348 );
349
350 const error = yield* Fiber.join(response).pipe(
351 Effect.match({
352 onFailure: (error) => error,
353 onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
354 }),
355 );
356 assert.instanceOf(error, CodexError.CodexAppServerRequestError);
357 assert.deepInclude(error, {
358 code: -32602,
359 errorMessage: "Invalid params",
360 method: "thread/start",
361 requestId: "1",
362 operation: "receive-response",
363 });
364 }),
365 );
366
367 it.effect("logs decode failures without copying the cause or wire payload", () =>
368 Effect.gen(function* () {
369 const secret = "codex-wire-secret-sentinel";
370 const { stdio, input } = yield* makeInMemoryStdio();
371 const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
372 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
373 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
374 stdio,
375 logIncoming: true,
376 logger: (event) =>
377 Effect.sync(() => {
378 events.push(event);
379 }),
380 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
381 });
382
383 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
384 yield* Deferred.await(termination);
385
386 const event = events.find(({ stage }) => stage === "decode_failed");
387 assert.exists(event);
388 assert.equal(event.direction, "incoming");
389 const payload = event.payload as Record<string, unknown>;
390 assert.equal(payload.operation, "decode-wire-message");
391 assert.isNumber(payload.issueCount);
392 assert.isArray(payload.issueKinds);
393 assert.isNumber(payload.maximumPathDepth);
394 assert.equal("cause" in payload, false);
395 assert.equal("detail" in payload, false);
396 assert.notInclude(encodeUnknownJsonString(event), secret);
397 }),
398 );
399
400 it.effect("describes unroutable messages with safe structural diagnostics", () =>
401 Effect.gen(function* () {
402 const secret = "codex-unroutable-secret-sentinel";
403 const { stdio, input } = yield* makeInMemoryStdio();
404 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
405 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
406 stdio,
407 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
408 });
409
410 yield* Queue.offer(
411 input,
412 encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
413 );
414
415 const error = yield* Deferred.await(termination);
416 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
417 assert.deepInclude(error, {
418 operation: "route-wire-message",
419 method: "thread/start",
420 payloadKind: "object",
421 presentFields: ["id", "method", "params"],
422 });
423 assert.isUndefined(error.requestId);
424 assert.notProperty(error, "detail");
425 assert.notProperty(error, "cause");
426 assert.notInclude(error.message, secret);
427 }),
428 );
429
430 it.effect("classifies an input stream ending without inventing a cause", () =>
431 Effect.gen(function* () {
432 const { stdio, input } = yield* makeInMemoryStdio();
433 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
434 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
435 stdio,
436 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
437 });
438
439 yield* Queue.end(input);
440
441 const error = yield* Deferred.await(termination);
442 assert.instanceOf(error, CodexError.CodexAppServerInputStreamEndedError);
443 assert.equal(error.message, "Codex App Server input stream ended.");
444 assert.equal("cause" in error, false);
445 }),
446 );
447});