@parcha/agentrun-import 0.1.0-beta.59 → 0.1.0-beta.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -10
- package/dist/cache.d.ts +90 -0
- package/dist/cache.js +266 -0
- package/dist/cli.js +34 -10
- package/dist/home.d.ts +112 -9
- package/dist/home.js +184 -109
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/internal.d.ts +18 -0
- package/dist/internal.js +12 -0
- package/dist/lines.d.ts +20 -3
- package/dist/lines.js +88 -31
- package/dist/pool-worker.js +22 -34
- package/dist/pool.d.ts +34 -8
- package/dist/pool.js +59 -14
- package/dist/read.js +4 -1
- package/dist/reader.d.ts +3 -0
- package/dist/readers/claude-code.d.ts +24 -0
- package/dist/readers/claude-code.js +77 -37
- package/dist/readers/codex.d.ts +58 -5
- package/dist/readers/codex.js +103 -73
- package/dist/readers/line-readers.d.ts +7 -0
- package/dist/readers/line-readers.js +10 -0
- package/dist/readers/pi.js +9 -2
- package/dist/record-index.d.ts +30 -3
- package/dist/record-index.js +128 -43
- package/dist/scan-wasm.d.ts +1 -0
- package/dist/scan-wasm.js +2 -0
- package/dist/scan.d.ts +21 -0
- package/dist/scan.js +164 -0
- package/dist/text.d.ts +3 -0
- package/dist/text.js +38 -2
- package/dist/types.d.ts +18 -0
- package/package.json +1 -1
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 {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
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";
|
|
@@ -31,73 +32,97 @@ export class ReadFailures extends Error {
|
|
|
31
32
|
}
|
|
32
33
|
/** A session's key: the sha256 of its file's path relative to the home, "/" between its parts, `#<id>` after it when its
|
|
33
34
|
* locator names one. */
|
|
34
|
-
const keyOf = (home, { file, id }) => {
|
|
35
|
+
export const keyOf = (home, { file, id }) => {
|
|
35
36
|
const path = relative(home, file).split(sep).join("/");
|
|
36
37
|
return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
|
|
37
38
|
};
|
|
38
|
-
const requestsOf = (read) => ("n" in read ? read.n : read.counts.n);
|
|
39
|
+
export 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
|
-
/**
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
|
55
|
-
const
|
|
56
|
-
for (const
|
|
57
|
-
addRequest(
|
|
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
|
-
/**
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
const
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
+
/** Each request of a part read whole (readSource's `whole`), as the sink takes it: a part priced as read keeps none. */
|
|
86
|
+
export function* requestsIn(read) {
|
|
87
|
+
if ("n" in read)
|
|
88
|
+
throw new Error("a part priced as read keeps no requests");
|
|
89
|
+
for (let i = 0; i < read.counts.n; i += 1)
|
|
90
|
+
yield requestAt(read.counts, i, read.session.model);
|
|
91
|
+
}
|
|
92
|
+
/** `session`'s requests (`c`) priced (Counted), their tokens added to `sums` (the source's so far). */
|
|
93
|
+
function counted(session, c, pricer, sums) {
|
|
94
|
+
const { n } = c;
|
|
95
|
+
const tokens = new Float64Array(USAGE_FIELDS);
|
|
85
96
|
const { catalog, calculate } = pricer;
|
|
86
97
|
const costs = catalog && calculate ? new Float64Array(n) : undefined;
|
|
87
98
|
let unpriceable = false;
|
|
99
|
+
// One request at a time, as priceRequest takes it: no object a request.
|
|
100
|
+
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
101
|
+
const request = {};
|
|
88
102
|
for (let i = 0; i < n; i += 1) {
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
if (
|
|
92
|
-
|
|
93
|
-
for (let k = 0; k <
|
|
94
|
-
const count =
|
|
103
|
+
const has = c.has[i];
|
|
104
|
+
const o = i * STRIDE;
|
|
105
|
+
if (has & HAS_USAGE) {
|
|
106
|
+
// cacheWrite1h and reasoning are 0 where the request has none.
|
|
107
|
+
for (let k = 0; k < USAGE_FIELDS; k += 1) {
|
|
108
|
+
const count = c.values[o + k];
|
|
95
109
|
if (!Number.isSafeInteger(count) || count < 0)
|
|
96
110
|
throw new Inexact();
|
|
97
111
|
tokens[k] += count;
|
|
98
112
|
}
|
|
99
113
|
}
|
|
100
114
|
if (costs && !unpriceable) {
|
|
115
|
+
request.model = modelAt(c, i, session.model);
|
|
116
|
+
if (has & HAS_USAGE) {
|
|
117
|
+
usage.input = c.values[o];
|
|
118
|
+
usage.output = c.values[o + 1];
|
|
119
|
+
usage.cacheRead = c.values[o + 2];
|
|
120
|
+
usage.cacheWrite = c.values[o + 3];
|
|
121
|
+
usage.cacheWrite1h = has & HAS_LONG ? c.values[o + 4] : undefined;
|
|
122
|
+
request.usage = usage;
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
request.usage = undefined;
|
|
101
126
|
const usd = priceRequest(request, catalog, calculate);
|
|
102
127
|
if (usd === undefined)
|
|
103
128
|
unpriceable = true;
|
|
@@ -105,10 +130,10 @@ function counted(read, pricer, sums) {
|
|
|
105
130
|
costs[i] = usd;
|
|
106
131
|
}
|
|
107
132
|
}
|
|
108
|
-
for (let k = 0; k <
|
|
133
|
+
for (let k = 0; k < USAGE_FIELDS; k += 1)
|
|
109
134
|
if ((sums[k] += tokens[k]) > Number.MAX_SAFE_INTEGER)
|
|
110
135
|
throw new Inexact();
|
|
111
|
-
return { session
|
|
136
|
+
return { session, n, tokens, costs, unpriceable };
|
|
112
137
|
}
|
|
113
138
|
/** A session's cost with its subagents': Claude Code's written cost holds its subagents' already (its cost-state), so it
|
|
114
139
|
* 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 +145,44 @@ export function withSubagentCosts(source, cost, subagents) {
|
|
|
120
145
|
}
|
|
121
146
|
/** A part with its own requests alone (none another session of the call holds) and the cost it wrote of them: its own
|
|
122
147
|
* when it holds none of another's, else its own requests' when each that used tokens is priced (mirror.ts ownRequests,
|
|
123
|
-
* over
|
|
124
|
-
*
|
|
148
|
+
* over its counts). Counted when `unpriced` is false and the prices are in hand (a part whose requests mirror another's
|
|
149
|
+
* is kept as read, AsRead, until the call knows which sessions it read). */
|
|
125
150
|
function ownPart(read, mirrored, pricer, unpriced) {
|
|
126
151
|
if ("n" in read || !read.mirrors)
|
|
127
152
|
return read;
|
|
128
|
-
const marks = read
|
|
129
|
-
const {
|
|
130
|
-
const at = Array.from({ length: counts.n }, (_, i) => i).filter((i) => !mirrored({ mirrors: marks.of[i] }));
|
|
153
|
+
const { counts: c, mirrors: marks } = read;
|
|
154
|
+
const at = Array.from({ length: c.n }, (_, i) => i).filter((i) => !mirrored({ mirrors: marks.of[i] }));
|
|
131
155
|
let own = read;
|
|
132
|
-
if (at.length !==
|
|
133
|
-
const priced = at.every((i) => !Number.isNaN(marks.cost[i]) || !(
|
|
156
|
+
if (at.length !== c.n) {
|
|
157
|
+
const priced = at.every((i) => !Number.isNaN(marks.cost[i]) || !(c.has[i] & HAS_USAGE));
|
|
134
158
|
const costUsd = priced ? at.reduce((n, i) => n + (Number.isNaN(marks.cost[i]) ? 0 : marks.cost[i]), 0) : undefined;
|
|
135
159
|
const { costUsd: _, ...session } = read.session;
|
|
136
|
-
// Its own requests' rows of Counts (
|
|
160
|
+
// Its own requests' rows of Counts (STRIDE numbers each: usage and time), copied in place.
|
|
137
161
|
const values = new Float64Array(at.length * STRIDE);
|
|
138
162
|
for (const [k, i] of at.entries())
|
|
139
|
-
values.set(
|
|
163
|
+
values.set(c.values.subarray(i * STRIDE, (i + 1) * STRIDE), k * STRIDE);
|
|
140
164
|
own = {
|
|
141
165
|
session: { ...session, ...(costUsd !== undefined ? { costUsd } : {}) },
|
|
142
|
-
counts: {
|
|
166
|
+
counts: {
|
|
167
|
+
n: at.length,
|
|
168
|
+
models: c.models,
|
|
169
|
+
model: Int32Array.from(at, (i) => c.model[i]),
|
|
170
|
+
values,
|
|
171
|
+
has: Uint8Array.from(at, (i) => c.has[i]),
|
|
172
|
+
},
|
|
143
173
|
};
|
|
144
174
|
}
|
|
145
|
-
return unpriced || !pricer.ready ? own : counted(own, pricer, new Float64Array(
|
|
175
|
+
return unpriced || !pricer.ready ? own : counted(own.session, own.counts, pricer, new Float64Array(USAGE_FIELDS));
|
|
146
176
|
}
|
|
147
177
|
/** 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
|
|
149
|
-
if (!Number.isSafeInteger(
|
|
150
|
-
throw new RangeError(`threads: a whole number from 1 to ${MOST_THREADS}, not ${
|
|
178
|
+
export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests, threads: asked, readAhead = readAheadBytes(), workerOldMb = OLD_MB } = {}) {
|
|
179
|
+
if (asked !== undefined && (!Number.isSafeInteger(asked) || asked < 1 || asked > MOST_THREADS))
|
|
180
|
+
throw new RangeError(`threads: a whole number from 1 to ${MOST_THREADS}, not ${asked}`);
|
|
151
181
|
if (!(readAhead >= 0))
|
|
152
182
|
throw new RangeError(`readAhead: a number of bytes, 0 or more, not ${readAhead}`);
|
|
153
|
-
if (!Number.isSafeInteger(workerOldMb) || workerOldMb <
|
|
154
|
-
throw new RangeError(`workerOldMb: a whole number of MB, at least
|
|
183
|
+
if (!Number.isSafeInteger(workerOldMb) || workerOldMb < MIN_OLD_MB)
|
|
184
|
+
throw new RangeError(`workerOldMb: a whole number of MB, at least ${MIN_OLD_MB}, not ${workerOldMb}`);
|
|
185
|
+
const threads = asked ?? defaultThreads(undefined, undefined, readAhead, workerOldMb);
|
|
155
186
|
const pool = !state && readers === READERS && threads > 1 ? new ReadPool(threads, readAhead, workerOldMb) : undefined;
|
|
156
187
|
try {
|
|
157
188
|
let prices;
|
|
@@ -169,7 +200,7 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
|
|
|
169
200
|
const lookups = new Map();
|
|
170
201
|
// Requests are priced as they are read once the prices are in hand: at once when the caller handed them in (or none),
|
|
171
202
|
// 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 (
|
|
203
|
+
// request with its time, so with one every part keeps its requests as read (AsRead) to the totals.
|
|
173
204
|
const pricer = {
|
|
174
205
|
ready: catalog === false || (catalog !== undefined && calculateCost !== undefined),
|
|
175
206
|
...(catalog ? { catalog } : {}),
|
|
@@ -187,8 +218,11 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
|
|
|
187
218
|
// files then share the threads with the next source's, and the largest files of every source are read first (pool.ts).
|
|
188
219
|
const ahead = new Map();
|
|
189
220
|
if (pool) {
|
|
221
|
+
// The pool reads the line sources (LINE_READERS) alone. Another (OpenCode: a session is rows of a database, or JSON
|
|
222
|
+
// files, its size not its file's) is read here, on this thread, as without a pool: the same totals either way.
|
|
190
223
|
for (const source of sources)
|
|
191
|
-
|
|
224
|
+
if (Object.hasOwn(LINE_READERS, source))
|
|
225
|
+
ahead.set(source, await listSource(home, source, readers, env, true));
|
|
192
226
|
const items = [...ahead].flatMap(([source, { listed, childList }]) => [...listed.map(({ locator, stats }) => ({ source, locator, size: stats.size })), ...childList.map(({ locator, size }) => ({ source, locator, size }))]);
|
|
193
227
|
const ids = pool.readAll(items);
|
|
194
228
|
let at = 0;
|
|
@@ -236,7 +270,7 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
|
|
|
236
270
|
part.read = ownPart(part.read, mirrored, pricer, all);
|
|
237
271
|
};
|
|
238
272
|
try {
|
|
239
|
-
// Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else
|
|
273
|
+
// Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else AsRead.
|
|
240
274
|
own(whole || ![...read.tops, ...read.children].some((part) => "n" in part.read));
|
|
241
275
|
}
|
|
242
276
|
catch (error) {
|
|
@@ -265,7 +299,15 @@ async function listSource(home, source, readers, env, sized = false) {
|
|
|
265
299
|
const childList = await Promise.all(children.map(async (child) => ({ ...child, size: sized ? ((await stat(child.locator.file).catch(() => undefined))?.size ?? 0) : 0 })));
|
|
266
300
|
return { listed, childList };
|
|
267
301
|
}
|
|
268
|
-
|
|
302
|
+
/** `source`'s locators read in the import's order, sessions first, then the subagents beside them, through one `seen`.
|
|
303
|
+
* A pass handed a state goes on from its cursors, and comes out as a fresh pass would: a record copied into many files
|
|
304
|
+
* 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
|
|
305
|
+
* gone, when its reader could not go on from its cursor (a new inode, truncated, rewritten), or when a locator holding a
|
|
306
|
+
* copy now comes before the one its record counts in (an append moved an older file after its resumed copy, a new file
|
|
307
|
+
* sorts before one it shares records with). A change of order among locators that share no record reads nothing again.
|
|
308
|
+
* With `each` (Each), each file is read with its chain and its turns, never through the pool, and the part keeps what
|
|
309
|
+
* `each` returns. */
|
|
310
|
+
export async function readSource(home, source, readers, env, state, lookups, pricer, whole, listing, each) {
|
|
269
311
|
const reader = readerOf(source, readers);
|
|
270
312
|
// The pool's listing, when parseHome read this source ahead (pool.ts); each read is taken below in order, or made again.
|
|
271
313
|
const { listed, childList, reads: ahead } = listing ?? (await listSource(home, source, readers, env));
|
|
@@ -289,48 +331,77 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
|
|
|
289
331
|
const read = async (locator, pooled) => {
|
|
290
332
|
const key = locatorKey(locator);
|
|
291
333
|
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.
|
|
293
|
-
//
|
|
294
|
-
//
|
|
334
|
+
// The records read so far, as the reader asks for them, each new one this locator's, each found one noted. A new
|
|
335
|
+
// record goes into the source's index at once (locators are read one at a time, so no other read adds to it before
|
|
336
|
+
// this one ends); a read that fails partway takes its records out again (undoTo the mark), so none is left owned
|
|
337
|
+
// that no cursor holds, which a retry would take for a copy. Staging them in an index of their own, then copying
|
|
338
|
+
// it in, held a big file's records twice.
|
|
295
339
|
// Records are held by their packed keys (packInto), each packed as it is asked for.
|
|
296
340
|
const me = locatorNumber(owners, key);
|
|
297
|
-
const
|
|
341
|
+
const mark = markOf(owners);
|
|
298
342
|
const found = new Set();
|
|
343
|
+
// A reader asks for a record and then adds it: the last record packed is kept packed, and when the last question
|
|
344
|
+
// of it found none and the index has taken nothing since (its tables and their counts as they were), it is added
|
|
345
|
+
// without another lookup.
|
|
299
346
|
const at = packed();
|
|
347
|
+
let asked;
|
|
348
|
+
let missedU;
|
|
349
|
+
let missedO;
|
|
350
|
+
let missedCount = -1;
|
|
351
|
+
const pack = (record) => {
|
|
352
|
+
if (record !== asked) {
|
|
353
|
+
packInto(record, at);
|
|
354
|
+
asked = record;
|
|
355
|
+
missedCount = -1;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const unchanged = () => missedCount !== -1 && missedU === owners.uuids && missedO === owners.others && missedCount === owners.uuids.count + owners.others.count;
|
|
300
359
|
const seen = {
|
|
301
360
|
has: (record) => {
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (owner === -1)
|
|
305
|
-
|
|
306
|
-
|
|
361
|
+
pack(record);
|
|
362
|
+
const owner = ownerOf(owners, at);
|
|
363
|
+
if (owner === -1) {
|
|
364
|
+
missedU = owners.uuids;
|
|
365
|
+
missedO = owners.others;
|
|
366
|
+
missedCount = owners.uuids.count + owners.others.count;
|
|
307
367
|
return false;
|
|
368
|
+
}
|
|
369
|
+
missedCount = -1;
|
|
308
370
|
if (owner !== me)
|
|
309
371
|
found.add(owners.locators[owner]);
|
|
310
372
|
return true;
|
|
311
373
|
},
|
|
312
374
|
add(record) {
|
|
313
|
-
|
|
314
|
-
if (
|
|
315
|
-
|
|
375
|
+
pack(record);
|
|
376
|
+
if (unchanged())
|
|
377
|
+
addNew(owners, at, me);
|
|
378
|
+
else
|
|
379
|
+
addRecord(owners, at, me);
|
|
380
|
+
missedCount = -1;
|
|
316
381
|
return this;
|
|
317
382
|
},
|
|
318
383
|
};
|
|
319
384
|
if (pooled) {
|
|
320
385
|
// 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
386
|
const made = await pooled();
|
|
322
|
-
|
|
323
|
-
|
|
387
|
+
if (made.ok && !anyIn(owners, made.mine) && !anyIn(owners, made.missed)) {
|
|
388
|
+
// None of its records is held: the larger index keeps its arrays, the other's records go in.
|
|
324
389
|
ownAll(made.mine, me);
|
|
325
|
-
|
|
390
|
+
addDisjoint(owners, made.mine);
|
|
326
391
|
return made.sessions;
|
|
327
392
|
}
|
|
328
393
|
}
|
|
329
|
-
|
|
394
|
+
// With no state the cursor is dropped: the read makes no copy for it. A pass that reads chains (`each`) reads each
|
|
395
|
+
// file with its turns and its chain; with no state it keeps no cursor, so a last line with no newline yet is in
|
|
396
|
+
// `seen` like any other, and its copy in a later file counts once.
|
|
397
|
+
const options = each ? { seen, chain: true, lookups, keepsCursor: kept !== undefined } : { turns: false, totals: true, seen, lookups, [DROPS_CURSOR]: !kept };
|
|
398
|
+
const result = await reader.read(locator, cursor, options).catch((error) => void unread.push({ locator, error }));
|
|
330
399
|
if (!result) {
|
|
331
400
|
// A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
|
|
332
401
|
// would hold none of them: the next pass reads it from its start. A locator that found them already read (a
|
|
333
402
|
// copy) skipped them, though the fresh pass counts them there: the source is read again.
|
|
403
|
+
// This read's records go, and with them, for a locator read before, those of its earlier reads.
|
|
404
|
+
undoTo(owners, mark);
|
|
334
405
|
if (kept && cursor !== undefined) {
|
|
335
406
|
kept.cursors.delete(key);
|
|
336
407
|
dropOwner(owners, me);
|
|
@@ -340,7 +411,6 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
|
|
|
340
411
|
}
|
|
341
412
|
return [];
|
|
342
413
|
}
|
|
343
|
-
addAll(owners, mine);
|
|
344
414
|
if (found.size)
|
|
345
415
|
for (const owner of found)
|
|
346
416
|
(copied.get(key) ?? copied.set(key, new Set()).get(key)).add(owner);
|
|
@@ -349,29 +419,29 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
|
|
|
349
419
|
if (state)
|
|
350
420
|
state.read += result.read;
|
|
351
421
|
kept?.cursors.set(key, result.cursor);
|
|
352
|
-
return result.sessions;
|
|
422
|
+
return each ? Promise.all(result.sessions.map(each)) : result.sessions;
|
|
353
423
|
};
|
|
354
424
|
const tops = [];
|
|
355
425
|
const children = [];
|
|
356
|
-
const sums = new Float64Array(
|
|
426
|
+
const sums = new Float64Array(USAGE_FIELDS);
|
|
357
427
|
// Each locator's sessions packed as soon as they are read. A totals read gives each request's counts alone, and its
|
|
358
428
|
// 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
429
|
// 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.
|
|
361
|
-
//
|
|
362
|
-
const pack = async (
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
if (!pricer.ready && fresh && top &&
|
|
430
|
+
// sink each part is priced once the prices are in hand. Once a session's own file is read that leaves its session to
|
|
431
|
+
// be priced at the totals (pricedAtTotals), the prices are loaded, and the parts read so far priced.
|
|
432
|
+
const pack = async (read, top) => {
|
|
433
|
+
const session = metaOf(read.session);
|
|
434
|
+
const requests = countsOf(read);
|
|
435
|
+
// A part whose requests mirror another's stays as read: its own are known once every source is read (ownPart).
|
|
436
|
+
if (read.requests.some((request) => request.mirrors !== undefined))
|
|
437
|
+
return { session, counts: trimmed(requests), mirrors: { of: read.requests.map((request) => request.mirrors), cost: Float64Array.from(read.requests, (request) => request.costUsd ?? Number.NaN) } };
|
|
438
|
+
if (!whole && !pricer.ready && fresh && top && pricedAtTotals(session, requests.n)) {
|
|
369
439
|
await pricer.load();
|
|
370
440
|
for (const part of [...tops, ...children])
|
|
371
|
-
if (
|
|
372
|
-
part.read = counted(part.read, pricer, sums);
|
|
441
|
+
if ("counts" in part.read && !part.read.mirrors)
|
|
442
|
+
part.read = counted(part.read.session, part.read.counts, pricer, sums);
|
|
373
443
|
}
|
|
374
|
-
return pricer.ready ? counted(
|
|
444
|
+
return !whole && pricer.ready ? counted(session, requests, pricer, sums) : { session, counts: trimmed(requests) };
|
|
375
445
|
};
|
|
376
446
|
for (const [i, { locator }] of listed.entries())
|
|
377
447
|
for (const session of await read(locator, pass === 0 ? ahead?.[i] : undefined))
|
|
@@ -386,7 +456,11 @@ async function readSource(home, source, readers, env, state, lookups, pricer, wh
|
|
|
386
456
|
state.sources[source] = undefined;
|
|
387
457
|
}
|
|
388
458
|
}
|
|
389
|
-
|
|
459
|
+
/** A source's sessions: each with its files (`parts`, in the import's order) and its subagents' (`children`); `untied`, a
|
|
460
|
+
* subagent's whose session is not under the home, a session of its own. A session whose every file holds only records
|
|
461
|
+
* an earlier file holds (copies) is none: its records count where they were first read. serve's import leaves such a
|
|
462
|
+
* file out the same way. */
|
|
463
|
+
export function groupsOf(tops, children) {
|
|
390
464
|
// Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
|
|
391
465
|
// parent's, as is each one beside a session's (Claude Code's subagents).
|
|
392
466
|
const sessions = new Map();
|
|
@@ -428,17 +502,16 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
|
|
|
428
502
|
// A subagent whose session is not under the home: a line of its own, but its prompts are its parent agent's.
|
|
429
503
|
for (const part of untied)
|
|
430
504
|
sessions.set(`\0${locatorKey(part.locator)}`, { parts: [part], children: [], untied: true });
|
|
505
|
+
return [...sessions.values()].filter(({ parts, children }) => !(parts.every(({ read }) => copiesAlone(read.session, requestsOf(read))) && children.length === 0));
|
|
506
|
+
}
|
|
507
|
+
async function totalsOf(home, source, tops, children, pricer, priceWith, calculateCost, sink) {
|
|
431
508
|
const out = [];
|
|
432
|
-
for (const { parts, children: subagents, untied } of
|
|
433
|
-
// A session whose every file holds only records an earlier file holds (copies) is no session: its records count where
|
|
434
|
-
// 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)
|
|
436
|
-
continue;
|
|
509
|
+
for (const { parts, children: subagents, untied } of groupsOf(tops, children)) {
|
|
437
510
|
const first = parts[0];
|
|
438
511
|
const tokens = noTokens();
|
|
439
512
|
let reasoning = 0;
|
|
440
513
|
let calls = 0;
|
|
441
|
-
// Parts priced as read (Counted) or not (
|
|
514
|
+
// 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
515
|
const all = [...parts, ...subagents].map(({ read }) => read);
|
|
443
516
|
const priced = all.filter((read) => "n" in read);
|
|
444
517
|
if (priced.length && (priced.length !== all.length || sink))
|
|
@@ -457,9 +530,9 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
|
|
|
457
530
|
}
|
|
458
531
|
}
|
|
459
532
|
else {
|
|
460
|
-
for (const
|
|
461
|
-
for (let i = 0; i <
|
|
462
|
-
requests.push(requestAt(
|
|
533
|
+
for (const { session, counts } of all)
|
|
534
|
+
for (let i = 0; i < counts.n; i += 1)
|
|
535
|
+
requests.push(requestAt(counts, i, session.model));
|
|
463
536
|
for (const { usage } of requests) {
|
|
464
537
|
calls += 1;
|
|
465
538
|
if (!usage)
|
|
@@ -505,15 +578,17 @@ async function totalsOf(home, source, tops, children, pricer, priceWith, calcula
|
|
|
505
578
|
};
|
|
506
579
|
out.push(totals);
|
|
507
580
|
if (sink) {
|
|
508
|
-
// The session's first time: the least finite one of its own files' requests (
|
|
509
|
-
// sink), read where they are held.
|
|
581
|
+
// The session's first time: the least finite one of its own files' requests (each part as read, as every part is
|
|
582
|
+
// with a sink), read where they are held.
|
|
510
583
|
let started;
|
|
511
|
-
for (const { read } of parts)
|
|
512
|
-
|
|
513
|
-
|
|
584
|
+
for (const { read } of parts) {
|
|
585
|
+
const { counts } = read;
|
|
586
|
+
for (let i = 0; i < counts.n; i += 1) {
|
|
587
|
+
const at = atOf(counts, i);
|
|
514
588
|
if (Number.isFinite(at) && (started === undefined || at < started))
|
|
515
589
|
started = at;
|
|
516
590
|
}
|
|
591
|
+
}
|
|
517
592
|
sink(totals, requests, started);
|
|
518
593
|
}
|
|
519
594
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { Answer, Ended, Mirror, ToolCall, Turn, Usage } from "./types.js";
|
|
1
|
+
export type { Answer, ChainRecord, 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
4
|
export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat, type UsageOptions } from "./usage.js";
|
|
@@ -12,3 +12,4 @@ export { builtinCatalog, type CalculateCost, type Catalog, catalogOf, type Liste
|
|
|
12
12
|
export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
|
|
13
13
|
export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals, withSubagentCosts } from "./home.js";
|
|
14
14
|
export { type Wrapped, wrappedHome } from "./wrapped.js";
|
|
15
|
+
export { analyzeCache, BREAK_DROP, CACHE_SOURCES, cacheHome, cacheTotals, type SessionCache, type CacheBreak, type CacheCause, CACHE_CAUSES, type CacheOptions, type CacheReport, CACHE_TTL_LONG_MS, CACHE_TTL_MS } from "./cache.js";
|
package/dist/index.js
CHANGED
|
@@ -11,3 +11,4 @@ export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
|
|
|
11
11
|
export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
|
|
12
12
|
export { parseHome, ReadFailures, withSubagentCosts } from "./home.js";
|
|
13
13
|
export { wrappedHome } from "./wrapped.js";
|
|
14
|
+
export { analyzeCache, BREAK_DROP, CACHE_SOURCES, cacheHome, cacheTotals, CACHE_CAUSES, CACHE_TTL_LONG_MS, CACHE_TTL_MS } from "./cache.js";
|
|
@@ -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
|
+
};
|
package/dist/internal.js
ADDED
|
@@ -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,6 +1,7 @@
|
|
|
1
1
|
import { type Counts } from "./counts.js";
|
|
2
2
|
import { type Env, type Reader, type ReadOptions } from "./reader.js";
|
|
3
|
-
import { type
|
|
3
|
+
import { type Shape } from "./scan.js";
|
|
4
|
+
import { type Answer, type ChainRecord, 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
|
|
6
7
|
* a total counts; a totals read's are in `counts` instead, each its model, usage and time alone. `own` is the source's own (LineSource.start). A turns: true read's holds the session's text (its
|
|
@@ -35,6 +36,9 @@ export type ReadContext<O = unknown> = {
|
|
|
35
36
|
seen: Set<string>;
|
|
36
37
|
keep: boolean;
|
|
37
38
|
add: (turn: Turn) => void;
|
|
39
|
+
/** The session's chain, when the read keeps one (ReadOptions.chain): the source pushes each record of the
|
|
40
|
+
* conversation onto it, in the order read, and marks the record that opens each request. */
|
|
41
|
+
chain?: ChainRecord[];
|
|
38
42
|
};
|
|
39
43
|
/** A JSONL source: where its files are, and how it reads one record of one into the session. */
|
|
40
44
|
export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name" | "harness" | "order"> & {
|
|
@@ -60,6 +64,15 @@ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name"
|
|
|
60
64
|
* 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
65
|
* read is a turns: false read, its requests whole. */
|
|
62
66
|
totals?: true;
|
|
67
|
+
/** What `record` reads of a record in a totals read: a line is then read for these fields alone, from its bytes (scan),
|
|
68
|
+
* every other value checked as JSON but not decoded, and parsed whole only when the scan leaves it to JSON.parse. It
|
|
69
|
+
* names every field whose value can change what a totals read gives (a field whose value goes only into a turn or
|
|
70
|
+
* text a totals read drops may be left out); the read itself takes the record's `timestamp`. Without it, or in any
|
|
71
|
+
* other read, each line is parsed whole. */
|
|
72
|
+
fields?: Shape;
|
|
73
|
+
/** The shape of the state (`own`) its cursors hold, set when it changes from one a release saved: a cursor saved at
|
|
74
|
+
* another (none for a source that never set one) is no place to go on from, and the file is read from its start. */
|
|
75
|
+
stateVersion?: number;
|
|
63
76
|
};
|
|
64
77
|
/** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
|
|
65
78
|
export declare class LineTooLong extends Error {
|
|
@@ -81,13 +94,17 @@ export type FileCursor = {
|
|
|
81
94
|
/** The last bytes before `offset` (up to 64, base64): a file rewritten in place to at least the same length no longer
|
|
82
95
|
* has them there, and is read from its start. */
|
|
83
96
|
mark: string;
|
|
84
|
-
/** Whether the read kept turns,
|
|
97
|
+
/** Whether the read kept turns, whether it was a totals read, and whether it kept a chain: a cursor of another kind is
|
|
98
|
+
* no place to go on from. */
|
|
85
99
|
keep: boolean;
|
|
86
100
|
totals?: boolean;
|
|
101
|
+
chain?: boolean;
|
|
102
|
+
/** Its reader's state shape when saved (LineSource.stateVersion). */
|
|
103
|
+
stateVersion?: number;
|
|
87
104
|
state: ReadState;
|
|
88
105
|
};
|
|
89
106
|
/** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it
|
|
90
107
|
* 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>;
|
|
108
|
+
export declare function resumes<S extends string, O>(spec: LineSource<S, O>, file: string, cursor: FileCursor | undefined, { turns: keep, totals: asked, chain }?: ReadOptions): Promise<boolean>;
|
|
92
109
|
/** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
|
|
93
110
|
export declare function lineReader<S extends string, O>(spec: LineSource<S, O>): Reader<S, FileCursor>;
|