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 { makeInMemoryStdio } from "./_internal/stdio.ts";
15const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
16
17const encoder = new TextEncoder();
18
19const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
20
21const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
22
23it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
24 it.effect(
25 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
26 () =>
27 Effect.gen(function* () {
28 const { stdio, input, output } = yield* makeInMemoryStdio();
29 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
30
31 const notificationDeferred =
32 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
33 const requestDeferred =
34 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
35
36 yield* transport.incomingNotifications.pipe(
37 Stream.take(1),
38 Stream.runCollect,
39 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
40 Effect.forkScoped,
41 );
42
43 yield* transport.incomingRequests.pipe(
44 Stream.take(1),
45 Stream.runCollect,
46 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
47 Effect.forkScoped,
48 );
49
50 yield* transport.notify("initialized");
51 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
52
53 const initializeParams = {
54 clientInfo: {
55 name: "effect-codex-app-server-test",
56 title: "Effect Codex App Server Test",
57 version: "0.0.0",
58 },
59 capabilities: {
60 experimentalApi: true,
61 optOutNotificationMethods: null,
62 },
63 };
64
65 const pendingInitialize = yield* transport
66 .request("initialize", initializeParams)
67 .pipe(Effect.forkScoped);
68 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
69 id: 1,
70 method: "initialize",
71 params: initializeParams,
72 });
73
74 yield* Queue.offer(
75 input,
76 encodeJsonl({
77 method: "item/agentMessage/delta",
78 params: {
79 delta: "Hello from the mock peer.",
80 itemId: "item-1",
81 threadId: "thread-1",
82 turnId: "turn-1",
83 },
84 }),
85 );
86 yield* Queue.offer(
87 input,
88 encodeJsonl({
89 id: 77,
90 method: "item/tool/requestUserInput",
91 params: {
92 itemId: "item-approval-1",
93 threadId: "thread-1",
94 turnId: "turn-1",
95 questions: [
96 {
97 id: "approved",
98 header: "Approve",
99 question: "Continue?",
100 },
101 ],
102 },
103 }),
104 );
105 yield* Queue.offer(
106 input,
107 encodeJsonl({
108 id: 1,
109 result: {
110 userAgent: "mock-codex-app-server",
111 codexHome: "/tmp/codex-home",
112 platformFamily: "unix",
113 platformOs: "macos",
114 },
115 }),
116 );
117
118 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
119 userAgent: "mock-codex-app-server",
120 codexHome: "/tmp/codex-home",
121 platformFamily: "unix",
122 platformOs: "macos",
123 });
124 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
125 {
126 method: "item/agentMessage/delta",
127 params: {
128 delta: "Hello from the mock peer.",
129 itemId: "item-1",
130 threadId: "thread-1",
131 turnId: "turn-1",
132 },
133 },
134 ]);
135 assert.deepEqual(yield* Deferred.await(requestDeferred), [
136 {
137 id: 77,
138 method: "item/tool/requestUserInput",
139 params: {
140 itemId: "item-approval-1",
141 threadId: "thread-1",
142 turnId: "turn-1",
143 questions: [
144 {
145 id: "approved",
146 header: "Approve",
147 question: "Continue?",
148 },
149 ],
150 },
151 },
152 ]);
153
154 yield* transport.respond(77, {
155 answers: {
156 approved: {
157 answers: ["yes"],
158 },
159 },
160 });
161 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
162 id: 77,
163 result: {
164 answers: {
165 approved: {
166 answers: ["yes"],
167 },
168 },
169 },
170 });
171
172 yield* transport.respondError(
173 78,
174 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
175 );
176 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
177 id: 78,
178 error: {
179 code: -32601,
180 message: "Method not found: x/test",
181 },
182 });
183 }),
184 );
185
186 it.effect.each([1, 7, 1024])(
187 "preserves JSONL framing and UTF-8 across %i-byte input chunks",
188 (chunkSize) =>
189 Effect.gen(function* () {
190 const { stdio, input } = yield* makeInMemoryStdio();
191 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
192 const rawLines: Array<unknown> = [];
193 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
194 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
195 stdio,
196 logIncoming: true,
197 logger: (event) =>
198 Effect.sync(() => {
199 if (event.stage === "raw") {
200 rawLines.push(event.payload);
201 }
202 }),
203 onNotification: (notification) =>
204 Effect.sync(() => {
205 notifications.push(notification);
206 }),
207 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
208 });
209
210 const firstLine = '{"method":"x/first",\r"params":{"text":"hé🙂"}}';
211 const secondLine = '{"method":"x/second","params":{"value":2}}';
212 const finalLine = '{"method":"x/final","params":{"text":"最後"}}\r';
213 const bytes = encoder.encode(`\n \t\r\n${firstLine}\r\n\n${secondLine}\n${finalLine}`);
214 for (let offset = 0; offset < bytes.length; offset += chunkSize) {
215 yield* Queue.offer(input, bytes.subarray(offset, offset + chunkSize));
216 }
217 yield* Queue.end(input);
218
219 assert.instanceOf(
220 yield* Deferred.await(termination),
221 CodexError.CodexAppServerInputStreamEndedError,
222 );
223 assert.deepEqual(notifications, [
224 { method: "x/first", params: { text: "hé🙂" } },
225 { method: "x/second", params: { value: 2 } },
226 { method: "x/final", params: { text: "最後" } },
227 ]);
228 assert.deepEqual(rawLines, [firstLine, secondLine, finalLine]);
229 }),
230 );
231
232 it.effect.each(["newline-terminated", "unfinished"])(
233 "rejects an oversized %s message using UTF-8 bytes before logging or parsing",
234 (framing) =>
235 Effect.gen(function* () {
236 const { stdio, input, output } = yield* makeInMemoryStdio();
237 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
238 const logged: Array<unknown> = [];
239 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
240 let reachedEnd = false;
241 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
242 stdio: Stdio.make({
243 ...stdio,
244 stdin: stdio.stdin.pipe(
245 Stream.concat(
246 Stream.suspend(() => {
247 reachedEnd = true;
248 return Stream.empty;
249 }),
250 ),
251 ),
252 }),
253 maxIncomingMessageBytes: 16,
254 logIncoming: true,
255 logger: (event) =>
256 Effect.sync(() => {
257 logged.push(event.payload);
258 }),
259 onNotification: (notification) =>
260 Effect.sync(() => {
261 notifications.push(notification);
262 }),
263 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
264 });
265 const pending = yield* Effect.forEach(["thread/read", "thread/list"], (method) =>
266 transport.request(method, {}).pipe(Effect.forkScoped),
267 );
268 yield* Effect.forEach(pending, () => Queue.take(output));
269
270 // Two 16-byte lines must survive; the 17-byte line is only 15 UTF-16 code units.
271 const firstLine = '{"method":"xé"}';
272 const secondLine = '{"method":"x/a"}';
273 const bytes = encoder.encode(
274 `${firstLine}\n${secondLine}\n{"method":"éé"}${framing === "unfinished" ? "" : "\n"}`,
275 );
276 // Split a UTF-8 sequence on both sides of the byte limit.
277 const firstSplit = bytes.indexOf(0xc3) + 1;
278 yield* Queue.offer(input, bytes.subarray(0, firstSplit));
279 if (framing === "unfinished") {
280 const lastSplit = bytes.lastIndexOf(0xc3) + 1;
281 yield* Queue.offer(input, bytes.subarray(firstSplit, lastSplit));
282 yield* Queue.offer(input, bytes.subarray(lastSplit));
283 } else {
284 yield* Queue.offer(input, bytes.subarray(firstSplit));
285 }
286 yield* Queue.end(input);
287
288 const error = yield* Deferred.await(termination);
289 assert.instanceOf(error, CodexError.CodexAppServerTransportError);
290 assert.equal(error.operation, "read-input-stream");
291 assert.isFalse(reachedEnd, "Must reject the unfinished line before reading EOF");
292 for (const response of pending) {
293 const failure = yield* Fiber.join(response).pipe(
294 Effect.match({
295 onFailure: (error) => error,
296 onSuccess: () => assert.fail("Expected the oversized message to fail the request"),
297 }),
298 );
299 assert.strictEqual(failure, error);
300 }
301 assert.deepEqual(notifications, [{ method: "xé" }, { method: "x/a" }]);
302 assert.deepEqual(logged, [firstLine, { method: "xé" }, secondLine, { method: "x/a" }]);
303 }),
304 );
305
306 it.effect("reports a malformed fragmented final line before input stream termination", () =>
307 Effect.gen(function* () {
308 const { stdio, input, output } = yield* makeInMemoryStdio();
309 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
310 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
311 stdio,
312 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
313 });
314 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
315 yield* Queue.take(output);
316
317 yield* Queue.offer(input, encoder.encode('{"id":1,'));
318 yield* Queue.offer(input, encoder.encode('"result":'));
319 yield* Queue.end(input);
320
321 const error = yield* Deferred.await(termination);
322 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
323 assert.equal(error.operation, "decode-wire-message");
324 const responseError = yield* Fiber.join(response).pipe(
325 Effect.match({
326 onFailure: (failure) => failure,
327 onSuccess: () => assert.fail("Expected the malformed response to fail the request"),
328 }),
329 );
330 assert.strictEqual(responseError, error);
331 }),
332 );
333
334 it.effect("keeps processing protocol messages while an approval is pending", () =>
335 Effect.gen(function* () {
336 const { stdio, input, output } = yield* makeInMemoryStdio();
337 const approvalStarted = yield* Deferred.make<void>();
338 const approvalDecision = yield* Deferred.make<{ readonly decision: string }>();
339 const notificationReceived = yield* Deferred.make<void>();
340 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
341 stdio,
342 onRequest: () =>
343 Deferred.succeed(approvalStarted, undefined).pipe(
344 Effect.andThen(Deferred.await(approvalDecision)),
345 ),
346 onNotification: () => Deferred.succeed(notificationReceived, undefined).pipe(Effect.asVoid),
347 });
348
349 const pendingRequest = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
350 yield* Queue.take(output);
351 yield* Queue.offer(
352 input,
353 encoder.encode(
354 `${[
355 encodeUnknownJsonString({ id: 7, method: "item/tool/requestUserInput", params: {} }),
356 encodeUnknownJsonString({ method: "item/agentMessage/delta", params: { delta: "ok" } }),
357 encodeUnknownJsonString({ id: 1, result: { threadId: "thread-1" } }),
358 ].join("\n")}\n`,
359 ),
360 );
361
362 yield* Deferred.await(approvalStarted);
363 yield* Deferred.await(notificationReceived);
364 assert.deepEqual(yield* Fiber.join(pendingRequest), { threadId: "thread-1" });
365
366 yield* Deferred.succeed(approvalDecision, { decision: "accept" });
367 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
368 id: 7,
369 result: { decision: "accept" },
370 });
371 }),
372 );
373
374 it.effect("rejects incoming requests after the active handler limit is reached", () =>
375 Effect.gen(function* () {
376 const { stdio, input, output } = yield* makeInMemoryStdio();
377 const handlersStarted = yield* Deferred.make<void>();
378 const releaseHandlers = yield* Deferred.make<void>();
379 let activeHandlers = 0;
380 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
381 stdio,
382 onRequest: () =>
383 Effect.sync(() => ++activeHandlers).pipe(
384 Effect.flatMap((count) =>
385 count === 32
386 ? Deferred.succeed(handlersStarted, undefined).pipe(Effect.asVoid)
387 : Effect.void,
388 ),
389 Effect.andThen(Deferred.await(releaseHandlers)),
390 Effect.as({ decision: "accept" }),
391 ),
392 });
393
394 const requests = Array.from({ length: 33 }, (_, index) =>
395 encodeUnknownJsonString({
396 id: index + 1,
397 method: "item/tool/requestUserInput",
398 params: {},
399 }),
400 );
401 yield* Queue.offer(input, encoder.encode(`${requests.join("\n")}\n`));
402 yield* Deferred.await(handlersStarted);
403
404 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
405 id: 33,
406 error: {
407 code: -32001,
408 message: "Too many Codex requests are already active.",
409 },
410 });
411 assert.equal(activeHandlers, 32);
412
413 yield* Deferred.succeed(releaseHandlers, undefined);
414 yield* Effect.forEach(Array.from({ length: 32 }), () => Queue.take(output), {
415 discard: true,
416 });
417 }),
418 );
419
420 it.effect("interrupts pending request handlers when the protocol terminates", () =>
421 Effect.gen(function* () {
422 const { stdio, input } = yield* makeInMemoryStdio();
423 const approvalStarted = yield* Deferred.make<void>();
424 const approvalInterrupted = yield* Deferred.make<void>();
425 const terminated = yield* Deferred.make<void>();
426 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
427 stdio,
428 onRequest: () =>
429 Deferred.succeed(approvalStarted, undefined).pipe(
430 Effect.andThen(Effect.never),
431 Effect.onInterrupt(() =>
432 Deferred.succeed(approvalInterrupted, undefined).pipe(Effect.asVoid),
433 ),
434 ),
435 onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
436 });
437
438 yield* Queue.offer(
439 input,
440 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
441 );
442 yield* Deferred.await(approvalStarted);
443 yield* Queue.end(input);
444
445 yield* Deferred.await(approvalInterrupted);
446 yield* Deferred.await(terminated);
447 }),
448 );
449
450 it.effect("rejects outgoing messages after an approval response cannot be encoded", () =>
451 Effect.gen(function* () {
452 const { stdio: baseStdio, input } = yield* makeInMemoryStdio();
453 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
454 const readerStopped = yield* Deferred.make<void>();
455 let notificationCount = 0;
456 let requestCount = 0;
457 const stdio = Stdio.make({
458 args: baseStdio.args,
459 stdin: baseStdio.stdin.pipe(
460 Stream.ensuring(Deferred.succeed(readerStopped, undefined).pipe(Effect.asVoid)),
461 ),
462 stdout: baseStdio.stdout,
463 stderr: baseStdio.stderr,
464 });
465 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
466 stdio,
467 onRequest: () =>
468 Effect.sync(() => ++requestCount).pipe(
469 Effect.map((count) => (count === 1 ? { invalid: 1n } : { ok: true })),
470 ),
471 onNotification: () => Effect.sync(() => notificationCount++).pipe(Effect.asVoid),
472 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
473 });
474
475 yield* Queue.offer(
476 input,
477 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
478 );
479
480 const failure = yield* Deferred.await(terminated);
481 assert.instanceOf(failure, CodexError.CodexAppServerProtocolParseError);
482 const requestFailure = yield* transport.request("thread/read", {}).pipe(
483 Effect.match({
484 onFailure: (error) => error,
485 onSuccess: () => assert.fail("Expected a terminated protocol request to fail"),
486 }),
487 );
488 const notificationFailure = yield* transport.notify("initialized").pipe(Effect.flip);
489 assert.strictEqual(requestFailure, failure);
490 assert.strictEqual(notificationFailure, failure);
491 yield* Deferred.await(readerStopped);
492
493 yield* Queue.offer(
494 input,
495 encoder.encode(
496 `${[
497 encodeUnknownJsonString({ method: "x/late-notification" }),
498 encodeUnknownJsonString({ id: 8, method: "x/late-request" }),
499 ].join("\n")}\n`,
500 ),
501 );
502
503 assert.equal(notificationCount, 0);
504 assert.equal(requestCount, 1);
505 assert.equal(yield* Queue.size(input), 1);
506 }),
507 );
508
509 it.effect("fails pending requests before interrupted handler cleanup completes", () =>
510 Effect.gen(function* () {
511 const { stdio, input, output } = yield* makeInMemoryStdio();
512 const handlerStarted = yield* Deferred.make<void>();
513 const finalizerStarted = yield* Deferred.make<void>();
514 const releaseFinalizer = yield* Deferred.make<void>();
515 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
516 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
517 stdio,
518 onRequest: () =>
519 Deferred.succeed(handlerStarted, undefined).pipe(
520 Effect.andThen(Effect.never),
521 Effect.onInterrupt(() =>
522 Deferred.succeed(finalizerStarted, undefined).pipe(
523 Effect.andThen(Deferred.await(releaseFinalizer)),
524 ),
525 ),
526 ),
527 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
528 });
529 const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
530 yield* Queue.take(output);
531 yield* Queue.offer(input, encodeJsonl({ id: 7, method: "x/approval" }));
532 yield* Deferred.await(handlerStarted);
533 yield* Queue.end(input);
534
535 const failure = yield* Deferred.await(terminated);
536 yield* Deferred.await(finalizerStarted);
537 const pendingFailure = yield* Fiber.join(pending).pipe(
538 Effect.match({
539 onFailure: (error) => error,
540 onSuccess: () => assert.fail("Expected the pending request to fail"),
541 }),
542 );
543 assert.strictEqual(pendingFailure, failure);
544
545 yield* Deferred.succeed(releaseFinalizer, undefined);
546 }),
547 );
548
549 it.effect("correlates response errors with the originating request", () =>
550 Effect.gen(function* () {
551 const { stdio, input, output } = yield* makeInMemoryStdio();
552 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
553
554 const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
555 yield* Queue.take(output);
556 yield* Queue.offer(
557 input,
558 encodeJsonl({
559 id: 1,
560 error: {
561 code: -32602,
562 message: "Invalid params",
563 data: { field: "cwd" },
564 },
565 }),
566 );
567
568 const error = yield* Fiber.join(response).pipe(
569 Effect.match({
570 onFailure: (error) => error,
571 onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
572 }),
573 );
574 assert.instanceOf(error, CodexError.CodexAppServerRequestError);
575 assert.deepInclude(error, {
576 code: -32602,
577 errorMessage: "Invalid params",
578 method: "thread/start",
579 requestId: "1",
580 operation: "receive-response",
581 });
582 }),
583 );
584
585 it.effect("logs decode failures without copying the cause or wire payload", () =>
586 Effect.gen(function* () {
587 const secret = "codex-wire-secret-sentinel";
588 const { stdio, input } = yield* makeInMemoryStdio();
589 const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
590 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
591 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
592 stdio,
593 logIncoming: true,
594 logger: (event) =>
595 Effect.sync(() => {
596 events.push(event);
597 }),
598 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
599 });
600
601 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
602 yield* Deferred.await(termination);
603
604 const event = events.find(({ stage }) => stage === "decode_failed");
605 assert.exists(event);
606 assert.equal(event.direction, "incoming");
607 const payload = event.payload as Record<string, unknown>;
608 assert.equal(payload.operation, "decode-wire-message");
609 assert.isNumber(payload.issueCount);
610 assert.isArray(payload.issueKinds);
611 assert.isNumber(payload.maximumPathDepth);
612 assert.equal("cause" in payload, false);
613 assert.equal("detail" in payload, false);
614 assert.notInclude(encodeUnknownJsonString(event), secret);
615 }),
616 );
617
618 it.effect("describes unroutable messages with safe structural diagnostics", () =>
619 Effect.gen(function* () {
620 const secret = "codex-unroutable-secret-sentinel";
621 const { stdio, input } = yield* makeInMemoryStdio();
622 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
623 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
624 stdio,
625 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
626 });
627
628 yield* Queue.offer(
629 input,
630 encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
631 );
632
633 const error = yield* Deferred.await(termination);
634 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
635 assert.deepInclude(error, {
636 operation: "route-wire-message",
637 method: "thread/start",
638 payloadKind: "object",
639 presentFields: ["id", "method", "params"],
640 });
641 assert.isUndefined(error.requestId);
642 assert.notProperty(error, "detail");
643 assert.notProperty(error, "cause");
644 assert.notInclude(error.message, secret);
645 }),
646 );
647});