Skip to content
TypeScript

fix(codex): end the session when an incoming message is too long (#19733)

Victor Vogele859e318a0ed
diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts
index 7249afff107..0b17a7b603c 100644
--- a/packages/effect-codex-app-server/src/protocol.test.ts
+++ b/packages/effect-codex-app-server/src/protocol.test.ts
@@ -371,6 +371,80 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
+ it.effect.each(["newline-terminated", "unfinished"])(
+ "rejects an oversized %s message using UTF-8 bytes before logging or parsing",
+ (framing) =>
+ Effect.gen(function* () {
+ const { stdio, input, output } = yield* makeInMemoryStdio();
+ const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
+ const logged: Array<unknown> = [];
+ const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
+ let reachedEnd = false;
+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio: Stdio.make({
+ ...stdio,
+ stdin: stdio.stdin.pipe(
+ Stream.concat(
+ Stream.suspend(() => {
+ reachedEnd = true;
+ return Stream.empty;
+ }),
+ ),
+ ),
+ }),
+ maxIncomingMessageBytes: 16,
+ logIncoming: true,
+ logger: (event) =>
+ Effect.sync(() => {
+ logged.push(event.payload);
+ }),
+ onNotification: (notification) =>
+ Effect.sync(() => {
+ notifications.push(notification);
+ }),
+ onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
+ });
+ const pending = yield* Effect.forEach(["thread/read", "thread/list"], (method) =>
+ transport.request(method, {}).pipe(Effect.forkScoped),
+ );
+ yield* Effect.forEach(pending, () => Queue.take(output));
+
+ // Two 16-byte lines must survive; the 17-byte line is only 15 UTF-16 code units.
+ const firstLine = '{"method":"xé"}';
+ const secondLine = '{"method":"x/a"}';
+ const bytes = encoder.encode(
+ `${firstLine}\n${secondLine}\n{"method":"éé"}${framing === "unfinished" ? "" : "\n"}`,
+ );
+ // Split a UTF-8 sequence on both sides of the byte limit.
+ const firstSplit = bytes.indexOf(0xc3) + 1;
+ yield* Queue.offer(input, bytes.subarray(0, firstSplit));
+ if (framing === "unfinished") {
+ const lastSplit = bytes.lastIndexOf(0xc3) + 1;
+ yield* Queue.offer(input, bytes.subarray(firstSplit, lastSplit));
+ yield* Queue.offer(input, bytes.subarray(lastSplit));
+ } else {
+ yield* Queue.offer(input, bytes.subarray(firstSplit));
+ }
+ yield* Queue.end(input);
+
+ const error = yield* Deferred.await(termination);
+ assert.instanceOf(error, CodexError.CodexAppServerTransportError);
+ assert.equal(error.operation, "read-input-stream");
+ assert.isFalse(reachedEnd, "Must reject the unfinished line before reading EOF");
+ for (const response of pending) {
+ const failure = yield* Fiber.join(response).pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the oversized message to fail the request"),
+ }),
+ );
+ assert.strictEqual(failure, error);
+ }
+ assert.deepEqual(notifications, [{ method: "xé" }, { method: "x/a" }]);
+ assert.deepEqual(logged, [firstLine, { method: "xé" }, secondLine, { method: "x/a" }]);
+ }),
+ );
+
it.effect("reports a malformed fragmented final line before input stream termination", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts
index c1f6cb1f1b6..bf67174033f 100644
--- a/packages/effect-codex-app-server/src/protocol.ts
+++ b/packages/effect-codex-app-server/src/protocol.ts
@@ -16,6 +16,8 @@ const isJsonRpcId = Schema.is(JsonRpcId);
const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
const MAX_BUFFERED_RAW_MESSAGES = 32;
+// Bound JSONL lines before joining and parsing; the LF delimiter is excluded.
+const MAX_INCOMING_MESSAGE_BYTES = 128 * 1024 * 1024;
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
@@ -39,6 +41,8 @@ export interface CodexAppServerPatchedProtocolOptions {
readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
+ // Test override; production uses MAX_INCOMING_MESSAGE_BYTES.
+ readonly maxIncomingMessageBytes?: number;
readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
readonly onNotification?: (
notification: CodexAppServerIncomingNotification,
@@ -164,7 +168,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
yield* Queue.sliding<CodexAppServerIncomingRequest>(MAX_BUFFERED_RAW_MESSAGES);
const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
const nextRequestId = yield* Ref.make(1);
+ const maxIncomingMessageBytes = options.maxIncomingMessageBytes ?? MAX_INCOMING_MESSAGE_BYTES;
const remainder: Array<string> = [];
+ let remainderBytes = 0;
const terminationHandled = yield* Ref.make(false);
const terminationFailure = yield* Ref.make(Option.none<CodexError.CodexAppServerError>());
const terminationSignal = yield* Deferred.make<void>();
@@ -399,26 +405,30 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
yield* options.stdio.stdin.pipe(
Stream.interruptWhen(Deferred.await(terminationSignal)),
Stream.decodeText(),
- Stream.runForEach((chunk) =>
- Effect.sync(() => {
- const lines: Array<string> = [];
+ Stream.runForEach(
+ Effect.fnUntraced(function* (chunk) {
let start = 0;
- for (
- let newline = chunk.indexOf("\n");
- newline !== -1;
- newline = chunk.indexOf("\n", start)
- ) {
- remainder.push(chunk.slice(start, newline));
- lines.push(remainder.join("").replace(/\r$/, ""));
+ while (start < chunk.length) {
+ const newline = chunk.indexOf("\n", start);
+ const fragment = chunk.slice(start, newline === -1 ? chunk.length : newline);
+ // decodeText holds back split UTF-8 sequences, so fragment byte sums are exact.
+ remainderBytes += Buffer.byteLength(fragment, "utf8");
+ if (remainderBytes > maxIncomingMessageBytes) {
+ remainder.length = 0;
+ return yield* new CodexError.CodexAppServerTransportError({
+ operation: "read-input-stream",
+ cause: new Error(`Incoming message exceeded ${maxIncomingMessageBytes} bytes.`),
+ });
+ }
+ remainder.push(fragment);
+ if (newline === -1) break;
+ const line = remainder.join("").replace(/\r$/, "");
remainder.length = 0;
+ remainderBytes = 0;
+ yield* handleLine(line);
start = newline + 1;
}
- // Keep unfinished lines in fragments so each chunk is scanned only once.
- if (start < chunk.length) {
- remainder.push(chunk.slice(start));
- }
- return lines;
- }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
+ }),
),
Effect.matchEffect({
onFailure: (error) =>