@parcha/agentrun-import 0.1.0-beta.59 → 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.
package/README.md CHANGED
@@ -31,19 +31,20 @@ const sessions = await parseHome(homedir(), { sources: ["claude-code", "codex"]
31
31
  it, parseHome throws `ReadFailures`. An unreadable file is never taken for an empty one.
32
32
  - `env` names where a source keeps its own directory (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`, OpenCode's `XDG_DATA_HOME` and
33
33
  `OPENCODE_DB`); without it the home's.
34
- - `threads` reads the files on that many worker threads (default: the cores the process may run on, at most 8; `1`
35
- reads them in order on the calling thread; at most 64). A read is kept only when it is the one the import's order would make; any
36
- other file is read again in order, so the totals are the same whatever the count. A call with a `state`, or with
37
- readers of its own, reads on the calling thread.
34
+ - `threads` reads the files on that many worker threads (default: the cores the process may run on less one, two on
35
+ two, at most 16, and no more than the workers whose heaps, 80 MiB each at the default `workerOldMb`, fit in the memory
36
+ still free (the machine's, page cache counted as free, at most its container's limit) once `readAhead` is set aside;
37
+ `1` reads them in order on the calling thread; at most 64). A read is kept only when it is the one the import's order
38
+ would make; any other file is read again in order, so the totals are the same whatever the count. A call with a
39
+ `state`, or with readers of its own, reads on the calling thread; so does OpenCode in any call (its sessions are rows of
40
+ a database, not files of lines).
38
41
  - `readAhead` caps the bytes of finished reads waiting to be taken (default 1 GiB, or a sixteenth of the memory the
39
42
  process may use, its container's limit when one is set, when that is less: 512 MiB at 8 GiB). Under it, files of 64 MiB and over are read first, largest first, then
40
43
  the rest in order; at it, the threads read only the file the import waits on. It is a cap on finished reads waiting,
41
44
  plus at most one read in flight per thread (one of those can be a giant file), not on the process's memory.
42
- - `workerOldMb` caps each worker's old generation (default 64). A line over an eighth of it, or a file that runs a worker
45
+ - `workerOldMb` caps each worker's old generation (default 64, at least 8, refused with a RangeError under it: at 1 or
46
+ 2 MB V8 ends the whole process as a worker starts, and at 3 to 7 the workers run out of memory). A line over an eighth of it, or a file that runs a worker
43
47
  out of memory, is read on the calling thread instead; past two such losses a thread, the calling thread reads the rest.
44
-
45
- On a 73.7 GB home, 8 threads took 90.9 s (median of 5) at a peak of 1.83 GiB, and 1 thread 441.1 s at 1.05 GiB
46
- (x1); with `readAhead` at 256 MiB, 8 threads took 136.5 s (x1). Measured on a loaded machine (load 17 to 45).
47
48
  - A request two sources wrote is counted once. OpenCode's claude-agent provider runs Claude Code, which writes each
48
49
  request into its own session file too; OpenCode names that session on the request (`mirrors`). When the same call
49
50
  reads that Claude Code session (serve's import: or its store holds it), the request counts there and not in the OpenCode session (tokens, calls and cost),
@@ -161,8 +162,9 @@ read looks up afresh.
161
162
 
162
163
  The cursor is the reader's own: hand it back to the same reader for the same locator. A JSONL source builds its reader
163
164
  with `lineReader` from a per-record function; its cursor is the file's device and inode, the byte after the last whole
164
- line read, and the read's state. A file replaced or truncated since is read from its start, and a last line with no
165
- newline yet is read but not consumed. A source that keeps many sessions in one file (a SQLite database) implements
165
+ line read, and the read's state. A file replaced or truncated since is read from its start, as is a cursor whose state
166
+ is of another shape than the reader's (its `stateVersion`: a Codex cursor saved by 0.1.0-beta.58 or before), and a last
167
+ line with no newline yet is read but not consumed. A source that keeps many sessions in one file (a SQLite database) implements
166
168
  `discover`, `idOf` and `read` itself and returns one locator per session, with its `id`, and `stat`: the session's own size and
167
169
  last write, which a caller's size caps and "still being written" check go by (`locatorSize`; without `stat`, the file's).
168
170
 
package/dist/home.d.ts CHANGED
@@ -67,10 +67,11 @@ export type ParseOptions = {
67
67
  * their times and models, text-free as the totals are. `started`: the time (ms) of the first request of the session's
68
68
  * own files (not its subagents'), absent when it has none. For a caller that buckets the same numbers (wrapped.ts). */
69
69
  requests?: (totals: SessionTotals, requests: readonly SessionRequest[], started: number | undefined) => void;
70
- /** Threads that read the sources' files ahead, largest first, without a state and with the registry's readers (default:
71
- * the cores this process may run on, at most 8: past that the largest files set the time, and each worker costs its
72
- * heap). Each read is kept only when it is the one parseHome would make in order; 1 reads every file in order on this
73
- * thread. At most MOST_THREADS (64). */
70
+ /** Threads that read the sources' files ahead, largest first, without a state and with the registry's readers. Default:
71
+ * the cores this process may run on less one (two on two), at most 16, and no more than the workers whose heaps (16 MB
72
+ * young generation plus `workerOldMb` each) fit in the memory still free (the machine's, at most its container's
73
+ * limit) once `readAhead` is set aside; at least 1 (pool.ts, defaultThreads). Each read is kept only when it is the
74
+ * one parseHome would make in order; 1 reads every file in order on this thread. At most MOST_THREADS (64). */
74
75
  threads?: number;
75
76
  /** With threads, a cap on the bytes of finished reads made ahead of the one being taken that may wait (default
76
77
  * readAheadBytes(): 1 GiB, or a sixteenth of the machine's memory when less); at it, the threads read only the file
@@ -78,8 +79,9 @@ export type ParseOptions = {
78
79
  * more memory and waits less behind a large file. A cap on finished reads waiting, plus at most one read in flight
79
80
  * per thread; not on the process's memory. */
80
81
  readAhead?: number;
81
- /** With threads, each worker's old generation in MB (default OLD_MB, 64). A worker that runs out of it gives its file
82
- * back, which is read on this thread, and another takes its place; past 2 x threads such losses the rest is read here. */
82
+ /** With threads, each worker's old generation in MB (default OLD_MB, 64; at least MIN_OLD_MB, 8: at 1 or 2 V8 ends the
83
+ * process as a worker starts, at 3 to 7 the workers run out of memory). A worker that runs out of it gives its file back, which is read on this
84
+ * thread, and another takes its place; past 2 x threads such losses the rest is read here. */
83
85
  workerOldMb?: number;
84
86
  };
85
87
  /** One model request of a session: when (ms), by which model ("provider/model", the session's when the request names none),
@@ -110,5 +112,5 @@ export declare const MOST_THREADS = 64;
110
112
  * when the session's is, or when one it adds is: never a subagent counted at 0. parseHome's totals and serve's import. */
111
113
  export declare function withSubagentCosts(source: string, cost: number | undefined, subagents: readonly (number | undefined)[]): number | undefined;
112
114
  /** Every session of `sources` under `home`, as totals, sorted by key. */
113
- export declare function parseHome(home: string, { sources, readers, state, catalog, calculateCost, env, failures, requests, threads, readAhead, workerOldMb }?: ParseOptions): Promise<SessionTotals[]>;
115
+ export declare function parseHome(home: string, { sources, readers, state, catalog, calculateCost, env, failures, requests, threads: asked, readAhead, workerOldMb }?: ParseOptions): Promise<SessionTotals[]>;
114
116
  export {};
package/dist/home.js CHANGED
@@ -5,15 +5,16 @@
5
5
  // call reads it, and counts once there.
6
6
  import { createHash } from "node:crypto";
7
7
  import { stat } from "node:fs/promises";
8
- import { availableParallelism } from "node:os";
9
8
  import { relative, sep } from "node:path";
10
9
  import { builtinCatalog, loadCalculateCost, priceRequest, priceRequests, roundUsd } from "./price.js";
11
10
  import { childrenOf, inOrder, readerOf, sessionLocators } from "./read.js";
12
11
  import { locatorKey } from "./reader.js";
13
12
  import { READERS, SOURCES } from "./readers/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";
13
+ import { LINE_READERS } from "./readers/line-readers.js";
14
+ import { addRequest, atOf, counts, HAS_LONG, HAS_REASONING, HAS_USAGE, STRIDE, trimmed, USAGE_FIELDS } from "./counts.js";
15
+ import { DROPS_CURSOR } from "./internal.js";
16
+ import { defaultThreads, MIN_OLD_MB, OLD_MB, ReadPool, readAheadBytes } from "./pool.js";
17
+ import { addDisjoint, addNew, addRecord, anyIn, dropOwner, locatorNumber, markOf, ownAll, ownerOf, recordIndex, undoTo } from "./record-index.js";
17
18
  import { packed, packInto } from "./record-key.js";
18
19
  import { mirroredIn, sessionKey } from "./mirror.js";
19
20
  import { addTokens, noTokens } from "./usage.js";
@@ -36,68 +37,85 @@ const keyOf = (home, { file, id }) => {
36
37
  return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
37
38
  };
38
39
  const requestsOf = (read) => ("n" in read ? read.n : read.counts.n);
40
+ /** A file of copies alone: it holds only records an earlier file holds, and no prompt. A session of such files alone, and
41
+ * no subagent, is no session (totalsOf). */
42
+ const copiesAlone = (session, requests) => session.copies > 0 && session.users === 0 && requests === 0;
43
+ /** Whether a session's own file (`session`, a part of a session of its own, no thread naming its parent) leaves its
44
+ * session to be priced at the totals: it wrote no cost (a session's cost is the source's own only when each of its files
45
+ * wrote one) and it is no file of copies alone (so the session is one). */
46
+ const pricedAtTotals = (session, requests) => !(session.child && session.parent) && session.costUsd === undefined && !copiesAlone(session, requests);
39
47
  /** 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
48
  * sum would pass it, and the source is read again with each request's tokens kept. */
41
49
  class Inexact extends Error {
42
50
  }
43
- /** The default threads' ceiling (ParseOptions.threads). */
44
- const MAX_THREADS = 8;
45
51
  /** The most threads parseHome takes: each is a worker with a heap of its own, and past the cores the largest files set
46
52
  * the time anyway. More is refused before any worker starts. */
47
53
  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) {
51
- const { id, child, parent, users, copies, costUsd, model } = read.session;
52
- const session = { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) };
54
+ /** A read's session as a total takes it, and no more. */
55
+ function metaOf({ id, child, parent, users, copies, costUsd, model }) {
56
+ return { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) };
57
+ }
58
+ /** A read's requests as their counts: a totals read's own, or those of a reader with no totals read, which gives its
59
+ * requests whole. */
60
+ function countsOf(read) {
53
61
  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) };
62
+ return read.counts;
63
+ const out = counts();
64
+ for (const { model, usage, at } of read.requests)
65
+ addRequest(out, model, usage, at);
61
66
  return out;
62
67
  }
63
- /** The i-th request of `read` as priceRequests and the requests sink take it. */
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];
68
+ /** Request i of `c`'s model: its own, else its session's (`fallback`). */
69
+ const modelAt = (c, i, fallback) => (c.model[i] === -1 ? fallback : c.models[c.model[i]]);
70
+ /** Request i of `c` as priceRequests and the requests sink take it, its model its own or else its session's. */
71
+ function requestAt(c, i, fallback) {
72
+ const model = modelAt(c, i, fallback);
73
+ const request = { at: atOf(c, i), ...(model !== undefined ? { model } : {}) };
74
+ const has = c.has[i];
69
75
  if (!(has & HAS_USAGE))
70
76
  return request;
71
- const { values } = counts;
72
77
  const o = i * STRIDE;
73
- const usage = { input: values[o], output: values[o + 1], cacheRead: values[o + 2], cacheWrite: values[o + 3] };
78
+ const usage = { input: c.values[o], output: c.values[o + 1], cacheRead: c.values[o + 2], cacheWrite: c.values[o + 3] };
74
79
  if (has & HAS_LONG)
75
- usage.cacheWrite1h = values[o + 4];
80
+ usage.cacheWrite1h = c.values[o + 4];
76
81
  if (has & HAS_REASONING)
77
- usage.reasoning = values[o + 5];
82
+ usage.reasoning = c.values[o + 5];
78
83
  return { ...request, usage };
79
84
  }
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
+ /** `session`'s requests (`c`) priced (Counted), their tokens added to `sums` (the source's so far). */
86
+ function counted(session, c, pricer, sums) {
87
+ const { n } = c;
88
+ const tokens = new Float64Array(USAGE_FIELDS);
85
89
  const { catalog, calculate } = pricer;
86
90
  const costs = catalog && calculate ? new Float64Array(n) : undefined;
87
91
  let unpriceable = false;
92
+ // One request at a time, as priceRequest takes it: no object a request.
93
+ const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
94
+ const request = {};
88
95
  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];
96
+ const has = c.has[i];
97
+ const o = i * STRIDE;
98
+ if (has & HAS_USAGE) {
99
+ // cacheWrite1h and reasoning are 0 where the request has none.
100
+ for (let k = 0; k < USAGE_FIELDS; k += 1) {
101
+ const count = c.values[o + k];
95
102
  if (!Number.isSafeInteger(count) || count < 0)
96
103
  throw new Inexact();
97
104
  tokens[k] += count;
98
105
  }
99
106
  }
100
107
  if (costs && !unpriceable) {
108
+ request.model = modelAt(c, i, session.model);
109
+ if (has & HAS_USAGE) {
110
+ usage.input = c.values[o];
111
+ usage.output = c.values[o + 1];
112
+ usage.cacheRead = c.values[o + 2];
113
+ usage.cacheWrite = c.values[o + 3];
114
+ usage.cacheWrite1h = has & HAS_LONG ? c.values[o + 4] : undefined;
115
+ request.usage = usage;
116
+ }
117
+ else
118
+ request.usage = undefined;
101
119
  const usd = priceRequest(request, catalog, calculate);
102
120
  if (usd === undefined)
103
121
  unpriceable = true;
@@ -105,10 +123,10 @@ function counted(read, pricer, sums) {
105
123
  costs[i] = usd;
106
124
  }
107
125
  }
108
- for (let k = 0; k < TOKEN_FIELDS; k += 1)
126
+ for (let k = 0; k < USAGE_FIELDS; k += 1)
109
127
  if ((sums[k] += tokens[k]) > Number.MAX_SAFE_INTEGER)
110
128
  throw new Inexact();
111
- return { session: read.session, n, tokens, costs, unpriceable };
129
+ return { session, n, tokens, costs, unpriceable };
112
130
  }
113
131
  /** A session's cost with its subagents': Claude Code's written cost holds its subagents' already (its cost-state), so it
114
132
  * stays as it is; every other source writes a subagent's cost on the subagent's own session, so each is added. Unknown
@@ -120,38 +138,44 @@ export function withSubagentCosts(source, cost, subagents) {
120
138
  }
121
139
  /** A part with its own requests alone (none another session of the call holds) and the cost it wrote of them: its own
122
140
  * 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). */
141
+ * over its counts). Counted when `unpriced` is false and the prices are in hand (a part whose requests mirror another's
142
+ * is kept as read, AsRead, until the call knows which sessions it read). */
125
143
  function ownPart(read, mirrored, pricer, unpriced) {
126
144
  if ("n" in read || !read.mirrors)
127
145
  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] }));
146
+ const { counts: c, mirrors: marks } = read;
147
+ const at = Array.from({ length: c.n }, (_, i) => i).filter((i) => !mirrored({ mirrors: marks.of[i] }));
131
148
  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));
149
+ if (at.length !== c.n) {
150
+ const priced = at.every((i) => !Number.isNaN(marks.cost[i]) || !(c.has[i] & HAS_USAGE));
134
151
  const costUsd = priced ? at.reduce((n, i) => n + (Number.isNaN(marks.cost[i]) ? 0 : marks.cost[i]), 0) : undefined;
135
152
  const { costUsd: _, ...session } = read.session;
136
- // Its own requests' rows of Counts (each STRIDE numbers: usage and time), their model indexes and HAS_* bits.
153
+ // Its own requests' rows of Counts (STRIDE numbers each: usage and time), copied in place.
137
154
  const values = new Float64Array(at.length * STRIDE);
138
155
  for (const [k, i] of at.entries())
139
- values.set(counts.values.subarray(i * STRIDE, (i + 1) * STRIDE), k * STRIDE);
156
+ values.set(c.values.subarray(i * STRIDE, (i + 1) * STRIDE), k * STRIDE);
140
157
  own = {
141
158
  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]) },
159
+ counts: {
160
+ n: at.length,
161
+ models: c.models,
162
+ model: Int32Array.from(at, (i) => c.model[i]),
163
+ values,
164
+ has: Uint8Array.from(at, (i) => c.has[i]),
165
+ },
143
166
  };
144
167
  }
145
- return unpriced || !pricer.ready ? own : counted(own, pricer, new Float64Array(TOKEN_FIELDS));
168
+ return unpriced || !pricer.ready ? own : counted(own.session, own.counts, pricer, new Float64Array(USAGE_FIELDS));
146
169
  }
147
170
  /** Every session of `sources` under `home`, as totals, sorted by key. */
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}`);
171
+ export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests, threads: asked, readAhead = readAheadBytes(), workerOldMb = OLD_MB } = {}) {
172
+ if (asked !== undefined && (!Number.isSafeInteger(asked) || asked < 1 || asked > MOST_THREADS))
173
+ throw new RangeError(`threads: a whole number from 1 to ${MOST_THREADS}, not ${asked}`);
151
174
  if (!(readAhead >= 0))
152
175
  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}`);
176
+ if (!Number.isSafeInteger(workerOldMb) || workerOldMb < MIN_OLD_MB)
177
+ throw new RangeError(`workerOldMb: a whole number of MB, at least ${MIN_OLD_MB}, not ${workerOldMb}`);
178
+ const threads = asked ?? defaultThreads(undefined, undefined, readAhead, workerOldMb);
155
179
  const pool = !state && readers === READERS && threads > 1 ? new ReadPool(threads, readAhead, workerOldMb) : undefined;
156
180
  try {
157
181
  let prices;
@@ -169,7 +193,7 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
169
193
  const lookups = new Map();
170
194
  // Requests are priced as they are read once the prices are in hand: at once when the caller handed them in (or none),
171
195
  // 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.
196
+ // request with its time, so with one every part keeps its requests as read (AsRead) to the totals.
173
197
  const pricer = {
174
198
  ready: catalog === false || (catalog !== undefined && calculateCost !== undefined),
175
199
  ...(catalog ? { catalog } : {}),
@@ -187,8 +211,11 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
187
211
  // files then share the threads with the next source's, and the largest files of every source are read first (pool.ts).
188
212
  const ahead = new Map();
189
213
  if (pool) {
214
+ // The pool reads the line sources (LINE_READERS) alone. Another (OpenCode: a session is rows of a database, or JSON
215
+ // files, its size not its file's) is read here, on this thread, as without a pool: the same totals either way.
190
216
  for (const source of sources)
191
- ahead.set(source, await listSource(home, source, readers, env, true));
217
+ if (Object.hasOwn(LINE_READERS, source))
218
+ ahead.set(source, await listSource(home, source, readers, env, true));
192
219
  const items = [...ahead].flatMap(([source, { listed, childList }]) => [...listed.map(({ locator, stats }) => ({ source, locator, size: stats.size })), ...childList.map(({ locator, size }) => ({ source, locator, size }))]);
193
220
  const ids = pool.readAll(items);
194
221
  let at = 0;
@@ -236,7 +263,7 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
236
263
  part.read = ownPart(part.read, mirrored, pricer, all);
237
264
  };
238
265
  try {
239
- // Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else Unpriced.
266
+ // Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else AsRead.
240
267
  own(whole || ![...read.tops, ...read.children].some((part) => "n" in part.read));
241
268
  }
242
269
  catch (error) {
@@ -289,48 +316,75 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
289
316
  const read = async (locator, pooled) => {
290
317
  const key = locatorKey(locator);
291
318
  const cursor = kept?.cursors.get(key);
292
- // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. Both are
293
- // staged and kept only when the read succeeds: a read that fails partway leaves no record owned that no cursor
294
- // holds, which a retry would take for a copy.
319
+ // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. A new
320
+ // record goes into the source's index at once (locators are read one at a time, so no other read adds to it before
321
+ // this one ends); a read that fails partway takes its records out again (undoTo the mark), so none is left owned
322
+ // that no cursor holds, which a retry would take for a copy. Staging them in an index of their own, then copying
323
+ // it in, held a big file's records twice.
295
324
  // Records are held by their packed keys (packInto), each packed as it is asked for.
296
325
  const me = locatorNumber(owners, key);
297
- const mine = recordIndex(64);
326
+ const mark = markOf(owners);
298
327
  const found = new Set();
328
+ // A reader asks for a record and then adds it: the last record packed is kept packed, and when the last question
329
+ // of it found none and the index has taken nothing since (its tables and their counts as they were), it is added
330
+ // without another lookup.
299
331
  const at = packed();
332
+ let asked;
333
+ let missedU;
334
+ let missedO;
335
+ let missedCount = -1;
336
+ const pack = (record) => {
337
+ if (record !== asked) {
338
+ packInto(record, at);
339
+ asked = record;
340
+ missedCount = -1;
341
+ }
342
+ };
343
+ const unchanged = () => missedCount !== -1 && missedU === owners.uuids && missedO === owners.others && missedCount === owners.uuids.count + owners.others.count;
300
344
  const seen = {
301
345
  has: (record) => {
302
- packInto(record, at);
303
- let owner = ownerOf(owners, at);
304
- if (owner === -1)
305
- owner = ownerOf(mine, at);
306
- if (owner === -1)
346
+ pack(record);
347
+ const owner = ownerOf(owners, at);
348
+ if (owner === -1) {
349
+ missedU = owners.uuids;
350
+ missedO = owners.others;
351
+ missedCount = owners.uuids.count + owners.others.count;
307
352
  return false;
353
+ }
354
+ missedCount = -1;
308
355
  if (owner !== me)
309
356
  found.add(owners.locators[owner]);
310
357
  return true;
311
358
  },
312
359
  add(record) {
313
- packInto(record, at);
314
- if (ownerOf(owners, at) === -1)
315
- addRecord(mine, at, me);
360
+ pack(record);
361
+ if (unchanged())
362
+ addNew(owners, at, me);
363
+ else
364
+ addRecord(owners, at, me);
365
+ missedCount = -1;
316
366
  return this;
317
367
  },
318
368
  };
319
369
  if (pooled) {
320
370
  // 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
371
  const made = await pooled();
322
- const held = (record) => ownerOf(owners, record) !== -1;
323
- if (made.ok && !someRecord(made.mine, held) && !someRecord(made.missed, held)) {
372
+ if (made.ok && !anyIn(owners, made.mine) && !anyIn(owners, made.missed)) {
373
+ // None of its records is held: the larger index keeps its arrays, the other's records go in.
324
374
  ownAll(made.mine, me);
325
- addAll(owners, made.mine);
375
+ addDisjoint(owners, made.mine);
326
376
  return made.sessions;
327
377
  }
328
378
  }
329
- const result = await reader.read(locator, cursor, { turns: false, totals: true, seen, lookups }).catch((error) => void unread.push({ locator, error }));
379
+ // With no state the cursor is dropped: the read makes no copy for it.
380
+ const options = { turns: false, totals: true, seen, lookups, [DROPS_CURSOR]: !kept };
381
+ const result = await reader.read(locator, cursor, options).catch((error) => void unread.push({ locator, error }));
330
382
  if (!result) {
331
383
  // A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
332
384
  // would hold none of them: the next pass reads it from its start. A locator that found them already read (a
333
385
  // copy) skipped them, though the fresh pass counts them there: the source is read again.
386
+ // This read's records go, and with them, for a locator read before, those of its earlier reads.
387
+ undoTo(owners, mark);
334
388
  if (kept && cursor !== undefined) {
335
389
  kept.cursors.delete(key);
336
390
  dropOwner(owners, me);
@@ -340,7 +394,6 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
340
394
  }
341
395
  return [];
342
396
  }
343
- addAll(owners, mine);
344
397
  if (found.size)
345
398
  for (const owner of found)
346
399
  (copied.get(key) ?? copied.set(key, new Set()).get(key)).add(owner);
@@ -353,25 +406,25 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
353
406
  };
354
407
  const tops = [];
355
408
  const children = [];
356
- const sums = new Float64Array(TOKEN_FIELDS);
409
+ const sums = new Float64Array(USAGE_FIELDS);
357
410
  // Each locator's sessions packed as soon as they are read. A totals read gives each request's counts alone, and its
358
411
  // cursor, kept in a state between passes, holds those too: no request is held as an object, by a pass or a state. A
359
412
  // 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)) {
413
+ // sink each part is priced once the prices are in hand. Once a session's own file is read that leaves its session to
414
+ // be priced at the totals (pricedAtTotals), the prices are loaded, and the parts read so far priced.
415
+ const pack = async (read, top) => {
416
+ const session = metaOf(read.session);
417
+ const requests = countsOf(read);
418
+ // A part whose requests mirror another's stays as read: its own are known once every source is read (ownPart).
419
+ if (read.requests.some((request) => request.mirrors !== undefined))
420
+ return { session, counts: trimmed(requests), mirrors: { of: read.requests.map((request) => request.mirrors), cost: Float64Array.from(read.requests, (request) => request.costUsd ?? Number.NaN) } };
421
+ if (!whole && !pricer.ready && fresh && top && pricedAtTotals(session, requests.n)) {
369
422
  await pricer.load();
370
423
  for (const part of [...tops, ...children])
371
- if (!("n" in part.read) && !part.read.mirrors)
372
- part.read = counted(part.read, pricer, sums);
424
+ if ("counts" in part.read && !part.read.mirrors)
425
+ part.read = counted(part.read.session, part.read.counts, pricer, sums);
373
426
  }
374
- return pricer.ready ? counted(unpriced, pricer, sums) : unpriced;
427
+ return !whole && pricer.ready ? counted(session, requests, pricer, sums) : { session, counts: trimmed(requests) };
375
428
  };
376
429
  for (const [i, { locator }] of listed.entries())
377
430
  for (const session of await read(locator, pass === 0 ? ahead?.[i] : undefined))
@@ -432,13 +485,13 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
432
485
  for (const { parts, children: subagents, untied } of sessions.values()) {
433
486
  // A session whose every file holds only records an earlier file holds (copies) is no session: its records count where
434
487
  // they were first read. serve's import leaves such a file out the same way.
435
- if (parts.every(({ read }) => read.session.copies > 0 && read.session.users === 0 && requestsOf(read) === 0) && subagents.length === 0)
488
+ if (parts.every(({ read }) => copiesAlone(read.session, requestsOf(read))) && subagents.length === 0)
436
489
  continue;
437
490
  const first = parts[0];
438
491
  const tokens = noTokens();
439
492
  let reasoning = 0;
440
493
  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.
494
+ // Parts priced as read (Counted) or not (AsRead): a source's are all one or all the other, and all AsRead with a sink.
442
495
  const all = [...parts, ...subagents].map(({ read }) => read);
443
496
  const priced = all.filter((read) => "n" in read);
444
497
  if (priced.length && (priced.length !== all.length || sink))
@@ -457,9 +510,9 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
457
510
  }
458
511
  }
459
512
  else {
460
- for (const read of all)
461
- for (let i = 0; i < read.counts.n; i += 1)
462
- requests.push(requestAt(read, i));
513
+ for (const { session, counts } of all)
514
+ for (let i = 0; i < counts.n; i += 1)
515
+ requests.push(requestAt(counts, i, session.model));
463
516
  for (const { usage } of requests) {
464
517
  calls += 1;
465
518
  if (!usage)
@@ -505,15 +558,17 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
505
558
  };
506
559
  out.push(totals);
507
560
  if (sink) {
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.
561
+ // The session's first time: the least finite one of its own files' requests (each part as read, as every part is
562
+ // with a sink), read where they are held.
510
563
  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);
564
+ for (const { read } of parts) {
565
+ const { counts } = read;
566
+ for (let i = 0; i < counts.n; i += 1) {
567
+ const at = atOf(counts, i);
514
568
  if (Number.isFinite(at) && (started === undefined || at < started))
515
569
  started = at;
516
570
  }
571
+ }
517
572
  sink(totals, requests, started);
518
573
  }
519
574
  }
@@ -0,0 +1,18 @@
1
+ import type { ReadOptions } from "./reader.js";
2
+ /** A read option keyed by a symbol, so no ReadOptions a caller writes can name it: true when the caller drops the read's
3
+ * cursor unread (parseHome with no state, the read pool's workers, readSession). The read then makes no copy for that
4
+ * cursor: its state is the read's own. A totals read's cursor holds the read's own counts, not a copy trimmed to its
5
+ * requests (the copy is the size of the counts), and its session and source state keep what a kept cursor forgets. A
6
+ * file whose last line has no newline yet is read with no copy of its whole state to leave that line out, so the
7
+ * cursor's state then holds the line its offset is before: hand such a cursor to no read. */
8
+ export declare const DROPS_CURSOR: unique symbol;
9
+ /** A read option keyed by a symbol, as DROPS_CURSOR is: true reads a file's next chunk only after this one's lines are
10
+ * read, into one buffer. Unset, the next chunk is read while this one's lines are, which pays where a core is spare to
11
+ * make the read (parseHome's own thread). The read pool's workers set it: their threads take every core they are given,
12
+ * so a read made ahead waits for one, and its chunk lands on another core than the one that reads it. */
13
+ export declare const NO_READ_AHEAD: unique symbol;
14
+ /** ReadOptions with this package's own options. */
15
+ export type InternalReadOptions = ReadOptions & {
16
+ [DROPS_CURSOR]?: boolean;
17
+ [NO_READ_AHEAD]?: boolean;
18
+ };
@@ -0,0 +1,12 @@
1
+ /** A read option keyed by a symbol, so no ReadOptions a caller writes can name it: true when the caller drops the read's
2
+ * cursor unread (parseHome with no state, the read pool's workers, readSession). The read then makes no copy for that
3
+ * cursor: its state is the read's own. A totals read's cursor holds the read's own counts, not a copy trimmed to its
4
+ * requests (the copy is the size of the counts), and its session and source state keep what a kept cursor forgets. A
5
+ * file whose last line has no newline yet is read with no copy of its whole state to leave that line out, so the
6
+ * cursor's state then holds the line its offset is before: hand such a cursor to no read. */
7
+ export const DROPS_CURSOR = Symbol("dropsCursor");
8
+ /** A read option keyed by a symbol, as DROPS_CURSOR is: true reads a file's next chunk only after this one's lines are
9
+ * read, into one buffer. Unset, the next chunk is read while this one's lines are, which pays where a core is spare to
10
+ * make the read (parseHome's own thread). The read pool's workers set it: their threads take every core they are given,
11
+ * so a read made ahead waits for one, and its chunk lands on another core than the one that reads it. */
12
+ export const NO_READ_AHEAD = Symbol("noReadAhead");
package/dist/lines.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type Counts } from "./counts.js";
2
2
  import { type Env, type Reader, type ReadOptions } from "./reader.js";
3
+ import { type Shape } from "./scan.js";
3
4
  import { type Answer, type SessionOf, type Turn } from "./types.js";
4
5
  /** 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
6
  * structuredClone or v8.serialize can copy it. `answers` holds every request read, whether turns are kept or not: what
@@ -60,6 +61,15 @@ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name"
60
61
  * added: the source sets no turn's model, usage or time after adding it, or keeps its requests in `counts` itself. Without it a totals
61
62
  * read is a turns: false read, its requests whole. */
62
63
  totals?: true;
64
+ /** What `record` reads of a record in a totals read: a line is then read for these fields alone, from its bytes (scan),
65
+ * every other value checked as JSON but not decoded, and parsed whole only when the scan leaves it to JSON.parse. It
66
+ * names every field whose value can change what a totals read gives (a field whose value goes only into a turn or
67
+ * text a totals read drops may be left out); the read itself takes the record's `timestamp`. Without it, or in any
68
+ * other read, each line is parsed whole. */
69
+ fields?: Shape;
70
+ /** The shape of the state (`own`) its cursors hold, set when it changes from one a release saved: a cursor saved at
71
+ * another (none for a source that never set one) is no place to go on from, and the file is read from its start. */
72
+ stateVersion?: number;
63
73
  };
64
74
  /** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
65
75
  export declare class LineTooLong extends Error {
@@ -84,6 +94,8 @@ export type FileCursor = {
84
94
  /** Whether the read kept turns, and whether it was a totals read: a cursor of another kind is no place to go on from. */
85
95
  keep: boolean;
86
96
  totals?: boolean;
97
+ /** Its reader's state shape when saved (LineSource.stateVersion). */
98
+ stateVersion?: number;
87
99
  state: ReadState;
88
100
  };
89
101
  /** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it