Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bin/dsh-codex-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ async function cmdDoctor(args) {
ok += 1
if (header.parentThreadId) subagents += 1
}
} catch {
/* unreadable */
} catch (error) {
if (error.code === 'CODEX_SESSION_TOO_LARGE') big += 1
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion docs/compat.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ What this plugin syncs from OpenAI Codex into DeepSeek Harness.
| `~/.codex/config.toml` model fields | System-prompt summary | **on** (`enableConfig`) | Same live re-read. |
| `[mcp_servers.*]` in `config.toml` | Mirrored MCP clients | **on** (`mcpMirror`) | Live file watch. Deny/silent lists apply. Restart DSH after toggling. |
| Reverse MCP (`codex-install`) | `[mcp_servers.dsh-plugins]` in Codex | one-shot CLI | Gives Codex `dsh_plugin_*` tools. |
| `~/.codex/sessions/**/rollout-*.jsonl` | Resumable DSH sessions (`codex-<id>`) | import commands | Idempotent. Real tool traces. Image fragments cleaned. Size guard on huge rollouts. |
| `~/.codex/sessions/**/rollout-*.jsonl[.zst]` | Resumable DSH sessions (`codex-<id>`) | import commands | Idempotent. Real tool traces. Image fragments cleaned. Size guard on huge rollouts. |
| Sub-agent rollouts | Optional | filtered by default | Keeps the session list focused. `/import-codex --include-subagents` or `importSubagents: true` includes them. |
| Reasoning summaries | Assistant messages | on | Plaintext / `summary` blocks fold into the imported turn. |

Expand Down Expand Up @@ -40,3 +40,5 @@ DSH sessions can be exported back to Codex as rollout JSONL files and indexed in
Runtime package versions and default activation checks are described in [COMPATIBILITY.md](COMPATIBILITY.md).

Reverse export preserves user and assistant text; it does not reconstruct tool traces or the original thread id. Use the native DSH archive export to retain the stored event log.

Compressed Codex rollouts (`.jsonl.zst`) are decoded in memory, including concatenated Zstandard frames. Node versions without native Zstandard require `zstd` on `PATH`. The import size limit applies to both stored and decoded bytes; corrupt frames are reported as unreadable. If both encodings of one rollout exist, the plain `.jsonl` is preferred. No source files are rewritten.
39 changes: 33 additions & 6 deletions lib/codex-reader.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* codex (OpenAI Codex CLI) session reader.
*
* Sessions live at ~/.codex/sessions/<year>/<month>/<day>/rollout-*.jsonl.
* Sessions live at ~/.codex/sessions/<year>/<month>/<day>/rollout-*.jsonl[.zst].
* Each line is a rollout event; the conversation is carried by:
* session_meta { id, cwd, timestamp }
* response_item — the model-visible items:
Expand All @@ -25,8 +25,32 @@
* fragments whose target attachment files are usually long gone.
*/

import { readFileSync, readdirSync } from 'node:fs'
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { decompressFrames } from './zstd-frame.mjs'

export const DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024

function tooLarge(file) {
return Object.assign(new Error(`Codex rollout exceeds maxSessionBytes: ${file}`), {
code: 'CODEX_SESSION_TOO_LARGE',
})
}

function readRollout(file, maxBytes) {
if (statSync(file).size > maxBytes) throw tooLarge(file)
let bytes = readFileSync(file)
if (file.endsWith('.jsonl.zst')) {
try {
bytes = decompressFrames(bytes, maxBytes)
} catch (error) {
if (error.code === 'ERR_BUFFER_TOO_LARGE' || error.code === 'ENOBUFS') throw tooLarge(file)
throw error
}
}
if (bytes.length > maxBytes) throw tooLarge(file)
return bytes.toString('utf8')
}

/** Default codex session root. */
export function defaultCodexRoot() {
Expand All @@ -49,11 +73,14 @@ export function listCodexSessions(root) {
for (const entry of entries) {
const path = join(dir, entry.name)
if (entry.isDirectory()) walk(path)
else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.startsWith('rollout-')) files.push(path)
else if (entry.isFile() && /\.jsonl(?:\.zst)?$/u.test(entry.name) && entry.name.startsWith('rollout-')) files.push(path)
}
}
walk(root)
return files.sort()
// Compression may leave both forms temporarily. Prefer the writable plain
// file, without dropping distinct continuation segments of the same thread.
const present = new Set(files)
return files.filter((file) => !file.endsWith('.zst') || !present.has(file.slice(0, -4))).sort()
}

