@parcha/agentrun-import 0.1.0-beta.58 → 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/dist/home.js CHANGED
@@ -1,15 +1,21 @@
1
1
  // Every session under a home, as totals: what each used, its subagents' requests with it, and what it cost. A session is
2
2
  // one per source and id, however many files write it (a Codex thread resumed in a new file, a Claude Code session copied
3
- // into a resumed one's); a subagent's is no session of its own but its parent's.
3
+ // into a resumed one's); a subagent's is no session of its own but its parent's. A request another source's session also
4
+ // holds (an OpenCode claude-agent request, which Claude Code writes too: its `mirrors`) is that session's, when the same
5
+ // call reads it, and counts once there.
4
6
  import { createHash } from "node:crypto";
7
+ import { stat } from "node:fs/promises";
8
+ import { availableParallelism } from "node:os";
5
9
  import { relative, sep } from "node:path";
6
- import { builtinCatalog, priceRequests } from "./price.js";
10
+ import { builtinCatalog, loadCalculateCost, priceRequest, priceRequests, roundUsd } from "./price.js";
7
11
  import { childrenOf, inOrder, readerOf, sessionLocators } from "./read.js";
8
12
  import { locatorKey } from "./reader.js";
9
13
  import { READERS, SOURCES } from "./readers/index.js";
10
- import { AT, HAS_LONG, HAS_REASONING, HAS_USAGE, STRIDE, USAGE_FIELDS } from "./counts.js";
11
- import { addAll, addRecord, dropOwner, locatorNumber, ownerOf, recordIndex } from "./record-index.js";
14
+ import { addRequest, atOf, counts as noCounts, HAS_LONG, HAS_REASONING, HAS_USAGE, STRIDE, trimmed } from "./counts.js";
15
+ import { OLD_MB, ReadPool, readAheadBytes } from "./pool.js";
16
+ import { addAll, addRecord, dropOwner, locatorNumber, ownAll, ownerOf, recordIndex, someRecord } from "./record-index.js";
12
17
  import { packed, packInto } from "./record-key.js";
18
+ import { mirroredIn, sessionKey } from "./mirror.js";
13
19
  import { addTokens, noTokens } from "./usage.js";
14
20
  /** The shape of the HomeState this version keeps: a state of any other is set aside. */
15
21
  const STATE_VERSION = 1;
@@ -29,121 +35,240 @@ const keyOf = (home, { file, id }) => {
29
35
  const path = relative(home, file).split(sep).join("/");
30
36
  return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
31
37
  };
