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

protocol.test.ts

762 lines28.1 KB

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