codex icon indicating copy to clipboard operation
codex copied to clipboard

TypeScript SDK: readline splits valid JSONL tool events at U+2028/U+2029

Open jaxxjj opened this issue 2 months ago • 4 comments

Summary

The TypeScript SDK uses readline.createInterface({ input: child.stdout, crlfDelay: Infinity }) to frame CLI JSONL output, then calls JSON.parse on each line. With Bun 1.4.0/1.4.2, readline also splits on literal U+2028 and U+2029. Both characters are legal inside JSON strings, so a valid tool-result event can be split into invalid fragments and fail with Failed to parse item.

This is not necessarily a Bun-only compatibility bug: current Node v24.x/v26.x source also includes these separators in readline's line-ending regex. Node v22.x source does not. Node v24/v26 behavior was inspected in source, not runtime-tested here.

SDK versions inspected

Both published @openai/codex-sdk 0.144.1 and 0.154.0 use this framing logic:

  • sdk/typescript/src/exec.ts: readline over CLI stdout
  • sdk/typescript/src/thread.ts: JSON.parse each yielded line

Minimal reproduction

This isolates the same framing/parsing path without credentials, an API call, or private data:

// repro.mjs
import { Readable } from "node:stream";
import { createInterface } from "node:readline";

for (const separator of ["\u2028", "\u2029"]) {
  const record = JSON.stringify({
    type: "item.completed",
    item: {
      id: "item_1",
      type: "command_execution",
      command: "example",
      aggregated_output: "alpha" + separator + "beta",
      exit_code: 0,
      status: "completed",
    },
  });

  // The full record itself is valid JSON.
  JSON.parse(record);

  const rl = createInterface({
    input: Readable.from([record + "\n"]),
    crlfDelay: Infinity,
  });

  let lines = 0;
  let failures = 0;
  for await (const line of rl) {
    lines++;
    try {
      JSON.parse(line);
    } catch {
      failures++;
    }
  }
  console.log({
    separator: separator.codePointAt(0).toString(16),
    lines,
    failures,
  });
}

Run with bun repro.mjs or node repro.mjs.

Observed results

Local runtime tests on macOS arm64:

Runtime Lines per record JSON parse failures
Bun 1.3.11 1 0
Bun 1.4.0 2 2
Bun 1.4.2 2 2
Node v23.7.0 1 0

Also reproduced with an actual child_process stdout pipe on Bun 1.4.0. Escaping U+2028 as the six ASCII characters backslash-u-2028 avoids the problem. Ordinary text passes.

The first fragment ends inside aggregated_output and produces an unterminated-string error. This was encountered while consuming a tool result containing a Unicode line separator.

Expected behavior / proposed fix

Frame the CLI JSONL protocol explicitly on LF (byte 0x0A), rather than inheriting readline's broader text-line semantics.

Suggested implementation considerations:

  • Preserve U+2028/U+2029 inside JSON strings.
  • Buffer partial records across stdout chunks.
  • Preserve UTF-8 characters split across chunks (e.g. decode complete byte records, or use a streaming decoder).
  • Handle CRLF and final unterminated records deliberately, retaining the existing contract.
  • Preserve subprocess cancellation, cleanup, and exit-error behavior.
  • Keep genuinely malformed JSON as an error; do not suppress JSON.parse failures.

Suggested regression tests: literal U+2028/U+2029, multiple records in one chunk, one record across chunks, split multibyte UTF-8, cancellation/exit, and malformed input.

References

  • https://unpkg.com/@openai/[email protected]/dist/index.js
  • https://github.com/oven-sh/bun/blob/bun-v1.4.2/src/js/internal/readline/interface.js#L65-L75
  • https://github.com/nodejs/node/blob/v24.x/lib/internal/readline/interface.js
  • https://github.com/nodejs/node/blob/v22.x/lib/internal/readline/interface.js

No credentials or private payloads are included.

jaxxjj avatar Sep 15 '26 16:09 jaxxjj

I've reproduced this on Node 24 and implemented a fix at davis0178/codex@fix-ts-sdk-jsonl-unicode-line-separators: it replaces the readline framing in sdk/typescript/src/exec.ts with an explicit newline split (CRLF/empty-line/final-line semantics preserved) plus a regression test — 15/15 exec tests pass locally. I couldn't open a PR because the repo's pull_request_creation_policy is collaborators_only, so please take the branch if useful. (AI-assisted fix, reviewed line-by-line by the submitter.)

davis0178 avatar Sep 27 '26 14:09 davis0178

Confirmed with Bun 1.4.4, @openai/codex-sdk 0.162.1, and the real Codex CLI 0.162.1.

I tested the full path with a temporary localhost Responses API fixture. The CLI and SDK were unmodified. The fixture returned assistant text containing literal U+2028 and U+2029; no credentials or external model calls were involved.

Results:

Path Result
Real CLI, stdout captured without readline and split only on LF Exit 0; every JSONL record parses; input and reply are preserved, including both literal separators
Same CLI through the unchanged TypeScript SDK, Unicode reply Throws Failed to parse item, with the first fragment ending inside item.text; observed after 139 ms
Same SDK/CLI with a plain ASCII reply Completes successfully

The CLI emits valid JSONL. The failure happens when the SDK frames that stdout with readline, before JSON.parse receives the complete record.

In a separate controlled test using SDK 0.162.1 and identical fixture output bytes, changing only the SDK host runtime produced:

SDK host runtime Result
Node 20.20.0 Pass
Node 22.22.0 Pass
Node 26.13.0 Fail
Bun 1.4.2 Fail

This confirms the issue depends on the runtime's text-line semantics, rather than malformed CLI JSON. The proposed LF-only framing should preserve split UTF-8 characters, CRLF, a final unterminated record, cancellation, and subprocess cleanup. Malformed JSON should still be reported as an error.

Related: #33617. This adds a reproduction with Bun 1.4.4 and SDK/CLI 0.162.1 to the existing reports.

Flower-F avatar Nov 03 '26 07:11 Flower-F

Still reproduces with @openai/codex-sdk 0.167.0 (the latest release, published 2026-11-07) under Bun 1.4.3: dist/index.js still frames stdout with readline.createInterface.

How we hit it: an agent ran rg over local JSONL chat transcripts, and the matched text contained a literal U+2028. The resulting ~1.08 MB command_execution item.completed event was cut at that character, and the turn died with Failed to parse item: <735 KB of partial JSON>. The error message embeds the whole fragment, so any consumer that displays error.message shows the user a wall of raw JSON.

A note for whoever lands the fix: tool-result events can be several MB, so the new splitter's cost on long lines matters. Appending each chunk to one pending string and searching it (pending += chunk; pending.indexOf("\n", from)) measured about 3x slower than readline on a 10 MB line under Bun 1.4.3, because the engine re-flattens the growing string on every chunk. Keeping the current line's pieces in an array, searching only the new chunk for LF, and joining once per line beat readline in every case we tried (20k small events, one 10 MB event, 50 × 1 MB events).

This is the same bug as #33617.

jkoppel avatar Nov 08 '26 09:11 jkoppel

I reproduced this on Node 24.22.1 at d8d840d. One valid JSON record containing both U+2028 and U+2029 came out of the SDK reader as three fragments. With the fork fix, the same record arrives intact even when two stdout writes split the UTF-8 bytes of U+2028.

The fix follows the suggestion above for large events. It scans each newly decoded chunk for LF and joins the pieces of a partial record once, when the record ends. The regression also covers CRLF and a final record without a trailing newline. Fix and regression test on my fork.

Cosmhyccc avatar Nov 17 '26 04:11 Cosmhyccc