32
- /** `read` as a total takes it (Compact), each request's model the one totalsOf prices it at. */
33
- function compact(read, models) {
38
+ const requestsOf = (read) => ("n" in read ? read.n : read.counts.n);
39
+ /** Tokens summed as reads come cannot round: thrown when a count is not a whole number of at most 2^53 - 1 or a source's
40
+ * sum would pass it, and the source is read again with each request's tokens kept. */
41
+ class Inexact extends Error {
42
+ }
43
+ /** The default threads' ceiling (ParseOptions.threads). */
44
+ const MAX_THREADS = 8;
45
+ /** The most threads parseHome takes: each is a worker with a heap of its own, and past the cores the largest files set
46
+ * the time anyway. More is refused before any worker starts. */
47
+ export const MOST_THREADS = 64;
48
+ /** `read` as a total takes it (Unpriced): its session's counts and ids, and its requests as Counts. A totals read's
49
+ * counts are kept as read; a reader with no totals read gives its requests whole, and they are counted the same way. */
50
+ function compact(read) {
34
51
  const { id, child, parent, users, copies, costUsd, model } = read.session;
35
- const { counts } = read;
36
- if (counts) {
37
- // A totals read's requests, as read: each one's model mapped to the pass's (its own, else the session's).
38
- const intern = (name) => {
39
- if (name === undefined)
40
- return -1;
41
- let at = models.index.get(name);
42
- if (at === undefined)
43
- models.index.set(name, (at = models.names.push(name) - 1));
44
- return at;
45
- };
46
- const names = counts.models.map(intern);
47
- const fallback = intern(model);
48
- // Each request's usage numbers, and apart from them its time (counts' stride is STRIDE, the time at AT).
49
- const usage = new Float64Array(counts.n * USAGE_FIELDS);
50
- const at = new Float64Array(counts.n);
51
- for (let i = 0; i < counts.n; i += 1) {
52
- usage.set(counts.values.subarray(i * STRIDE, i * STRIDE + USAGE_FIELDS), i * USAGE_FIELDS);
53
- at[i] = counts.values[i * STRIDE + AT];
54
- }
55
- return {
56
- session: { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) },
57
- models: counts.model.slice(0, counts.n).map((at) => (at === -1 ? fallback : names[at])),
58
- usage,
59
- has: counts.has.slice(0, counts.n),
60
- at,
61
- };
62
- }
63
- const n = read.requests.length;
64
- const out = { session: { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) }, models: new Int32Array(n), usage: new Float64Array(n * USAGE_FIELDS), has: new Uint8Array(n), at: new Float64Array(n) };
65
- for (let i = 0; i < n; i += 1) {
66
- const request = read.requests[i];
67
- out.at[i] = request.at;
68
- const name = request.model ?? model;
69
- let at = -1;
70
- if (name !== undefined) {
71
- at = models.index.get(name) ?? -1;
72
- if (at === -1)
73
- models.index.set(name, (at = models.names.push(name) - 1));
74
- }
75
- out.models[i] = at;
76
- const { usage } = request;
77
- if (!usage)
78
- continue;
79
- const o = i * USAGE_FIELDS;
80
- out.usage[o] = usage.input;
81
- out.usage[o + 1] = usage.output;
82
- out.usage[o + 2] = usage.cacheRead;
83
- out.usage[o + 3] = usage.cacheWrite;
84
- let has = HAS_USAGE;
85
- if (usage.cacheWrite1h !== undefined) {
86
- out.usage[o + 4] = usage.cacheWrite1h;
87
- has |= HAS_LONG;
88
- }
89
- if (usage.reasoning !== undefined) {
90
- out.usage[o + 5] = usage.reasoning;
91
- has |= HAS_REASONING;
92
- }
93
- out.has[i] = has;
94
- }
52
+ const session = { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) };
53
+ if (read.counts)
54
+ return { session, counts: trimmed(read.counts) };
55
+ const counts = noCounts();
56
+ for (const request of read.requests)
57
+ addRequest(counts, request.model, request.usage, request.at);
58
+ const out = { session, counts: trimmed(counts) };
59
+ if (read.requests.some((request) => request.mirrors !== undefined))
60
+ out.mirrors = { of: read.requests.map((request) => request.mirrors), cost: Float64Array.from(read.requests, (request) => request.costUsd ?? Number.NaN) };
95
61
  return out;
96
62
  }
97
63
  /** The i-th request of `read` as priceRequests and the requests sink take it. */
