@parcha/agentrun-import 0.1.0-beta.57 → 0.1.0-beta.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -18
- package/dist/cli.js +23 -8
- package/dist/home.d.ts +22 -1
- package/dist/home.js +324 -131
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -2
- package/dist/lines.d.ts +12 -1
- package/dist/lines.js +66 -8
- package/dist/mirror.d.ts +13 -0
- package/dist/mirror.js +15 -0
- package/dist/pool-worker.d.ts +6 -0
- package/dist/pool-worker.js +62 -0
- package/dist/pool.d.ts +80 -0
- package/dist/pool.js +243 -0
- package/dist/price.d.ts +13 -5
- package/dist/price.js +31 -21
- package/dist/read.d.ts +14 -4
- package/dist/read.js +37 -6
- package/dist/reader.d.ts +38 -8
- package/dist/readers/claude-code.js +2 -2
- package/dist/readers/codex.d.ts +7 -1
- package/dist/readers/codex.js +429 -9
- package/dist/readers/copilot.d.ts +4 -0
- package/dist/readers/copilot.js +224 -0
- package/dist/readers/index.d.ts +2 -0
- package/dist/readers/index.js +4 -0
- package/dist/readers/opencode.d.ts +42 -0
- package/dist/readers/opencode.js +920 -0
- package/dist/readers/pi.js +2 -2
- package/dist/record-index.d.ts +4 -0
- package/dist/record-index.js +35 -0
- package/dist/text.d.ts +2 -0
- package/dist/text.js +2 -0
- package/dist/types.d.ts +20 -3
- package/dist/usage.d.ts +6 -2
- package/dist/usage.js +42 -1
- package/dist/wrapped.d.ts +2 -0
- package/dist/wrapped.js +10 -4
- package/package.json +4 -2
package/dist/readers/codex.js
CHANGED
|
@@ -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 {
|
|
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,7 +51,7 @@ function codexFailed(output) {
|
|
|
50
51
|
}
|
|
51
52
|
return undefined;
|
|
52
53
|
}
|
|
53
|
-
function
|
|
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
|
|
@@ -88,16 +89,23 @@ function record(value, at, { state, keep, add }) {
|
|
|
88
89
|
codex.openAt = codex.unpaidAt = undefined;
|
|
89
90
|
};
|
|
90
91
|
if (value.type === "session_meta") {
|
|
91
|
-
|
|
92
|
-
|
|
92
|
+
// A fork writes its parent's session_meta after its own (Codex 0.154): one whose id is the thread this rollout forked
|
|
93
|
+
// from is that copy, and says nothing of this rollout. Any other later session_meta still counts, as Codex writes it.
|
|
94
|
+
const id = str(payload.id);
|
|
95
|
+
if (id && codex.forkedFrom?.has(id))
|
|
96
|
+
return;
|
|
97
|
+
const parent = parentIn(payload);
|
|
98
|
+
for (const from of [str(payload.forked_from_id), parent])
|
|
99
|
+
if (from && from !== id)
|
|
100
|
+
(codex.forkedFrom ??= new Set()).add(from);
|
|
101
|
+
if (id)
|
|
102
|
+
session.id = id;
|
|
93
103
|
if (str(payload.cwd))
|
|
94
104
|
session.cwd = payload.cwd;
|
|
95
105
|
if (str(payload.model_provider))
|
|
96
106
|
codex.provider = payload.model_provider;
|
|
97
107
|
if (str(payload.parent_thread_id) || (isObject(payload.source) && isObject(payload.source.subagent)))
|
|
98
108
|
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
109
|
if (parent)
|
|
102
110
|
session.parent = parent;
|
|
103
111
|
return;
|
|
@@ -230,6 +238,355 @@ function record(value, at, { state, keep, add }) {
|
|
|
230
238
|
add(turn);
|
|
231
239
|
}
|
|
232
240
|
}
|
|
241
|
+
const usageFields = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
|
|
242
|
+
/** 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
|
+
* undefined. Two requests with the same counts are the same key: as ccusage compares them. */
|
|
244
|
+
function usageOf(value, last) {
|
|
245
|
+
const payload = isObject(value.payload) ? value.payload : undefined;
|
|
246
|
+
if (value.type !== "event_msg" || payload?.type !== "token_count" || !isObject(payload.info))
|
|
247
|
+
return undefined;
|
|
248
|
+
const { info } = payload;
|
|
249
|
+
const total = isObject(info.total_token_usage) ? JSON.stringify(info.total_token_usage) : undefined;
|
|
250
|
+
if (total !== undefined && total === last.total)
|
|
251
|
+
return undefined;
|
|
252
|
+
last.total = total;
|
|
253
|
+
const use = isObject(info.last_token_usage) ? info.last_token_usage : undefined;
|
|
254
|
+
const counts = usageFields.map((field) => {
|
|
255
|
+
const n = use?.[field];
|
|
256
|
+
return typeof n === "number" ? n : 0;
|
|
257
|
+
});
|
|
258
|
+
// No usage when every count but the total is 0, as ccusage's CodexRawUsage::is_empty has it: a fork's first
|
|
259
|
+
// token_count can carry only a total_tokens, and that is no request of the parent's to match.
|
|
260
|
+
return counts.slice(0, -1).some((n) => n > 0) ? counts.join(",") : undefined;
|
|
261
|
+
}
|
|
262
|
+
/** The longest run at the start of `child` equal to the start of `parent`, or to its end. */
|
|
263
|
+
function copiedLength(parent, child) {
|
|
264
|
+
const pattern = child.slice(0, parent.length);
|
|
265
|
+
let prefix = 0;
|
|
266
|
+
while (prefix < pattern.length && pattern[prefix] === parent[prefix])
|
|
267
|
+
prefix += 1;
|
|
268
|
+
if (!pattern.length)
|
|
269
|
+
return 0;
|
|
270
|
+
// The longest start of `pattern` that `parent` ends with: a prefix function over it, run along the parent's end.
|
|
271
|
+
const fail = new Array(pattern.length).fill(0);
|
|
272
|
+
for (let i = 1, k = 0; i < pattern.length; i += 1) {
|
|
273
|
+
while (k > 0 && pattern[i] !== pattern[k])
|
|
274
|
+
k = fail[k - 1];
|
|
275
|
+
if (pattern[i] === pattern[k])
|
|
276
|
+
k += 1;
|
|
277
|
+
fail[i] = k;
|
|
278
|
+
}
|
|
279
|
+
let matched = 0;
|
|
280
|
+
for (const use of parent.slice(parent.length - pattern.length)) {
|
|
281
|
+
while (matched > 0 && use !== pattern[matched])
|
|
282
|
+
matched = fail[matched - 1];
|
|
283
|
+
if (use === pattern[matched])
|
|
284
|
+
matched += 1;
|
|
285
|
+
if (matched === pattern.length)
|
|
286
|
+
break;
|
|
287
|
+
}
|
|
288
|
+
return Math.max(prefix, matched);
|
|
289
|
+
}
|
|
290
|
+
/** A rollout's lines, parsed, each record that is a JSON object. A line longer than `maxLine` bytes ends the reading with
|
|
291
|
+
* LineTooLong before it is decoded, as the line reader's does (a read pool's worker bounds its heap so). Its file is
|
|
292
|
+
* closed however the reading stops. */
|
|
293
|
+
async function* recordsOf(file, maxLine = Number.POSITIVE_INFINITY) {
|
|
294
|
+
const handle = await open(file, "r");
|
|
295
|
+
const parsed = (bytes) => {
|
|
296
|
+
try {
|
|
297
|
+
const value = JSON.parse(bytes.toString("utf8"));
|
|
298
|
+
return isObject(value) ? value : undefined;
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
return undefined;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
try {
|
|
305
|
+
const buffer = Buffer.allocUnsafe(1 << 20);
|
|
306
|
+
let rest = [];
|
|
307
|
+
let restBytes = 0;
|
|
308
|
+
let offset = 0;
|
|
309
|
+
for (let at = 0;;) {
|
|
310
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, at);
|
|
311
|
+
if (!bytesRead)
|
|
312
|
+
break;
|
|
313
|
+
at += bytesRead;
|
|
314
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
315
|
+
let from = 0;
|
|
316
|
+
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
|
|
317
|
+
if (restBytes + nl - from > maxLine)
|
|
318
|
+
throw new LineTooLong(file, offset, restBytes + nl - from, maxLine);
|
|
319
|
+
const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
|
|
320
|
+
rest = [];
|
|
321
|
+
restBytes = 0;
|
|
322
|
+
offset += whole.length + 1;
|
|
323
|
+
from = nl + 1;
|
|
324
|
+
const value = parsed(whole);
|
|
325
|
+
if (value)
|
|
326
|
+
yield value;
|
|
327
|
+
}
|
|
328
|
+
if (from < chunk.length) {
|
|
329
|
+
restBytes += chunk.length - from;
|
|
330
|
+
if (restBytes > maxLine)
|
|
331
|
+
throw new LineTooLong(file, offset, restBytes, maxLine);
|
|
332
|
+
// A copy: the buffer is read into again.
|
|
333
|
+
rest.push(Buffer.from(chunk.subarray(from)));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const last = rest.length ? parsed(Buffer.concat(rest)) : undefined;
|
|
337
|
+
if (last)
|
|
338
|
+
yield last;
|
|
339
|
+
}
|
|
340
|
+
finally {
|
|
341
|
+
await handle.close();
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/** 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
|
|
345
|
+
* it. Longer than `maxLine` bytes, it ends the read with LineTooLong before it is decoded. */
|
|
346
|
+
async function firstRecord(file, maxLine = Number.POSITIVE_INFINITY) {
|
|
347
|
+
const handle = await open(file, "r");
|
|
348
|
+
try {
|
|
349
|
+
const chunks = [];
|
|
350
|
+
let bytes = 0;
|
|
351
|
+
for (let position = 0; position < 16 * 1024 * 1024;) {
|
|
352
|
+
const chunk = Buffer.alloc(64 * 1024);
|
|
353
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
|
|
354
|
+
if (bytesRead === 0)
|
|
355
|
+
break;
|
|
356
|
+
const end = chunk.subarray(0, bytesRead).indexOf(10);
|
|
357
|
+
chunks.push(chunk.subarray(0, end === -1 ? bytesRead : end));
|
|
358
|
+
bytes += end === -1 ? bytesRead : end;
|
|
359
|
+
if (bytes > maxLine)
|
|
360
|
+
throw new LineTooLong(file, 0, bytes, maxLine);
|
|
361
|
+
if (end !== -1)
|
|
362
|
+
break;
|
|
363
|
+
position += bytesRead;
|
|
364
|
+
}
|
|
365
|
+
try {
|
|
366
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
367
|
+
return isObject(value) ? value : undefined;
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
finally {
|
|
374
|
+
await handle.close();
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/** The parent's usages, each with its time, as its rollout holds them: the last few read kept, as a parent's forks are
|
|
378
|
+
* read one after another. */
|
|
379
|
+
const parentUsages = new Map();
|
|
380
|
+
async function usagesOf(file, maxLine) {
|
|
381
|
+
const stats = await stat(file);
|
|
382
|
+
const mark = `${stats.size}:${stats.mtimeMs}`;
|
|
383
|
+
const kept = parentUsages.get(file);
|
|
384
|
+
if (kept?.mark === mark)
|
|
385
|
+
return kept;
|
|
386
|
+
const out = { mark, uses: [], ats: [] };
|
|
387
|
+
const last = {};
|
|
388
|
+
for await (const value of recordsOf(file, maxLine)) {
|
|
389
|
+
const use = usageOf(value, last);
|
|
390
|
+
if (use === undefined)
|
|
391
|
+
continue;
|
|
392
|
+
out.uses.push(use);
|
|
393
|
+
out.ats.push(timeOf(value.timestamp));
|
|
394
|
+
}
|
|
395
|
+
parentUsages.delete(file);
|
|
396
|
+
parentUsages.set(file, out);
|
|
397
|
+
if (parentUsages.size > 4)
|
|
398
|
+
parentUsages.delete(parentUsages.keys().next().value);
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
/** Every rollout under a sessions directory by the thread id its name ends with, in the order a walk of its
|
|
402
|
+
* year/month/day directories meets them. */
|
|
403
|
+
async function rolloutsUnder(sessions) {
|
|
404
|
+
const out = new Map();
|
|
405
|
+
for (const year of await entries(sessions)) {
|
|
406
|
+
if (!year.isDirectory())
|
|
407
|
+
continue;
|
|
408
|
+
for (const month of await entries(join(sessions, year.name))) {
|
|
409
|
+
if (!month.isDirectory())
|
|
410
|
+
continue;
|
|
411
|
+
for (const day of await entries(join(sessions, year.name, month.name))) {
|
|
412
|
+
if (!day.isDirectory())
|
|
413
|
+
continue;
|
|
414
|
+
const dir = join(sessions, year.name, month.name, day.name);
|
|
415
|
+
for (const entry of await entries(dir)) {
|
|
416
|
+
const id = entry.isFile() && entry.name.startsWith("rollout-") ? /-([0-9a-f-]{36})\.jsonl$/i.exec(entry.name)?.[1] : undefined;
|
|
417
|
+
if (id)
|
|
418
|
+
(out.get(id) ?? out.set(id, []).get(id)).push(join(dir, entry.name));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return out;
|
|
424
|
+
}
|
|
425
|
+
/** The parent's rollout: in the sessions directory `file` is under, named by the parent's id, on its UUIDv7 date (a
|
|
426
|
+
* day either side, as the directories are local dates) else anywhere there. Anywhere is one walk of the directory per
|
|
427
|
+
* import (`lookups`), however many forks look there, found or not. Not archived_sessions: the import reads no rollout
|
|
428
|
+
* there, and a copy of a parent it does not read is the only count of that history. */
|
|
429
|
+
async function parentFile(file, parent, lookups) {
|
|
430
|
+
const sessions = dirname(dirname(dirname(dirname(file))));
|
|
431
|
+
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;
|
|
432
|
+
if (Number.isFinite(ms)) {
|
|
433
|
+
for (const shift of [0, -1, 1]) {
|
|
434
|
+
const dir = join(sessions, ...new Date(ms + shift * 86_400_000).toISOString().slice(0, 10).split("-"));
|
|
435
|
+
const name = (await entries(dir)).find((entry) => entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(`-${parent}.jsonl`) && join(dir, entry.name) !== file)?.name;
|
|
436
|
+
if (name)
|
|
437
|
+
return join(dir, name);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const key = `codex:rollouts:${sessions}`;
|
|
441
|
+
let index = lookups?.get(key);
|
|
442
|
+
if (!index) {
|
|
443
|
+
index = rolloutsUnder(sessions);
|
|
444
|
+
lookups?.set(key, index);
|
|
445
|
+
}
|
|
446
|
+
// As the tree was when listed: a parent archived or deleted since is found missing when read (forkReplay).
|
|
447
|
+
return (await index).get(parent)?.find((path) => path !== file);
|
|
448
|
+
}
|
|
449
|
+
/** The rollout parentFile finds for `parent` now, when it is there to read; else null. */
|
|
450
|
+
async function parentNow(file, parent, lookups) {
|
|
451
|
+
const path = await parentFile(file, parent, lookups);
|
|
452
|
+
return path ? stat(path).then(() => path, () => null) : null;
|
|
453
|
+
}
|
|
454
|
+
/** The parent's history `file` copied in, when it is a fork that did: read before the fork's own lines, so its records
|
|
455
|
+
* read as copies (record). And the parent it looked for, when it did, so a read going on from its cursor can tell
|
|
456
|
+
* whether that parent has come or gone since. Lines past `maxLine` bytes, in the fork or its parent, end it with
|
|
457
|
+
* LineTooLong. */
|
|
458
|
+
async function forkReplay(file, lookups, maxLine) {
|
|
459
|
+
const first = await firstRecord(file, maxLine);
|
|
460
|
+
const payload = isObject(first?.payload) ? first.payload : undefined;
|
|
461
|
+
if (first?.type !== "session_meta" || !payload)
|
|
462
|
+
return { replay: null };
|
|
463
|
+
const own = str(payload.id)?.trim() || undefined;
|
|
464
|
+
const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
|
|
465
|
+
const spawnedBy = str(spawn?.parent_thread_id);
|
|
466
|
+
const parent = str(payload.forked_from_id) ?? spawnedBy;
|
|
467
|
+
// A rollout that names its history's base reads it by reference, copying none; one named <thread>_<rollout> whose
|
|
468
|
+
// id is the thread goes on with that thread, as no fork.
|
|
469
|
+
if (!parent || payload.history_base !== undefined)
|
|
470
|
+
return { replay: null };
|
|
471
|
+
const named = /-([0-9a-f-]{36})_([0-9a-f-]{36})\.jsonl$/i.exec(basename(file));
|
|
472
|
+
if (named && named[1] !== named[2] && own === named[1])
|
|
473
|
+
return { replay: null };
|
|
474
|
+
const records = recordsOf(file, maxLine);
|
|
475
|
+
let looked;
|
|
476
|
+
try {
|
|
477
|
+
await records.next();
|
|
478
|
+
const forkedAt = timeOf(first.timestamp);
|
|
479
|
+
let stream;
|
|
480
|
+
const parentStream = async () => {
|
|
481
|
+
if (stream)
|
|
482
|
+
return stream;
|
|
483
|
+
const path = await parentFile(file, parent, lookups);
|
|
484
|
+
// A parent gone or unreadable by the time it is read (the walk's index is the import's, listed once) is one the
|
|
485
|
+
// import does not count: the fork's copy is the only count of that history, as when there is no parent.
|
|
486
|
+
const parentRead = path
|
|
487
|
+
? await usagesOf(path, maxLine).catch((error) => {
|
|
488
|
+
if (error instanceof LineTooLong)
|
|
489
|
+
throw error;
|
|
490
|
+
return undefined;
|
|
491
|
+
})
|
|
492
|
+
: undefined;
|
|
493
|
+
looked = { parent, path: parentRead ? path : null };
|
|
494
|
+
if (!parentRead)
|
|
495
|
+
return (stream = []);
|
|
496
|
+
const { uses, ats } = parentRead;
|
|
497
|
+
const cut = forkedAt === undefined ? -1 : ats.findIndex((t) => t !== undefined && t > forkedAt);
|
|
498
|
+
return (stream = cut === -1 ? uses : uses.slice(0, cut));
|
|
499
|
+
};
|
|
500
|
+
const uses = [];
|
|
501
|
+
const last = {};
|
|
502
|
+
let foreign;
|
|
503
|
+
let boundary;
|
|
504
|
+
let marked = false;
|
|
505
|
+
// Whether the read reached the file's end with the copy's end unknown: no own marker, and the run could still grow.
|
|
506
|
+
let ended = true;
|
|
507
|
+
// Whether the usages so far are the parent's first ones, and where in the parent's they could start a run that ends
|
|
508
|
+
// at its end: while either holds the copied run can grow, so the read goes on.
|
|
509
|
+
let prefix = true;
|
|
510
|
+
let starts = [];
|
|
511
|
+
const grows = (parentUses, use) => {
|
|
512
|
+
const i = uses.length - 1;
|
|
513
|
+
prefix &&= parentUses[i] === use;
|
|
514
|
+
starts = i === 0 ? parentUses.flatMap((u, j) => (u === use ? [j] : [])) : starts.filter((j) => j + i < parentUses.length && parentUses[j + i] === use);
|
|
515
|
+
return uses.length < parentUses.length && (prefix || starts.length > 0);
|
|
516
|
+
};
|
|
517
|
+
for await (const value of records) {
|
|
518
|
+
const p = isObject(value.payload) ? value.payload : undefined;
|
|
519
|
+
const marker = value.type === "token_usage_record" ? "record" : value.type === "event_msg" && p?.type === "thread_settings_applied" ? "settings" : undefined;
|
|
520
|
+
if (marker) {
|
|
521
|
+
const thread = str(p?.thread_id)?.trim() || undefined;
|
|
522
|
+
if (thread)
|
|
523
|
+
marked = true;
|
|
524
|
+
if (thread && thread === own) {
|
|
525
|
+
boundary = uses.length;
|
|
526
|
+
ended = false;
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
if (marker === "record" && !thread && spawnedBy) {
|
|
530
|
+
ended = false;
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
533
|
+
if (thread && own)
|
|
534
|
+
foreign ??= uses.length;
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const use = usageOf(value, last);
|
|
538
|
+
if (use === undefined)
|
|
539
|
+
continue;
|
|
540
|
+
uses.push(use);
|
|
541
|
+
// Read on only while the copied run can still grow, or while a thread's marker may yet bound one.
|
|
542
|
+
if (!grows(await parentStream(), use) && !marked) {
|
|
543
|
+
ended = false;
|
|
544
|
+
break;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const window = uses.slice(0, boundary ?? uses.length);
|
|
548
|
+
const skip = [];
|
|
549
|
+
if (window.length) {
|
|
550
|
+
const copied = copiedLength(await parentStream(), window);
|
|
551
|
+
if (copied)
|
|
552
|
+
skip.push([0, copied]);
|
|
553
|
+
}
|
|
554
|
+
// Copied, and counted in the parent, only when the parent's rollout was read: else nothing counts it but the fork.
|
|
555
|
+
if (foreign !== undefined && boundary !== undefined && boundary > foreign && looked?.path)
|
|
556
|
+
skip.push([foreign, boundary]);
|
|
557
|
+
const found = looked ? { looked } : {};
|
|
558
|
+
if (!skip.length && !ended)
|
|
559
|
+
return { replay: null, ...found };
|
|
560
|
+
return { replay: { skip, until: skip.length ? Math.max(...skip.map(([, to]) => to)) - 1 : -1, seen: 0, open: ended }, ...found };
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
await records.return(undefined);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
/** One record: a fork's copy of its parent's history is read as a copy (forkReplay); a turn_context in it still sets
|
|
567
|
+
* the model and effort, and a usage in it that is no copy counts. */
|
|
568
|
+
function record(value, at, context) {
|
|
569
|
+
const { own } = context.state;
|
|
570
|
+
const replay = own.replay;
|
|
571
|
+
if (!replay || replay.seen > replay.until || value.type === "session_meta")
|
|
572
|
+
return readRecord(value, at, context);
|
|
573
|
+
const use = usageOf(value, replay);
|
|
574
|
+
if (use !== undefined) {
|
|
575
|
+
const ordinal = replay.seen;
|
|
576
|
+
replay.seen += 1;
|
|
577
|
+
if (!replay.skip.some(([from, to]) => ordinal >= from && ordinal < to))
|
|
578
|
+
return readRecord(value, at, context);
|
|
579
|
+
own.total = replay.total;
|
|
580
|
+
own.open = own.unpaid = undefined;
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
if (value.type === "turn_context")
|
|
584
|
+
readRecord(value, at, context);
|
|
585
|
+
else if (value.type === "token_usage_record")
|
|
586
|
+
own.records = true;
|
|
587
|
+
own.open = own.unpaid = undefined;
|
|
588
|
+
return false;
|
|
589
|
+
}
|
|
233
590
|
const spec = {
|
|
234
591
|
source: "codex",
|
|
235
592
|
name: "Codex",
|
|
@@ -278,4 +635,67 @@ const spec = {
|
|
|
278
635
|
// A turns: false cursor keeps each held prompt for its count alone: a read resumed from it gives no first prompt.
|
|
279
636
|
forget: (own) => ({ ...own, held: own.held.map(({ index, turn }) => ({ index, turn: { ...turn, text: "" } })) }),
|
|
280
637
|
};
|
|
281
|
-
|
|
638
|
+
/** The thread a session_meta payload names as the one it ran under. */
|
|
639
|
+
function parentIn(payload) {
|
|
640
|
+
const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
|
|
641
|
+
return str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
|
|
642
|
+
}
|
|
643
|
+
/** How much of a rollout parentOf reads at most: its first line, session_meta, holds the instructions the thread ran
|
|
644
|
+
* with (some 20 KB, more with its tools), read to its end within this. */
|
|
645
|
+
const FIRST_LINE_BYTES = 64 * 1024 * 1024;
|
|
646
|
+
const CHUNK_BYTES = 256 * 1024;
|
|
647
|
+
/** The thread a rollout ran under, from its first line alone (session_meta), read to its end but never past
|
|
648
|
+
* 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
|
|
649
|
+
* for it. None when that line does not end within it. */
|
|
650
|
+
async function parentOf({ file }) {
|
|
651
|
+
const handle = await open(file, "r");
|
|
652
|
+
try {
|
|
653
|
+
const line = [];
|
|
654
|
+
for (let at = 0;;) {
|
|
655
|
+
if (at >= FIRST_LINE_BYTES)
|
|
656
|
+
return undefined;
|
|
657
|
+
const chunk = Buffer.alloc(CHUNK_BYTES);
|
|
658
|
+
const { bytesRead } = await handle.read(chunk, 0, CHUNK_BYTES, at);
|
|
659
|
+
const end = chunk.subarray(0, bytesRead).indexOf(10);
|
|
660
|
+
line.push(chunk.subarray(0, end < 0 ? bytesRead : end));
|
|
661
|
+
at += bytesRead;
|
|
662
|
+
if (end >= 0 || bytesRead < CHUNK_BYTES)
|
|
663
|
+
break;
|
|
664
|
+
}
|
|
665
|
+
const value = JSON.parse(Buffer.concat(line).toString("utf8"));
|
|
666
|
+
return isObject(value) && value.type === "session_meta" && isObject(value.payload) ? parentIn(value.payload) : undefined;
|
|
667
|
+
}
|
|
668
|
+
catch {
|
|
669
|
+
return undefined;
|
|
670
|
+
}
|
|
671
|
+
finally {
|
|
672
|
+
await handle.close();
|
|
673
|
+
}
|
|
674
|
+
}
|
|
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
|
+
};
|
|
@@ -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>;
|