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("routes a large notification fragmented across thousands of input chunks", () =>
294 Effect.gen(function* () {
295 const { stdio, input, output } = yield* makeInMemoryStdio();
296 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
297 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
298 stdio,
299 onNotification: (notification) =>
300 Effect.sync(() => {
301 notifications.push(notification);
302 }),
303 });
304 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
305 yield* Queue.take(output);
306
307 const notification = {
308 method: "turn/diff/updated",
309 params: {
310 threadId: "thread-1",
311 turnId: "turn-1",
312 diff: "x".repeat(4 * 1024 * 1024),
313 },
314 };
315 const bytes = encoder.encode(
316 `${encodeUnknownJsonString(notification)}\n${encodeUnknownJsonString({ id: 1, result: { ok: true } })}\n`,
317 );
318 for (let offset = 0; offset < bytes.length; offset += 1024) {
319 yield* Queue.offer(input, bytes.subarray(offset, offset + 1024));
320 }
321
322 assert.deepEqual(yield* Fiber.join(response), { ok: true });
323 assert.deepEqual(notifications, [notification]);
324 }),
325 );
326
327 it.effect.each([1, 7, 1024])(
328 "preserves JSONL framing and UTF-8 across %i-byte input chunks",
329 (chunkSize) =>
330 Effect.gen(function* () {
331 const { stdio, input } = yield* makeInMemoryStdio();
332 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
333 const rawLines: Array<unknown> = [];
334 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
335 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
336 stdio,
337 logIncoming: true,
338 logger: (event) =>
339 Effect.sync(() => {
340 if (event.stage === "raw") {
341 rawLines.push(event.payload);
342 }
343 }),
344 onNotification: (notification) =>
345 Effect.sync(() => {
346 notifications.push(notification);
347 }),
348 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
349 });
350
351 const firstLine = '{"method":"x/first",\r"params":{"text":"hé🙂"}}';
352 const secondLine = '{"method":"x/second","params":{"value":2}}';
353 const finalLine = '{"method":"x/final","params":{"text":"最後"}}\r';
354 const bytes = encoder.encode(`\n \t\r\n${firstLine}\r\n\n${secondLine}\n${finalLine}`);
355 for (let offset = 0; offset < bytes.length; offset += chunkSize) {
356 yield* Queue.offer(input, bytes.subarray(offset, offset + chunkSize));
357 }
358 yield* Queue.end(input);
359
360 assert.instanceOf(
361 yield* Deferred.await(termination),
362 CodexError.CodexAppServerInputStreamEndedError,
363 );
364 assert.deepEqual(notifications, [
365 { method: "x/first", params: { text: "hé🙂" } },
366 { method: "x/second", params: { value: 2 } },
367 { method: "x/final", params: { text: "最後" } },
368 ]);
369 assert.deepEqual(rawLines, [firstLine, secondLine, finalLine]);
370 }),
371 );
372
373 it.effect("reports a malformed fragmented final line before input stream termination", () =>
374 Effect.gen(function* () {
375 const { stdio, input, output } = yield* makeInMemoryStdio();
376 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
377 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
378 stdio,
379 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
380 });
381 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
382 yield* Queue.take(output);
383
384 yield* Queue.offer(input, encoder.encode('{"id":1,'));
385 yield* Queue.offer(input, encoder.encode('"result":'));
386 yield* Queue.end(input);
387
388 const error = yield* Deferred.await(termination);
389 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
390 assert.equal(error.operation, "decode-wire-message");
391 const responseError = yield* Fiber.join(response).pipe(
392 Effect.match({
393 onFailure: (failure) => failure,
394 onSuccess: () => assert.fail("Expected the malformed response to fail the request"),
395 }),
396 );
397 assert.strictEqual(responseError, error);
398 }),
399 );
400
401 it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
402 Effect.gen(function* () {
403 const { stdio } = yield* makeInMemoryStdio();
404 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
405
406 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
407 assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
408 assert.equal(bigintError.operation, "encode-wire-message");
409 assert.equal(bigintError.method, "x/test");
410 assert.exists(bigintError.cause);
411 assert.equal(
412 bigintError.message,
413 "Codex App Server protocol operation 'encode-wire-message' failed for method 'x/test'.",
414 );
415
416 const circular: Record<string, unknown> = {};
417 circular.self = circular;
418 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
419 assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
420 assert.equal(circularError.operation, "encode-wire-message");
421 assert.equal(circularError.method, "x/test");
422 assert.exists(circularError.cause);
423
424 const requestError = yield* transport.request("x/request", 1n).pipe(
425 Effect.match({
426 onFailure: (error) => error,
427 onSuccess: () => assert.fail("Expected request encoding to fail"),
428 }),
429 );
430 assert.instanceOf(requestError, CodexError.CodexAppServerProtocolParseError);
431 assert.deepInclude(requestError, {
432 operation: "encode-wire-message",
433 method: "x/request",
434 requestId: "1",
435 });
436 }),
437 );
438
439 it.effect("correlates response errors with the originating request", () =>
440 Effect.gen(function* () {
441 const { stdio, input, output } = yield* makeInMemoryStdio();
442 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
443
444 const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
445 yield* Queue.take(output);
446 yield* Queue.offer(
447 input,
448 encodeJsonl({
449 id: 1,
450 error: {
451 code: -32602,
452 message: "Invalid params",
453 data: { field: "cwd" },
454 },
455 }),
456 );
457
458 const error = yield* Fiber.join(response).pipe(
459 Effect.match({
460 onFailure: (error) => error,
461 onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
462 }),
463 );
464 assert.instanceOf(error, CodexError.CodexAppServerRequestError);
465 assert.deepInclude(error, {
466 code: -32602,
467 errorMessage: "Invalid params",
468 method: "thread/start",
469 requestId: "1",
470 operation: "receive-response",
471 });
472 }),
473 );
474
475 it.effect("logs decode failures without copying the cause or wire payload", () =>
476 Effect.gen(function* () {
477 const secret = "codex-wire-secret-sentinel";
478 const { stdio, input } = yield* makeInMemoryStdio();
479 const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
480 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
481 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
482 stdio,
483 logIncoming: true,
484 logger: (event) =>
485 Effect.sync(() => {
486 events.push(event);
487 }),
488 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
489 });
490
491 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
492 yield* Deferred.await(termination);
493
494 const event = events.find(({ stage }) => stage === "decode_failed");
495 assert.exists(event);
496 assert.equal(event.direction, "incoming");
497 const payload = event.payload as Record<string, unknown>;
498 assert.equal(payload.operation, "decode-wire-message");
499 assert.isNumber(payload.issueCount);
500 assert.isArray(payload.issueKinds);
501 assert.isNumber(payload.maximumPathDepth);
502 assert.equal("cause" in payload, false);
503 assert.equal("detail" in payload, false);
504 assert.notInclude(encodeUnknownJsonString(event), secret);
505 }),
506 );
507
508 it.effect("describes unroutable messages with safe structural diagnostics", () =>
509 Effect.gen(function* () {
510 const secret = "codex-unroutable-secret-sentinel";
511 const { stdio, input } = yield* makeInMemoryStdio();
512 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
513 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
514 stdio,
515 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
516 });
517
518 yield* Queue.offer(
519 input,
520 encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
521 );
522
523 const error = yield* Deferred.await(termination);
524 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
525 assert.deepInclude(error, {
526 operation: "route-wire-message",
527 method: "thread/start",
528 payloadKind: "object",
529 presentFields: ["id", "method", "params"],
530 });
531 assert.isUndefined(error.requestId);
532 assert.notProperty(error, "detail");
533 assert.notProperty(error, "cause");
534 assert.notInclude(error.message, secret);
535 }),
536 );
537
538 it.effect("classifies an input stream ending without inventing a cause", () =>
539 Effect.gen(function* () {
540 const { stdio, input } = yield* makeInMemoryStdio();
541 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
542 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
543 stdio,
544 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
545 });
546
547 yield* Queue.end(input);
548
549 const error = yield* Deferred.await(termination);
550 assert.instanceOf(error, CodexError.CodexAppServerInputStreamEndedError);
551 assert.equal(error.message, "Codex App Server input stream ended.");
552 assert.equal("cause" in error, false);
553 }),
554 );
555});