98
- function requestAt(read, i, models) {
99
- const index = read.models[i];
100
- const model = index === -1 ? undefined : models.names[index];
101
- const request = { at: read.at[i], ...(model !== undefined ? { model } : {}) };
102
- const has = read.has[i];
64
+ function requestAt({ session, counts }, i) {
65
+ // Its own model, else the session's.
66
+ const model = counts.models[counts.model[i]] ?? session.model;
67
+ const request = { at: atOf(counts, i), ...(model !== undefined ? { model } : {}) };
68
+ const has = counts.has[i];
103
69
  if (!(has & HAS_USAGE))
104
70
  return request;
105
- const o = i * USAGE_FIELDS;
106
- const usage = { input: read.usage[o], output: read.usage[o + 1], cacheRead: read.usage[o + 2], cacheWrite: read.usage[o + 3] };
71
+ const { values } = counts;
72
+ const o = i * STRIDE;
73
+ const usage = { input: values[o], output: values[o + 1], cacheRead: values[o + 2], cacheWrite: values[o + 3] };
107
74
  if (has & HAS_LONG)
108
- usage.cacheWrite1h = read.usage[o + 4];
75
+ usage.cacheWrite1h = values[o + 4];
109
76
  if (has & HAS_REASONING)
110
- usage.reasoning = read.usage[o + 5];
77
+ usage.reasoning = values[o + 5];
111
78
  return { ...request, usage };
112
79
  }
80
+ const TOKEN_FIELDS = 6;
81
+ /** `read` priced (Counted), its tokens added to `sums` (the source's so far). */
82
+ function counted(read, pricer, sums) {
83
+ const { n } = read.counts;
84
+ const tokens = new Float64Array(TOKEN_FIELDS);
85
+ const { catalog, calculate } = pricer;
86
+ const costs = catalog && calculate ? new Float64Array(n) : undefined;
87
+ let unpriceable = false;
88
+ for (let i = 0; i < n; i += 1) {
89
+ const request = requestAt(read, i);
90
+ const { usage } = request;
91
+ if (usage) {
92
+ const counts = [usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.cacheWrite1h ?? 0, usage.reasoning ?? 0];
93
+ for (let k = 0; k < TOKEN_FIELDS; k += 1) {
94
+ const count = counts[k];
95
+ if (!Number.isSafeInteger(count) || count < 0)
96
+ throw new Inexact();
97
+ tokens[k] += count;
98
+ }
99
+ }
100
+ if (costs && !unpriceable) {
101
+ const usd = priceRequest(request, catalog, calculate);
102
+ if (usd === undefined)
103
+ unpriceable = true;
104
+ else
105
+ costs[i] = usd;
106
+ }
107
+ }
108
+ for (let k = 0; k < TOKEN_FIELDS; k += 1)
109
+ if ((sums[k] += tokens[k]) > Number.MAX_SAFE_INTEGER)
110
+ throw new Inexact();
111
+ return { session: read.session, n, tokens, costs, unpriceable };
112
+ }
113
+ /** A session's cost with its subagents': Claude Code's written cost holds its subagents' already (its cost-state), so it
114
+ * stays as it is; every other source writes a subagent's cost on the subagent's own session, so each is added. Unknown
115
+ * when the session's is, or when one it adds is: never a subagent counted at 0. parseHome's totals and serve's import. */
116
+ export function withSubagentCosts(source, cost, subagents) {
117
+ if (source === "claude-code" || cost === undefined)
118
+ return cost;
119
+ return subagents.reduce((sum, usd) => (sum === undefined || usd === undefined ? undefined : sum + usd), cost);
120
+ }
121
+ /** A part with its own requests alone (none another session of the call holds) and the cost it wrote of them: its own
122
+ * when it holds none of another's, else its own requests' when each that used tokens is priced (mirror.ts ownRequests,
123
+ * over the packed requests). Counted when `unpriced` is false and the prices are in hand (a part whose requests mirror
124
+ * another's is kept Unpriced until the call knows which sessions it read). */
125
+ function ownPart(read, mirrored, pricer, unpriced) {
126
+ if ("n" in read || !read.mirrors)
127
+ return read;
128
+ const marks = read.mirrors;
129
+ const { counts } = read;
130
+ const at = Array.from({ length: counts.n }, (_, i) => i).filter((i) => !mirrored({ mirrors: marks.of[i] }));
131
+ let own = read;
132
+ if (at.length !== counts.n) {
133
+ const priced = at.every((i) => !Number.isNaN(marks.cost[i]) || !(counts.has[i] & HAS_USAGE));
134
+ const costUsd = priced ? at.reduce((n, i) => n + (Number.isNaN(marks.cost[i]) ? 0 : marks.cost[i]), 0) : undefined;
135
+ const { costUsd: _, ...session } = read.session;
136
+ // Its own requests' rows of Counts (each STRIDE numbers: usage and time), their model indexes and HAS_* bits.
137
+ const values = new Float64Array(at.length * STRIDE);
138
+ for (const [k, i] of at.entries())
139
+ values.set(counts.values.subarray(i * STRIDE, (i + 1) * STRIDE), k * STRIDE);
140
+ own = {
141
+ session: { ...session, ...(costUsd !== undefined ? { costUsd } : {}) },
142
+ counts: { n: at.length, models: counts.models, model: Int32Array.from(at, (i) => counts.model[i]), values, has: Uint8Array.from(at, (i) => counts.has[i]) },
143
+ };
144
+ }
145
+ return unpriced || !pricer.ready ? own : counted(own, pricer, new Float64Array(TOKEN_FIELDS));
146
+ }
113
147
  /** Every session of `sources` under `home`, as totals, sorted by key. */
114
- export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests } = {}) {
115
- let prices;
116
- const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
117
- const out = [];
118
- const failed = [];
119
- if (state) {
120
- if (state.version !== STATE_VERSION) {
121
- state.version = STATE_VERSION;
122
- state.sources = {};
148
+ export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests, threads = Math.min(availableParallelism(), MAX_THREADS), readAhead = readAheadBytes(), workerOldMb = OLD_MB } = {}) {
149
+ if (!Number.isSafeInteger(threads) || threads < 1 || threads > MOST_THREADS)
150
+ throw new RangeError(`threads: a whole number from 1 to ${MOST_THREADS}, not ${threads}`);
151
+ if (!(readAhead >= 0))
152
+ throw new RangeError(`readAhead: a number of bytes, 0 or more, not ${readAhead}`);
153
+ if (!Number.isSafeInteger(workerOldMb) || workerOldMb < 1)
154
+ throw new RangeError(`workerOldMb: a whole number of MB, at least 1, not ${workerOldMb}`);
155
+ const pool = !state && readers === READERS && threads > 1 ? new ReadPool(threads, readAhead, workerOldMb) : undefined;
156
+ try {
157
+ let prices;
158
+ const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
159
+ const out = [];
160
+ const failed = [];
161
+ if (state) {
162
+ if (state.version !== STATE_VERSION) {
163
+ state.version = STATE_VERSION;
164
+ state.sources = {};
165
+ }
166
+ state.read = 0;
167
+ }
168
+ // What readers look up once for this import (a Codex fork's parent anywhere in its sessions), shared by its files.
169
+ const lookups = new Map();
170
+ // Requests are priced as they are read once the prices are in hand: at once when the caller handed them in (or none),
171
+ // else loaded when a session is read that the totals will price, as they would load them. A requests sink takes each
172
+ // request with its time, so with one every part keeps its requests (Unpriced) to the totals.
173
+ const pricer = {
174
+ ready: catalog === false || (catalog !== undefined && calculateCost !== undefined),
175
+ ...(catalog ? { catalog } : {}),
176
+ ...(catalog && calculateCost ? { calculate: calculateCost } : {}),
177
+ async load() {
178
+ if (this.ready)
179
+ return;
180
+ this.catalog = await priceWith();
181
+ this.calculate = this.catalog ? (calculateCost ?? (await loadCalculateCost())) : undefined;
182
+ this.ready = true;
183
+ },
184
+ };
185
+ const whole = requests !== undefined;
186
+ // With a pool, every source is listed first and all their files queued at once, in the import's order: a source's last
187
+ // files then share the threads with the next source's, and the largest files of every source are read first (pool.ts).
188
+ const ahead = new Map();
189
+ if (pool) {
190
+ for (const source of sources)
191
+ ahead.set(source, await listSource(home, source, readers, env, true));
192
+ const items = [...ahead].flatMap(([source, { listed, childList }]) => [...listed.map(({ locator, stats }) => ({ source, locator, size: stats.size })), ...childList.map(({ locator, size }) => ({ source, locator, size }))]);
193
+ const ids = pool.readAll(items);
194
+ let at = 0;
195
+ for (const listing of ahead.values()) {
196
+ listing.ids = ids.slice(at, (at += listing.listed.length + listing.childList.length));
197
+ listing.reads = listing.ids.map((id) => () => pool.take(id));
198
+ }
199
+ }
200
+ // Every session this call read, by source and id, and the sources held to be totalled after the rest.
201
+ const readKeys = new Set();
202
+ const mirroring = [];
203
+ for (const source of sources) {
204
+ let read;
205
+ try {
206
+ read = await readSource(home, source, readers, env, state, lookups, pricer, whole, ahead.get(source));
207
+ }
208
+ catch (error) {
209
+ if (!(error instanceof Inexact))
210
+ throw error;
211
+ // Tokens that cannot be summed as read: the source again, each request's tokens kept to the totals.
212
+ if (state)
213
+ (state.sources ??= {})[source] = undefined;
214
+ // The pool's reads of this source left untaken would hold the read-ahead for nothing.
215
+ pool?.drop(ahead.get(source)?.ids ?? []);
216
+ read = await readSource(home, source, readers, env, state, lookups, pricer, true);
217
+ }
218
+ const { tops, children, unread } = read;
219
+ for (const part of [...tops, ...children])
220
+ readKeys.add(sessionKey(source, part.read.session.id));
221
+ // A source whose requests mirror another's (OpenCode's claude-agent ones) is totalled once every source is read: a
222
+ // mirrored request counts in the session it mirrors when this call reads that one too.
223
+ if ([...tops, ...children].some(({ read }) => "mirrors" in read && read.mirrors))
224
+ mirroring.push({ source, read });
225
+ else
226
+ out.push(...(await totalsOf(home, source, tops, children, pricer, priceWith, calculateCost, requests)));
227
+ failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
123
228
  }
124
- state.read = 0;
229
+ // A request that mirrors a session this call read is counted in it, not again: each part keeps its own requests alone.
230
+ const mirrored = mirroredIn(readKeys);
231
+ for (const held of mirroring) {
232
+ const { source } = held;
233
+ let { read } = held;
234
+ const own = (all) => {
235
+ for (const part of [...read.tops, ...read.children])
236
+ part.read = ownPart(part.read, mirrored, pricer, all);
237
+ };
238
+ try {
239
+ // Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else Unpriced.
240
+ own(whole || ![...read.tops, ...read.children].some((part) => "n" in part.read));
241
+ }
242
+ catch (error) {
243
+ if (!(error instanceof Inexact))
244
+ throw error;
245
+ // As a source read above: again, each request's tokens kept to the totals.
246
+ if (state)
247
+ (state.sources ??= {})[source] = undefined;
248
+ read = await readSource(home, source, readers, env, state, lookups, pricer, true);
249
+ own(true);
250
+ }
251
+ out.push(...(await totalsOf(home, source, read.tops, read.children, pricer, priceWith, calculateCost, requests)));
252
+ }
253
+ if (failed.length && !failures)
254
+ throw new ReadFailures(failed);
255
+ failures?.push(...failed);
256
+ return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
125
257
  }
126
- for (const source of sources) {
127
- const models = { names: [], index: new Map() };
128
- const { tops, children, unread } = await readSource(home, source, readers, env, state, models);
129
- out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost, requests)));
130
- failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
258
+ finally {
259
+ pool?.close();
131
260
  }
