@parcha/agentrun-import 0.1.0-beta.58 → 0.1.0-beta.60

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.
Files changed (46) hide show
  1. package/README.md +111 -20
  2. package/dist/cli.js +23 -8
  3. package/dist/home.d.ts +24 -1
  4. package/dist/home.js +394 -146
  5. package/dist/index.d.ts +7 -5
  6. package/dist/index.js +4 -2
  7. package/dist/internal.d.ts +18 -0
  8. package/dist/internal.js +12 -0
  9. package/dist/lines.d.ts +24 -1
  10. package/dist/lines.js +135 -25
  11. package/dist/mirror.d.ts +13 -0
  12. package/dist/mirror.js +15 -0
  13. package/dist/pool-worker.d.ts +6 -0
  14. package/dist/pool-worker.js +50 -0
  15. package/dist/pool.d.ts +106 -0
  16. package/dist/pool.js +288 -0
  17. package/dist/price.d.ts +13 -5
  18. package/dist/price.js +31 -21
  19. package/dist/read.d.ts +14 -4
  20. package/dist/read.js +41 -7
  21. package/dist/reader.d.ts +38 -8
  22. package/dist/readers/claude-code.d.ts +24 -0
  23. package/dist/readers/claude-code.js +51 -35
  24. package/dist/readers/codex.d.ts +60 -1
  25. package/dist/readers/codex.js +494 -52
  26. package/dist/readers/copilot.d.ts +4 -0
  27. package/dist/readers/copilot.js +224 -0
  28. package/dist/readers/index.d.ts +2 -0
  29. package/dist/readers/index.js +4 -0
  30. package/dist/readers/line-readers.d.ts +7 -0
  31. package/dist/readers/line-readers.js +10 -0
  32. package/dist/readers/opencode.d.ts +42 -0
  33. package/dist/readers/opencode.js +920 -0
  34. package/dist/readers/pi.js +2 -2
  35. package/dist/record-index.d.ts +32 -1
  36. package/dist/record-index.js +133 -13
  37. package/dist/scan-wasm.d.ts +1 -0
  38. package/dist/scan-wasm.js +2 -0
  39. package/dist/scan.d.ts +21 -0
  40. package/dist/scan.js +164 -0
  41. package/dist/text.d.ts +3 -0
  42. package/dist/text.js +36 -2
  43. package/dist/types.d.ts +20 -3
  44. package/dist/usage.d.ts +6 -2
  45. package/dist/usage.js +42 -1
  46. package/package.json +4 -2
@@ -1,9 +1,10 @@
1
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";
2
+ import { open, stat } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
3
4
  import { addRequest, setUsage } from "../counts.js";
4
- import { lineReader } from "../lines.js";
5
+ import { LineTooLong, lineReader, resumes } from "../lines.js";
5
6
  import { entries, rememberUser } from "../reader.js";
6
- import { argsOf, effortOf, isObject, str, textOf } from "../text.js";
7
+ import { argsOf, effortOf, isObject, str, textOf, timeOf } from "../text.js";
7
8
  import { normalizeUsage } from "../usage.js";
8
9
  // 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
9
10
  // <INSTRUCTIONS>; and the bare tags around an image. Only these: a prompt the person wrote as a tagged element is theirs,
@@ -50,54 +51,54 @@ function codexFailed(output) {
50
51
  }
51
52
  return undefined;
52
53
  }
53
- function record(value, at, { state, keep, add }) {
54
+ function readRecord(value, at, { state, keep, add }) {
54
55
  const { session, names, turns, own: codex, counts } = state;
55
56
  const payload = isObject(value.payload) ? value.payload : {};
56
57
  // One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
57
- // 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.
58
60
  const answer = () => {
59
- const turn = { role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) };
60
- add(turn);
61
- return turn;
62
- };
63
- const request = () => codex.open ?? (codex.open = codex.unpaid = answer());
64
- // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
65
- const answered = (usage, response) => {
66
- const tokens = normalizeUsage("openai", usage);
67
- const turn = codex.unpaid ?? answer();
68
- if (tokens)
69
- turn.usage = tokens;
70
- if (response)
71
- turn.key = response;
72
- codex.open = codex.unpaid = undefined;
61
+ if (counts)
62
+ return addRequest(counts, session.model, undefined, at);
63
+ add({ role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) });
64
+ return state.answers.length - 1;
73
65
  };
