@parcha/agentrun-import 0.0.0-bootstrap.0 → 0.1.0-beta.55

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/dist/read.js ADDED
@@ -0,0 +1,54 @@
1
+ import { lstat, stat } from "node:fs/promises";
2
+ import { READERS } from "./readers/index.js";
3
+ /** The reader of `source` among `readers`; one that is not there throws. */
4
+ export function readerOf(source, readers = READERS) {
5
+ const reader = readers[source];
6
+ if (!reader)
7
+ throw new Error(`no reader for the source ${source}`);
8
+ return reader;
9
+ }
10
+ /** The locators of `source` under `home`, by path, never through a link (a file that is not a regular file is dropped). */
11
+ export async function sessionLocators(home, source, { env, readers } = {}) {
12
+ // A home whose source directory is itself a link is read as found (the person's own), but no file is a link.
13
+ const out = [];
14
+ const found = (await readerOf(source, readers).discover(home, env)).sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : (a.id ?? "").localeCompare(b.id ?? "")));
15
+ for (const locator of found)
16
+ if ((await lstat(locator.file).catch(() => null))?.isFile())
17
+ out.push(locator);
18
+ return out;
19
+ }
20
+ /** The locators of `source`, each with its file's stats (one gone since it was listed is passed over), in the import's
21
+ * order: the reader's (Claude Code's by project folder, oldest written first: the first file holding a copied record
22
+ * keeps it), else as they were listed. */
23
+ export async function inOrder(locators, source, readers) {
24
+ const out = [];
25
+ for (const locator of locators) {
26
+ const stats = await stat(locator.file).catch(() => null);
27
+ if (stats)
28
+ out.push({ locator, stats });
29
+ }
30
+ const order = readerOf(source, readers).order;
31
+ if (order)
32
+ out.sort((a, b) => order({ file: a.locator.file, mtimeMs: a.stats.mtimeMs }, { file: b.locator.file, mtimeMs: b.stats.mtimeMs }));
33
+ return out;
34
+ }
35
+ /** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
36
+ * (Claude Code's <session id>/subagents/). */
37
+ export async function childrenOf(home, source, { env, readers } = {}) {
38
+ return (await readerOf(source, readers).children?.(home, env)) ?? [];
39
+ }
40
+ /** The one session at `locator` (a file alone is its first session), read whole; `turns: false` keeps only what a
41
+ * listing shows. A locator whose session is not there throws. */
42
+ export async function readSession(locator, source, { readers, ...options } = {}) {
43
+ const at = typeof locator === "string" ? { file: locator } : locator;
44
+ const { sessions } = await readerOf(source, readers).read(at, undefined, { ...options, keepsCursor: false });
45
+ const found = at.id === undefined ? sessions[0] : sessions.find(({ locator }) => locator.id === at.id);
46
+ if (!found)
47
+ throw new Error(`no session ${at.id ?? ""} in ${at.file}`);
48
+ const session = found.session;
49
+ if (found.locator.id !== undefined)
50
+ session.within = found.locator.id;
51
+ return session;
52
+ }
53
+ /** Where a session read by readSession is: its file, and its id there when the file holds many. */
54
+ export const locatorOf = ({ file, within }) => (within === undefined ? { file } : { file, id: within });
@@ -0,0 +1,69 @@
1
+ import type { Dirent } from "node:fs";
2
+ import type { Answer, SessionOf, Turn } from "./types.js";
3
+ /** The environment a reader may look in for its source's own directories (CLAUDE_CONFIG_DIR, CODEX_HOME). */
4
+ export type Env = Readonly<Record<string, string | undefined>>;
5
+ /** A session's identity: the file it is in, and its id in that file where one file holds many (OpenCode's database). */
6
+ export type Locator = {
7
+ file: string;
8
+ id?: string;
9
+ };
10
+ /** A locator as one string: the file, with `#id` after it when it names one. */
11
+ export declare const locatorKey: ({ file, id }: Locator) => string;
12
+ /** One session a read found: where it is, what it is, and every request read (each counted once), whether turns are kept
13
+ * or not: what a total counts. */
14
+ export type SessionRead<S extends string = string> = {
15
+ locator: Locator;
16
+ session: SessionOf<S>;
17
+ requests: Answer[];
18
+ };
19
+ export type ReadResult<S extends string = string, C = unknown> = {
20
+ /** The locator's sessions: one for a file of one session; each in the file, or the one its id names, for a file of
21
+ * many. */
22
+ sessions: SessionRead<S>[];
23
+ /** Where a later read goes on from. The reader's own: hand it back to the same reader's read, nothing else. */
24
+ cursor: C;
25
+ /** The bytes this read took. */
26
+ read: number;
27
+ /** Whether it went on from the cursor it was handed (false: it read the locator from its start). */
28
+ resumed: boolean;
29
+ };
30
+ export type ReadOptions = {
31
+ /** false keeps only what a listing shows: no turns, nor a request's text or call arguments. */
32
+ turns?: boolean;
33
+ /** The records and requests an import has read already, across its files: a record in it (a copy a resumed session's
34
+ * file carries) adds nothing, and this read's are added to it. A cursor read with one is resumed with the same one. */
35
+ seen?: Set<string>;
36
+ /** false when the caller keeps no cursor from this read (readSession): a last line still being written then adds to
37
+ * `seen` like any other, as no later read takes it again. Default true: it is left out of `seen` until a read from
38
+ * the cursor takes it whole. */
39
+ keepsCursor?: boolean;
40
+ };
41
+ export type Reader<S extends string = string, C = unknown> = {
42
+ source: S;
43
+ /** The source's name as a person reads it. */
44
+ name: string;
45
+ /** The harness of serve that runs what the source ran. */
46
+ harness: string;
47
+ /** The candidate locators of the source under `home`, any order (`env`: where the source's own directory is named). */
48
+ discover: (home: string, env?: Env) => Promise<Locator[]>;
49
+ /** One locator read, from its start or from `cursor` (one this reader returned for the same locator). A cursor that no
50
+ * longer fits (the file replaced, truncated, rewritten) is read from the start, `resumed` false. */
51
+ read: (locator: Locator, cursor?: C, options?: ReadOptions) => Promise<ReadResult<S, C>>;
52
+ /** The import's order of the listed locators, when not their path's (a record copied into two files is the first's). */
53
+ order?: (a: {
54
+ file: string;
55
+ mtimeMs: number;
56
+ }, b: {
57
+ file: string;
58
+ mtimeMs: number;
59
+ }) => number;
60
+ /** Subagents' sessions that name no parent themselves, each with the session it ran under (`of`). */
61
+ children?: (home: string, env?: Env) => Promise<{
62
+ locator: Locator;
63
+ of: Locator;
64
+ }[]>;
65
+ };
66
+ /** A directory's entries, none when it cannot be read. */
67
+ export declare const entries: (dir: string) => Promise<Dirent[]>;
68
+ /** A user turn counted in `session`: its users, its first prompt, and the person's first words. */
69
+ export declare function rememberUser(session: SessionOf, turn: Turn): void;
package/dist/reader.js ADDED
@@ -0,0 +1,14 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { personsWords } from "./text.js";
3
+ /** A locator as one string: the file, with `#id` after it when it names one. */
4
+ export const locatorKey = ({ file, id }) => (id === undefined ? file : `${file}#${id}`);
5
+ /** A directory's entries, none when it cannot be read. */
6
+ export const entries = async (dir) => readdir(dir, { withFileTypes: true }).catch(() => []);
7
+ /** A user turn counted in `session`: its users, its first prompt, and the person's first words. */
8
+ export function rememberUser(session, turn) {
9
+ if (turn.role !== "user")
10
+ return;
11
+ session.users += 1;
12
+ session.firstPrompt ??= turn.text;
13
+ session.titleText ??= personsWords(turn.text);
14
+ }
@@ -0,0 +1,10 @@
1
+ import { type Env } from "../reader.js";
2
+ /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
3
+ * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
4
+ * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
5
+ * link. */
6
+ export declare function childFiles(home: string, env?: Env): Promise<{
7
+ file: string;
8
+ of: string;
9
+ }[]>;
10
+ export declare const claudeCode: import("../reader.js").Reader<"claude-code", import("../lines.js").FileCursor>;
@@ -0,0 +1,239 @@
1
+ // Claude Code: ~/.claude/projects/<cwd slug>/<session id>.jsonl, its subagents' in <session id>/subagents/ (children).
2
+ import { lstat } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { lineReader } from "../lines.js";
5
+ import { entries } from "../reader.js";
6
+ import { argsOf, effortOf, INTERRUPTED, isObject, str, textOf } from "../text.js";
7
+ import { normalizeUsage } from "../usage.js";
8
+ // The titles Claude Code writes into a session's file, each again as it changes, and the field each holds it in.
9
+ const TITLES = new Map([
10
+ ["custom-title", "customTitle"],
11
+ ["ai-title", "aiTitle"],
12
+ ["summary", "summary"],
13
+ ]);
14
+ /** One of Claude Code's title records: kept by kind, the latest of each. A summary names the last message of the
15
+ * conversation it titles (leafUuid), which can be another session's: held until the file's end. */
16
+ function titleRecord(value, session, titles) {
17
+ // As written: the cut matches a key or a passphrase as the source wrote it, so the title is put on one line after it.
18
+ const title = str(value[TITLES.get(value.type)])?.trim();
19
+ if (!title || (str(value.sessionId) && value.sessionId !== session.id))
20
+ return;
21
+ if (value.type === "custom-title")
22
+ titles.custom = title;
23
+ else if (value.type === "ai-title")
24
+ titles.ai = title;
25
+ else
26
+ titles.summaries.push({ title, ...(str(value.leafUuid) ? { leaf: value.leafUuid } : {}) });
27
+ }
28
+ /** A request's key: its message id with the request id it was sent as (ccusage's pair). Claude Code writes one line per
29
+ * content block of a response, each with both. */
30
+ const keyOf = (message, value) => {
31
+ const id = str(message.id);
32
+ const request = str(value.requestId);
33
+ return id && request ? `${id}:${request}` : id;
34
+ };
35
+ /** Claude Code's record; false for one read already (the import's earlier file, or this file's own repeat). */
36
+ function record(value, at, { state, seen, keep, add }) {
37
+ const { session, names, own } = state;
38
+ // Claude Code names a session's file for its id (<id>.jsonl): the file's own, whatever a record in it says. A resumed
39
+ // session's file can open with records copied from the session it resumed, each still naming that one.
40
+ if (!session.id)
41
+ session.id = basename(session.file, ".jsonl");
42
+ if (!session.cwd && str(value.cwd))
43
+ session.cwd = value.cwd;
44
+ if (value.isSidechain === true)
45
+ session.child = true;
46
+ if (TITLES.has(value.type))
47
+ return titleRecord(value, session, own.titles);
48
+ if (str(value.uuid))
49
+ own.titles.uuids.add(value.uuid);
50
+ if (value.type === "cost-state") {
51
+ // The last one is the session's: unknown when the CLI could not price a model it used.
52
+ session.costUsd = typeof value.totalCostUSD === "number" && Number.isFinite(value.totalCostUSD) && value.totalCostUSD >= 0 && value.hasUnknownModelCost !== true ? value.totalCostUSD : undefined;
53
+ return;
54
+ }
55
+ // A record written twice (a session carried on in its own file, or copied into a resumed one's) is read once, and moves
56
+ // no time a second time, whatever its type.
57
+ const uuid = str(value.uuid);
58
+ if (uuid && seen.has(`u:${uuid}`))
59
+ return false;
60
+ if (uuid)
61
+ seen.add(`u:${uuid}`);
62
+ if ((value.type !== "user" && value.type !== "assistant") || !isObject(value.message))
63
+ return;
64
+ if (value.isMeta === true || value.isCompactSummary === true || value.isVisibleInTranscriptOnly === true)
65
+ return;
66
+ const mark = uuid ? { uuids: [uuid] } : {};
67
+ const message = value.message;
68
+ if (value.type === "assistant") {
69
+ const model = str(message.model);
70
+ const synthetic = model === "<synthetic>";
71
+ if (model && !synthetic)
72
+ session.model = `anthropic/${model}`;
73
+ const blocks = Array.isArray(message.content) ? message.content : [{ type: "text", text: textOf(message.content) }];
74
+ const text = blocks
75
+ .filter((b) => isObject(b) && b.type === "text")
76
+ .map((b) => b.text)
77
+ .join("\n");
78
+ const calls = blocks
79
+ .filter((b) => isObject(b) && b.type === "tool_use")
80
+ .map((b) => ({
81
+ type: "toolCall",
82
+ id: String(b.id ?? ""),
83
+ name: String(b.name ?? ""),
84
+ arguments: keep ? argsOf(b.input) : {},
85
+ }));
86
+ for (const call of calls)
87
+ names.set(call.id, call.name);
88
+ // The CLI's own turns (model <synthetic>): one marked an API error is a request that failed; any other ("No response
89
+ // requested.") is no request, kept as the CLI's note.
90
+ const failed = value.isApiErrorMessage === true;
91
+ if (synthetic && !failed) {
92
+ if (text)
93
+ add({ role: "note", author: "Claude Code", text, at, ...mark });
94
+ return;
95
+ }
96
+ session.state = failed ? "failed" : "completed";
97
+ // One request's blocks come as lines of one key, a parallel call's result between two of them: one turn. Each line
98
+ // repeats the request's usage, and the last one written holds its final counts (an earlier one may hold only the
99
+ // stream's start): the last line's usage is the request's.
100
+ const key = keyOf(message, value);
101
+ const usage = normalizeUsage("anthropic", message.usage);
102
+ const held = key ? own.keyed.get(key) : undefined;
103
+ if (held) {
104
+ if (keep)
105
+ held.text = [held.text, text].filter(Boolean).join("\n");
106
+ held.calls.push(...calls);
107
+ if (uuid)
108
+ held.uuids = [...(held.uuids ?? []), uuid];
109
+ if (usage)
110
+ held.usage = usage;
111
+ return;
112
+ }
113
+ // A request an earlier file of the import holds: counted there, never again; its calls' results are copies too. A
114
+ // store imported before requests were keyed by message and request id holds the bare message id ("l:", serve's).
115
+ if (key && (seen.has(`m:${key}`) || (str(message.id) && seen.has(`l:${message.id}`)))) {
116
+ for (const call of calls)
117
+ own.copied.add(call.id);
118
+ return false;
119
+ }
120
+ if (!key && !text && calls.length === 0)
121
+ return;
122
+ const effort = effortOf(value.perTurnEffort) ?? effortOf(value.effort);
123
+ // Without turns, no answer text: the request is kept for its counts, in the result and the cursor alike.
124
+ const turn = { role: "assistant", text: keep ? text : "", calls, at, ...(key ? { key } : {}), ...(session.model ? { model: session.model } : {}), ...(effort ? { effort } : {}), ...(usage ? { usage } : {}), ...(failed ? { error: text || "API error" } : {}), ...mark };
125
+ if (key) {
126
+ own.keyed.set(key, turn);
127
+ seen.add(`m:${key}`);
128
+ }
129
+ add(turn);
130
+ return;
131
+ }
132
+ if (typeof message.content === "string") {
133
+ if (INTERRUPTED.test(message.content))
134
+ session.state = "stopped";
135
+ else
136
+ session.state = "completed";
137
+ return add({ role: "user", text: message.content, at, ...mark });
138
+ }
139
+ if (!Array.isArray(message.content))
140
+ return;
141
+ const said = [];
142
+ let results = 0;
143
+ let copies = 0;
144
+ for (const block of message.content) {
145
+ if (!isObject(block))
146
+ continue;
147
+ if (block.type === "text" && typeof block.text === "string")
148
+ said.push(block.text);
149
+ else if (block.type === "tool_result") {
150
+ const id = String(block.tool_use_id ?? "");
151
+ results += 1;
152
+ if (own.copied.has(id)) {
153
+ copies += 1;
154
+ continue;
155
+ }
156
+ add({
157
+ role: "toolResult",
158
+ callId: id,
159
+ name: names.get(id) ?? "",
160
+ text: textOf(block.content),
161
+ isError: block.is_error === true,
162
+ at,
163
+ ...mark,
164
+ });
165
+ }
166
+ }
167
+ if (said.length) {
168
+ const text = said.join("\n");
169
+ session.state = INTERRUPTED.test(text) ? "stopped" : "completed";
170
+ add({ role: "user", text, at, ...mark });
171
+ }
172
+ // Results of copied calls alone: a copy, which moves no time either.
173
+ if (results > 0 && copies === results && !said.length)
174
+ return false;
175
+ }
176
+ /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
177
+ * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
178
+ * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
179
+ * link. */
180
+ export async function childFiles(home, env) {
181
+ const root = join(configDir(home, env), "projects");
182
+ const out = [];
183
+ for (const project of await entries(root)) {
184
+ if (!project.isDirectory())
185
+ continue;
186
+ for (const session of await entries(join(root, project.name))) {
187
+ if (!session.isDirectory())
188
+ continue;
189
+ const walk = async (dir, depth) => {
190
+ for (const entry of await entries(dir)) {
191
+ if (entry.isDirectory() && depth < 3)
192
+ await walk(join(dir, entry.name), depth + 1);
193
+ else if (entry.isFile() && entry.name.endsWith(".jsonl"))
194
+ out.push({ file: join(dir, entry.name), of: join(root, project.name, `${session.name}.jsonl`) });
195
+ }
196
+ };
197
+ // The folder itself is no link: one that points elsewhere holds no subagent of this session's.
198
+ const subagents = join(root, project.name, session.name, "subagents");
199
+ if ((await lstat(subagents).catch(() => null))?.isDirectory())
200
+ await walk(subagents, 0);
201
+ }
202
+ }
203
+ return out.sort((a, b) => a.file.localeCompare(b.file));
204
+ }
205
+ /** Claude Code's own directory: CLAUDE_CONFIG_DIR where the environment names it, else ~/.claude. */
206
+ const configDir = (home, env) => env?.CLAUDE_CONFIG_DIR || join(home, ".claude");
207
+ const spec = {
208
+ source: "claude-code",
209
+ name: "Claude Code",
210
+ harness: "claude-agent",
211
+ async files(home, env) {
212
+ const root = join(configDir(home, env), "projects");
213
+ const out = [];
214
+ for (const project of await entries(root)) {
215
+ if (!project.isDirectory())
216
+ continue;
217
+ for (const file of await entries(join(root, project.name)))
218
+ if (file.isFile() && file.name.endsWith(".jsonl"))
219
+ out.push(join(root, project.name, file.name));
220
+ }
221
+ return out;
222
+ },
223
+ // By project folder, oldest written first: the first file holding a copied record keeps it.
224
+ order: (a, b) => dirname(a.file).localeCompare(dirname(b.file)) || a.mtimeMs - b.mtimeMs || a.file.localeCompare(b.file),
225
+ children: childFiles,
226
+ start: () => ({ keyed: new Map(), copied: new Set(), titles: { summaries: [], uuids: new Set() } }),
227
+ record,
228
+ finish(out, turns, { state: { own } }) {
229
+ const { titles } = own;
230
+ const sourceTitle = titles.custom ?? titles.ai ?? titles.summaries.findLast(({ leaf }) => leaf === undefined || titles.uuids.has(leaf))?.title;
231
+ if (sourceTitle)
232
+ out.sourceTitle = sourceTitle;
233
+ return turns;
234
+ },
235
+ idOf: (file) => basename(file, ".jsonl"),
236
+ // A turns: false cursor keeps no title: a read resumed from it gives none.
237
+ forget: (own) => ({ ...own, titles: { summaries: [], uuids: new Set() } }),
238
+ };
239
+ export const claudeCode = lineReader(spec);
@@ -0,0 +1 @@
1
+ export declare const codex: import("../reader.js").Reader<"codex", import("../lines.js").FileCursor>;
@@ -0,0 +1,242 @@
1
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. A subagent's thread names its parent in its session_meta.
2
+ import { basename, join } from "node:path";
3
+ import { lineReader } from "../lines.js";
4
+ import { entries, rememberUser } from "../reader.js";
5
+ import { argsOf, effortOf, isObject, str, textOf } from "../text.js";
6
+ import { normalizeUsage } from "../usage.js";
7
+ // The blocks the Codex CLI adds to a user message, each one of its own elements whole, an AGENTS.md as a heading over its
8
+ // <INSTRUCTIONS>; and the bare tags around an image. Only these: a prompt the person wrote as a tagged element is theirs,
9
+ // and a block the CLI adds later reads as text until it is named here.
10
+ const CODEX_BLOCK = /^\s*(?:#[^\n]*\n\s*)?<([A-Za-z_]+)(?:\s[^>]*)?>[\s\S]*<\/\1>\s*$/;
11
+ const CODEX_BLOCKS = new Set(["environment_context", "user_instructions", "INSTRUCTIONS", "turn_aborted", "subagent_notification", "skill", "user_shell_command", "user_action", "recommended_plugins", "codex_internal_context"]);
12
+ const IMAGE_TAG = /^\s*<\/?image\b[^>]*>\s*$/;
13
+ const typed = (text) => !CODEX_BLOCKS.has(CODEX_BLOCK.exec(text)?.[1] ?? "") && !IMAGE_TAG.test(text);
14
+ /** The person's words in a Codex user message: "" when the CLI wrote all of it. */
15
+ const wordsOf = (content) => textOf(Array.isArray(content) ? content.filter((block) => !isObject(block) || typeof block.text !== "string" || typed(block.text)) : content);
16
+ // The response items of the model's own output: each of one request, until its usage comes.
17
+ const CODEX_OUTPUTS = new Set(["reasoning", "function_call", "custom_tool_call", "web_search_call", "tool_search_call"]);
18
+ const CODEX_HEAD = /^(?:Command|Chunk ID|Exit code): /;
19
+ const CODEX_EXIT = /^(?:Exit code: |Process exited with code )(-?\d+)$/;
20
+ /** Whether a Codex tool call failed, as its output says, else undefined: a structured output's success flag or
21
+ * metadata.exit_code, the exit code in a shell call's head (the lines before "Output:"), or how a script ended. */
22
+ function codexFailed(output) {
23
+ if (isObject(output) && typeof output.success === "boolean")
24
+ return !output.success;
25
+ const text = textOf(isObject(output) && "content" in output ? output.content : output);
26
+ if (text.startsWith("{")) {
27
+ try {
28
+ const parsed = JSON.parse(text);
29
+ if (isObject(parsed) && isObject(parsed.metadata) && typeof parsed.metadata.exit_code === "number")
30
+ return parsed.metadata.exit_code !== 0;
31
+ }
32
+ catch {
33
+ // Not JSON: read as text.
34
+ }
35
+ }
36
+ const lines = text.split("\n", 64);
37
+ if (/^Script failed\b/.test(lines[0]))
38
+ return true;
39
+ if (/^Script completed\b/.test(lines[0]))
40
+ return false;
41
+ if (!CODEX_HEAD.test(lines[0]))
42
+ return undefined;
43
+ for (const line of lines) {
44
+ if (line === "Output:")
45
+ break;
46
+ const code = CODEX_EXIT.exec(line)?.[1];
47
+ if (code !== undefined)
48
+ return code !== "0";
49
+ }
50
+ return undefined;
51
+ }
52
+ function record(value, at, { state, keep, add }) {
53
+ const { session, names, turns, own: codex } = state;
54
+ const payload = isObject(value.payload) ? value.payload : {};
55
+ // One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
56
+ // compaction's, one whose output is no item read here) is a turn of its own.
57
+ const answer = () => {
58
+ const turn = { role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) };
59
+ add(turn);
60
+ return turn;
61
+ };
62
+ const request = () => codex.open ?? (codex.open = codex.unpaid = answer());
63
+ // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
64
+ const answered = (usage, response) => {
65
+ const tokens = normalizeUsage("openai", usage);
66
+ const turn = codex.unpaid ?? answer();
67
+ if (tokens)
68
+ turn.usage = tokens;
69
+ if (response)
70
+ turn.key = response;
71
+ codex.open = codex.unpaid = undefined;
72
+ };
73
+ if (value.type === "session_meta") {
74
+ if (str(payload.id))
75
+ session.id = payload.id;
76
+ if (str(payload.cwd))
77
+ session.cwd = payload.cwd;
78
+ if (str(payload.model_provider))
79
+ codex.provider = payload.model_provider;
80
+ if (str(payload.parent_thread_id) || (isObject(payload.source) && isObject(payload.source.subagent)))
81
+ session.child = true;
82
+ const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
83
+ const parent = str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
84
+ if (parent)
85
+ session.parent = parent;
86
+ return;
87
+ }
88
+ if (value.type === "turn_context") {
89
+ const model = str(payload.model);
90
+ if (model)
91
+ session.model = model.includes("/") ? model : `${codex.provider ?? "openai"}/${model}`;
92
+ if (!session.cwd && str(payload.cwd))
93
+ session.cwd = payload.cwd;
94
+ state.effort = effortOf(payload.effort);
95
+ // A new turn: a request left open (aborted) has no usage to come.
96
+ codex.open = codex.unpaid = undefined;
97
+ return;
98
+ }
99
+ // Each request's usage: a token_usage_record per response where the rollout has them (they also count requests no
100
+ // token_count reports, such as a compaction's), else each token_count whose total moved (one that repeats the last
101
+ // total is no new request).
102
+ if (value.type === "token_usage_record") {
103
+ codex.records = true;
104
+ const id = str(payload.response_id);
105
+ if (id && codex.responses.has(id))
106
+ return;
107
+ if (id)
108
+ codex.responses.add(id);
109
+ return answered(payload.usage, id);
110
+ }
111
+ if (value.type === "event_msg") {
112
+ if (payload.type === "user_message") {
113
+ codex.events = true;
114
+ if (str(payload.message))
115
+ add({ role: "user", text: payload.message, at });
116
+ }
117
+ else if (payload.type === "token_count") {
118
+ const info = isObject(payload.info) ? payload.info : undefined;
119
+ if (!info || codex.records)
120
+ return;
121
+ const total = isObject(info.total_token_usage) ? JSON.stringify(info.total_token_usage) : undefined;
122
+ if (total !== undefined && total === codex.total)
123
+ return;
124
+ codex.total = total;
125
+ answered(info.last_token_usage);
126
+ }
127
+ else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
128
+ // An item's id is its call's in some Codex versions: its status then says whether the call failed.
129
+ const { id, status, exit_code: code } = payload.item;
130
+ const failed = status === "failed" || (typeof code === "number" && code !== 0) ? true : status === "completed" ? false : undefined;
131
+ if (failed === undefined)
132
+ return;
133
+ codex.items.set(id, failed);
134
+ const result = codex.results.get(id);
135
+ if (result && !result.stated)
136
+ result.turn.isError = failed;
137
+ }
138
+ else if (payload.type === "task_complete")
139
+ session.state = "completed";
140
+ else if (payload.type === "turn_aborted")
141
+ session.state = "stopped";
142
+ else if (payload.type === "error")
143
+ session.state = "failed";
144
+ return;
145
+ }
146
+ if (value.type !== "response_item")
147
+ return;
148
+ if (payload.type === "message" && payload.role === "user") {
149
+ const text = wordsOf(payload.content);
150
+ if (text)
151
+ codex.held.push({ index: turns.length, turn: { role: "user", text, at } });
152
+ }
153
+ else if (payload.type === "message" && payload.role === "assistant") {
154
+ const text = textOf(payload.content);
155
+ if (text) {
156
+ const turn = request();
157
+ if (keep)
158
+ turn.text = [turn.text, text].filter(Boolean).join("\n");
159
+ }
160
+ }
161
+ else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
162
+ const turn = request();
163
+ if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
164
+ return;
165
+ const id = String(payload.call_id ?? payload.id ?? "");
166
+ const name = String(payload.name ?? "");
167
+ names.set(id, name);
168
+ turn.calls.push({
169
+ type: "toolCall",
170
+ id,
171
+ name,
172
+ arguments: keep ? argsOf(payload.type === "function_call" ? payload.arguments : payload.input) : {},
173
+ });
174
+ }
175
+ else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
176
+ const id = String(payload.call_id ?? "");
177
+ const output = isObject(payload.output) && "content" in payload.output ? payload.output.content : payload.output;
178
+ const stated = codexFailed(payload.output);
179
+ // The model saw a result: what it writes next is another request.
180
+ if (codex.open?.calls.some((call) => call.id === id))
181
+ codex.open = undefined;
182
+ const turn = {
183
+ role: "toolResult",
184
+ callId: id,
185
+ name: names.get(id) ?? "",
186
+ // Without turns, no output text: the result is kept for whether it failed, in the result and the cursor alike.
187
+ text: keep ? textOf(output) : "",
188
+ isError: stated ?? codex.items.get(id) ?? false,
189
+ at,
190
+ };
191
+ codex.results.set(id, { turn, stated: stated !== undefined });
192
+ add(turn);
193
+ }
194
+ }
195
+ const spec = {
196
+ source: "codex",
197
+ name: "Codex",
198
+ harness: "codex",
199
+ async files(home, env) {
200
+ const out = [];
201
+ const walk = async (dir, depth) => {
202
+ for (const entry of await entries(dir)) {
203
+ if (entry.isDirectory() && depth < 3)
204
+ await walk(join(dir, entry.name), depth + 1);
205
+ else if (entry.isFile() && depth === 3 && /^rollout-.*\.jsonl$/.test(entry.name))
206
+ out.push(join(dir, entry.name));
207
+ }
208
+ };
209
+ // CODEX_HOME where the environment names it, else ~/.codex.
210
+ await walk(join(env?.CODEX_HOME || join(home, ".codex"), "sessions"), 0);
211
+ return out;
212
+ },
213
+ start: () => ({ events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() }),
214
+ record,
215
+ // Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
216
+ // writes the user message alone. One source per file, so no turn counts twice.
217
+ finish(out, turns, { state: { own }, keep }) {
218
+ if (own.events || !own.held.length)
219
+ return turns;
220
+ // Held indexes refer to the non-user turns as read. Merge both ordered lists once: inserting each user into the middle
221
+ // of the transcript shifts its remaining turns again and again on a long current-Codex session.
222
+ const ordered = [];
223
+ let next = 0;
224
+ for (const { index, turn } of own.held) {
225
+ rememberUser(out, turn);
226
+ if (keep) {
227
+ while (next < index)
228
+ ordered.push(turns[next++]);
229
+ ordered.push(turn);
230
+ }
231
+ }
232
+ if (!keep)
233
+ return turns;
234
+ while (next < turns.length)
235
+ ordered.push(turns[next++]);
236
+ return ordered;
237
+ },
238
+ idOf: (file) => basename(file, ".jsonl"),
239
+ // A turns: false cursor keeps each held prompt for its count alone: a read resumed from it gives no first prompt.
240
+ forget: (own) => ({ ...own, held: own.held.map(({ index, turn }) => ({ index, turn: { ...turn, text: "" } })) }),
241
+ };
242
+ export const codex = lineReader(spec);
@@ -0,0 +1,12 @@
1
+ import type { Reader } from "../reader.js";
2
+ export declare const READERS: {
3
+ readonly "claude-code": Reader<"claude-code", import("../lines.js").FileCursor>;
4
+ readonly codex: Reader<"codex", import("../lines.js").FileCursor>;
5
+ readonly pi: Reader<"pi", import("../lines.js").FileCursor>;
6
+ };
7
+ export type Source = keyof typeof READERS;
8
+ export declare const SOURCES: Source[];
9
+ /** The harness of serve that runs what each source ran. */
10
+ export declare const HARNESS_OF: Record<Source, string>;
11
+ /** Each source's name as a person reads it. */
12
+ export declare const SOURCE_NAMES: Record<Source, string>;
@@ -0,0 +1,13 @@
1
+ import { claudeCode } from "./claude-code.js";
2
+ import { codex } from "./codex.js";
3
+ import { pi } from "./pi.js";
4
+ export const READERS = {
5
+ "claude-code": claudeCode,
6
+ codex,
7
+ pi,
8
+ };
9
+ export const SOURCES = Object.keys(READERS);
10
+ /** The harness of serve that runs what each source ran. */
11
+ export const HARNESS_OF = Object.fromEntries(SOURCES.map((source) => [source, READERS[source].harness]));
12
+ /** Each source's name as a person reads it. */
13
+ export const SOURCE_NAMES = Object.fromEntries(SOURCES.map((source) => [source, READERS[source].name]));