132
- if (failed.length && !failures)
133
- throw new ReadFailures(failed);
134
- failures?.push(...failed);
135
- return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
136
261
  }
137
- /** `source`'s locators read in the import's order, sessions first, then the subagents beside them, through one `seen`.
138
- * A pass handed a state goes on from its cursors, and comes out as a fresh pass would: a record copied into many files
139
- * counts in the first of them in the order as it is now. The whole source is read again when a locator it read before is
140
- * gone, when its reader could not go on from its cursor (a new inode, truncated, rewritten), or when a locator holding a
141
- * copy now comes before the one its record counts in (an append moved an older file after its resumed copy, a new file
142
- * sorts before one it shares records with). A change of order among locators that share no record reads nothing again. */
143
- async function readSource(home, source, readers, env, state, models) {
144
- const reader = readerOf(source, readers);
262
+ async function listSource(home, source, readers, env, sized = false) {
145
263
  const listed = await inOrder(await sessionLocators(home, source, { ...(env ? { env } : {}), readers }), source, readers);
146
- const childList = await childrenOf(home, source, { ...(env ? { env } : {}), readers });
264
+ const children = await childrenOf(home, source, { ...(env ? { env } : {}), readers });
265
+ const childList = await Promise.all(children.map(async (child) => ({ ...child, size: sized ? ((await stat(child.locator.file).catch(() => undefined))?.size ?? 0) : 0 })));
266
+ return { listed, childList };
267
+ }
268
+ async function readSource(home, source, readers, env, state, lookups, pricer, whole, listing) {
269
+ const reader = readerOf(source, readers);
270
+ // The pool's listing, when parseHome read this source ahead (pool.ts); each read is taken below in order, or made again.
271
+ const { listed, childList, reads: ahead } = listing ?? (await listSource(home, source, readers, env));
147
272
  // Each locator's place in this pass's order of reading.
148
273
  const place = new Map([...listed.map(({ locator }) => locatorKey(locator)), ...childList.map(({ locator }) => locatorKey(locator))].map((key, at) => [key, at]));
149
274
  // Whether a locator holds a copy of a record that now counts after it: the fresh pass would count it in that locator.
@@ -154,12 +279,14 @@ async function readSource(home, source, readers, env, state, models) {
154
279
  // read from its start and its state rebuilt.
155
280
  if (kept && ([...kept.cursors.keys()].some((key) => !place.has(key)) || outOfOrder(kept)))
156
281
  kept = undefined;
282
+ // A pass from nothing is the last: only its sessions may load the prices (one resumed may be read again).
283
+ const fresh = !kept || kept.cursors.size === 0;
157
284
  if (state && !kept)
158
285
  kept = state.sources[source] = { cursors: new Map(), owners: recordIndex(), copied: new Map() };
159
286
  const { owners, copied } = kept ?? { owners: recordIndex(), copied: new Map() };
160
287
  let restarted = false;
161
288
  const unread = [];
162
- const read = async (locator) => {
289
+ const read = async (locator, pooled) => {
163
290
  const key = locatorKey(locator);
164
291
  const cursor = kept?.cursors.get(key);
165
292
  // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. Both are
@@ -189,7 +316,17 @@ async function readSource(home, source, readers, env, state, models) {
189
316
  return this;
190
317
  },
191
318
  };
192
- const result = await reader.read(locator, cursor, { turns: false, totals: true, seen }).catch((error) => void unread.push({ locator, error }));
319
+ if (pooled) {
320
+ // The pool's read is this one when none of the records it added, or asked for and did not hold, is one read before it.
321
+ const made = await pooled();
322
+ const held = (record) => ownerOf(owners, record) !== -1;
323
+ if (made.ok && !someRecord(made.mine, held) && !someRecord(made.missed, held)) {
324
+ ownAll(made.mine, me);
325
+ addAll(owners, made.mine);
326
+ return made.sessions;
327
+ }
328
+ }
329
+ const result = await reader.read(locator, cursor, { turns: false, totals: true, seen, lookups }).catch((error) => void unread.push({ locator, error }));
193
330
  if (!result) {
194
331
  // A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
195
332
  // would hold none of them: the next pass reads it from its start. A locator that found them already read (a
@@ -215,16 +352,33 @@ async function readSource(home, source, readers, env, state, models) {
215
352
  return result.sessions;
216
353
  };
217
354
  const tops = [];
355
+ const children = [];
356
+ const sums = new Float64Array(TOKEN_FIELDS);
218
357
  // Each locator's sessions packed as soon as they are read. A totals read gives each request's counts alone, and its
219
358
  // cursor, kept in a state between passes, holds those too: no request is held as an object, by a pass or a state. A
220
- // reader with no totals read gives its requests whole: only one locator's are held so at a time.
221
- for (const { locator } of listed)
222
- for (const session of await read(locator))
223
- tops.push({ locator: session.locator, read: compact(session, models) });
224
- const children = [];
225
- for (const { locator, of } of childList)
226
- for (const session of await read(locator))
227
- children.push({ locator: session.locator, read: compact(session, models), of });
359
+ // reader with no totals read gives its requests whole: only one locator's are held so at a time. Without a requests
360
+ // sink each part is priced once the prices are in hand. A session's own file that wrote no cost and is no file of
361
+ // copies alone is one the totals price: the prices are loaded then, and the parts read so far priced.
362
+ const pack = async (session, top) => {
363
+ const unpriced = compact(session);
364
+ // A part whose requests mirror another's stays Unpriced: its own are known once every source is read (ownPart).
365
+ if (whole || unpriced.mirrors)
366
+ return unpriced;
367
+ const { child, parent, costUsd, copies, users } = session.session;
368
+ if (!pricer.ready && fresh && top && !(child && parent) && costUsd === undefined && !(copies > 0 && users === 0 && (session.counts?.n ?? session.requests.length) === 0)) {
369
+ await pricer.load();
370
+ for (const part of [...tops, ...children])
371
+ if (!("n" in part.read) && !part.read.mirrors)
372
+ part.read = counted(part.read, pricer, sums);
373
+ }
374
+ return pricer.ready ? counted(unpriced, pricer, sums) : unpriced;
375
+ };
376
+ for (const [i, { locator }] of listed.entries())
377
+ for (const session of await read(locator, pass === 0 ? ahead?.[i] : undefined))
378
+ tops.push({ locator: session.locator, read: await pack(session, true) });
379
+ for (const [i, { locator, of }] of childList.entries())
380
+ for (const session of await read(locator, pass === 0 ? ahead?.[listed.length + i] : undefined))
381
+ children.push({ locator: session.locator, read: await pack(session, false), of });
228
382
  // A locator its reader could not go on in, or a copy this pass found whose record counts after it: read the source
229
383
  // again, from nothing.
230
384
  if (pass > 0 || !kept || !(restarted || outOfOrder(kept)))
@@ -232,7 +386,7 @@ async function readSource(home, source, readers, env, state, models) {
232
386
  state.sources[source] = undefined;
233
387
  }
234
388
  }
235
- async function totalsOf(home, source, tops, children, models, priceWith, calculateCost, sink) {
389
+ async function totalsOf(home, source, tops, children, pricer, priceWith, calculateCost, sink) {
236
390
  // Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
237
391
  // parent's, as is each one beside a session's (Claude Code's subagents).
238
392
  const sessions = new Map();
@@ -278,28 +432,59 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
278
432
  for (const { parts, children: subagents, untied } of sessions.values()) {
279
433
  // A session whose every file holds only records an earlier file holds (copies) is no session: its records count where
280
434
  // they were first read. serve's import leaves such a file out the same way.
281
- if (parts.every(({ read }) => read.session.copies > 0 && read.session.users === 0 && read.models.length === 0) && subagents.length === 0)
435
+ if (parts.every(({ read }) => read.session.copies > 0 && read.session.users === 0 && requestsOf(read) === 0) && subagents.length === 0)
282
436
  continue;
283
437
  const first = parts[0];
284
438
  const tokens = noTokens();
285
439
  let reasoning = 0;
286
440
  let calls = 0;
441
+ // Parts priced as read (Counted) or not (Unpriced): a source's are all one or all the other, and all Unpriced with a sink.
442
+ const all = [...parts, ...subagents].map(({ read }) => read);
443
+ const priced = all.filter((read) => "n" in read);
444
+ if (priced.length && (priced.length !== all.length || sink))
445
+ throw new Error("parts priced and not in one session");
287
446
  const requests = [];
288
- for (const { read } of [...parts, ...subagents])
289
- for (let i = 0; i < read.models.length; i += 1)
290
- requests.push(requestAt(read, i, models));
291
- for (const { usage } of requests) {
292
- calls += 1;
293
- if (!usage)
294
- continue;
295
- addTokens(tokens, usage);
296
- reasoning += usage.reasoning ?? 0;
447
+ if (priced.length) {
448
+ // Whole counts summed below 2^53: the same sums in any order.
449
+ for (const read of priced) {
450
+ calls += read.n;
451
+ tokens.input += read.tokens[0];
452
+ tokens.output += read.tokens[1];
453
+ tokens.cacheRead += read.tokens[2];
454
+ tokens.cacheWrite += read.tokens[3];
455
+ tokens.cacheWrite1h += read.tokens[4];
456
+ reasoning += read.tokens[5];
457
+ }
458
+ }
459
+ else {
460
+ for (const read of all)
461
+ for (let i = 0; i < read.counts.n; i += 1)
462
+ requests.push(requestAt(read, i));
463
+ for (const { usage } of requests) {
464
+ calls += 1;
465
+ if (!usage)
466
+ continue;
467
+ addTokens(tokens, usage);
468
+ reasoning += usage.reasoning ?? 0;
469
+ }
297
470
  }
298
- // The source's own cost, when each of its files wrote one: Claude Code writes the session's running total (a moved
299
- // session's copy goes on from the original's), so the highest; another source prices each request, so their sum.
300
- const written = parts.flatMap(({ read }) => (read.session.costUsd !== undefined ? [read.session.costUsd] : []));
301
- let cost = written.length === parts.length ? (source === "claude-code" ? Math.max(...written) : written.reduce((n, usd) => n + usd, 0)) : undefined;
302
- if (cost === undefined) {
471
+ // The source's own cost, when each of its files wrote one: Claude Code writes the session's running total, its
472
+ // subagents' with it (a moved session's copy goes on from the original's), so the highest; another source prices each
473
+ // request, so the sum of its files' and its subagents' (OpenCode's subagent is a session of its own).
474
+ const written = parts.map(({ read }) => read.session.costUsd);
475
+ const files = written.some((usd) => usd === undefined) ? undefined : source === "claude-code" ? Math.max(...written) : written.reduce((n, usd) => n + usd, 0);
476
+ let cost = withSubagentCosts(source, files, subagents.map(({ read }) => read.session.costUsd));
477
+ if (cost === undefined && priced.length) {
478
+ // Each request's cost as priced when read, summed in the order priceRequests sums them.
479
+ if (pricer.catalog && pricer.calculate && !priced.some(({ unpriceable }) => unpriceable)) {
480
+ let total = 0;
481
+ for (const { costs, n } of priced)
482
+ for (let i = 0; i < n; i += 1)
483
+ total += costs[i];
484
+ cost = roundUsd(total);
485
+ }
486
+ }
487
+ else if (cost === undefined) {
303
488
  const catalog = await priceWith();
304
489
  cost = catalog ? await priceRequests(requests, catalog, calculateCost) : undefined;
305
490
  }
@@ -320,8 +505,16 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
320
505
  };
321
506
  out.push(totals);
322
507
  if (sink) {
323
- const times = parts.flatMap(({ read }) => Array.from(read.at)).filter(Number.isFinite);
324
- sink(totals, requests, times.reduce((least, at) => (least === undefined || at < least ? at : least), undefined));
508
+ // The session's first time: the least finite one of its own files' requests (Unpriced, as every part is with a
509
+ // sink), read where they are held.
510
+ let started;
511
+ for (const { read } of parts)
512
+ for (let i = 0; i < read.counts.n; i += 1) {
513
+ const at = atOf(read.counts, i);
514
+ if (Number.isFinite(at) && (started === undefined || at < started))
515
+ started = at;
516
+ }
517
+ sink(totals, requests, started);
325
518
  }
326
519
  }
327
520
  return out;
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- export type { Answer, Ended, ToolCall, Turn, Usage } from "./types.js";
1
+ export type { Answer, Ended, Mirror, ToolCall, Turn, Usage } from "./types.js";
2
2
  export { ACTIVE_GAP_MS } from "./types.js";
3
3
  export { mostEffortOf, personsWords } from "./text.js";
4
- export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat } from "./usage.js";
4
+ export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat, type UsageOptions } from "./usage.js";
5
5
  export { atOf, type Counts } from "./counts.js";
6
- export { type Env, type Locator, locatorKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
6
+ export { type Env, type Locator, type LocatorSize, locatorKey, type OrderKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
7
7
  export { type FileCursor, type LineSource, lineReader, type ReadContext, type ReadState } from "./lines.js";
8
8
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES, type Source } from "./readers/index.js";
9
- export { childrenOf, inOrder, locatorOf, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
9
+ export { copilotSessionId } from "./readers/copilot.js";
10
+ export { childrenOf, inOrder, locatorOf, locatorParent, locatorSize, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
10
11
  export { builtinCatalog, type CalculateCost, type Catalog, catalogOf, type Listed, type ModelCost, type Priced, priceRequests } from "./price.js";
11
- export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals } from "./home.js";
12
+ export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
13
+ export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals, withSubagentCosts } from "./home.js";
12
14
  export { type Wrapped, wrappedHome } from "./wrapped.js";
package/dist/index.js CHANGED
@@ -5,7 +5,9 @@ export { atOf } from "./counts.js";
5
5
  export { locatorKey } from "./reader.js";
6
6
  export { lineReader } from "./lines.js";
7
7
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES } from "./readers/index.js";
8
- export { childrenOf, inOrder, locatorOf, readerOf, readSession, sessionLocators } from "./read.js";
8
+ export { copilotSessionId } from "./readers/copilot.js";
9
+ export { childrenOf, inOrder, locatorOf, locatorParent, locatorSize, readerOf, readSession, sessionLocators } from "./read.js";
9
10
  export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
10
- export { parseHome, ReadFailures } from "./home.js";
11
+ export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
12
+ export { parseHome, ReadFailures, withSubagentCosts } from "./home.js";
11
13
  export { wrappedHome } from "./wrapped.js";
package/dist/lines.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Counts } from "./counts.js";
2
- import { type Env, type Reader } from "./reader.js";
2
+ import { type Env, type Reader, type ReadOptions } from "./reader.js";
3
3
  import { type Answer, type SessionOf, type Turn } from "./types.js";
4
4
  /** One file's read so far, all of it plain data (no function, Maps and Sets allowed), so a cursor can carry it and
5
5
  * structuredClone or v8.serialize can copy it. `answers` holds every request read, whether turns are kept or not: what
@@ -61,6 +61,14 @@ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name"
61
61
  * read is a turns: false read, its requests whole. */
62
62
  totals?: true;
63
63
  };
64
+ /** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
65
+ export declare class LineTooLong extends Error {
66
+ readonly file: string;
67
+ readonly offset: number;
68
+ readonly bytes: number;
69
+ readonly maxLine: number;
70
+ constructor(file: string, offset: number, bytes: number, maxLine: number);
71
+ }
64
72
  /** Where a read of a file stopped, and what it had read. Plain data (Maps, Sets and shared objects, no function):
65
73
  * structuredClone or v8.serialize keeps it whole. Read it through its reader alone. A turns: true read's cursor
66
74
  * holds the session's text, as its state does (ReadState); keep or send it as you would the session. */
@@ -78,5 +86,8 @@ export type FileCursor = {
78
86
  totals?: boolean;
79
87
  state: ReadState;
80
88
  };
89
+ /** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it
90
+ * reads: so a reader built on it can choose how to read before reading. A file it cannot open is no place to go on. */
91
+ export declare function resumes<S extends string, O>(spec: LineSource<S, O>, file: string, cursor: FileCursor | undefined, { turns: keep, totals: asked }?: ReadOptions): Promise<boolean>;
81
92
  /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
82
93
  export declare function lineReader<S extends string, O>(spec: LineSource<S, O>): Reader<S, FileCursor>;