74
- // A totals read's: the same, each request its model, usage and time alone.
75
- const answerAt = () => addRequest(counts, session.model, undefined, at);
76
- const requestAt = () => {
66
+ const request = () => {
77
67
  if (codex.openAt === undefined) {
78
- codex.openAt = codex.unpaidAt = answerAt();
68
+ codex.openAt = codex.unpaidAt = answer();
79
69
  codex.openCalls = [];
80
70
  }
81
71
  return codex.openAt;
82
72
  };
83
- const answeredAt = (usage) => {
73
+ const usageOn = (i, tokens) => (counts ? setUsage(counts, i, tokens) : (state.answers[i].usage = tokens));
74
+ // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
75
+ const answered = (usage, response) => {
84
76
  const tokens = normalizeUsage("openai", usage);
85
- const index = codex.unpaidAt ?? answerAt();
77
+ const i = codex.unpaidAt ?? answer();
86
78
  if (tokens)
87
- setUsage(counts, index, tokens);
79
+ usageOn(i, tokens);
80
+ if (response && !counts)
81
+ state.answers[i].key = response;
88
82
  codex.openAt = codex.unpaidAt = undefined;
89
83
  };
90
84
  if (value.type === "session_meta") {
91
- if (str(payload.id))
92
- session.id = payload.id;
85
+ // A fork writes its parent's session_meta after its own (Codex 0.154): one whose id is the thread this rollout forked
86
+ // from is that copy, and says nothing of this rollout. Any other later session_meta still counts, as Codex writes it.
87
+ const id = str(payload.id);
88
+ if (id && codex.forkedFrom?.has(id))
89
+ return;
90
+ const parent = parentIn(payload);
91
+ for (const from of [str(payload.forked_from_id), parent])
92
+ if (from && from !== id)
93
+ (codex.forkedFrom ??= new Set()).add(from);
94
+ if (id)
95
+ session.id = id;
93
96
  if (str(payload.cwd))
94
97
  session.cwd = payload.cwd;
95
98
  if (str(payload.model_provider))
96
99
  codex.provider = payload.model_provider;
97
100
  if (str(payload.parent_thread_id) || (isObject(payload.source) && isObject(payload.source.subagent)))
98
101
  session.child = true;
99
- const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
100
- const parent = str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
101
102
  if (parent)
102
103
  session.parent = parent;
103
104
  return;
@@ -110,7 +111,6 @@ function record(value, at, { state, keep, add }) {
110
111
  session.cwd = payload.cwd;
111
112
  state.effort = effortOf(payload.effort);
112
113
  // A new turn: a request left open (aborted) has no usage to come.
113
- codex.open = codex.unpaid = undefined;
114
114
  codex.openAt = codex.unpaidAt = undefined;
115
115
  return;
116
116
  }
@@ -124,7 +124,7 @@ function record(value, at, { state, keep, add }) {
124
124
  return;
125
125
  if (id)
126
126
  codex.responses.add(id);
127
- return counts ? answeredAt(payload.usage) : answered(payload.usage, id);
127
+ return answered(payload.usage, id);
128
128
  }
129
129
  if (value.type === "event_msg") {
130
130
  if (payload.type === "user_message") {
@@ -140,10 +140,7 @@ function record(value, at, { state, keep, add }) {
140
140
  if (total !== undefined && total === codex.total)
141
141
  return;
142
142
  codex.total = total;
143
- if (counts)
144
- answeredAt(info.last_token_usage);
145
- else
146
- answered(info.last_token_usage);
143
+ answered(info.last_token_usage);
147
144
  }
148
145
  else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
149
146
  // Whether a call failed is its result's turn's: none is kept without turns.
@@ -176,29 +173,28 @@ function record(value, at, { state, keep, add }) {
176
173
  }
177
174
  else if (payload.type === "message" && payload.role === "assistant") {
178
175
  const text = textOf(payload.content);
179
- if (text && counts)
180
- requestAt();
181
- else if (text) {
182
- const turn = request();
183
- if (keep)
184
- turn.text = [turn.text, text].filter(Boolean).join("\n");
176
+ if (!text)
177
+ return;
178
+ const i = request();
179
+ if (keep) {
180
+ const turn = state.answers[i];
181
+ turn.text = [turn.text, text].filter(Boolean).join("\n");
185
182
  }
186
183
  }
187
- else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type) && counts) {
188
- requestAt();
189
- if (payload.type === "function_call" || payload.type === "custom_tool_call")
190
- codex.openCalls.push(String(payload.call_id ?? payload.id ?? ""));
191
- }
192
184
  else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
193
- const turn = request();
185
+ const i = request();
194
186
  if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
195
187
  return;
196
188
  const id = String(payload.call_id ?? payload.id ?? "");
189
+ codex.openCalls.push(id);
190
+ // A totals read keeps no call: the request's counts are all it holds.
191
+ if (counts)
192
+ return;
197
193
  const name = String(payload.name ?? "");
198
194
  // A tool's name is for its result's turn: none is kept without turns.
199
195
  if (keep)
200
196
  names.set(id, name);
201
- turn.calls.push({
197
+ state.answers[i].calls.push({
202
198
  type: "toolCall",
203
199
  id,
204
200
  name,
@@ -208,8 +204,6 @@ function record(value, at, { state, keep, add }) {
208
204
  else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
209
205
  const id = String(payload.call_id ?? "");
210
206
  // The model saw a result: what it writes next is another request.
211
- if (codex.open?.calls.some((call) => call.id === id))
212
- codex.open = undefined;
213
207
  if (codex.openAt !== undefined && codex.openCalls.includes(id))
214
208
  codex.openAt = undefined;
215
209
  // A result is a turn alone (no count): none is kept without turns.
@@ -230,6 +224,380 @@ function record(value, at, { state, keep, add }) {
230
224
  add(turn);
231
225
  }
232
226
  }
227
+ /** What record reads of a line in a totals read (LineSource.fields). A call's arguments and output, and an item's
228
+ * output, are left out: a totals read keeps no call's arguments nor result; so is everything of the records it reads
229
+ * nothing of (compacted, reasoning's encrypted content). */
230
+ const FIELDS = {
231
+ type: true,
232
+ payload: {
233
+ type: true,
234
+ id: true,
235
+ cwd: true,
236
+ model_provider: true,
237
+ parent_thread_id: true,
238
+ forked_from_id: true,
239
+ source: true,
240
+ model: true,
241
+ effort: true,
242
+ response_id: true,
243
+ usage: true,
244
+ message: true,
245
+ info: true,
246
+ item: { id: true },
247
+ role: true,
248
+ content: [{ type: true, text: true, content: true }],
249
+ call_id: true,
250
+ },
251
+ };
252
+ const usageFields = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
253
+ /** 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
254
+ * undefined. Two requests with the same counts are the same key: as ccusage compares them. */
255
+ function usageOf(value, last) {
256
+ const payload = isObject(value.payload) ? value.payload : undefined;
257
+ if (value.type !== "event_msg" || payload?.type !== "token_count" || !isObject(payload.info))
258
+ return undefined;
259
+ const { info } = payload;
260
+ const total = isObject(info.total_token_usage) ? JSON.stringify(info.total_token_usage) : undefined;
261
+ if (total !== undefined && total === last.total)
262
+ return undefined;
263
+ last.total = total;
264
+ const use = isObject(info.last_token_usage) ? info.last_token_usage : undefined;
265
+ const counts = usageFields.map((field) => {
266
+ const n = use?.[field];
267
+ return typeof n === "number" ? n : 0;
268
+ });
269
+ // No usage when every count but the total is 0, as ccusage's CodexRawUsage::is_empty has it: a fork's first
270
+ // token_count can carry only a total_tokens, and that is no request of the parent's to match.
271
+ return counts.slice(0, -1).some((n) => n > 0) ? counts.join(",") : undefined;
272
+ }
273
+ /** The longest run at the start of `child` equal to the start of `parent`, or to its end. */
274
+ function copiedLength(parent, child) {
275
+ const pattern = child.slice(0, parent.length);
276
+ let prefix = 0;
277
+ while (prefix < pattern.length && pattern[prefix] === parent[prefix])
278
+ prefix += 1;
279
+ if (!pattern.length)
280
+ return 0;
281
+ // The longest start of `pattern` that `parent` ends with: a prefix function over it, run along the parent's end.
282
+ const fail = new Array(pattern.length).fill(0);
283
+ for (let i = 1, k = 0; i < pattern.length; i += 1) {
284
+ while (k > 0 && pattern[i] !== pattern[k])
285
+ k = fail[k - 1];
286
+ if (pattern[i] === pattern[k])
287
+ k += 1;
288
+ fail[i] = k;
289
+ }
290
+ let matched = 0;
291
+ for (const use of parent.slice(parent.length - pattern.length)) {
292
+ while (matched > 0 && use !== pattern[matched])
293
+ matched = fail[matched - 1];
294
+ if (use === pattern[matched])
295
+ matched += 1;
296
+ if (matched === pattern.length)
297
+ break;
298
+ }
299
+ return Math.max(prefix, matched);
300
+ }
301
+ /** A rollout's lines, parsed, each record that is a JSON object. A line longer than `maxLine` bytes ends the reading with
302
+ * LineTooLong before it is decoded, as the line reader's does (a read pool's worker bounds its heap so). Its file is
303
+ * closed however the reading stops. */
304
+ async function* recordsOf(file, maxLine = Number.POSITIVE_INFINITY) {
305
+ const handle = await open(file, "r");
306
+ const parsed = (bytes) => {
307
+ try {
308
+ const value = JSON.parse(bytes.toString("utf8"));
309
+ return isObject(value) ? value : undefined;
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ };
315
+ try {
316
+ const buffer = Buffer.allocUnsafe(1 << 20);
317
+ let rest = [];
318
+ let restBytes = 0;
319
+ let offset = 0;
320
+ for (let at = 0;;) {
321
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, at);
322
+ if (!bytesRead)
323
+ break;
324
+ at += bytesRead;
325
+ const chunk = buffer.subarray(0, bytesRead);
326
+ let from = 0;
327
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
328
+ if (restBytes + nl - from > maxLine)
329
+ throw new LineTooLong(file, offset, restBytes + nl - from, maxLine);
330
+ const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
331
+ rest = [];
332
+ restBytes = 0;
333
+ offset += whole.length + 1;
334
+ from = nl + 1;
335
+ const value = parsed(whole);
336
+ if (value)
337
+ yield value;
338
+ }
339
+ if (from < chunk.length) {
340
+ restBytes += chunk.length - from;
341
+ if (restBytes > maxLine)
342
+ throw new LineTooLong(file, offset, restBytes, maxLine);
343
+ // A copy: the buffer is read into again.
344
+ rest.push(Buffer.from(chunk.subarray(from)));
345
+ }
346
+ }
347
+ const last = rest.length ? parsed(Buffer.concat(rest)) : undefined;
348
+ if (last)
349
+ yield last;
350
+ }
351
+ finally {
352
+ await handle.close();
353
+ }
354
+ }
355
+ /** A rollout's first line as a JSON object, read alone (up to 16 MiB), so a rollout that is no fork is not streamed for
356
+ * it. Longer than `maxLine` bytes, it ends the read with LineTooLong before it is decoded. */
357
+ async function firstRecord(file, maxLine = Number.POSITIVE_INFINITY) {
358
+ const handle = await open(file, "r");
359
+ try {
360
+ const chunks = [];
361
+ let bytes = 0;
362
+ for (let position = 0; position < 16 * 1024 * 1024;) {
363
+ const chunk = Buffer.alloc(64 * 1024);
364
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
365
+ if (bytesRead === 0)
366
+ break;
367
+ const end = chunk.subarray(0, bytesRead).indexOf(10);
368
+ chunks.push(chunk.subarray(0, end === -1 ? bytesRead : end));
369
+ bytes += end === -1 ? bytesRead : end;
370
+ if (bytes > maxLine)
371
+ throw new LineTooLong(file, 0, bytes, maxLine);
372
+ if (end !== -1)
373
+ break;
374
+ position += bytesRead;
375
+ }
376
+ try {
377
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
378
+ return isObject(value) ? value : undefined;
379
+ }
380
+ catch {
381
+ return undefined;
382
+ }
383
+ }
384
+ finally {
385
+ await handle.close();
386
+ }
387
+ }
388
+ /** The parent's usages, each with its time, as its rollout holds them: the last few read kept, as a parent's forks are
389
+ * read one after another. */
390
+ const parentUsages = new Map();
391
+ async function usagesOf(file, maxLine) {
392
+ const stats = await stat(file);
393
+ const mark = `${stats.size}:${stats.mtimeMs}`;
394
+ const kept = parentUsages.get(file);
395
+ if (kept?.mark === mark)
396
+ return kept;
397
+ const out = { mark, uses: [], ats: [] };
398
+ const last = {};
399
+ for await (const value of recordsOf(file, maxLine)) {
400
+ const use = usageOf(value, last);
401
+ if (use === undefined)
402
+ continue;
403
+ out.uses.push(use);
404
+ out.ats.push(timeOf(value.timestamp));
405
+ }
406
+ parentUsages.delete(file);
407
+ parentUsages.set(file, out);
408
+ if (parentUsages.size > 4)
409
+ parentUsages.delete(parentUsages.keys().next().value);
410
+ return out;
411
+ }
412
+ /** Every rollout under a sessions directory by the thread id its name ends with, in the order a walk of its
413
+ * year/month/day directories meets them. */
414
+ async function rolloutsUnder(sessions) {
415
+ const out = new Map();
416
+ for (const year of await entries(sessions)) {
417
+ if (!year.isDirectory())
418
+ continue;
419
+ for (const month of await entries(join(sessions, year.name))) {
420
+ if (!month.isDirectory())
421
+ continue;
422
+ for (const day of await entries(join(sessions, year.name, month.name))) {
423
+ if (!day.isDirectory())
424
+ continue;
425
+ const dir = join(sessions, year.name, month.name, day.name);
426
+ for (const entry of await entries(dir)) {
427
+ const id = entry.isFile() && entry.name.startsWith("rollout-") ? /-([0-9a-f-]{36})\.jsonl$/i.exec(entry.name)?.[1] : undefined;
428
+ if (id)
429
+ (out.get(id) ?? out.set(id, []).get(id)).push(join(dir, entry.name));
430
+ }
431
+ }
432
+ }
433
+ }
434
+ return out;
435
+ }
436
+ /** The parent's rollout: in the sessions directory `file` is under, named by the parent's id, on its UUIDv7 date (a
437
+ * day either side, as the directories are local dates) else anywhere there. Anywhere is one walk of the directory per
438
+ * import (`lookups`), however many forks look there, found or not. Not archived_sessions: the import reads no rollout
439
+ * there, and a copy of a parent it does not read is the only count of that history. */
440
+ async function parentFile(file, parent, lookups) {
441
+ const sessions = dirname(dirname(dirname(dirname(file))));
442
+ const ms = /^[0-9a-f]{8}-[0-9a-f]{4}-7/i.test(parent) ? Number.parseInt(parent.replace(/-/g, "").slice(0, 12), 16) : Number.NaN;
443
+ if (Number.isFinite(ms)) {
444
+ for (const shift of [0, -1, 1]) {
445
+ const dir = join(sessions, ...new Date(ms + shift * 86_400_000).toISOString().slice(0, 10).split("-"));
446
+ const name = (await entries(dir)).find((entry) => entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(`-${parent}.jsonl`) && join(dir, entry.name) !== file)?.name;
447
+ if (name)
448
+ return join(dir, name);
449
+ }
450
+ }
451
+ const key = `codex:rollouts:${sessions}`;
452
+ let index = lookups?.get(key);
453
+ if (!index) {
454
+ index = rolloutsUnder(sessions);
455
+ lookups?.set(key, index);
456
+ }
457
+ // As the tree was when listed: a parent archived or deleted since is found missing when read (forkReplay).
458
+ return (await index).get(parent)?.find((path) => path !== file);
459
+ }
460
+ /** The rollout parentFile finds for `parent` now, when it is there to read; else null. */
461
+ async function parentNow(file, parent, lookups) {
462
+ const path = await parentFile(file, parent, lookups);
463
+ return path ? stat(path).then(() => path, () => null) : null;
464
+ }
465
+ /** The parent's history `file` copied in, when it is a fork that did: read before the fork's own lines, so its records
466
+ * read as copies (record). And the parent it looked for, when it did, so a read going on from its cursor can tell
467
+ * whether that parent has come or gone since. Lines past `maxLine` bytes, in the fork or its parent, end it with
468
+ * LineTooLong. */
469
+ async function forkReplay(file, lookups, maxLine) {
470
+ const first = await firstRecord(file, maxLine);
471
+ const payload = isObject(first?.payload) ? first.payload : undefined;
472
+ if (first?.type !== "session_meta" || !payload)
473
+ return { replay: null };
474
+ const own = str(payload.id)?.trim() || undefined;
475
+ const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
476
+ const spawnedBy = str(spawn?.parent_thread_id);
477
+ const parent = str(payload.forked_from_id) ?? spawnedBy;
478
+ // A rollout that names its history's base reads it by reference, copying none; one named <thread>_<rollout> whose
479
+ // id is the thread goes on with that thread, as no fork.
480
+ if (!parent || payload.history_base !== undefined)
481
+ return { replay: null };
482
+ const named = /-([0-9a-f-]{36})_([0-9a-f-]{36})\.jsonl$/i.exec(basename(file));
483
+ if (named && named[1] !== named[2] && own === named[1])
484
+ return { replay: null };
485
+ const records = recordsOf(file, maxLine);
486
+ let looked;
487
+ try {
488
+ await records.next();
489
+ const forkedAt = timeOf(first.timestamp);
490
+ let stream;
491
+ const parentStream = async () => {
492
+ if (stream)
493
+ return stream;
494
+ const path = await parentFile(file, parent, lookups);
495
+ // A parent gone or unreadable by the time it is read (the walk's index is the import's, listed once) is one the
496
+ // import does not count: the fork's copy is the only count of that history, as when there is no parent.
497
+ const parentRead = path
498
+ ? await usagesOf(path, maxLine).catch((error) => {
499
+ if (error instanceof LineTooLong)
500
+ throw error;
501
+ return undefined;
502
+ })
503
+ : undefined;
504
+ looked = { parent, path: parentRead ? path : null };
505
+ if (!parentRead)
506
+ return (stream = []);
507
+ const { uses, ats } = parentRead;
508
+ const cut = forkedAt === undefined ? -1 : ats.findIndex((t) => t !== undefined && t > forkedAt);
509
+ return (stream = cut === -1 ? uses : uses.slice(0, cut));
510
+ };
511
+ const uses = [];
512
+ const last = {};
513
+ let foreign;
514
+ let boundary;
515
+ let marked = false;
516
+ // Whether the read reached the file's end with the copy's end unknown: no own marker, and the run could still grow.
517
+ let ended = true;
518
+ // Whether the usages so far are the parent's first ones, and where in the parent's they could start a run that ends
519
+ // at its end: while either holds the copied run can grow, so the read goes on.
520
+ let prefix = true;
521
+ let starts = [];
522
+ const grows = (parentUses, use) => {
523
+ const i = uses.length - 1;
524
+ prefix &&= parentUses[i] === use;
525
+ starts = i === 0 ? parentUses.flatMap((u, j) => (u === use ? [j] : [])) : starts.filter((j) => j + i < parentUses.length && parentUses[j + i] === use);
526
+ return uses.length < parentUses.length && (prefix || starts.length > 0);
527
+ };
528
+ for await (const value of records) {
529
+ const p = isObject(value.payload) ? value.payload : undefined;
530
+ const marker = value.type === "token_usage_record" ? "record" : value.type === "event_msg" && p?.type === "thread_settings_applied" ? "settings" : undefined;
531
+ if (marker) {
532
+ const thread = str(p?.thread_id)?.trim() || undefined;
533
+ if (thread)
534
+ marked = true;
535
+ if (thread && thread === own) {
536
+ boundary = uses.length;
537
+ ended = false;
538
+ break;
539
+ }
540
+ if (marker === "record" && !thread && spawnedBy) {
541
+ ended = false;
542
+ break;
543
+ }
544
+ if (thread && own)
545
+ foreign ??= uses.length;
546
+ continue;
547
+ }
548
+ const use = usageOf(value, last);
549
+ if (use === undefined)
550
+ continue;
551
+ uses.push(use);
552
+ // Read on only while the copied run can still grow, or while a thread's marker may yet bound one.
553
+ if (!grows(await parentStream(), use) && !marked) {
554
+ ended = false;
555
+ break;
556
+ }
557
+ }
558
+ const window = uses.slice(0, boundary ?? uses.length);
559
+ const skip = [];
560
+ if (window.length) {
561
+ const copied = copiedLength(await parentStream(), window);
562
+ if (copied)
563
+ skip.push([0, copied]);
564
+ }
565
+ // Copied, and counted in the parent, only when the parent's rollout was read: else nothing counts it but the fork.
566
+ if (foreign !== undefined && boundary !== undefined && boundary > foreign && looked?.path)
567
+ skip.push([foreign, boundary]);
568
+ const found = looked ? { looked } : {};
569
+ if (!skip.length && !ended)
570
+ return { replay: null, ...found };
571
+ return { replay: { skip, until: skip.length ? Math.max(...skip.map(([, to]) => to)) - 1 : -1, seen: 0, open: ended }, ...found };
572
+ }
573
+ finally {
574
+ await records.return(undefined);
575
+ }
576
+ }
577
+ /** One record: a fork's copy of its parent's history is read as a copy (forkReplay); a turn_context in it still sets
578
+ * the model and effort, and a usage in it that is no copy counts. */
579
+ function record(value, at, context) {
580
+ const { own } = context.state;
581
+ const replay = own.replay;
582
+ if (!replay || replay.seen > replay.until || value.type === "session_meta")
583
+ return readRecord(value, at, context);
584
+ const use = usageOf(value, replay);
585
+ if (use !== undefined) {
586
+ const ordinal = replay.seen;
587
+ replay.seen += 1;
588
+ if (!replay.skip.some(([from, to]) => ordinal >= from && ordinal < to))
589
+ return readRecord(value, at, context);
590
+ own.total = replay.total;
591
+ own.openAt = own.unpaidAt = undefined;
592
+ return false;
593
+ }
594
+ if (value.type === "turn_context")
595
+ readRecord(value, at, context);
596
+ else if (value.type === "token_usage_record")
597
+ own.records = true;
598
+ own.openAt = own.unpaidAt = undefined;
599
+ return false;
600
+ }
233
601
  const spec = {
234
602
  source: "codex",
235
603
  name: "Codex",
@@ -251,6 +619,11 @@ const spec = {
251
619
  start: () => ({ events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() }),
252
620
  record,
253
621
  totals: true,
622
+ fields: FIELDS,
623
+ // 2: a fork's copy of its parent's history (replay, looked, forkedFrom). 1 (never released): the open and unpaid
624
+ // requests by their index (openAt, unpaidAt). 0.1.0-beta.58 and before held them as Answers (open, unpaid), which this
625
+ // record never reads. A cursor of another shape goes on from nothing.
626
+ stateVersion: 2,
254
627
  // Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
255
628
  // writes the user message alone. One source per file, so no turn counts twice.
256
629
  finish(out, turns, { state: { own }, keep }) {
@@ -278,4 +651,73 @@ const spec = {
278
651
  // A turns: false cursor keeps each held prompt for its count alone: a read resumed from it gives no first prompt.
279
652
  forget: (own) => ({ ...own, held: own.held.map(({ index, turn }) => ({ index, turn: { ...turn, text: "" } })) }),
280
653
  };
281
- export const codex = lineReader(spec);
654
+ /** The thread a session_meta payload names as the one it ran under. */
655
+ function parentIn(payload) {
656
+ const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
657
+ return str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
658
+ }
659
+ /** How much of a rollout parentOf reads at most: its first line, session_meta, holds the instructions the thread ran
660
+ * with (some 20 KB, more with its tools), read to its end within this. */
661
+ const FIRST_LINE_BYTES = 64 * 1024 * 1024;
662
+ const CHUNK_BYTES = 256 * 1024;
663
+ /** The thread a rollout ran under, from its first line alone (session_meta), read to its end but never past
664
+ * FIRST_LINE_BYTES: what ties a file no one reads whole (over a caller's cap) to its parent, so the parent's run waits
665
+ * for it. None when that line does not end within it. */
666
+ async function parentOf({ file }) {
667
+ const handle = await open(file, "r");
668
+ try {
669
+ const line = [];
670
+ for (let at = 0;;) {
671
+ if (at >= FIRST_LINE_BYTES)
672
+ return undefined;
673
+ const chunk = Buffer.alloc(CHUNK_BYTES);
674
+ const { bytesRead } = await handle.read(chunk, 0, CHUNK_BYTES, at);
675
+ const end = chunk.subarray(0, bytesRead).indexOf(10);
676
+ line.push(chunk.subarray(0, end < 0 ? bytesRead : end));
677
+ at += bytesRead;
678
+ if (end >= 0 || bytesRead < CHUNK_BYTES)
679
+ break;
680
+ }
681
+ const value = JSON.parse(Buffer.concat(line).toString("utf8"));
682
+ return isObject(value) && value.type === "session_meta" && isObject(value.payload) ? parentIn(value.payload) : undefined;
683
+ }
684
+ catch {
685
+ return undefined;
686
+ }
687
+ finally {
688
+ await handle.close();
689
+ }
690
+ }
691
+ /** 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
692
+ * history a fork copied in (forkReplay); a read going on from a cursor has it in the cursor's state. Whether a read goes
693
+ * on is decided before reading, so each read reads the file once: a rollout the line reader would start over (rewritten
694
+ * in place), and a fork whose copy was still open where the last read ended and that has grown since, are read from
695
+ * their start with the copy found again. */
696
+ export function codexReader(source) {
697
+ const lines = lineReader(source);
698
+ return {
699
+ ...lines,
700
+ parentOf,
701
+ async read(locator, cursor, options) {
702
+ const fresh = async () => {
703
+ const { replay, looked } = await forkReplay(locator.file, options?.lookups, options?.maxLine);
704
+ return replay || looked ? lineReader({ ...source, start: () => ({ ...source.start(), replay, ...(looked ? { looked } : {}) }) }).read(locator, undefined, options) : lines.read(locator, undefined, options);
705
+ };
706
+ if (!cursor || !(await resumes(source, locator.file, cursor, options)))
707
+ return fresh();
708
+ const own = cursor.state.own;
709
+ if (own?.replay?.open === true && (await stat(locator.file)).size > cursor.offset)
710
+ return fresh();
711
+ // The parent its last read looked for come or gone since (restored from an archive, archived): what the fork copied
712
+ // counts in one place again, as a read from its start would have it.
713
+ if (own?.looked && (await parentNow(locator.file, own.looked.parent, options?.lookups)) !== own.looked.path)
714
+ return fresh();
715
+ // Rewritten between the check and this read, the line reader starts over without the copy and says so (resumed
716
+ // false): the caller reads again from nothing (parseHome), and that read is fresh.
717
+ return lines.read(locator, cursor, options);
718
+ },
719
+ };
720
+ }
721
+ export const codex = codexReader(spec);
722
+ /** The source as lineReader takes it (a test reads with it, its fields or not). */
723
+ export const codexLines = spec;
@@ -0,0 +1,4 @@
1
+ /** A Copilot session file's id from its path: its folder's name (session-state/<id>/events.jsonl), else the older
2
+ * flat file's name (session-state/<id>.jsonl). A session.start's sessionId, where there is one, wins over it. */
3
+ export declare const copilotSessionId: (file: string) => string;
4
+ export declare const copilot: import("../reader.js").Reader<"copilot", import("../lines.js").FileCursor>;