Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

protocol.test.ts

801 lines29.7 KB

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