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 Stdio from "effect/Stdio";
7import * as Stream from "effect/Stream";
8
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, it } from "@effect/vitest";
11
12import * as CodexError from "./errors.ts";
13import * as CodexProtocol from "./protocol.ts";
14import * as CodexRpc from "./rpc.ts";
15import * as CodexSchema from "./schema.ts";
16import { makeInMemoryStdio } from "./_internal/stdio.ts";
17const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
18
19const encoder = new TextEncoder();
20
21const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
22
23const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
24const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
25 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
26);
27const decodeAccountRateLimitsResponse = Schema.decodeUnknownEffect(
28 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
29);
30const decodeConsumeRateLimitResetCreditParams = Schema.decodeUnknownEffect(
31 CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
32);
33const decodeConsumeRateLimitResetCreditResponse = Schema.decodeUnknownEffect(
34 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
35);
36
37it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
38 it.effect("maps account usage responses to the upstream token usage schema", () =>
39 Effect.gen(function* () {
40 assert.strictEqual(
41 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
42 CodexSchema.V2GetAccountTokenUsageResponse,
43 );
44 const decoded = yield* decodeAccountTokenUsageResponse({
45 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
46 summary: { lifetimeTokens: 42 },
47 });
48 assert.deepEqual(decoded, {
49 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
50 summary: { lifetimeTokens: 42 },
51 });
52 }),
53 );
54
55 it.effect("maps earned rate-limit reset credits from account rate-limit snapshots", () =>
56 Effect.gen(function* () {
57 assert.strictEqual(
58 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
59 CodexSchema.V2GetAccountRateLimitsResponse,
60 );
61
62 const response = {
63 rateLimits: {},
64 rateLimitResetCredits: {
65 availableCount: 2,
66 credits: [
67 {
68 id: "RateLimitResetCredit_1",
69 resetType: "codexRateLimits",
70 status: "available",
71 grantedAt: 1_781_654_400,
72 expiresAt: 1_784_246_400,
73 title: "Full reset",
74 description: "Ready to redeem",
75 },
76 {
77 id: "RateLimitResetCredit_2",
78 resetType: "unknown",
79 status: "unknown",
80 grantedAt: 1_781_654_401,
81 expiresAt: null,
82 },
83 ],
84 },
85 } as const;
86
87 assert.deepEqual(yield* decodeAccountRateLimitsResponse(response), response);
88 assert.deepEqual(
89 yield* decodeAccountRateLimitsResponse({
90 rateLimits: {},
91 rateLimitResetCredits: { availableCount: 2, credits: null },
92 }),
93 {
94 rateLimits: {},
95 rateLimitResetCredits: { availableCount: 2, credits: null },
96 },
97 );
98 }),
99 );
100
101 it.effect("maps the earned rate-limit reset consume request and response", () =>
102 Effect.gen(function* () {
103 assert.equal(
104 CodexRpc.CLIENT_REQUEST_METHODS["account/rateLimitResetCredit/consume"],
105 "account/rateLimitResetCredit/consume",
106 );
107 assert.strictEqual(
108 CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
109 CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,
110 );
111 assert.strictEqual(
112 CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
113 CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,
114 );
115
116 assert.deepEqual(
117 yield* decodeConsumeRateLimitResetCreditParams({
118 idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
119 creditId: "RateLimitResetCredit_1",
120 }),
121 {
122 idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
123 creditId: "RateLimitResetCredit_1",
124 },
125 );
126 assert.deepEqual(yield* decodeConsumeRateLimitResetCreditResponse({ outcome: "reset" }), {
127 outcome: "reset",
128 });
129 }),
130 );
131
132 it.effect(
133 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
134 () =>
135 Effect.gen(function* () {
136 const { stdio, input, output } = yield* makeInMemoryStdio();
137 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
138
139 const notificationDeferred =
140 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
141 const requestDeferred =
142 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
143
144 yield* transport.incomingNotifications.pipe(
145 Stream.take(1),
146 Stream.runCollect,
147 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
148 Effect.forkScoped,
149 );
150
151 yield* transport.incomingRequests.pipe(
152 Stream.take(1),
153 Stream.runCollect,
154 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
155 Effect.forkScoped,
156 );
157
158 yield* transport.notify("initialized");
159 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
160
161 const initializeParams = {
162 clientInfo: {
163 name: "effect-codex-app-server-test",
164 title: "Effect Codex App Server Test",
165 version: "0.0.0",
166 },
167 capabilities: {
168 experimentalApi: true,
169 optOutNotificationMethods: null,
170 },
171 };
172
173 const pendingInitialize = yield* transport
174 .request("initialize", initializeParams)
175 .pipe(Effect.forkScoped);
176 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
177 id: 1,
178 method: "initialize",
179 params: initializeParams,
180 });
181
182 yield* Queue.offer(
183 input,
184 encodeJsonl({
185 method: "item/agentMessage/delta",
186 params: {
187 delta: "Hello from the mock peer.",
188 itemId: "item-1",
189 threadId: "thread-1",
190 turnId: "turn-1",
191 },
192 }),
193 );
194 yield* Queue.offer(
195 input,
196 encodeJsonl({
197 id: 77,
198 method: "item/tool/requestUserInput",
199 params: {
200 itemId: "item-approval-1",
201 threadId: "thread-1",
202 turnId: "turn-1",
203 questions: [
204 {
205 id: "approved",
206 header: "Approve",
207 question: "Continue?",
208 },
209 ],
210 },
211 }),
212 );
213 yield* Queue.offer(
214 input,
215 encodeJsonl({
216 id: 1,
217 result: {
218 userAgent: "mock-codex-app-server",
219 codexHome: "/tmp/codex-home",
220 platformFamily: "unix",
221 platformOs: "macos",
222 },
223 }),
224 );
225
226 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
227 userAgent: "mock-codex-app-server",
228 codexHome: "/tmp/codex-home",
229 platformFamily: "unix",
230 platformOs: "macos",
231 });
232 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
233 {
234 method: "item/agentMessage/delta",
235 params: {
236 delta: "Hello from the mock peer.",
237 itemId: "item-1",
238 threadId: "thread-1",
239 turnId: "turn-1",
240 },
241 },
242 ]);
243 assert.deepEqual(yield* Deferred.await(requestDeferred), [
244 {
245 id: 77,
246 method: "item/tool/requestUserInput",
247 params: {
248 itemId: "item-approval-1",
249 threadId: "thread-1",
250 turnId: "turn-1",
251 questions: [
252 {
253 id: "approved",
254 header: "Approve",
255 question: "Continue?",
256 },
257 ],
258 },
259 },
260 ]);
261
262 yield* transport.respond(77, {
263 answers: {
264 approved: {
265 answers: ["yes"],
266 },
267 },
268 });
269 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
270 id: 77,
271 result: {
272 answers: {
273 approved: {
274 answers: ["yes"],
275 },
276 },
277 },
278 });
279
280 yield* transport.respondError(
281 78,
282 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
283 );
284 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
285 id: 78,
286 error: {
287 code: -32601,
288 message: "Method not found: x/test",
289 },
290 });
291 }),
292 );
293
294 it.effect("routes a large notification fragmented across thousands of input chunks", () =>
295 Effect.gen(function* () {
296 const { stdio, input, output } = yield* makeInMemoryStdio();
297 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
298 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
299 stdio,
300 onNotification: (notification) =>
301 Effect.sync(() => {
302 notifications.push(notification);
303 }),
304 });
305 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
306 yield* Queue.take(output);
307
308 const notification = {
309 method: "turn/diff/updated",
310 params: {
311 threadId: "thread-1",
312 turnId: "turn-1",
313 diff: "x".repeat(4 * 1024 * 1024),
314 },
315 };
316 const bytes = encoder.encode(
317 `${encodeUnknownJsonString(notification)}\n${encodeUnknownJsonString({ id: 1, result: { ok: true } })}\n`,
318 );
319 for (let offset = 0; offset < bytes.length; offset += 1024) {
320 yield* Queue.offer(input, bytes.subarray(offset, offset + 1024));
321 }
322
323 assert.deepEqual(yield* Fiber.join(response), { ok: true });
324 assert.deepEqual(notifications, [notification]);
325 }),
326 );
327
328 it.effect.each([1, 7, 1024])(
329 "preserves JSONL framing and UTF-8 across %i-byte input chunks",
330 (chunkSize) =>
331 Effect.gen(function* () {
332 const { stdio, input } = yield* makeInMemoryStdio();
333 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
334 const rawLines: Array<unknown> = [];
335 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
336 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
337 stdio,
338 logIncoming: true,
339 logger: (event) =>
340 Effect.sync(() => {
341 if (event.stage === "raw") {
342 rawLines.push(event.payload);
343 }
344 }),
345 onNotification: (notification) =>
346 Effect.sync(() => {
347 notifications.push(notification);
348 }),
349 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
350 });
351
352 const firstLine = '{"method":"x/first",\r"params":{"text":"hé🙂"}}';
353 const secondLine = '{"method":"x/second","params":{"value":2}}';
354 const finalLine = '{"method":"x/final","params":{"text":"最後"}}\r';
355 const bytes = encoder.encode(`\n \t\r\n${firstLine}\r\n\n${secondLine}\n${finalLine}`);
356 for (let offset = 0; offset < bytes.length; offset += chunkSize) {
357 yield* Queue.offer(input, bytes.subarray(offset, offset + chunkSize));
358 }
359 yield* Queue.end(input);
360
361 assert.instanceOf(
362 yield* Deferred.await(termination),
363 CodexError.CodexAppServerInputStreamEndedError,
364 );
365 assert.deepEqual(notifications, [
366 { method: "x/first", params: { text: "hé🙂" } },
367 { method: "x/second", params: { value: 2 } },
368 { method: "x/final", params: { text: "最後" } },
369 ]);
370 assert.deepEqual(rawLines, [firstLine, secondLine, finalLine]);
371 }),
372 );
373
374 it.effect.each(["newline-terminated", "unfinished"])(
375 "rejects an oversized %s message using UTF-8 bytes before logging or parsing",
376 (framing) =>
377 Effect.gen(function* () {
378 const { stdio, input, output } = yield* makeInMemoryStdio();
379 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
380 const logged: Array<unknown> = [];
381 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
382 let reachedEnd = false;
383 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
384 stdio: Stdio.make({
385 ...stdio,
386 stdin: stdio.stdin.pipe(
387 Stream.concat(
388 Stream.suspend(() => {
389 reachedEnd = true;
390 return Stream.empty;
391 }),
392 ),
393 ),
394 }),
395 maxIncomingMessageBytes: 16,
396 logIncoming: true,
397 logger: (event) =>
398 Effect.sync(() => {
399 logged.push(event.payload);
400 }),
401 onNotification: (notification) =>
402 Effect.sync(() => {
403 notifications.push(notification);
404 }),
405 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
406 });
407 const pending = yield* Effect.forEach(["thread/read", "thread/list"], (method) =>
408 transport.request(method, {}).pipe(Effect.forkScoped),
409 );
410 yield* Effect.forEach(pending, () => Queue.take(output));
411
412 // Two 16-byte lines must survive; the 17-byte line is only 15 UTF-16 code units.
413 const firstLine = '{"method":"xé"}';
414 const secondLine = '{"method":"x/a"}';
415 const bytes = encoder.encode(
416 `${firstLine}\n${secondLine}\n{"method":"éé"}${framing === "unfinished" ? "" : "\n"}`,
417 );
418 // Split a UTF-8 sequence on both sides of the byte limit.
419 const firstSplit = bytes.indexOf(0xc3) + 1;
420 yield* Queue.offer(input, bytes.subarray(0, firstSplit));
421 if (framing === "unfinished") {
422 const lastSplit = bytes.lastIndexOf(0xc3) + 1;
423 yield* Queue.offer(input, bytes.subarray(firstSplit, lastSplit));
424 yield* Queue.offer(input, bytes.subarray(lastSplit));
425 } else {
426 yield* Queue.offer(input, bytes.subarray(firstSplit));
427 }
428 yield* Queue.end(input);
429
430 const error = yield* Deferred.await(termination);
431 assert.instanceOf(error, CodexError.CodexAppServerTransportError);
432 assert.equal(error.operation, "read-input-stream");
433 assert.isFalse(reachedEnd, "Must reject the unfinished line before reading EOF");
434 for (const response of pending) {
435 const failure = yield* Fiber.join(response).pipe(
436 Effect.match({
437 onFailure: (error) => error,
438 onSuccess: () => assert.fail("Expected the oversized message to fail the request"),
439 }),
440 );
441 assert.strictEqual(failure, error);
442 }
443 assert.deepEqual(notifications, [{ method: "xé" }, { method: "x/a" }]);
444 assert.deepEqual(logged, [firstLine, { method: "xé" }, secondLine, { method: "x/a" }]);
445 }),
446 );
447
448 it.effect("reports a malformed fragmented final line before input stream termination", () =>
449 Effect.gen(function* () {
450 const { stdio, input, output } = yield* makeInMemoryStdio();
451 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
452 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
453 stdio,
454 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
455 });
456 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
457 yield* Queue.take(output);
458
459 yield* Queue.offer(input, encoder.encode('{"id":1,'));
460 yield* Queue.offer(input, encoder.encode('"result":'));
461 yield* Queue.end(input);
462
463 const error = yield* Deferred.await(termination);
464 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
465 assert.equal(error.operation, "decode-wire-message");
466 const responseError = yield* Fiber.join(response).pipe(
467 Effect.match({
468 onFailure: (failure) => failure,
469 onSuccess: () => assert.fail("Expected the malformed response to fail the request"),
470 }),
471 );
472 assert.strictEqual(responseError, error);
473 }),
474 );
475
476 it.effect("keeps only recent raw notifications after their callbacks run", () =>
477 Effect.gen(function* () {
478 const { stdio, input } = yield* makeInMemoryStdio();
479 const handled = yield* Deferred.make<void>();
480 let handledCount = 0;
481 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
482 stdio,
483 onNotification: () =>
484 Effect.sync(() => ++handledCount).pipe(
485 Effect.flatMap((count) =>
486 count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
487 ),
488 ),
489 });
490
491 const messages = Array.from({ length: 64 }, (_, index) =>
492 encodeUnknownJsonString({
493 method: "item/agentMessage/delta",
494 params: { index },
495 }),
496 );
497 yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
498 yield* Deferred.await(handled);
499
500 const retained = yield* transport.incomingNotifications.pipe(
501 Stream.take(32),
502 Stream.runCollect,
503 );
504
505 assert.equal(handledCount, 64);
506 assert.equal(retained.length, 32);
507 assert.deepEqual(retained[0]?.params, { index: 32 });
508 assert.deepEqual(retained[31]?.params, { index: 63 });
509 }),
510 );
511
512 it.effect("keeps processing protocol messages while an approval is pending", () =>
513 Effect.gen(function* () {
514 const { stdio, input, output } = yield* makeInMemoryStdio();
515 const approvalStarted = yield* Deferred.make<void>();
516 const approvalDecision = yield* Deferred.make<{ readonly decision: string }>();
517 const notificationReceived = yield* Deferred.make<void>();
518 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
519 stdio,
520 onRequest: () =>
521 Deferred.succeed(approvalStarted, undefined).pipe(
522 Effect.andThen(Deferred.await(approvalDecision)),
523 ),
524 onNotification: () => Deferred.succeed(notificationReceived, undefined).pipe(Effect.asVoid),
525 });
526
527 const pendingRequest = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
528 yield* Queue.take(output);
529 yield* Queue.offer(
530 input,
531 encoder.encode(
532 `${[
533 encodeUnknownJsonString({ id: 7, method: "item/tool/requestUserInput", params: {} }),
534 encodeUnknownJsonString({ method: "item/agentMessage/delta", params: { delta: "ok" } }),
535 encodeUnknownJsonString({ id: 1, result: { threadId: "thread-1" } }),
536 ].join("\n")}\n`,
537 ),
538 );
539
540 yield* Deferred.await(approvalStarted);
541 yield* Deferred.await(notificationReceived);
542 assert.deepEqual(yield* Fiber.join(pendingRequest), { threadId: "thread-1" });
543
544 yield* Deferred.succeed(approvalDecision, { decision: "accept" });
545 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
546 id: 7,
547 result: { decision: "accept" },
548 });
549 }),
550 );
551
552 it.effect("rejects incoming requests after the active handler limit is reached", () =>
553 Effect.gen(function* () {
554 const { stdio, input, output } = yield* makeInMemoryStdio();
555 const handlersStarted = yield* Deferred.make<void>();
556 const releaseHandlers = yield* Deferred.make<void>();
557 let activeHandlers = 0;
558 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
559 stdio,
560 onRequest: () =>
561 Effect.sync(() => ++activeHandlers).pipe(
562 Effect.flatMap((count) =>
563 count === 32
564 ? Deferred.succeed(handlersStarted, undefined).pipe(Effect.asVoid)
565 : Effect.void,
566 ),
567 Effect.andThen(Deferred.await(releaseHandlers)),
568 Effect.as({ decision: "accept" }),
569 ),
570 });
571
572 const requests = Array.from({ length: 33 }, (_, index) =>
573 encodeUnknownJsonString({
574 id: index + 1,
575 method: "item/tool/requestUserInput",
576 params: {},
577 }),
578 );
579 yield* Queue.offer(input, encoder.encode(`${requests.join("\n")}\n`));
580 yield* Deferred.await(handlersStarted);
581
582 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
583 id: 33,
584 error: {
585 code: -32001,
586 message: "Too many Codex requests are already active.",
587 },
588 });
589 assert.equal(activeHandlers, 32);
590
591 yield* Deferred.succeed(releaseHandlers, undefined);
592 yield* Effect.forEach(Array.from({ length: 32 }), () => Queue.take(output), {
593 discard: true,
594 });
595 }),
596 );
597
598 it.effect("interrupts pending request handlers when the protocol terminates", () =>
599 Effect.gen(function* () {
600 const { stdio, input } = yield* makeInMemoryStdio();
601 const approvalStarted = yield* Deferred.make<void>();
602 const approvalInterrupted = yield* Deferred.make<void>();
603 const terminated = yield* Deferred.make<void>();
604 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
605 stdio,
606 onRequest: () =>
607 Deferred.succeed(approvalStarted, undefined).pipe(
608 Effect.andThen(Effect.never),
609 Effect.onInterrupt(() =>
610 Deferred.succeed(approvalInterrupted, undefined).pipe(Effect.asVoid),
611 ),
612 ),
613 onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
614 });
615
616 yield* Queue.offer(
617 input,
618 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
619 );
620 yield* Deferred.await(approvalStarted);
621 yield* Queue.end(input);
622
623 yield* Deferred.await(approvalInterrupted);
624 yield* Deferred.await(terminated);
625 }),
626 );
627
628 it.effect("rejects outgoing messages after an approval response cannot be encoded", () =>
629 Effect.gen(function* () {
630 const { stdio: baseStdio, input } = yield* makeInMemoryStdio();
631 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
632 const readerStopped = yield* Deferred.make<void>();
633 let notificationCount = 0;
634 let requestCount = 0;
635 const stdio = Stdio.make({
636 args: baseStdio.args,
637 stdin: baseStdio.stdin.pipe(
638 Stream.ensuring(Deferred.succeed(readerStopped, undefined).pipe(Effect.asVoid)),
639 ),
640 stdout: baseStdio.stdout,
641 stderr: baseStdio.stderr,
642 });
643 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
644 stdio,
645 onRequest: () =>
646 Effect.sync(() => ++requestCount).pipe(
647 Effect.map((count) => (count === 1 ? { invalid: 1n } : { ok: true })),
648 ),
649 onNotification: () => Effect.sync(() => notificationCount++).pipe(Effect.asVoid),
650 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
651 });
652
653 yield* Queue.offer(
654 input,
655 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
656 );
657
658 const failure = yield* Deferred.await(terminated);
659 assert.instanceOf(failure, CodexError.CodexAppServerProtocolParseError);
660 const requestFailure = yield* transport.request("thread/read", {}).pipe(
661 Effect.match({
662 onFailure: (error) => error,
663 onSuccess: () => assert.fail("Expected a terminated protocol request to fail"),
664 }),
665 );
666 const notificationFailure = yield* transport.notify("initialized").pipe(Effect.flip);
667 assert.strictEqual(requestFailure, failure);
668 assert.strictEqual(notificationFailure, failure);
669 yield* Deferred.await(readerStopped);
670
671 yield* Queue.offer(
672 input,
673 encoder.encode(
674 `${[
675 encodeUnknownJsonString({ method: "x/late-notification" }),
676 encodeUnknownJsonString({ id: 8, method: "x/late-request" }),
677 ].join("\n")}\n`,
678 ),
679 );
680
681 assert.equal(notificationCount, 0);
682 assert.equal(requestCount, 1);
683 assert.equal(yield* Queue.size(input), 1);
684 }),
685 );
686
687 it.effect("fails pending requests before interrupted handler cleanup completes", () =>
688 Effect.gen(function* () {
689 const { stdio, input, output } = yield* makeInMemoryStdio();
690 const handlerStarted = yield* Deferred.make<void>();
691 const finalizerStarted = yield* Deferred.make<void>();
692 const releaseFinalizer = yield* Deferred.make<void>();
693 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
694 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
695 stdio,
696 onRequest: () =>
697 Deferred.succeed(handlerStarted, undefined).pipe(
698 Effect.andThen(Effect.never),
699 Effect.onInterrupt(() =>
700 Deferred.succeed(finalizerStarted, undefined).pipe(
701 Effect.andThen(Deferred.await(releaseFinalizer)),
702 ),
703 ),
704 ),
705 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
706 });
707 const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
708 yield* Queue.take(output);
709 yield* Queue.offer(input, encodeJsonl({ id: 7, method: "x/approval" }));
710 yield* Deferred.await(handlerStarted);
711 yield* Queue.end(input);
712
713 const failure = yield* Deferred.await(terminated);
714 yield* Deferred.await(finalizerStarted);
715 const pendingFailure = yield* Fiber.join(pending).pipe(
716 Effect.match({
717 onFailure: (error) => error,
718 onSuccess: () => assert.fail("Expected the pending request to fail"),
719 }),
720 );
721 assert.strictEqual(pendingFailure, failure);
722
723 yield* Deferred.succeed(releaseFinalizer, undefined);
724 }),
725 );
726
727 it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
728 Effect.gen(function* () {
729 const { stdio } = yield* makeInMemoryStdio();
730 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
731
732 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
733 assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
734 assert.equal(bigintError.operation, "encode-wire-message");
735 assert.equal(bigintError.method, "x/test");
736 assert.exists(bigintError.cause);
737 assert.equal(
738 bigintError.message,
739 "Codex App Server protocol operation 'encode-wire-message' failed for method 'x/test'.",
740 );
741
742 const circular: Record<string, unknown> = {};
743 circular.self = circular;
744 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
745 assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
746 assert.equal(circularError.operation, "encode-wire-message");
747 assert.equal(circularError.method, "x/test");
748 assert.exists(circularError.cause);
749
750 const requestError = yield* transport.request("x/request", 1n).pipe(
751 Effect.match({
752 onFailure: (error) => error,
753 onSuccess: () => assert.fail("Expected request encoding to fail"),
754 }),
755 );
756 assert.instanceOf(requestError, CodexError.CodexAppServerProtocolParseError);
757 assert.deepInclude(requestError, {
758 operation: "encode-wire-message",
759 method: "x/request",
760 requestId: "1",
761 });
762 }),
763 );
764
765 it.effect("correlates response errors with the originating request", () =>
766 Effect.gen(function* () {
767 const { stdio, input, output } = yield* makeInMemoryStdio();
768 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
769
770 const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
771 yield* Queue.take(output);
772 yield* Queue.offer(
773 input,
774 encodeJsonl({
775 id: 1,
776 error: {
777 code: -32602,
778 message: "Invalid params",
779 data: { field: "cwd" },
780 },
781 }),
782 );
783
784 const error = yield* Fiber.join(response).pipe(
785 Effect.match({
786 onFailure: (error) => error,
787 onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
788 }),
789 );
790 assert.instanceOf(error, CodexError.CodexAppServerRequestError);
791 assert.deepInclude(error, {
792 code: -32602,
793 errorMessage: "Invalid params",
794 method: "thread/start",
795 requestId: "1",
796 operation: "receive-response",
797 });
798 }),
799 );
800
801 it.effect("logs decode failures without copying the cause or wire payload", () =>
802 Effect.gen(function* () {
803 const secret = "codex-wire-secret-sentinel";
804 const { stdio, input } = yield* makeInMemoryStdio();
805 const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
806 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
807 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
808 stdio,
809 logIncoming: true,
810 logger: (event) =>
811 Effect.sync(() => {
812 events.push(event);
813 }),
814 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
815 });
816
817 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
818 yield* Deferred.await(termination);
819
820 const event = events.find(({ stage }) => stage === "decode_failed");
821 assert.exists(event);
822 assert.equal(event.direction, "incoming");
823 const payload = event.payload as Record<string, unknown>;
824 assert.equal(payload.operation, "decode-wire-message");
825 assert.isNumber(payload.issueCount);
826 assert.isArray(payload.issueKinds);
827 assert.isNumber(payload.maximumPathDepth);
828 assert.equal("cause" in payload, false);
829 assert.equal("detail" in payload, false);
830 assert.notInclude(encodeUnknownJsonString(event), secret);
831 }),
832 );
833
834 it.effect("describes unroutable messages with safe structural diagnostics", () =>
835 Effect.gen(function* () {
836 const secret = "codex-unroutable-secret-sentinel";
837 const { stdio, input } = yield* makeInMemoryStdio();
838 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
839 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
840 stdio,
841 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
842 });
843
844 yield* Queue.offer(
845 input,
846 encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
847 );
848
849 const error = yield* Deferred.await(termination);
850 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
851 assert.deepInclude(error, {
852 operation: "route-wire-message",
853 method: "thread/start",
854 payloadKind: "object",
855 presentFields: ["id", "method", "params"],
856 });
857 assert.isUndefined(error.requestId);
858 assert.notProperty(error, "detail");
859 assert.notProperty(error, "cause");
860 assert.notInclude(error.message, secret);
861 }),
862 );
863
864 it.effect("classifies an input stream ending without inventing a cause", () =>
865 Effect.gen(function* () {
866 const { stdio, input } = yield* makeInMemoryStdio();
867 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
868 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
869 stdio,
870 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
871 });
872
873 yield* Queue.end(input);
874
875 const error = yield* Deferred.await(termination);
876 assert.instanceOf(error, CodexError.CodexAppServerInputStreamEndedError);
877 assert.equal(error.message, "Codex App Server input stream ended.");
878 assert.equal("cause" in error, false);
879 }),
880 );
881});