@parcha/agentrun-import 0.1.0-beta.59 → 0.1.0-beta.61

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.
@@ -4,9 +4,9 @@ import { basename, dirname, join } from "node:path";
4
4
  import { addRequest, setUsage } from "../counts.js";
5
5
  import { lineReader } from "../lines.js";
6
6
  import { entries } from "../reader.js";
7
- import { addRecord, ownerOf, recordIndex } from "../record-index.js";
7
+ import { addNew, ownerOf, recordIndex } from "../record-index.js";
8
8
  import { packed, packInto } from "../record-key.js";
9
- import { argsOf, effortOf, FAILED, INTERRUPTED, isObject, str, textOf } from "../text.js";
9
+ import { argsOf, effortOf, FAILED, hashOf, INTERRUPTED, isObject, str, textOf } from "../text.js";
10
10
  import { normalizeUsage } from "../usage.js";
11
11
  // The titles Claude Code writes into a session's file, each again as it changes, and the field each holds it in.
12
12
  const TITLES = new Map([
@@ -37,7 +37,21 @@ const keyOf = (message, value) => {
37
37
  };
38
38
  const PACKED = packed();
39
39
  /** Claude Code's record; false for one read already (the import's earlier file, or this file's own repeat). */
40
- function record(value, at, { state, seen, keep, add }) {
40
+ /** A record of the conversation as the chain holds it (ChainRecord): its uuid, its parent's, a hash of what it put in the
41
+ * conversation, and whether it is a compaction (a compact_boundary, which starts a new chain, or the summary after it)
42
+ * or a sidechain's. Each record the file holds, a copy too: a later record's chain runs through it. */
43
+ const linkOf = (value, uuid) => {
44
+ const message = isObject(value.message) ? value.message : undefined;
45
+ const compact = value.isCompactSummary === true || (value.type === "system" && value.subtype === "compact_boundary");
46
+ return {
47
+ id: uuid,
48
+ ...(str(value.parentUuid) ? { parent: value.parentUuid } : {}),
49
+ hash: hashOf([value.type, value.subtype ?? null, message ? [message.role, message.content] : (value.content ?? value.attachment ?? null)]),
50
+ ...(compact ? { compact: true } : {}),
51
+ ...(value.isSidechain === true ? { sidechain: true } : {}),
52
+ };
53
+ };
54
+ function record(value, at, { state, seen, keep, add, chain }) {
41
55
  const { session, names, own, counts } = state;
42
56
  // Claude Code names a session's file for its id (<id>.jsonl): the file's own, whatever a record in it says. A resumed
43
57
  // session's file can open with records copied from the session it resumed, each still naming that one.
@@ -60,8 +74,16 @@ function record(value, at, { state, seen, keep, add }) {
60
74
  // A record written twice (a session carried on in its own file, or copied into a resumed one's) is read once, and moves
61
75
  // no time a second time, whatever its type.
62
76
  const uuid = str(value.uuid);
63
- if (uuid && seen.has(`u:${uuid}`))
77
+ const link = chain && uuid ? linkOf(value, uuid) : undefined;
78
+ if (link)
79
+ chain.push(link);
80
+ if (uuid && seen.has(`u:${uuid}`)) {
81
+ // A copy is in the chain (a later record's runs through it), but happened in the earlier file: a compaction it
82
+ // repeats is no evidence for a break in this one.
83
+ if (link)
84
+ link.copy = true;
64
85
  return false;
86
+ }
65
87
  if (uuid)
66
88
  seen.add(`u:${uuid}`);
67
89
  if ((value.type !== "user" && value.type !== "assistant") || !isObject(value.message))
@@ -106,32 +128,13 @@ function record(value, at, { state, seen, keep, add }) {
106
128
  // stream's start): the last line's usage is the request's.
107
129
  const key = keyOf(message, value);
108
130
  const usage = normalizeUsage("anthropic", message.usage);
109
- if (counts) {
110
- // A totals read: the request's model, usage and time alone, its later lines' usage over it, as below.
111
- // Started small: a session's file often holds a request or two, and its cursor keeps the index.
112
- const indexes = (own.indexes ??= recordIndex(2));
113
- const packed = key ? packInto(key, PACKED) : undefined;
114
- const index = packed ? ownerOf(indexes, packed) : -1;
115
- if (index !== -1) {
116
- if (usage)
117
- setUsage(counts, index, usage);
118
- return;
119
- }
120
- if (key && (seen.has(`m:${key}`) || (str(message.id) && seen.has(`l:${message.id}`)))) {
121
- for (const call of calls)
122
- own.copied.add(call.id);
123
- return false;
124
- }
125
- if (!key && !text && calls.length === 0)
126
- return;
127
- const added = addRequest(counts, session.model, usage, at);
128
- if (packed) {
129
- addRecord(indexes, packed, added);
130
- seen.add(`m:${key}`);
131
- }
132
- return;
133
- }
134
- const held = key ? own.keyed.get(key) : undefined;
131
+ // A request this file holds already, by its key: as its Answer, or a totals read's as its index in its counts (its
132
+ // model, usage and time alone), by its key packed. Started small: a session's file often holds a request or two, and
133
+ // its cursor keeps the index.
134
+ const indexes = counts ? (own.indexes ??= recordIndex(2)) : undefined;
135
+ const packed = indexes && key ? packInto(key, PACKED) : undefined;
136
+ const index = packed ? ownerOf(indexes, packed) : -1;
137
+ const held = key && !counts ? own.keyed.get(key) : undefined;
135
138
  if (held) {
136
139
  if (keep)
137
140
  held.text = [held.text, text].filter(Boolean).join("\n");
@@ -142,6 +145,11 @@ function record(value, at, { state, seen, keep, add }) {
142
145
  held.usage = usage;
143
146
  return;
144
147
  }
148
+ if (index !== -1) {
149
+ if (usage)
150
+ setUsage(counts, index, usage);
151
+ return;
152
+ }
145
153
  // A request an earlier file of the import holds: counted there, never again; its calls' results are copies too. A
146
154
  // store imported before requests were keyed by message and request id holds the bare message id ("l:", serve's).
147
155
  if (key && (seen.has(`m:${key}`) || (str(message.id) && seen.has(`l:${message.id}`)))) {
@@ -151,14 +159,24 @@ function record(value, at, { state, seen, keep, add }) {
151
159
  }
152
160
  if (!key && !text && calls.length === 0)
153
161
  return;
154
- const effort = effortOf(value.perTurnEffort) ?? effortOf(value.effort);
155
- // Without turns, no answer text: the request is kept for its counts, in the result and the cursor alike.
156
- const turn = { role: "assistant", text: keep ? text : "", calls, at, ...(key ? { key } : {}), ...(session.model ? { model: session.model } : {}), ...(effort ? { effort } : {}), ...(usage ? { usage } : {}), ...(failed ? { error: keep ? text || "API error" : FAILED } : {}), ...mark };
157
- if (key) {
158
- own.keyed.set(key, turn);
159
- seen.add(`m:${key}`);
162
+ if (counts) {
163
+ const added = addRequest(counts, session.model, usage, at);
164
+ // ownerOf found none above, and nothing has been added to this file's index since.
165
+ if (packed)
166
+ addNew(indexes, packed, added);
167
+ }
168
+ else {
169
+ const effort = effortOf(value.perTurnEffort) ?? effortOf(value.effort);
170
+ // Without turns, no answer text: the request is kept for its counts, in the result and the cursor alike.
171
+ const turn = { role: "assistant", text: keep ? text : "", calls, at, ...(key ? { key } : {}), ...(session.model ? { model: session.model } : {}), ...(effort ? { effort } : {}), ...(usage ? { usage } : {}), ...(failed ? { error: keep ? text || "API error" : FAILED } : {}), ...mark };
172
+ if (key)
173
+ own.keyed.set(key, turn);
174
+ add(turn);
175
+ if (link)
176
+ link.request = state.answers.length - 1;
160
177
  }
161
- add(turn);
178
+ if (key)
179
+ seen.add(`m:${key}`);
162
180
  return;
163
181
  }
164
182
  if (typeof message.content === "string") {
@@ -236,6 +254,25 @@ export async function childFiles(home, env) {
236
254
  }
237
255
  /** Claude Code's own directory: CLAUDE_CONFIG_DIR where the environment names it, else ~/.claude. */
238
256
  const configDir = (home, env) => env?.CLAUDE_CONFIG_DIR || join(home, ".claude");
257
+ /** The counts normalizeUsage takes from Anthropic's usage (usage.ts). */
258
+ const USAGE = { input_tokens: true, output_tokens: true, cache_read_input_tokens: true, cache_creation_input_tokens: true, cache_creation: { ephemeral_1h_input_tokens: true } };
259
+ /** What record reads of a line in a totals read (LineSource.fields). A tool_result's content is left out: it is only the
260
+ * result's turn's text, which a totals read keeps none of; so are a tool_use's input (its call's arguments, kept only
261
+ * with turns), a thinking block's text, and every field record reads only with turns (titles, efforts). */
262
+ const FIELDS = {
263
+ cwd: true,
264
+ isSidechain: true,
265
+ type: true,
266
+ uuid: true,
267
+ totalCostUSD: true,
268
+ hasUnknownModelCost: true,
269
+ isMeta: true,
270
+ isCompactSummary: true,
271
+ isVisibleInTranscriptOnly: true,
272
+ isApiErrorMessage: true,
273
+ requestId: true,
274
+ message: { model: true, id: true, usage: USAGE, content: [{ type: true, text: true, id: true, name: true, tool_use_id: true, is_error: true }] },
275
+ };
239
276
  const spec = {
240
277
  source: "claude-code",
241
278
  name: "Claude Code",
@@ -258,6 +295,7 @@ const spec = {
258
295
  start: () => ({ keyed: new Map(), copied: new Set(), titles: { summaries: [], uuids: new Set() } }),
259
296
  record,
260
297
  totals: true,
298
+ fields: FIELDS,
261
299
  finish(out, turns, { state: { own } }) {
262
300
  const { titles } = own;
263
301
  const sourceTitle = titles.custom ?? titles.ai ?? titles.summaries.findLast(({ leaf }) => leaf === undefined || titles.uuids.has(leaf))?.title;
@@ -270,3 +308,5 @@ const spec = {
270
308
  forget: (own) => ({ ...own, titles: { summaries: [], uuids: new Set() } }),
271
309
  };
272
310
  export const claudeCode = lineReader(spec);
311
+ /** The source as lineReader takes it (a test reads with it, its fields or not). */
312
+ export const claudeCodeLines = spec;
@@ -1,7 +1,60 @@
1
- import { type FileCursor } from "../lines.js";
1
+ import { type FileCursor, type LineSource } from "../lines.js";
2
2
  import { type Reader } from "../reader.js";
3
- /** Codex's reader: a read from a rollout's start first finds the parent's history a fork copied in (forkReplay); a read
4
- * going on from a cursor has it in the cursor's state. Whether a read goes on is decided before reading, so each read
5
- * reads the file once: a rollout the line reader would start over (rewritten in place), and a fork whose copy was still
6
- * open where the last read ended and that has grown since, are read from their start with the copy found again. */
3
+ import type { Turn } from "../types.js";
4
+ /** Whether the file has user_message events, and its user messages, each with its place among the turns, held to the
5
+ * file's end. `openAt`: the request the model's output items join, until a result of one of its calls (`openCalls`);
6
+ * `unpaidAt`, the latest request whose usage has not come (written after its calls' results at times), each by its index
7
+ * in the read's answers, or a totals read's counts; `records`, whether the file has token_usage_records, with the
8
+ * responses they counted, and `total`, the last token_count's total; `items`, whether each completed item failed, and
9
+ * `results`, each tool result by call id, with whether its output said; `provider`, the model provider its session_meta
10
+ * names; `forkedFrom`, the threads its session_meta says it forked or was spawned from; `replay`, the parent's history
11
+ * a fork copied in (forkReplay), null when there is none. */
12
+ type Own = {
13
+ forkedFrom?: Set<string>;
14
+ replay?: Replay | null;
15
+ looked?: Looked;
16
+ events: boolean;
17
+ held: {
18
+ index: number;
19
+ turn: Turn;
20
+ }[];
21
+ openAt?: number;
22
+ unpaidAt?: number;
23
+ openCalls?: string[];
24
+ records: boolean;
25
+ responses: Set<string>;
26
+ total?: string;
27
+ items: Map<string, boolean>;
28
+ results: Map<string, {
29
+ turn: Extract<Turn, {
30
+ role: "toolResult";
31
+ }>;
32
+ stated: boolean;
33
+ }>;
34
+ provider?: string;
35
+ };
36
+ /** A fork's copy (forkReplay): the usages to skip, by ordinal, the last of them, the usages read so far, and the total
37
+ * the last skipped one left; `open`, whether the file ended before its copy's end could be known, so a read of more of it
38
+ * finds the copy again (codex.read). */
39
+ type Replay = {
40
+ skip: [number, number][];
41
+ until: number;
42
+ seen: number;
43
+ total?: string;
44
+ open: boolean;
45
+ };
46
+ /** The parent a fork's read looked for, and the rollout it read for it: null when there was none to read. */
47
+ type Looked = {
48
+ parent: string;
49
+ path: string | null;
50
+ };
51
+ /** Codex's reader over `source` (spec, or a test's variant of it): a read from a rollout's start first finds the parent's
52
+ * history a fork copied in (forkReplay); a read going on from a cursor has it in the cursor's state. Whether a read goes
53
+ * on is decided before reading, so each read reads the file once: a rollout the line reader would start over (rewritten
54
+ * in place), and a fork whose copy was still open where the last read ended and that has grown since, are read from
55
+ * their start with the copy found again. */
56
+ export declare function codexReader(source: LineSource<"codex", Own>): Reader<"codex", FileCursor>;
7
57
  export declare const codex: Reader<"codex", FileCursor>;
58
+ /** The source as lineReader takes it (a test reads with it, its fields or not). */
59
+ export declare const codexLines: LineSource<"codex", Own>;
60
+ export {};
@@ -51,43 +51,44 @@ function codexFailed(output) {
51
51
  }
52
52
  return undefined;
53
53
  }
54
- function readRecord(value, at, { state, keep, add }) {
54
+ function readRecord(value, at, { state, keep, add, chain }) {
55
55
  const { session, names, turns, own: codex, counts } = state;
56
56
  const payload = isObject(value.payload) ? value.payload : {};
57
57
  // One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
58
- // compaction's, one whose output is no item read here) is a turn of its own.
58
+ // compaction's, one whose output is no item read here) is a turn of its own. Each is held by its index: in the read's
59
+ // answers, or a totals read's counts, each request its model, usage and time alone. A read's request is in the chain
60
+ // too (a totals read keeps none).
59
61
  const answer = () => {
60
- const turn = { role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) };
61
- add(turn);
62
- return turn;
63
- };
64
- const request = () => codex.open ?? (codex.open = codex.unpaid = answer());
65
- // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
66
- const answered = (usage, response) => {
67
- const tokens = normalizeUsage("openai", usage);
68
- const turn = codex.unpaid ?? answer();
69
- if (tokens)
70
- turn.usage = tokens;
71
- if (response)
72
- turn.key = response;
73
- codex.open = codex.unpaid = undefined;
62
+ if (counts)
63
+ return addRequest(counts, session.model, undefined, at);
64
+ add({ role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) });
65
+ chain?.push({ request: state.answers.length - 1 });
66
+ return state.answers.length - 1;
74
67
  };
75
- // A totals read's: the same, each request its model, usage and time alone.
76
- const answerAt = () => addRequest(counts, session.model, undefined, at);
77
- const requestAt = () => {
68
+ const request = () => {
78
69
  if (codex.openAt === undefined) {
79
- codex.openAt = codex.unpaidAt = answerAt();
70
+ codex.openAt = codex.unpaidAt = answer();
80
71
  codex.openCalls = [];
81
72
  }
82
73
  return codex.openAt;
83
74
  };
84
- const answeredAt = (usage) => {
75
+ const usageOn = (i, tokens) => (counts ? setUsage(counts, i, tokens) : (state.answers[i].usage = tokens));
76
+ // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
77
+ const answered = (usage, response) => {
85
78
  const tokens = normalizeUsage("openai", usage);
86
- const index = codex.unpaidAt ?? answerAt();
79
+ const i = codex.unpaidAt ?? answer();
87
80
  if (tokens)
88
- setUsage(counts, index, tokens);
81
+ usageOn(i, tokens);
82
+ if (response && !counts)
83
+ state.answers[i].key = response;
89
84
  codex.openAt = codex.unpaidAt = undefined;
90
85
  };
86
+ // A rollout's prompt only grows, but for a compaction, which replaces the history with its summary: the chain holds the
87
+ // requests and the compactions, in their order, and no record ids (a rollout names none to rewind to).
88
+ if (value.type === "compacted") {
89
+ chain?.push({ compact: true });
90
+ return;
91
+ }
91
92
  if (value.type === "session_meta") {
92
93
  // A fork writes its parent's session_meta after its own (Codex 0.154): one whose id is the thread this rollout forked
93
94
  // from is that copy, and says nothing of this rollout. Any other later session_meta still counts, as Codex writes it.
@@ -118,7 +119,6 @@ function readRecord(value, at, { state, keep, add }) {
118
119
  session.cwd = payload.cwd;
119
120
  state.effort = effortOf(payload.effort);
120
121
  // A new turn: a request left open (aborted) has no usage to come.
121
- codex.open = codex.unpaid = undefined;
122
122
  codex.openAt = codex.unpaidAt = undefined;
123
123
  return;
124
124
  }
@@ -132,7 +132,7 @@ function readRecord(value, at, { state, keep, add }) {
132
132
  return;
133
133
  if (id)
134
134
  codex.responses.add(id);
135
- return counts ? answeredAt(payload.usage) : answered(payload.usage, id);
135
+ return answered(payload.usage, id);
136
136
  }
137
137
  if (value.type === "event_msg") {
138
138
  if (payload.type === "user_message") {
@@ -148,10 +148,7 @@ function readRecord(value, at, { state, keep, add }) {
148
148
  if (total !== undefined && total === codex.total)
149
149
  return;
150
150
  codex.total = total;
151
- if (counts)
152
- answeredAt(info.last_token_usage);
153
- else
154
- answered(info.last_token_usage);
151
+ answered(info.last_token_usage);
155
152
  }
156
153
  else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
157
154
  // Whether a call failed is its result's turn's: none is kept without turns.
@@ -184,29 +181,28 @@ function readRecord(value, at, { state, keep, add }) {
184
181
  }
185
182
  else if (payload.type === "message" && payload.role === "assistant") {
186
183
  const text = textOf(payload.content);
187
- if (text && counts)
188
- requestAt();
189
- else if (text) {
190
- const turn = request();
191
- if (keep)
192
- turn.text = [turn.text, text].filter(Boolean).join("\n");
184
+ if (!text)
185
+ return;
186
+ const i = request();
187
+ if (keep) {
188
+ const turn = state.answers[i];
189
+ turn.text = [turn.text, text].filter(Boolean).join("\n");
193
190
  }
194
191
  }
195
- else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type) && counts) {
196
- requestAt();
197
- if (payload.type === "function_call" || payload.type === "custom_tool_call")
198
- codex.openCalls.push(String(payload.call_id ?? payload.id ?? ""));
199
- }
200
192
  else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
201
- const turn = request();
193
+ const i = request();
202
194
  if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
203
195
  return;
204
196
  const id = String(payload.call_id ?? payload.id ?? "");
197
+ codex.openCalls.push(id);
198
+ // A totals read keeps no call: the request's counts are all it holds.
199
+ if (counts)
200
+ return;
205
201
  const name = String(payload.name ?? "");
206
202
  // A tool's name is for its result's turn: none is kept without turns.
207
203
  if (keep)
208
204
  names.set(id, name);
209
- turn.calls.push({
205
+ state.answers[i].calls.push({
210
206
  type: "toolCall",
211
207
  id,
212
208
  name,
@@ -216,8 +212,6 @@ function readRecord(value, at, { state, keep, add }) {
216
212
  else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
217
213
  const id = String(payload.call_id ?? "");
218
214
  // The model saw a result: what it writes next is another request.
219
- if (codex.open?.calls.some((call) => call.id === id))
220
- codex.open = undefined;
221
215
  if (codex.openAt !== undefined && codex.openCalls.includes(id))
222
216
  codex.openAt = undefined;
223
217
  // A result is a turn alone (no count): none is kept without turns.
@@ -238,6 +232,31 @@ function readRecord(value, at, { state, keep, add }) {
238
232
  add(turn);
239
233
  }
240
234
  }
235
+ /** What record reads of a line in a totals read (LineSource.fields). A call's arguments and output, and an item's
236
+ * output, are left out: a totals read keeps no call's arguments nor result; so is everything of the records it reads
237
+ * nothing of (compacted, reasoning's encrypted content). */
238
+ const FIELDS = {
239
+ type: true,
240
+ payload: {
241
+ type: true,
242
+ id: true,
243
+ cwd: true,
244
+ model_provider: true,
245
+ parent_thread_id: true,
246
+ forked_from_id: true,
247
+ source: true,
248
+ model: true,
249
+ effort: true,
250
+ response_id: true,
251
+ usage: true,
252
+ message: true,
253
+ info: true,
254
+ item: { id: true },
255
+ role: true,
256
+ content: [{ type: true, text: true, content: true }],
257
+ call_id: true,
258
+ },
259
+ };
241
260
  const usageFields = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
242
261
  /** A token_count's usage as a key, when the count is a usage (its total moved from `last.total`, which it moves on), else
243
262
  * undefined. Two requests with the same counts are the same key: as ccusage compares them. */
@@ -577,14 +596,14 @@ function record(value, at, context) {
577
596
  if (!replay.skip.some(([from, to]) => ordinal >= from && ordinal < to))
578
597
  return readRecord(value, at, context);
579
598
  own.total = replay.total;
580
- own.open = own.unpaid = undefined;
599
+ own.openAt = own.unpaidAt = undefined;
581
600
  return false;
582
601
  }
583
602
  if (value.type === "turn_context")
584
603
  readRecord(value, at, context);
585
604
  else if (value.type === "token_usage_record")
586
605
  own.records = true;
587
- own.open = own.unpaid = undefined;
606
+ own.openAt = own.unpaidAt = undefined;
588
607
  return false;
589
608
  }
590
609
  const spec = {
@@ -608,6 +627,11 @@ const spec = {
608
627
  start: () => ({ events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() }),
609
628
  record,
610
629
  totals: true,
630
+ fields: FIELDS,
631
+ // 2: a fork's copy of its parent's history (replay, looked, forkedFrom). 1 (never released): the open and unpaid
632
+ // requests by their index (openAt, unpaidAt). 0.1.0-beta.58 and before held them as Answers (open, unpaid), which this
633
+ // record never reads. A cursor of another shape goes on from nothing.
634
+ stateVersion: 2,
611
635
  // Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
612
636
  // writes the user message alone. One source per file, so no turn counts twice.
613
637
  finish(out, turns, { state: { own }, keep }) {
@@ -672,30 +696,36 @@ async function parentOf({ file }) {
672
696
  await handle.close();
673
697
  }
674
698
  }
675
- const lines = lineReader(spec);
676
- /** Codex's reader: a read from a rollout's start first finds the parent's history a fork copied in (forkReplay); a read
677
- * going on from a cursor has it in the cursor's state. Whether a read goes on is decided before reading, so each read
678
- * reads the file once: a rollout the line reader would start over (rewritten in place), and a fork whose copy was still
679
- * open where the last read ended and that has grown since, are read from their start with the copy found again. */
680
- export const codex = {
681
- ...lines,
682
- parentOf,
683
- async read(locator, cursor, options) {
684
- const fresh = async () => {
685
- const { replay, looked } = await forkReplay(locator.file, options?.lookups, options?.maxLine);
686
- return replay || looked ? lineReader({ ...spec, start: () => ({ ...spec.start(), replay, ...(looked ? { looked } : {}) }) }).read(locator, undefined, options) : lines.read(locator, undefined, options);
687
- };
688
- if (!cursor || !(await resumes(spec, locator.file, cursor, options)))
689
- return fresh();
690
- const own = cursor.state.own;
691
- if (own?.replay?.open === true && (await stat(locator.file)).size > cursor.offset)
692
- return fresh();
693
- // The parent its last read looked for come or gone since (restored from an archive, archived): what the fork copied
694
- // counts in one place again, as a read from its start would have it.
695
- if (own?.looked && (await parentNow(locator.file, own.looked.parent, options?.lookups)) !== own.looked.path)
696
- return fresh();
697
- // Rewritten between the check and this read, the line reader starts over without the copy and says so (resumed
698
- // false): the caller reads again from nothing (parseHome), and that read is fresh.
699
- return lines.read(locator, cursor, options);
700
- },
701
- };
699
+ /** Codex's reader over `source` (spec, or a test's variant of it): a read from a rollout's start first finds the parent's
700
+ * history a fork copied in (forkReplay); a read going on from a cursor has it in the cursor's state. Whether a read goes
701
+ * on is decided before reading, so each read reads the file once: a rollout the line reader would start over (rewritten
702
+ * in place), and a fork whose copy was still open where the last read ended and that has grown since, are read from
703
+ * their start with the copy found again. */
704
+ export function codexReader(source) {
705
+ const lines = lineReader(source);
706
+ return {
707
+ ...lines,
708
+ parentOf,
709
+ async read(locator, cursor, options) {
710
+ const fresh = async () => {
711
+ const { replay, looked } = await forkReplay(locator.file, options?.lookups, options?.maxLine);
712
+ return replay || looked ? lineReader({ ...source, start: () => ({ ...source.start(), replay, ...(looked ? { looked } : {}) }) }).read(locator, undefined, options) : lines.read(locator, undefined, options);
713
+ };
714
+ if (!cursor || !(await resumes(source, locator.file, cursor, options)))
715
+ return fresh();
716
+ const own = cursor.state.own;
717
+ if (own?.replay?.open === true && (await stat(locator.file)).size > cursor.offset)
718
+ return fresh();
719
+ // The parent its last read looked for come or gone since (restored from an archive, archived): what the fork copied
720
+ // counts in one place again, as a read from its start would have it.
721
+ if (own?.looked && (await parentNow(locator.file, own.looked.parent, options?.lookups)) !== own.looked.path)
722
+ return fresh();
723
+ // Rewritten between the check and this read, the line reader starts over without the copy and says so (resumed
724
+ // false): the caller reads again from nothing (parseHome), and that read is fresh.
725
+ return lines.read(locator, cursor, options);
726
+ },
727
+ };
728
+ }
729
+ export const codex = codexReader(spec);
730
+ /** The source as lineReader takes it (a test reads with it, its fields or not). */
731
+ export const codexLines = spec;
@@ -0,0 +1,7 @@
1
+ import type { Reader } from "../reader.js";
2
+ export declare const LINE_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
+ readonly copilot: Reader<"copilot", import("../lines.js").FileCursor>;
7
+ };
@@ -0,0 +1,10 @@
1
+ import { claudeCode } from "./claude-code.js";
2
+ import { codex } from "./codex.js";
3
+ import { copilot } from "./copilot.js";
4
+ import { pi } from "./pi.js";
5
+ export const LINE_READERS = {
6
+ "claude-code": claudeCode,
7
+ codex,
8
+ pi,
9
+ copilot,
10
+ };
@@ -2,10 +2,15 @@
2
2
  import { basename, join } from "node:path";
3
3
  import { lineReader } from "../lines.js";
4
4
  import { entries } from "../reader.js";
5
- import { argsOf, effortOf, FAILED, isObject, str, textOf, timeOf } from "../text.js";
5
+ import { argsOf, effortOf, FAILED, hashOf, isObject, str, textOf, timeOf } from "../text.js";
6
6
  import { normalizeUsage } from "../usage.js";
7
- function record(value, at, { state, keep, add }) {
7
+ function record(value, at, { state, keep, add, chain }) {
8
8
  const { session, priced } = state;
9
+ // Each entry after the session's own names the one before it (parentId): a branch names an earlier one. pi writes no
10
+ // compaction or sidechain record in the sessions read here, so the chain marks none.
11
+ const link = chain && value.type !== "session" && str(value.id) ? { id: value.id, ...(str(value.parentId) ? { parent: value.parentId } : {}), hash: hashOf([value.type, isObject(value.message) ? [value.message.role, value.message.content] : (value.modelId ?? value.thinkingLevel ?? null)]) } : undefined;
12
+ if (link)
13
+ chain.push(link);
9
14
  if (value.type === "session") {
10
15
  if (str(value.id))
11
16
  session.id = value.id;
@@ -74,6 +79,8 @@ function record(value, at, { state, keep, add }) {
74
79
  ...(tokens ? { usage: tokens } : {}),
75
80
  ...(message.stopReason === "error" ? { error: keep ? (str(message.errorMessage) ?? "unknown error") : FAILED } : {}),
76
81
  });
82
+ if (link)
83
+ link.request = state.answers.length - 1;
77
84
  }
78
85
  }
79
86
  const spec = {
@@ -1,9 +1,13 @@
1
1
  import { type Packed } from "./record-key.js";
2
2
  /** One kind of key's entries, in the order added, and the open-addressing slots (linear probing) that find them:
3
- * 0 an empty slot, else an entry's index + 1. */
3
+ * 0 an empty slot, else an entry's index + 1. Each slot's tag is its entry's hash's top byte: a probe passes a slot
4
+ * whose tag differs without reading the entry (a miss walks the whole run). A table of fewer than TAGGED slots has
5
+ * none (a file's own index, saved in its cursor, stays as small as it was); an index saved without them (an older
6
+ * HomeState) has them built the first time it is probed. */
4
7
  type Table = {
5
8
  count: number;
6
9
  slots: Int32Array;
10
+ tags?: Uint8Array;
7
11
  owners: Int32Array;
8
12
  };
9
13
  /** A uuid's keys: four 32-bit words an entry. */
@@ -25,6 +29,9 @@ export type RecordIndex = {
25
29
  };
26
30
  /** An empty index, its slots `slots` (a power of 2) to start with. */
27
31
  export declare const recordIndex: (slots?: number) => RecordIndex;
32
+ /** Every typed array `index` holds, its slots' tags with them when its tables have any: what a worker moves to the main
33
+ * thread with the index (pool-worker.ts), and what the pool counts it holding (pool.ts). */
34
+ export declare const indexArrays: ({ uuids, others }: RecordIndex) => (Int32Array | Uint8Array | Float64Array)[];
28
35
  /** The number of `locator` in `index`, given one when it has none. */
29
36
  export declare function locatorNumber(index: RecordIndex, locator: string): number;
30
37
  /** The owner (its number) of the record packed as `key`, else -1. */
@@ -32,12 +39,32 @@ export declare function ownerOf(index: RecordIndex, { bytes, length }: Packed):
32
39
  /** The record packed as `key` added, owned by `owner` (a number of the index the owners refer to); one held already is
33
40
  * left as it is. */
34
41
  export declare function addRecord(index: RecordIndex, key: Packed, owner: number): void;
42
+ /** The record packed as `key` added, owned by `owner`, where `index` is known not to hold it (ownerOf gave -1 for it,
43
+ * and nothing was added since): addRecord without looking it up again. */
44
+ export declare function addNew(index: RecordIndex, key: Packed, owner: number): void;
35
45
  /** Every record of `from` added to `into`, in the order `from` took them, each with its owner. */
36
46
  export declare function addAll(into: RecordIndex, from: RecordIndex): void;
47
+ /** Whether `into` holds any record of `from`. */
48
+ export declare function anyIn(into: RecordIndex, from: RecordIndex): boolean;
49
+ /** The records of `from` that `held` does not hold, with their owners, in an index of their own. */
50
+ export declare function notIn(from: RecordIndex, held: RecordIndex): RecordIndex;
51
+ /** Every record of `from` added to `into`, where the two hold no record in common: per kind of key, the table with more
52
+ * entries keeps its arrays and the other's entries are added to it, so a big read's records are not copied (and held
53
+ * twice) to join a smaller index. `from` is used up: it holds what `into` held. */
54
+ export declare function addDisjoint(into: RecordIndex, from: RecordIndex): void;
55
+ /** Where `index`'s entries end now: undoTo takes it back there. */
56
+ export type Mark = {
57
+ uuids: number;
58
+ others: number;
59
+ used: number;
60
+ };
61
+ export declare const markOf: (index: RecordIndex) => Mark;
62
+ /** `index` as it was at `mark`: the entries added since taken out, last first. With linear probing, taking out the
63
+ * last entry added leaves the slots as they were before it (a grow puts the entries back in their order, so this holds
64
+ * across one), at the cost of the entries taken out, where dropOwner rebuilds the whole index. */
65
+ export declare function undoTo(index: RecordIndex, mark: Mark): void;
37
66
  /** `index` without the records `owner` owns: the rest kept in their order. */
38
67
  export declare function dropOwner(index: RecordIndex, owner: number): void;
39
- /** Each record of `from` packed, in the order taken, until `stop` returns true for one: whether one did. */
40
- export declare function someRecord(from: RecordIndex, stop: (key: Packed) => boolean): boolean;
41
68
  /** Every record of `index` now owned by `owner`. */
42
69
  export declare function ownAll(index: RecordIndex, owner: number): void;
43
70
  export {};