notesoup 0.53.2 → 0.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/plugins/claude/src/helper.d.ts +2 -1
- package/dist/plugins/claude/src/helper.js +21 -24
- package/dist/plugins/claude/src/history.d.ts +3 -14
- package/dist/plugins/claude/src/history.js +2 -298
- package/dist/plugins/claude/src/text.d.ts +0 -1
- package/dist/plugins/claude/src/text.js +0 -1
- package/dist/plugins/codex/src/history.d.ts +3 -8
- package/dist/plugins/codex/src/history.js +2 -238
- package/dist/plugins/codex/src/hooks.js +1 -1
- package/dist/plugins/codex/src/identity.d.ts +1 -1
- package/dist/plugins/codex/src/identity.js +3 -3
- package/dist/plugins/codex/src/mcp.js +9 -8
- package/dist/plugins/codex/src/text.d.ts +1 -1
- package/dist/plugins/codex/src/text.js +2 -2
- package/dist/plugins/codex/src/transcript.d.ts +3 -39
- package/dist/plugins/codex/src/transcript.js +2 -313
- package/dist/plugins/dsh/engine.js +2 -2
- package/dist/plugins/dsh/history.d.ts +3 -0
- package/dist/plugins/dsh/history.js +15 -0
- package/dist/plugins/dsh/tools.js +12 -12
- package/dist/plugins/dsh/window.d.ts +1 -0
- package/dist/plugins/dsh/window.js +7 -3
- package/dist/plugins/pi/history-tools.d.ts +1 -1
- package/dist/plugins/pi/history-tools.js +9 -5
- package/dist/plugins/pi/history.d.ts +2 -3
- package/dist/plugins/pi/history.js +4 -147
- package/dist/plugins/pi/notes/tools.js +8 -6
- package/dist/plugins/pi/render.js +7 -4
- package/dist/plugins/pi/runtime.js +2 -2
- package/dist/plugins/pi/window.js +21 -7
- package/dist/src/boot/render.js +9 -11
- package/dist/src/boot/snapshot.d.ts +7 -7
- package/dist/src/boot/snapshot.js +17 -17
- package/dist/src/boot/text.d.ts +5 -3
- package/dist/src/boot/text.js +18 -10
- package/dist/src/dream/git.d.ts +2 -11
- package/dist/src/dream/git.js +6 -23
- package/dist/src/dream/lock.d.ts +2 -2
- package/dist/src/dream/lock.js +3 -3
- package/dist/src/history/claude.d.ts +16 -0
- package/dist/src/history/claude.js +336 -0
- package/dist/src/history/codex-transcript.d.ts +39 -0
- package/dist/src/history/codex-transcript.js +315 -0
- package/dist/src/history/codex.d.ts +8 -0
- package/dist/src/history/codex.js +238 -0
- package/dist/src/history/corpus.d.ts +35 -0
- package/dist/src/history/corpus.js +54 -0
- package/dist/src/history/history.d.ts +4 -8
- package/dist/src/history/history.js +3 -11
- package/dist/src/history/local.d.ts +17 -0
- package/dist/src/history/local.js +101 -0
- package/dist/src/history/pi.d.ts +36 -0
- package/dist/src/history/pi.js +202 -0
- package/dist/src/history/query.d.ts +15 -5
- package/dist/src/history/query.js +42 -13
- package/dist/src/index.d.ts +6 -3
- package/dist/src/index.js +6 -4
- package/dist/src/notes/address.d.ts +8 -8
- package/dist/src/notes/address.js +13 -13
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.js +2 -2
- package/dist/src/notes/index.d.ts +1 -1
- package/dist/src/notes/index.js +1 -1
- package/dist/src/notes/paths.d.ts +6 -6
- package/dist/src/notes/paths.js +9 -9
- package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
- package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
- package/dist/src/notes/store.d.ts +4 -4
- package/dist/src/notes/store.js +55 -52
- package/dist/src/tools/dream.d.ts +21 -3
- package/dist/src/tools/dream.js +54 -16
- package/dist/src/tools/history.d.ts +7 -19
- package/dist/src/tools/history.js +80 -93
- package/dist/src/tools/notes-context.d.ts +10 -0
- package/dist/src/tools/notes-context.js +27 -0
- package/dist/src/tools/notes.d.ts +69 -20
- package/dist/src/tools/notes.js +40 -31
- package/dist/test/boot.integration.test.js +2 -3
- package/dist/test/claude-history.test.js +47 -34
- package/dist/test/claude-mod.test.js +96 -50
- package/dist/test/codex-history.test.js +4 -10
- package/dist/test/codex-plugin.test.js +50 -12
- package/dist/test/context-edit-budget.test.js +121 -0
- package/dist/test/dependencies.test.js +73 -6
- package/dist/test/dream-tools.test.js +153 -8
- package/dist/test/dsh.test.js +88 -19
- package/dist/test/helpers/dsh.d.ts +4 -1
- package/dist/test/helpers/dsh.js +20 -4
- package/dist/test/helpers/extension.d.ts +5 -1
- package/dist/test/helpers/extension.js +33 -2
- package/dist/test/helpers/history-corpus.d.ts +7 -0
- package/dist/test/helpers/history-corpus.js +26 -0
- package/dist/test/history-corpus.test.js +307 -0
- package/dist/test/history.integration.test.js +40 -48
- package/dist/test/host-neutral.test.js +20 -33
- package/dist/test/model-facing-text.test.js +14 -8
- package/dist/test/notes-cwd.test.d.ts +1 -0
- package/dist/test/notes-cwd.test.js +114 -0
- package/dist/test/notes-library.test.js +4 -4
- package/dist/test/notes-query-namespaces.test.d.ts +1 -0
- package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
- package/dist/test/notes.integration.test.js +73 -24
- package/dist/test/notes.test.js +51 -21
- package/dist/test/pi-render.test.js +33 -1
- package/dist/test/project-namespace.test.d.ts +1 -0
- package/dist/test/project-namespace.test.js +324 -0
- package/docs/architecture.md +19 -12
- package/docs/claude-code-mod.md +7 -5
- package/docs/codex.md +6 -6
- package/docs/dsh.md +9 -9
- package/docs/history-sessions.md +52 -0
- package/docs/notes-library.md +9 -5
- package/docs/skills.md +3 -3
- package/docs/tool-results.md +14 -8
- package/package.json +4 -6
- package/playbook.md +6 -6
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +2164 -1341
- package/plugins/claude/hooks/register.ts +19 -11
- package/plugins/claude/playbook.md +6 -6
- package/plugins/claude/skills/memory/SKILL.md +9 -7
- package/plugins/claude/src/helper.ts +22 -25
- package/plugins/claude/src/history.ts +3 -257
- package/plugins/claude/src/text.ts +0 -1
- package/plugins/codex/README.md +1 -1
- package/plugins/codex/dist/codex/notesoup.js +1582 -969
- package/plugins/codex/src/history.ts +3 -193
- package/plugins/codex/src/hooks.ts +1 -1
- package/plugins/codex/src/identity.ts +3 -3
- package/plugins/codex/src/mcp.ts +9 -8
- package/plugins/codex/src/text.ts +2 -2
- package/plugins/codex/src/transcript.ts +3 -275
- package/plugins/dsh/engine.ts +2 -2
- package/plugins/dsh/history.ts +17 -0
- package/plugins/dsh/tools.ts +12 -12
- package/plugins/dsh/window.ts +8 -3
- package/plugins/paseo/OVERVIEW.md +4 -4
- package/plugins/paseo/README.md +1 -1
- package/plugins/paseo/client/brain-empty-card.tsx +3 -4
- package/plugins/paseo/client/markdown.tsx +159 -0
- package/plugins/paseo/client/notes-op-card.tsx +35 -34
- package/plugins/paseo/client/notes-op-transformer.ts +17 -68
- package/plugins/paseo/client/paper-card.tsx +8 -19
- package/plugins/paseo/client/paper-palette.ts +40 -0
- package/plugins/paseo/client/sticky-card.tsx +6 -4
- package/plugins/paseo/package.json +3 -0
- package/plugins/paseo/paseo-plugin.json +2 -2
- package/plugins/paseo/shared/notes-op.ts +13 -9
- package/plugins/paseo/test/notes-op.test.ts +52 -73
- package/plugins/paseo/test/paper-palette.test.ts +54 -0
- package/plugins/pi/history-tools.ts +11 -5
- package/plugins/pi/history.ts +8 -157
- package/plugins/pi/notes/tools.ts +8 -6
- package/plugins/pi/render.ts +6 -4
- package/plugins/pi/runtime.ts +2 -2
- package/plugins/pi/window.ts +22 -7
- package/skills/memory/SKILL.md +9 -7
- package/src/boot/render.ts +10 -13
- package/src/boot/snapshot.ts +20 -20
- package/src/boot/text.ts +18 -10
- package/src/dream/git.ts +7 -24
- package/src/dream/lock.ts +3 -3
- package/src/history/claude.ts +286 -0
- package/src/history/codex-transcript.ts +276 -0
- package/src/history/codex.ts +193 -0
- package/src/history/corpus.ts +69 -0
- package/src/history/history.ts +5 -12
- package/src/history/local.ts +93 -0
- package/src/history/pi.ts +199 -0
- package/src/history/query.ts +45 -15
- package/src/index.ts +8 -5
- package/src/notes/address.ts +13 -13
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +2 -2
- package/src/notes/index.ts +1 -1
- package/src/notes/paths.ts +9 -9
- package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
- package/src/notes/store.ts +61 -58
- package/src/tools/dream.ts +63 -16
- package/src/tools/history.ts +71 -101
- package/src/tools/notes-context.ts +29 -0
- package/src/tools/notes.ts +39 -29
- package/dist/test/project-home.test.js +0 -134
- /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
- /package/dist/test/{project-home.test.d.ts → history-corpus.test.d.ts} +0 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/** Read-only local rollout decoder for official Codex 0.160.1 (d27764b82f71).
|
|
2
|
+
* Wire owners: history/src/{lib,rollout_payload}.rs, rollout/src/ordinal.rs,
|
|
3
|
+
* thread-store/src/local/rollout_lineage.rs. Not an app-server history client.
|
|
4
|
+
* Native .jsonl.zst reads require Node >=22.15 (node:zlib zstdDecompressSync).
|
|
5
|
+
*/
|
|
6
|
+
import { readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
7
|
+
import { basename, dirname, join, relative, sep } from "node:path";
|
|
8
|
+
import * as zlib from "node:zlib";
|
|
9
|
+
|
|
10
|
+
export type CodexTranscriptSource = { transcriptPath: string; threadId: string };
|
|
11
|
+
export type CodexTranscriptState = {
|
|
12
|
+
threadId: string;
|
|
13
|
+
rootSessionId: string;
|
|
14
|
+
cliVersion: string;
|
|
15
|
+
cwd: string;
|
|
16
|
+
model?: string;
|
|
17
|
+
/** Native, UNPREFIXED identities, also used by MCP _meta.windowId. */
|
|
18
|
+
currentWindowId?: string;
|
|
19
|
+
currentWindowNumber?: number;
|
|
20
|
+
firstWindowId?: string;
|
|
21
|
+
previousWindowId?: string;
|
|
22
|
+
};
|
|
23
|
+
export type NativeObject = Record<string, unknown>;
|
|
24
|
+
export type CodexRecord = {
|
|
25
|
+
type: string;
|
|
26
|
+
payload: NativeObject;
|
|
27
|
+
metadata?: NativeObject;
|
|
28
|
+
timestamp: string;
|
|
29
|
+
/** One record owns one seq, including records omitted from presentation. */
|
|
30
|
+
seq: number;
|
|
31
|
+
/** Metadata belongs to its physical segment, not the root-scoped session_id. */
|
|
32
|
+
owner: string;
|
|
33
|
+
/** Native window at this point, absent only when the producer did not persist it. */
|
|
34
|
+
windowId?: string;
|
|
35
|
+
};
|
|
36
|
+
type Position = { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number };
|
|
37
|
+
type Segment = { meta: NativeObject; records: CodexRecord[] };
|
|
38
|
+
const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
39
|
+
const UUID_RE = new RegExp(`^${UUID}$`);
|
|
40
|
+
const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
|
|
41
|
+
const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
|
|
42
|
+
const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
|
|
43
|
+
// Explicit resource limits, not guessed sequence offsets or partial successful history.
|
|
44
|
+
const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
|
|
45
|
+
export function nativeObject(value: unknown, field: string): NativeObject {
|
|
46
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an object`);
|
|
47
|
+
return value as NativeObject;
|
|
48
|
+
}
|
|
49
|
+
export function nativeString(value: unknown, field: string): string {
|
|
50
|
+
if (typeof value !== "string") throw new Error(`Invalid Codex ${field}: expected a string`);
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function responseShape(value: unknown): void {
|
|
54
|
+
const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
|
|
55
|
+
if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
|
|
56
|
+
}
|
|
57
|
+
function id(value: unknown, field: string): string {
|
|
58
|
+
const result = nativeString(value, field);
|
|
59
|
+
if (!UUID_RE.test(result)) throw new Error(`Invalid Codex ${field}: expected a canonical UUID`);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
function integer(value: unknown, field: string): number {
|
|
63
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER) throw new Error(`Invalid Codex ${field}: unsafe or negative integer`);
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function position(value: unknown): Position | undefined {
|
|
67
|
+
if (value == null) return undefined;
|
|
68
|
+
const p = nativeObject(value, "history_base");
|
|
69
|
+
return { thread_id: id(p.thread_id, "history_base.thread_id (rollout ID)"), end_ordinal_exclusive: integer(p.end_ordinal_exclusive, "history_base ordinal"), end_byte_offset: integer(p.end_byte_offset, "history_base byte offset") };
|
|
70
|
+
}
|
|
71
|
+
function initialWindow(meta: NativeObject): string | undefined {
|
|
72
|
+
return meta.context_window == null ? undefined : id(nativeObject(meta.context_window, "context_window").window_id, "context_window.window_id");
|
|
73
|
+
}
|
|
74
|
+
function checkMeta(meta: NativeObject): void {
|
|
75
|
+
id(meta.id, "session_meta.id");
|
|
76
|
+
if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
|
|
77
|
+
if (meta.cli_version !== "0.160.1") throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
|
|
78
|
+
nativeString(meta.cwd, "session_meta.cwd");
|
|
79
|
+
if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
|
|
80
|
+
for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
|
|
81
|
+
for (const field of ["forked_from_ordinal_exclusive", "subagent_history_start_ordinal"]) if (meta[field] != null) integer(meta[field], field);
|
|
82
|
+
initialWindow(meta);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Only newline-committed records count. A valid JSON value without its newline is still an append tail. */
|
|
86
|
+
function segmentFromBytes(bytes: Buffer, cutoff?: Position): Segment {
|
|
87
|
+
const limit = cutoff?.end_byte_offset ?? bytes.length;
|
|
88
|
+
if (limit > bytes.length || (cutoff && (limit === 0 || bytes[limit - 1] !== 10))) throw new Error("Unavailable Codex lineage: cutoff is not a complete decoded JSONL boundary");
|
|
89
|
+
const records: CodexRecord[] = [];
|
|
90
|
+
let meta: NativeObject | undefined, previous = -1, lineNumber = 0;
|
|
91
|
+
for (let offset = 0; offset < limit;) {
|
|
92
|
+
const newline = bytes.indexOf(10, offset);
|
|
93
|
+
if (newline < 0 || newline >= limit) break;
|
|
94
|
+
lineNumber++;
|
|
95
|
+
let row: NativeObject;
|
|
96
|
+
try {
|
|
97
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, newline));
|
|
98
|
+
row = nativeObject(JSON.parse(text), "record");
|
|
99
|
+
} catch { throw new Error(`Malformed committed Codex JSONL record at line ${lineNumber}`); }
|
|
100
|
+
offset = newline + 1;
|
|
101
|
+
const type = nativeString(row.type, "record.type");
|
|
102
|
+
if (!RECORD_TYPES.has(type)) throw new Error(`Unsupported Codex rollout record: ${type}`);
|
|
103
|
+
const payload = nativeObject(row.payload, `${type}.payload`);
|
|
104
|
+
if (!meta) {
|
|
105
|
+
if (type !== "session_meta") throw new Error("Invalid Codex transcript: first record must be session_meta");
|
|
106
|
+
meta = payload;
|
|
107
|
+
checkMeta(meta);
|
|
108
|
+
} else if (type === "session_meta") {
|
|
109
|
+
// Legacy copied forks can contain replayed metadata with no provable original
|
|
110
|
+
// coordinates. Do not relabel a copied tree as independently spoken events.
|
|
111
|
+
throw new Error("Unavailable Codex history: copied session_meta ancestry has no proved source addresses");
|
|
112
|
+
}
|
|
113
|
+
const paginated = meta.history_mode === "paginated";
|
|
114
|
+
const ordinal = paginated ? integer(row.ordinal, "paginated record ordinal") : lineNumber - 1;
|
|
115
|
+
if (!paginated && row.ordinal != null) throw new Error("Invalid Codex legacy transcript: unexpected ordinal");
|
|
116
|
+
if (ordinal <= previous) throw new Error("Invalid Codex transcript: non-increasing record ordinals");
|
|
117
|
+
if (records.length === 0 && ordinal !== (position(meta.history_base)?.end_ordinal_exclusive ?? 0)) throw new Error("Invalid Codex transcript: metadata ordinal does not match history_base");
|
|
118
|
+
previous = ordinal;
|
|
119
|
+
if (cutoff && ordinal >= cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
|
|
120
|
+
if (type === "event_msg" && payload.type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
|
|
121
|
+
if (type === "response_item") responseShape(payload);
|
|
122
|
+
records.push({ type, payload, timestamp: nativeString(row.timestamp, "record.timestamp"), seq: ordinal + 1, owner: meta.id as string, ...(row.metadata == null ? {} : { metadata: nativeObject(row.metadata, "response metadata") }) });
|
|
123
|
+
}
|
|
124
|
+
if (!meta) throw new Error("Unavailable Codex transcript: no committed session_meta yet");
|
|
125
|
+
const base = position(meta.history_base);
|
|
126
|
+
if (base && meta.history_mode !== "paginated") throw new Error("Invalid Codex history_base on a non-paginated transcript");
|
|
127
|
+
if (cutoff && meta.history_mode !== "paginated") throw new Error("Unavailable Codex lineage: referenced source is not paginated");
|
|
128
|
+
// A cutoff is a native coordinate pair, not permission to approximate an ordinal
|
|
129
|
+
// inside a gap. Usually the included prefix already proves its exclusive end.
|
|
130
|
+
if (cutoff && previous + 1 !== cutoff.end_ordinal_exclusive) {
|
|
131
|
+
const nextNewline = bytes.indexOf(10, limit);
|
|
132
|
+
if (nextNewline < 0) throw new Error("Unavailable Codex lineage: ordinal cutoff is beyond the proved prefix");
|
|
133
|
+
let next: NativeObject;
|
|
134
|
+
try { next = nativeObject(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(limit, nextNewline))), "cutoff successor"); }
|
|
135
|
+
catch { throw new Error("Unavailable Codex lineage: cannot prove ordinal cutoff successor"); }
|
|
136
|
+
if (integer(next.ordinal, "cutoff successor ordinal") !== cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
|
|
137
|
+
}
|
|
138
|
+
const start = meta.subagent_history_start_ordinal;
|
|
139
|
+
if (start != null && (meta.history_mode !== "paginated" || previous < integer(start, "subagent history start") - 1)) throw new Error("Unavailable Codex history: incomplete inherited subagent prefix");
|
|
140
|
+
return { meta, records };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function within(root: string, path: string): boolean {
|
|
144
|
+
const rel = relative(root, path);
|
|
145
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
146
|
+
}
|
|
147
|
+
/** Infer storage roots only from the supplied native path, never $HOME or a private DB. */
|
|
148
|
+
function storageHome(path: string): string {
|
|
149
|
+
for (let cursor = dirname(path); dirname(cursor) !== cursor; cursor = dirname(cursor)) {
|
|
150
|
+
if (basename(cursor) === "sessions" || basename(cursor) === "archived_sessions") return dirname(cursor);
|
|
151
|
+
}
|
|
152
|
+
throw new Error("Unavailable Codex lineage: transcript must be under native sessions/ or archived_sessions/ to resolve history_base");
|
|
153
|
+
}
|
|
154
|
+
async function referencedPath(home: string, rolloutId: string): Promise<string> {
|
|
155
|
+
const matches: string[] = [], directories = [join(home, "sessions"), join(home, "archived_sessions")];
|
|
156
|
+
let entriesSeen = 0;
|
|
157
|
+
while (directories.length) {
|
|
158
|
+
const directory = directories.pop()!;
|
|
159
|
+
let entries;
|
|
160
|
+
try { entries = await readdir(directory, { withFileTypes: true }); }
|
|
161
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
162
|
+
for (const entry of entries) {
|
|
163
|
+
if (++entriesSeen > MAX_DIRECTORY_ENTRIES) throw new Error("Unavailable Codex lineage: native directory discovery limit exceeded");
|
|
164
|
+
const path = join(directory, entry.name);
|
|
165
|
+
if (entry.isDirectory()) directories.push(path);
|
|
166
|
+
else if (entry.isFile()) {
|
|
167
|
+
const name = FILE_RE.exec(entry.name);
|
|
168
|
+
if (name && (name[2] ?? name[1]) === rolloutId) matches.push(path);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
|
|
173
|
+
return matches[0]!;
|
|
174
|
+
}
|
|
175
|
+
async function decodedBytes(path: string, remaining: number): Promise<Buffer> {
|
|
176
|
+
const info = await stat(path);
|
|
177
|
+
if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
178
|
+
const bytes = await readFile(path);
|
|
179
|
+
// 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
|
|
180
|
+
if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
|
|
181
|
+
const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
|
|
182
|
+
if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
|
|
183
|
+
return decoded;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
|
|
187
|
+
export async function readCodexTranscript(source: CodexTranscriptSource): Promise<{ state: CodexTranscriptState; records: CodexRecord[]; highestSeq: number }> {
|
|
188
|
+
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
|
|
189
|
+
id(source.threadId, "requested threadId");
|
|
190
|
+
try {
|
|
191
|
+
let path = await realpath(source.transcriptPath), cutoff: Position | undefined, home: string | undefined;
|
|
192
|
+
let remaining = MAX_BYTES;
|
|
193
|
+
const segments: Segment[] = [], seen = new Set<string>();
|
|
194
|
+
while (true) {
|
|
195
|
+
if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
|
|
196
|
+
seen.add(path);
|
|
197
|
+
const bytes = await decodedBytes(path, remaining);
|
|
198
|
+
remaining -= bytes.length;
|
|
199
|
+
const segment = segmentFromBytes(bytes, cutoff);
|
|
200
|
+
if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
|
|
201
|
+
if (cutoff) {
|
|
202
|
+
const name = FILE_RE.exec(basename(path));
|
|
203
|
+
if (!name || (name[2] ?? name[1]) !== cutoff.thread_id || name[1] !== segment.meta.id) throw new Error("Unavailable Codex lineage: native filename/rollout/metadata identity mismatch");
|
|
204
|
+
}
|
|
205
|
+
segments.unshift(segment);
|
|
206
|
+
const base = position(segment.meta.history_base);
|
|
207
|
+
if (!base) break;
|
|
208
|
+
if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
|
|
209
|
+
home ??= storageHome(path);
|
|
210
|
+
path = await realpath(await referencedPath(home, base.thread_id));
|
|
211
|
+
if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
|
|
212
|
+
cutoff = base;
|
|
213
|
+
}
|
|
214
|
+
// history_base is physical; forked_from_ordinal_exclusive is the logical
|
|
215
|
+
// parent boundary (protocol.rs HistoryPosition, revert_thread.rs). A revert
|
|
216
|
+
// may retain this thread's own later delta, but cannot grow inherited history.
|
|
217
|
+
for (let index = 0; index < segments.length; index++) {
|
|
218
|
+
const meta = segments[index]!.meta, end = meta.forked_from_ordinal_exclusive;
|
|
219
|
+
if (end != null && meta.forked_from_id != null) {
|
|
220
|
+
for (const ancestor of segments.slice(0, index)) {
|
|
221
|
+
if (ancestor.meta.id !== meta.id && ancestor.records.some((record) => record.seq - 1 >= (end as number))) throw new Error("Unavailable Codex lineage: physical ancestry exceeds the logical fork cutoff");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const selected = segments.at(-1)!.meta;
|
|
226
|
+
const state: CodexTranscriptState = { threadId: source.threadId, rootSessionId: (selected.session_id ?? selected.id) as string, cliVersion: selected.cli_version as string, cwd: selected.cwd as string };
|
|
227
|
+
const records: CodexRecord[] = [];
|
|
228
|
+
let window: string | undefined, first: string | undefined, previousWindow: string | undefined, number: number | undefined, sawCompacted = false, lastSeq = 0;
|
|
229
|
+
let contextModel: string | undefined, settingsModel: string | undefined;
|
|
230
|
+
for (const segment of segments) {
|
|
231
|
+
// Native reconstruction uses the requested header's initial identity unless
|
|
232
|
+
// an inherited checkpoint supplies the effective window (rollout_reconstruction.rs).
|
|
233
|
+
if (!sawCompacted) { window = initialWindow(segment.meta); first = window; previousWindow = undefined; number = window ? 0 : undefined; }
|
|
234
|
+
for (const record of segment.records) {
|
|
235
|
+
if (record.seq <= lastSeq) throw new Error("Unavailable Codex lineage: overlapping source coordinates");
|
|
236
|
+
lastSeq = record.seq;
|
|
237
|
+
if (record.type === "compacted") {
|
|
238
|
+
sawCompacted = true;
|
|
239
|
+
const p = record.payload;
|
|
240
|
+
nativeString(p.message, "compacted.message");
|
|
241
|
+
if (p.replacement_history != null && !Array.isArray(p.replacement_history)) throw new Error("Invalid Codex replacement_history");
|
|
242
|
+
if (Array.isArray(p.replacement_history)) p.replacement_history.forEach(responseShape);
|
|
243
|
+
if (p.replacement_history_metadata != null && (!Array.isArray(p.replacement_history_metadata) || !Array.isArray(p.replacement_history) || p.replacement_history_metadata.length !== p.replacement_history.length)) throw new Error("Invalid Codex replacement_history_metadata alignment");
|
|
244
|
+
// Numeric legacy window_id has no usable native identity; don't turn it
|
|
245
|
+
// into a UUID, or silently assign subsequent records to the old window.
|
|
246
|
+
window = p.window_id == null || typeof p.window_id === "number" ? undefined : id(p.window_id, "compacted.window_id");
|
|
247
|
+
number = p.window_number == null ? (typeof p.window_id === "number" ? integer(p.window_id, "legacy window number") : undefined) : integer(p.window_number, "window_number");
|
|
248
|
+
first = p.first_window_id == null ? undefined : id(p.first_window_id, "first_window_id");
|
|
249
|
+
previousWindow = p.previous_window_id == null ? undefined : id(p.previous_window_id, "previous_window_id");
|
|
250
|
+
}
|
|
251
|
+
record.windowId = window;
|
|
252
|
+
// Explicitly copied subagent inference context isn't child-local history.
|
|
253
|
+
// Preserve its coordinates as holes, not invented parent event addresses.
|
|
254
|
+
const start = segment.meta.subagent_history_start_ordinal;
|
|
255
|
+
if (start != null && record.type !== "session_meta" && record.seq - 1 < (start as number)) continue;
|
|
256
|
+
if (record.owner === source.threadId && record.type === "turn_context") contextModel = nativeString(record.payload.model, "turn_context.model");
|
|
257
|
+
if (record.type === "event_msg" && record.payload.type === "thread_settings_applied" && record.payload.thread_id === source.threadId) {
|
|
258
|
+
settingsModel = nativeString(nativeObject(record.payload.thread_settings, "thread_settings").model, "thread_settings.model");
|
|
259
|
+
}
|
|
260
|
+
records.push(record);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
Object.assign(state, { currentWindowId: window, currentWindowNumber: number, firstWindowId: first, previousWindowId: previousWindow });
|
|
264
|
+
// Native latest model settings win over a frozen companion TurnContext after
|
|
265
|
+
// compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
|
|
266
|
+
if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
|
|
267
|
+
return { state, records, highestSeq: lastSeq };
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Same decoder and ownership as history; no independently guessed boot window. */
|
|
274
|
+
export async function readCodexTranscriptState(source: CodexTranscriptSource): Promise<CodexTranscriptState> {
|
|
275
|
+
return (await readCodexTranscript(source)).state;
|
|
276
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
|
|
2
|
+
import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
|
|
3
|
+
import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./codex-transcript.js";
|
|
4
|
+
export type { CodexTranscriptSource } from "./codex-transcript.js";
|
|
5
|
+
export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection };
|
|
6
|
+
|
|
7
|
+
const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
|
|
8
|
+
const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
|
|
9
|
+
// protocol.rs serializes v1 task_* spellings; turn_* are explicit serde aliases.
|
|
10
|
+
const HOST_EVENTS = new Set(["token_count", "thread_goal_updated", "task_started", "task_complete", "turn_started", "turn_complete", "turn_aborted", "thread_settings_applied", "entered_review_mode", "exited_review_mode", "patch_apply_end", "sub_agent_activity"]);
|
|
11
|
+
const HOST_ITEMS = new Set(["Plan", "FileChange", "CollabAgentToolCall", "SubAgentActivity", "ImageView", "Extension", "EnteredReviewMode", "ExitedReviewMode"]);
|
|
12
|
+
const OPAQUE_RESPONSES = new Set(["reasoning", "compaction", "compaction_summary", "context_compaction", "image_generation_call"]);
|
|
13
|
+
const HOST_RESPONSES = new Set(["configuration_update", "tool_search_call", "tool_search_output", "web_search_call"]);
|
|
14
|
+
function optionalString(value: unknown, field: string): string | undefined { return value == null ? undefined : str(value, field); }
|
|
15
|
+
function array(value: unknown, field: string): unknown[] {
|
|
16
|
+
if (!Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an array`);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/** No image/audio decoding, opaque plaintext recovery, or stringification disguised as message text. */
|
|
20
|
+
function textContent(value: unknown): string {
|
|
21
|
+
return array(value, "content").map((value) => {
|
|
22
|
+
const part = obj(value, "content part");
|
|
23
|
+
switch (part.type) {
|
|
24
|
+
case "input_text": case "output_text": return str(part.text, "content text");
|
|
25
|
+
case "input_image": return "[Codex image content omitted]";
|
|
26
|
+
case "input_audio": return "[Codex audio content omitted]";
|
|
27
|
+
case "encrypted_content": return "[Codex encrypted content unavailable]";
|
|
28
|
+
default: throw new Error(`Unsupported Codex content part: ${String(part.type)}`);
|
|
29
|
+
}
|
|
30
|
+
}).join("\n");
|
|
31
|
+
}
|
|
32
|
+
function output(value: unknown): string { return typeof value === "string" ? value : textContent(value); }
|
|
33
|
+
function argumentsOf(raw: string): NativeObject {
|
|
34
|
+
// Custom/invalid/non-object JSON cannot fit the shared object field. Keep the
|
|
35
|
+
// original wire string under an explicit raw label rather than lose it.
|
|
36
|
+
try {
|
|
37
|
+
const parsed: unknown = JSON.parse(raw);
|
|
38
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as NativeObject;
|
|
39
|
+
} catch { /* Native tool calls may persist unparseable model arguments. */ }
|
|
40
|
+
return { raw_arguments: raw };
|
|
41
|
+
}
|
|
42
|
+
function callKey(record: CodexRecord, callId: string): string { return `${record.owner}:${callId}`; }
|
|
43
|
+
function context(record: CodexRecord, text: string): DecodedHistoryItem {
|
|
44
|
+
if (!record.windowId) throw new Error(`Unavailable Codex history: native window identity missing at seq ${record.seq}; cannot assign a stable window address`);
|
|
45
|
+
return { seq: record.seq, windowId: record.windowId, role: "system", text, createdAt: record.timestamp };
|
|
46
|
+
}
|
|
47
|
+
function host(record: CodexRecord, kind: string, payload: unknown): DecodedHistoryItem { return context(record, `Codex ${kind}\n${JSON.stringify(payload)}`); }
|
|
48
|
+
|
|
49
|
+
type ToolFact = { error?: boolean; text?: string };
|
|
50
|
+
/** Presentation records contribute OUTCOME evidence, never duplicate raw tool dialogue. */
|
|
51
|
+
function fact(item: NativeObject): ToolFact {
|
|
52
|
+
if (item.type === "CommandExecution") {
|
|
53
|
+
const status = str(item.status, "CommandExecution.status");
|
|
54
|
+
if (!["completed", "failed", "declined", "in_progress"].includes(status)) throw new Error(`Unsupported Codex command status: ${status}`);
|
|
55
|
+
return { error: status === "failed" || status === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0), text: optionalString(item.formatted_output, "formatted_output") };
|
|
56
|
+
}
|
|
57
|
+
if (item.type === "McpToolCall") {
|
|
58
|
+
const result = item.result == null ? undefined : obj(item.result, "MCP result");
|
|
59
|
+
if (result?.isError != null && typeof result.isError !== "boolean") throw new Error("Invalid Codex MCP isError");
|
|
60
|
+
return { error: item.status === "failed" || item.error != null || result?.isError === true, ...(result === undefined ? {} : { text: JSON.stringify(result) }) };
|
|
61
|
+
}
|
|
62
|
+
if (item.type === "DynamicToolCall") return { error: item.success === false || item.status === "failed" || item.error != null };
|
|
63
|
+
if (item.type === "FileChange" || item.type === "CollabAgentToolCall") return { error: item.status === "failed" || item.status === "declined" || item.status === "interrupted" };
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
function toolDisplay(item: NativeObject): boolean {
|
|
67
|
+
return ["CommandExecution", "McpToolCall", "DynamicToolCall", "CollabAgentToolCall", "FileChange", "ImageView", "Extension"].includes(String(item.type));
|
|
68
|
+
}
|
|
69
|
+
function response(record: CodexRecord, facts: Map<string, ToolFact>): DecodedHistoryItem {
|
|
70
|
+
const p = record.payload, type = str(p.type, "response_item.type"), base = context(record, "");
|
|
71
|
+
if (type === "message") {
|
|
72
|
+
if (!["user", "assistant", "system", "developer"].includes(str(p.role, "message.role"))) throw new Error(`Unsupported Codex message role: ${String(p.role)}`);
|
|
73
|
+
return { ...base, role: record.metadata?.compaction_output === true ? "system" : p.role as "user" | "assistant" | "system" | "developer", text: textContent(p.content) };
|
|
74
|
+
}
|
|
75
|
+
if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
|
|
76
|
+
const callId = optionalString(p.call_id, "call_id") ?? (type === "local_shell_call" ? optionalString(p.id, "local shell id") : undefined);
|
|
77
|
+
if (!callId) throw new Error("Invalid Codex tool call: missing native call ID");
|
|
78
|
+
const name = type === "local_shell_call" ? "local_shell" : str(p.name, "tool name");
|
|
79
|
+
const args = type === "local_shell_call" ? obj(p.action, "local shell action") : type === "custom_tool_call" ? { input: str(p.input, "custom tool input") } : argumentsOf(str(p.arguments, "function arguments"));
|
|
80
|
+
return { ...base, role: "tool_call", toolName: p.namespace ? `${str(p.namespace, "namespace")}.${name}` : name, toolCallId: callKey(record, callId), arguments: args };
|
|
81
|
+
}
|
|
82
|
+
if (type === "function_call_output" || type === "custom_tool_call_output") {
|
|
83
|
+
const callId = optionalString(p.call_id, "output.call_id"), recorded = callId ? facts.get(callKey(record, callId)) : undefined;
|
|
84
|
+
return { ...base, role: "tool", text: output(p.output), ...(callId ? { toolCallId: callKey(record, callId) } : {}), ...(p.name == null ? {} : { toolName: str(p.name, "output.name") }), ...(recorded?.error === undefined ? {} : { toolError: recorded.error }) };
|
|
85
|
+
}
|
|
86
|
+
if (type === "agent_message") return host(record, "agent_message", { author: p.author, recipient: p.recipient, text: textContent(p.content) });
|
|
87
|
+
if (OPAQUE_RESPONSES.has(type)) {
|
|
88
|
+
// Preserve recorded summaries and available metadata, not encrypted blobs or image bytes.
|
|
89
|
+
const { encrypted_content: _encrypted, result: _image, ...readable } = p;
|
|
90
|
+
return host(record, `${type} (opaque content omitted; not recovered plaintext)`, readable);
|
|
91
|
+
}
|
|
92
|
+
if (HOST_RESPONSES.has(type)) return host(record, type, p);
|
|
93
|
+
throw new Error(`Unsupported Codex response item: ${type}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** One display record without a raw equivalent (e.g. user-shell command). */
|
|
97
|
+
function standaloneTool(record: CodexRecord, item: NativeObject): DecodedHistoryItem {
|
|
98
|
+
const base = context(record, ""), recorded = fact(item);
|
|
99
|
+
if (item.type === "CommandExecution") {
|
|
100
|
+
array(item.command, "command").forEach((part) => str(part, "command argument"));
|
|
101
|
+
return { ...base, role: "tool", toolName: "terminal", arguments: { command: item.command, cwd: item.cwd, source: item.source, ...(item.interaction_input == null ? {} : { interaction_input: item.interaction_input }) }, text: recorded.text ?? JSON.stringify({ stdout: item.stdout, stderr: item.stderr, aggregated_output: item.aggregated_output }), recordedStatus: item.status === "in_progress" ? "unfinished" : recorded.error ? "error" : "ok" };
|
|
102
|
+
}
|
|
103
|
+
const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
|
|
104
|
+
return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState> {
|
|
108
|
+
const { state, records, highestSeq } = await readCodexTranscript(source);
|
|
109
|
+
const facts = new Map<string, ToolFact>(), callsSeen = new Set<string>(), responseIdsSeen = new Set<string>();
|
|
110
|
+
const windows = new Map<string, DecodedHistoryWindow>(), branchSeqs = new Set<number>();
|
|
111
|
+
const addWindow = (nativeId: string, createdAt?: string): DecodedHistoryWindow => {
|
|
112
|
+
const windowId = `codex:${source.threadId}:${nativeId}`;
|
|
113
|
+
let window = windows.get(windowId);
|
|
114
|
+
if (!window) { window = { windowId, createdAt, items: [] }; windows.set(windowId, window); }
|
|
115
|
+
return window;
|
|
116
|
+
};
|
|
117
|
+
// Outcome inventory can enrich the raw result even when ItemCompleted follows it.
|
|
118
|
+
for (const record of records) {
|
|
119
|
+
const p = record.payload;
|
|
120
|
+
if (record.type === "event_msg" && p.type === "item_completed") {
|
|
121
|
+
if (p.thread_id !== record.owner) throw new Error("Invalid Codex ItemCompleted thread identity");
|
|
122
|
+
const item = obj(p.item, "ItemCompleted.item");
|
|
123
|
+
if (toolDisplay(item)) facts.set(callKey(record, str(item.id, "TurnItem.id")), fact(item));
|
|
124
|
+
} else if (record.type === "event_msg" && p.type === "patch_apply_end") {
|
|
125
|
+
if (typeof p.success !== "boolean") throw new Error("Invalid Codex patch_apply_end.success");
|
|
126
|
+
facts.set(callKey(record, str(p.call_id, "patch call_id")), { error: !p.success });
|
|
127
|
+
} else if (record.type === "event_msg" && p.type === "mcp_tool_call_end") {
|
|
128
|
+
const result = obj(p.result, "MCP Result envelope");
|
|
129
|
+
const ok = result.Ok == null ? undefined : obj(result.Ok, "MCP Result.Ok");
|
|
130
|
+
if (ok === undefined && typeof result.Err !== "string") throw new Error("Invalid Codex MCP Result: expected Ok or Err");
|
|
131
|
+
facts.set(callKey(record, str(p.call_id, "MCP call_id")), { error: result.Err != null || ok?.isError === true, text: JSON.stringify(result) });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (const record of records) {
|
|
135
|
+
branchSeqs.add(record.seq);
|
|
136
|
+
if (record.windowId) addWindow(record.windowId, record.type === "session_meta" || record.type === "compacted" ? record.timestamp : undefined);
|
|
137
|
+
const p = record.payload;
|
|
138
|
+
let item: DecodedHistoryItem | undefined;
|
|
139
|
+
switch (record.type) {
|
|
140
|
+
case "session_meta":
|
|
141
|
+
if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
|
|
142
|
+
break;
|
|
143
|
+
case "response_item": {
|
|
144
|
+
item = response(record, facts);
|
|
145
|
+
if (p.id != null) responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
|
|
146
|
+
if (item.role === "tool_call" && item.toolCallId) {
|
|
147
|
+
if (callsSeen.has(item.toolCallId)) throw new Error(`Unavailable Codex history: duplicate native call ID ${item.toolCallId}`);
|
|
148
|
+
callsSeen.add(item.toolCallId);
|
|
149
|
+
}
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case "compacted": item = context(record, `Codex compaction boundary\n${JSON.stringify({ message: p.message, window_number: p.window_number, first_window_id: p.first_window_id, previous_window_id: p.previous_window_id, window_id: p.window_id, replacement_history_items: Array.isArray(p.replacement_history) ? p.replacement_history.length : null })}\nreplacement_history is an inference checkpoint, not new conversation events.`); break;
|
|
153
|
+
case "event_msg": {
|
|
154
|
+
const type = str(p.type, "event_msg.type");
|
|
155
|
+
if (DISPLAY_COPIES.has(type)) break;
|
|
156
|
+
// A rollback changes the native selected window retrospectively. Until its
|
|
157
|
+
// turn semantics are decoded, don't return stale-but-plausible boot facts.
|
|
158
|
+
if (type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
|
|
159
|
+
if (type === "patch_apply_end" && callsSeen.has(callKey(record, str(p.call_id, "patch call_id")))) break;
|
|
160
|
+
if (type === "mcp_tool_call_end") {
|
|
161
|
+
const call = callKey(record, str(p.call_id, "MCP call_id"));
|
|
162
|
+
if (!callsSeen.has(call)) item = host(record, "MCP completion without a recorded raw call", p);
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
if (type === "item_completed") {
|
|
166
|
+
const display = obj(p.item, "ItemCompleted.item"), kind = str(display.type, "TurnItem.type");
|
|
167
|
+
if (ITEM_COPIES.has(kind)) break;
|
|
168
|
+
if (toolDisplay(display) && callsSeen.has(callKey(record, str(display.id, "TurnItem.id")))) break;
|
|
169
|
+
if (kind === "CommandExecution" || kind === "McpToolCall") {
|
|
170
|
+
item = standaloneTool(record, display);
|
|
171
|
+
} else if (kind === "FunctionCallOutput") {
|
|
172
|
+
// hook_runtime.rs record_pending_input persists raw output FIRST,
|
|
173
|
+
// then emits this presentation copy with the SAME response-item ID.
|
|
174
|
+
if (!responseIdsSeen.has(callKey(record, str(display.id, "FunctionCallOutput.id")))) item = host(record, "FunctionCallOutput display without raw output", display);
|
|
175
|
+
} else if (HOST_ITEMS.has(kind) || kind === "DynamicToolCall") item = host(record, kind, display);
|
|
176
|
+
else throw new Error(`Unsupported Codex TurnItem: ${kind}`);
|
|
177
|
+
} else if (HOST_EVENTS.has(type)) {
|
|
178
|
+
// Lifecycle's repeated final answer isn't a second assistant message.
|
|
179
|
+
const { last_agent_message: _displayCopy, ...facts } = p;
|
|
180
|
+
item = host(record, type, facts);
|
|
181
|
+
}
|
|
182
|
+
else throw new Error(`Unsupported Codex persisted event: ${type}`);
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case "turn_context": case "token_usage_record": case "security_risk_score": case "inter_agent_communication_metadata": break;
|
|
186
|
+
case "world_state": item = context(record, "Codex world_state snapshot/patch omitted from the text projection; not a newly spoken message."); break;
|
|
187
|
+
case "inter_agent_communication": item = host(record, "inter-agent communication", { author: p.author, recipient: p.recipient, content: p.encrypted_content == null ? p.content : "[encrypted content unavailable]", trigger_turn: p.trigger_turn }); break;
|
|
188
|
+
case "retained_context": case "realtime_item": item = context(record, `Codex ${record.type} omitted from text projection; native structured/retained context is not newly spoken dialogue.`); break;
|
|
189
|
+
}
|
|
190
|
+
if (item) addWindow(record.windowId!).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
|
|
191
|
+
}
|
|
192
|
+
return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
|
|
193
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** A read-only history corpus: identity/discovery is separate from loading a projection. */
|
|
2
|
+
import { failure, success, type Outcome } from "../tools/result.js";
|
|
3
|
+
import type { HistoryProjection } from "./history.js";
|
|
4
|
+
|
|
5
|
+
export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
|
|
6
|
+
export type HistorySessionData = { projection: HistoryProjection; notice?: string };
|
|
7
|
+
export type HistorySession = {
|
|
8
|
+
harness: HistoryHarness;
|
|
9
|
+
id: string;
|
|
10
|
+
modifiedAt: number;
|
|
11
|
+
load(): Promise<HistorySessionData>;
|
|
12
|
+
};
|
|
13
|
+
export type HistoryCorpus = {
|
|
14
|
+
currentHarness: HistoryHarness;
|
|
15
|
+
sessions(harness?: HistoryHarness): Promise<HistorySession[]>;
|
|
16
|
+
};
|
|
17
|
+
/** A lazy current projection preserves native host checks, without requiring it for a foreign read. */
|
|
18
|
+
export type HistoryContext = HistoryProjection | { current(): HistoryProjection | Promise<HistoryProjection>; corpus: HistoryCorpus };
|
|
19
|
+
export type SessionSelector = { harness?: HistoryHarness; id: string; wildcard: boolean };
|
|
20
|
+
const HARNESSES = new Set<string>(["pi", "claude", "codex", "dsh"]);
|
|
21
|
+
|
|
22
|
+
export function sessionIdentity(session: Pick<HistorySession, "harness" | "id">): string {
|
|
23
|
+
return `${session.harness}:${session.id}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function parseSessionSelector(value: string): Outcome<SessionSelector> {
|
|
27
|
+
const colon = value.indexOf(":");
|
|
28
|
+
const harness = colon < 0 ? undefined : value.slice(0, colon);
|
|
29
|
+
const id = colon < 0 ? value : value.slice(colon + 1);
|
|
30
|
+
if (id.length === 0 || id.includes(":") || (harness !== undefined && !HARNESSES.has(harness))) {
|
|
31
|
+
return failure("invalid_session", "Pass a session ID or prefix, optionally prefixed by pi:, claude:, codex:, or dsh:.");
|
|
32
|
+
}
|
|
33
|
+
return success({ ...(harness === undefined ? {} : { harness: harness as HistoryHarness }), id, wildcard: id.includes("*") });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** '*' is the only metacharacter; all other characters match literally. */
|
|
37
|
+
export function matchesSession(session: HistorySession, selector: SessionSelector): boolean {
|
|
38
|
+
if (selector.harness !== undefined && selector.harness !== session.harness) return false;
|
|
39
|
+
const escaped = selector.id.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
40
|
+
return new RegExp(`^${escaped}$`).test(session.id);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>> {
|
|
44
|
+
if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
|
|
45
|
+
const matching = (pool: HistorySession[]) => {
|
|
46
|
+
const exact = pool.filter((session) => session.id === selector.id);
|
|
47
|
+
return exact.length ? exact : pool.filter((session) => session.id.startsWith(selector.id));
|
|
48
|
+
};
|
|
49
|
+
let matches: HistorySession[];
|
|
50
|
+
if (selector.harness !== undefined) matches = matching((await corpus.sessions(selector.harness)).filter((session) => session.harness === selector.harness));
|
|
51
|
+
else {
|
|
52
|
+
matches = matching((await corpus.sessions(corpus.currentHarness)).filter((session) => session.harness === corpus.currentHarness));
|
|
53
|
+
if (matches.length === 0) matches = matching((await corpus.sessions()).filter((session) => session.harness !== corpus.currentHarness));
|
|
54
|
+
}
|
|
55
|
+
if (matches.length === 0) return failure("unknown_session", `No local session matches ${JSON.stringify(selector.harness ? `${selector.harness}:${selector.id}` : selector.id)}.`);
|
|
56
|
+
if (matches.length > 1) return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
|
|
57
|
+
return success(matches[0]!);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>> {
|
|
61
|
+
try { return success(await session.load()); }
|
|
62
|
+
catch (error) {
|
|
63
|
+
return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function currentHistory(context: HistoryContext): HistoryProjection | Promise<HistoryProjection> {
|
|
68
|
+
return "current" in context ? context.current() : context;
|
|
69
|
+
}
|
package/src/history/history.ts
CHANGED
|
@@ -45,8 +45,8 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
|
|
|
45
45
|
|
|
46
46
|
/** Paired result seqs stay on the branch but redirect readers to the call's event. */
|
|
47
47
|
export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
|
|
48
|
-
/** The filters one selection applies before paging:
|
|
49
|
-
export type HistoryFilter = {
|
|
48
|
+
/** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
|
|
49
|
+
export type HistoryFilter = { roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
|
|
50
50
|
|
|
51
51
|
/** Native entries after the adapter allocates seqs and selects the active branch. */
|
|
52
52
|
export type DecodedHistoryItem = {
|
|
@@ -209,8 +209,8 @@ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<
|
|
|
209
209
|
|
|
210
210
|
/** Stable identity and a verbatim preview, starting at the search match when present. */
|
|
211
211
|
export const HistoryPageItemSchema = Type.Object({
|
|
212
|
+
session: Type.Optional(Type.String()),
|
|
212
213
|
seq: Type.Integer({ minimum: 1 }),
|
|
213
|
-
window_id: Type.String(),
|
|
214
214
|
role: HistoryRoleSchema,
|
|
215
215
|
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
216
216
|
...ToolSummarySchema.properties,
|
|
@@ -222,6 +222,7 @@ export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
|
|
|
222
222
|
|
|
223
223
|
/** A run of tool/context events the conversation view replaces with counts. */
|
|
224
224
|
export const HistoryFoldedRowSchema = Type.Object({
|
|
225
|
+
session: Type.Optional(Type.String()),
|
|
225
226
|
folded: Type.Literal(true),
|
|
226
227
|
first_seq: Type.Integer({ minimum: 1 }),
|
|
227
228
|
last_seq: Type.Integer({ minimum: 1 }),
|
|
@@ -246,7 +247,6 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
|
|
|
246
247
|
const truncated = start > 0 || start + limit < chars.length;
|
|
247
248
|
return {
|
|
248
249
|
seq: event.seq,
|
|
249
|
-
window_id: event.windowId,
|
|
250
250
|
role: event.role,
|
|
251
251
|
created_at: event.createdAt ?? null,
|
|
252
252
|
...toolSummary(event),
|
|
@@ -260,19 +260,12 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
|
|
|
260
260
|
return projection.windows.flatMap((current) => current.items);
|
|
261
261
|
}
|
|
262
262
|
|
|
263
|
-
export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
|
|
264
|
-
if (typeof params.window_id !== "string") return undefined;
|
|
265
|
-
const known = projection.windows.map((current) => current.windowId);
|
|
266
|
-
return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
|
|
267
|
-
}
|
|
268
|
-
|
|
269
263
|
/**
|
|
270
|
-
* Whether one event is inside the selection: its
|
|
264
|
+
* Whether one event is inside the selection: its seq bounds, and a half-open
|
|
271
265
|
* [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
|
|
272
266
|
* time or a time that cannot be read.
|
|
273
267
|
*/
|
|
274
268
|
export function inSelection(event: HistoryEvent, params: HistoryFilter): boolean {
|
|
275
|
-
if (typeof params.window_id === "string" && params.window_id !== event.windowId) return false;
|
|
276
269
|
if (params.after_seq !== undefined && event.seq <= params.after_seq) return false;
|
|
277
270
|
if (params.before_seq !== undefined && event.seq >= params.before_seq) return false;
|
|
278
271
|
if (params.sinceMs === undefined && params.untilMs === undefined) return true;
|