/**
Expand Down Expand Up @@ -136,7 +163,7 @@ function normalizeContentBlock(block) {
* Parse one codex rollout file into normalized messages.
* @returns { header: {id, createdAt, cwd}, messages: normalized[] }
*/
export function parseCodexSession(file) {
export function parseCodexSession(file, { maxSessionBytes = DEFAULT_MAX_SESSION_BYTES } = {}) {
const header = { id: undefined, createdAt: undefined, cwd: undefined }
const messages = []
let lastUserText
Expand All @@ -152,7 +179,7 @@ export function parseCodexSession(file) {
pending = []
}

for (const rawLine of readFileSync(file, 'utf8').split('\n')) {
for (const rawLine of readRollout(file, maxSessionBytes).split('\n')) {
const line = rawLine.trim()
if (line.length === 0) continue
let event
Expand Down
20 changes: 10 additions & 10 deletions lib/import-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Adapted from dsh-import-agents (c) Chang-Tong / dongzhangust, MIT, with two
* field-hardened fixes:
* 1. SIZE GUARD — rollout files larger than `maxSessionBytes` (default
* 256 MiB) are skipped with a note. The stock reader does
* 256 MiB, stored or decoded) are skipped with a note. The stock reader does
* `readFileSync(file, 'utf8')`, and a single file >512 MiB makes Node
* throw "Cannot create a string longer than 0x1fffffe8 characters",
* which aborted the whole import-all (hit in the wild with a 679 MB
Expand All @@ -22,14 +22,12 @@
import { statSync } from 'node:fs'
import { join } from 'node:path'

import { listCodexSessions, parseCodexSession, isSubagentThread } from './codex-reader.mjs'
import { listCodexSessions, parseCodexSession, isSubagentThread, DEFAULT_MAX_SESSION_BYTES } from './codex-reader.mjs'
import { buildDshEvents, deriveImportTitle } from './convert.mjs'
import { migrateToCurrent } from './session-migrate.mjs'
import { normalizePersistence } from './persistence-facade.mjs'
import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs'

const DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024

function projectLabel(cwd) {
if (typeof cwd !== 'string' || cwd.length === 0) return '(no project)'
const parts = cwd.replace(/\\/gu, '/').split('/').filter(Boolean)
Expand Down Expand Up @@ -231,9 +229,10 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo
}
let parsed
try {
parsed = parseCodexSession(file)
} catch {
unreadable += 1
parsed = parseCodexSession(file, { maxSessionBytes: maxBytes })
} catch (error) {
if (error.code === 'CODEX_SESSION_TOO_LARGE') skippedBig += 1
else unreadable += 1
continue
}
if (parsed.header.id === undefined) continue
Expand Down Expand Up @@ -399,9 +398,10 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j
}
let parsed
try {
parsed = parseCodexSession(file)
} catch {
unreadable += 1
parsed = parseCodexSession(file, { maxSessionBytes: maxBytes })
} catch (error) {
if (error.code === 'CODEX_SESSION_TOO_LARGE') skippedBig += 1
else unreadable += 1
continue
}
if (parsed.header.id === undefined) continue
Expand Down
32 changes: 32 additions & 0 deletions lib/zstd-frame.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,35 @@ export function compressChecksummedFrame(input) {
maxBuffer: Math.max(1 << 20, input.length * 2),
})
}

/** Bound decoded bytes before a highly compressible rollout becomes a string. */
export function decompressFrames(input, maxOutputLength) {
if (typeof zlib.zstdDecompressSync === 'function') {
// The synchronous Node decoder stops after one frame. Codex rollouts can
// contain multiple frames; account for their combined decoded size.
const chunks = []
let offset = 0
let length = 0
do {
const { buffer, engine } = zlib.zstdDecompressSync(input.subarray(offset), {
info: true,
maxOutputLength: Math.max(1, maxOutputLength - length),
})
if (engine.bytesWritten <= 0) throw new Error('Zstandard decoder made no progress')
length += buffer.length
if (length > maxOutputLength) {
throw Object.assign(new RangeError('Decoded Zstandard data exceeds size limit'), {
code: 'ERR_BUFFER_TOO_LARGE',
})
}
chunks.push(buffer)
offset += engine.bytesWritten
} while (offset < input.length)
return Buffer.concat(chunks, length)
}
return execFileSync('zstd', ['--quiet', '--decompress', '--stdout'], {
input,
maxBuffer: maxOutputLength,
stdio: ['pipe', 'pipe', 'pipe'],
})
}
1 change: 1 addition & 0 deletions scripts/run-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const suites = [
'test/host.smoke.mjs',
'test/client.render.mjs',
'test/codex-reader.test.mjs',
'test/compressed-rollouts.test.mjs',
'test/import-service.test.mjs',
'test/plugin-skill.test.mjs',
'test/export-codex.test.mjs',
Expand Down
114 changes: 114 additions & 0 deletions test/compressed-rollouts.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { compressChecksummedFrame, decompressFrames } from '../lib/zstd-frame.mjs'
import { listCodexSessions, parseCodexSession } from '../lib/codex-reader.mjs'
import { importCodex, listImportCatalog } from '../lib/import-service.js'

function fixture(t) {
const home = mkdtempSync(join(tmpdir(), 'codex-compressed-'))
t.after(() => rmSync(home, { recursive: true, force: true }))
const dir = join(home, 'sessions', '2026', '10', '20')
mkdirSync(dir, { recursive: true })
return { home, dir }
}
function body(id, text = 'Hello', extra = {}) {
return Buffer.from([
{ type: 'session_meta', payload: { id, cwd: '/tmp/project', timestamp: '2026-10-20T00:00:00Z', ...extra } },
{ type: 'response_item', timestamp: '2026-10-20T00:00:01Z', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } },
{ type: 'response_item', timestamp: '2026-10-20T00:00:02Z', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Reply' }] } },
].map(x => JSON.stringify(x)).join('\n') + '\n')
}
function destination() {
const stored = new Map()
return { stored, persistence: {
async list() { return [...stored.values()].map(x => x.meta) },
async create(meta) { stored.set(meta.id, { meta, events: [] }) },
async append(id, events) { stored.get(id).events.push(...events) },
async inspect(id) { return stored.get(id) },
} }
}
const ctx = { get: () => undefined }

test('plain and concatenated Zstandard rollout frames parse identically', t => {
const { dir } = fixture(t)
const bytes = body('main', '你好 🌏')
const plain = join(dir, 'rollout-main.jsonl')
const compressed = plain + '.zst'
writeFileSync(plain, bytes)
const split = bytes.indexOf(10) + 1
writeFileSync(compressed, Buffer.concat([
compressChecksummedFrame(bytes.subarray(0, split)),
compressChecksummedFrame(bytes.subarray(split)),
]))
writeFileSync(join(dir, 'rollout-ignored.jsonl.zst.bak'), bytes)
writeFileSync(join(dir, 'unrelated.jsonl.zst'), bytes)
assert.deepEqual(parseCodexSession(compressed), parseCodexSession(plain))
assert.deepEqual(listCodexSessions(dir), [plain])
rmSync(plain)
assert.deepEqual(listCodexSessions(dir), [compressed])
})

test('decoded limit covers the sum of frames and later-frame checksums are verified', () => {
const first = compressChecksummedFrame(Buffer.from('a'.repeat(1024)))
const second = compressChecksummedFrame(Buffer.from('b'.repeat(1024)))
const frames = Buffer.concat([first, second])
assert.equal(decompressFrames(frames, 2048).length, 2048)
assert.throws(() => decompressFrames(frames, 1500), error =>
error.code === 'ERR_BUFFER_TOO_LARGE' || error.code === 'ENOBUFS')
second[second.length - 1] ^= 1
assert.throws(() => decompressFrames(Buffer.concat([first, second]), 2048))
})

test('catalog and import include compressed history; dual copies do not duplicate messages', async t => {
const { home, dir } = fixture(t)
const bytes = body('main')
writeFileSync(join(dir, 'rollout-main.jsonl'), bytes)
writeFileSync(join(dir, 'rollout-main.jsonl.zst'), compressChecksummedFrame(bytes))
writeFileSync(join(dir, 'rollout-other.jsonl.zst'), compressChecksummedFrame(body('other')))
writeFileSync(join(dir, 'rollout-sub.jsonl.zst'), compressChecksummedFrame(body('sub', 'Child', { parent_thread_id: 'main' })))
const { persistence, stored } = destination()
const catalog = await listImportCatalog(persistence, {}, home)
assert.equal(catalog.projects[0].sessions.length, 2)
const first = await importCodex(ctx, persistence, {}, home)
assert.equal(stored.size, 2)
assert.match(first.join('\n'), /subagent-skipped 1/)
assert.equal(stored.get('codex-main').events.filter(x => x.type === 'user/message').length, 1)
const second = await importCodex(ctx, persistence, {}, home)
assert.match(second.join('\n'), /imported 0, updated 0, skipped 2/)
})

test('compressed continuation segments remain separate and merge in chronological order', async t => {
const { home, dir } = fixture(t)
writeFileSync(join(dir, 'rollout-01.jsonl.zst'), compressChecksummedFrame(body('main', 'First')))
writeFileSync(join(dir, 'rollout-02.jsonl.zst'), compressChecksummedFrame(body('main', 'Second')))
assert.equal(listCodexSessions(dir).length, 2)
const { persistence, stored } = destination()
await importCodex(ctx, persistence, {}, home)
assert.equal(stored.size, 1)
const users = stored.get('codex-main').events.filter(x => x.type === 'user/message')
assert.equal(users.length, 2)
assert.match(JSON.stringify(users[0]), /First/)
assert.match(JSON.stringify(users[1]), /Second/)
})

test('decoded size limit counts as oversized while corrupt frames count as unreadable', async t => {
const { home, dir } = fixture(t)
const large = join(dir, 'rollout-large.jsonl.zst')
writeFileSync(large, compressChecksummedFrame(body('large', 'x'.repeat(32000))))
const corrupt = compressChecksummedFrame(body('bad'))
corrupt[corrupt.length - 1] ^= 1
writeFileSync(join(dir, 'rollout-bad.jsonl.zst'), corrupt)
writeFileSync(join(dir, 'rollout-good.jsonl.zst'), compressChecksummedFrame(body('good')))
assert.throws(() => parseCodexSession(large, { maxSessionBytes: 1024 }), { code: 'CODEX_SESSION_TOO_LARGE' })
const { persistence, stored } = destination()
const catalog = await listImportCatalog(persistence, { maxSessionBytes: 1024 }, home)
assert.equal(catalog.skippedBig, 1)
assert.equal(catalog.unreadable, 1)
assert.equal(catalog.projects[0].sessions.length, 1)
const lines = await importCodex(ctx, persistence, { maxSessionBytes: 1024 }, home)
assert.match(lines.join('\n'), /oversized-skipped 1, unreadable 1/)
assert.deepEqual([...stored.keys()], ['codex-good'])
})