@parcha/agentrun-import 0.1.0-beta.58 → 0.1.0-beta.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -20
- package/dist/cli.js +23 -8
- package/dist/home.d.ts +24 -1
- package/dist/home.js +394 -146
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -2
- package/dist/internal.d.ts +18 -0
- package/dist/internal.js +12 -0
- package/dist/lines.d.ts +24 -1
- package/dist/lines.js +135 -25
- package/dist/mirror.d.ts +13 -0
- package/dist/mirror.js +15 -0
- package/dist/pool-worker.d.ts +6 -0
- package/dist/pool-worker.js +50 -0
- package/dist/pool.d.ts +106 -0
- package/dist/pool.js +288 -0
- package/dist/price.d.ts +13 -5
- package/dist/price.js +31 -21
- package/dist/read.d.ts +14 -4
- package/dist/read.js +41 -7
- package/dist/reader.d.ts +38 -8
- package/dist/readers/claude-code.d.ts +24 -0
- package/dist/readers/claude-code.js +51 -35
- package/dist/readers/codex.d.ts +60 -1
- package/dist/readers/codex.js +494 -52
- package/dist/readers/copilot.d.ts +4 -0
- package/dist/readers/copilot.js +224 -0
- package/dist/readers/index.d.ts +2 -0
- package/dist/readers/index.js +4 -0
- package/dist/readers/line-readers.d.ts +7 -0
- package/dist/readers/line-readers.js +10 -0
- package/dist/readers/opencode.d.ts +42 -0
- package/dist/readers/opencode.js +920 -0
- package/dist/readers/pi.js +2 -2
- package/dist/record-index.d.ts +32 -1
- package/dist/record-index.js +133 -13
- 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 +36 -2
- package/dist/types.d.ts +20 -3
- package/dist/usage.d.ts +6 -2
- package/dist/usage.js +42 -1
- package/package.json +4 -2
package/dist/home.js
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
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";
|
|
5
8
|
import { relative, sep } from "node:path";
|
|
6
|
-
import { builtinCatalog, priceRequests } from "./price.js";
|
|
9
|
+
import { builtinCatalog, loadCalculateCost, priceRequest, priceRequests, roundUsd } from "./price.js";
|
|
7
10
|
import { childrenOf, inOrder, readerOf, sessionLocators } from "./read.js";
|
|
8
11
|
import { locatorKey } from "./reader.js";
|
|
9
12
|
import { READERS, SOURCES } from "./readers/index.js";
|
|
10
|
-
import {
|
|
11
|
-
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";
|
|
12
18
|
import { packed, packInto } from "./record-key.js";
|
|
19
|
+
import { mirroredIn, sessionKey } from "./mirror.js";
|
|
13
20
|
import { addTokens, noTokens } from "./usage.js";
|
|
14
21
|
/** The shape of the HomeState this version keeps: a state of any other is set aside. */
|
|
15
22
|
const STATE_VERSION = 1;
|
|
@@ -29,121 +36,266 @@ const keyOf = (home, { file, id }) => {
|
|
|
29
36
|
const path = relative(home, file).split(sep).join("/");
|
|
30
37
|
return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
|
|
31
38
|
};
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
}
|
|
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);
|
|
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
|
|
48
|
+
* sum would pass it, and the source is read again with each request's tokens kept. */
|
|
49
|
+
class Inexact extends Error {
|
|
50
|
+
}
|
|
51
|
+
/** The most threads parseHome takes: each is a worker with a heap of its own, and past the cores the largest files set
|
|
52
|
+
* the time anyway. More is refused before any worker starts. */
|
|
53
|
+
export const MOST_THREADS = 64;
|
|
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) {
|
|
61
|
+
if (read.counts)
|
|
62
|
+
return read.counts;
|
|
63
|
+
const out = counts();
|
|
64
|
+
for (const { model, usage, at } of read.requests)
|
|
65
|
+
addRequest(out, model, usage, at);
|
|
95
66
|
return out;
|
|
96
67
|
}
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
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];
|
|
103
75
|
if (!(has & HAS_USAGE))
|
|
104
76
|
return request;
|
|
105
|
-
const o = i *
|
|
106
|
-
const usage = { input:
|
|
77
|
+
const o = i * STRIDE;
|
|
78
|
+
const usage = { input: c.values[o], output: c.values[o + 1], cacheRead: c.values[o + 2], cacheWrite: c.values[o + 3] };
|
|
107
79
|
if (has & HAS_LONG)
|
|
108
|
-
usage.cacheWrite1h =
|
|
80
|
+
usage.cacheWrite1h = c.values[o + 4];
|
|
109
81
|
if (has & HAS_REASONING)
|
|
110
|
-
usage.reasoning =
|
|
82
|
+
usage.reasoning = c.values[o + 5];
|
|
111
83
|
return { ...request, usage };
|
|
112
84
|
}
|
|
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);
|
|
89
|
+
const { catalog, calculate } = pricer;
|
|
90
|
+
const costs = catalog && calculate ? new Float64Array(n) : undefined;
|
|
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 = {};
|
|
95
|
+
for (let i = 0; i < n; i += 1) {
|
|
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];
|
|
102
|
+
if (!Number.isSafeInteger(count) || count < 0)
|
|
103
|
+
throw new Inexact();
|
|
104
|
+
tokens[k] += count;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
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;
|
|
119
|
+
const usd = priceRequest(request, catalog, calculate);
|
|
120
|
+
if (usd === undefined)
|
|
121
|
+
unpriceable = true;
|
|
122
|
+
else
|
|
123
|
+
costs[i] = usd;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (let k = 0; k < USAGE_FIELDS; k += 1)
|
|
127
|
+
if ((sums[k] += tokens[k]) > Number.MAX_SAFE_INTEGER)
|
|
128
|
+
throw new Inexact();
|
|
129
|
+
return { session, n, tokens, costs, unpriceable };
|
|
130
|
+
}
|
|
131
|
+
/** A session's cost with its subagents': Claude Code's written cost holds its subagents' already (its cost-state), so it
|
|
132
|
+
* stays as it is; every other source writes a subagent's cost on the subagent's own session, so each is added. Unknown
|
|
133
|
+
* when the session's is, or when one it adds is: never a subagent counted at 0. parseHome's totals and serve's import. */
|
|
134
|
+
export function withSubagentCosts(source, cost, subagents) {
|
|
135
|
+
if (source === "claude-code" || cost === undefined)
|
|
136
|
+
return cost;
|
|
137
|
+
return subagents.reduce((sum, usd) => (sum === undefined || usd === undefined ? undefined : sum + usd), cost);
|
|
138
|
+
}
|
|
139
|
+
/** A part with its own requests alone (none another session of the call holds) and the cost it wrote of them: its own
|
|
140
|
+
* when it holds none of another's, else its own requests' when each that used tokens is priced (mirror.ts ownRequests,
|
|
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). */
|
|
143
|
+
function ownPart(read, mirrored, pricer, unpriced) {
|
|
144
|
+
if ("n" in read || !read.mirrors)
|
|
145
|
+
return read;
|
|
146
|
+
const { counts: c, mirrors: marks } = read;
|
|
147
|
+
const at = Array.from({ length: c.n }, (_, i) => i).filter((i) => !mirrored({ mirrors: marks.of[i] }));
|
|
148
|
+
let own = read;
|
|
149
|
+
if (at.length !== c.n) {
|
|
150
|
+
const priced = at.every((i) => !Number.isNaN(marks.cost[i]) || !(c.has[i] & HAS_USAGE));
|
|
151
|
+
const costUsd = priced ? at.reduce((n, i) => n + (Number.isNaN(marks.cost[i]) ? 0 : marks.cost[i]), 0) : undefined;
|
|
152
|
+
const { costUsd: _, ...session } = read.session;
|
|
153
|
+
// Its own requests' rows of Counts (STRIDE numbers each: usage and time), copied in place.
|
|
154
|
+
const values = new Float64Array(at.length * STRIDE);
|
|
155
|
+
for (const [k, i] of at.entries())
|
|
156
|
+
values.set(c.values.subarray(i * STRIDE, (i + 1) * STRIDE), k * STRIDE);
|
|
157
|
+
own = {
|
|
158
|
+
session: { ...session, ...(costUsd !== undefined ? { costUsd } : {}) },
|
|
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
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return unpriced || !pricer.ready ? own : counted(own.session, own.counts, pricer, new Float64Array(USAGE_FIELDS));
|
|
169
|
+
}
|
|
113
170
|
/** 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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if (
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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}`);
|
|
174
|
+
if (!(readAhead >= 0))
|
|
175
|
+
throw new RangeError(`readAhead: a number of bytes, 0 or more, not ${readAhead}`);
|
|
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);
|
|
179
|
+
const pool = !state && readers === READERS && threads > 1 ? new ReadPool(threads, readAhead, workerOldMb) : undefined;
|
|
180
|
+
try {
|
|
181
|
+
let prices;
|
|
182
|
+
const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
|
|
183
|
+
const out = [];
|
|
184
|
+
const failed = [];
|
|
185
|
+
if (state) {
|
|
186
|
+
if (state.version !== STATE_VERSION) {
|
|
187
|
+
state.version = STATE_VERSION;
|
|
188
|
+
state.sources = {};
|
|
189
|
+
}
|
|
190
|
+
state.read = 0;
|
|
191
|
+
}
|
|
192
|
+
// What readers look up once for this import (a Codex fork's parent anywhere in its sessions), shared by its files.
|
|
193
|
+
const lookups = new Map();
|
|
194
|
+
// Requests are priced as they are read once the prices are in hand: at once when the caller handed them in (or none),
|
|
195
|
+
// else loaded when a session is read that the totals will price, as they would load them. A requests sink takes each
|
|
196
|
+
// request with its time, so with one every part keeps its requests as read (AsRead) to the totals.
|
|
197
|
+
const pricer = {
|
|
198
|
+
ready: catalog === false || (catalog !== undefined && calculateCost !== undefined),
|
|
199
|
+
...(catalog ? { catalog } : {}),
|
|
200
|
+
...(catalog && calculateCost ? { calculate: calculateCost } : {}),
|
|
201
|
+
async load() {
|
|
202
|
+
if (this.ready)
|
|
203
|
+
return;
|
|
204
|
+
this.catalog = await priceWith();
|
|
205
|
+
this.calculate = this.catalog ? (calculateCost ?? (await loadCalculateCost())) : undefined;
|
|
206
|
+
this.ready = true;
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
const whole = requests !== undefined;
|
|
210
|
+
// With a pool, every source is listed first and all their files queued at once, in the import's order: a source's last
|
|
211
|
+
// files then share the threads with the next source's, and the largest files of every source are read first (pool.ts).
|
|
212
|
+
const ahead = new Map();
|
|
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.
|
|
216
|
+
for (const source of sources)
|
|
217
|
+
if (Object.hasOwn(LINE_READERS, source))
|
|
218
|
+
ahead.set(source, await listSource(home, source, readers, env, true));
|
|
219
|
+
const items = [...ahead].flatMap(([source, { listed, childList }]) => [...listed.map(({ locator, stats }) => ({ source, locator, size: stats.size })), ...childList.map(({ locator, size }) => ({ source, locator, size }))]);
|
|
220
|
+
const ids = pool.readAll(items);
|
|
221
|
+
let at = 0;
|
|
222
|
+
for (const listing of ahead.values()) {
|
|
223
|
+
listing.ids = ids.slice(at, (at += listing.listed.length + listing.childList.length));
|
|
224
|
+
listing.reads = listing.ids.map((id) => () => pool.take(id));
|
|
225
|
+
}
|
|
123
226
|
}
|
|
124
|
-
|
|
227
|
+
// Every session this call read, by source and id, and the sources held to be totalled after the rest.
|
|
228
|
+
const readKeys = new Set();
|
|
229
|
+
const mirroring = [];
|
|
230
|
+
for (const source of sources) {
|
|
231
|
+
let read;
|
|
232
|
+
try {
|
|
233
|
+
read = await readSource(home, source, readers, env, state, lookups, pricer, whole, ahead.get(source));
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (!(error instanceof Inexact))
|
|
237
|
+
throw error;
|
|
238
|
+
// Tokens that cannot be summed as read: the source again, each request's tokens kept to the totals.
|
|
239
|
+
if (state)
|
|
240
|
+
(state.sources ??= {})[source] = undefined;
|
|
241
|
+
// The pool's reads of this source left untaken would hold the read-ahead for nothing.
|
|
242
|
+
pool?.drop(ahead.get(source)?.ids ?? []);
|
|
243
|
+
read = await readSource(home, source, readers, env, state, lookups, pricer, true);
|
|
244
|
+
}
|
|
245
|
+
const { tops, children, unread } = read;
|
|
246
|
+
for (const part of [...tops, ...children])
|
|
247
|
+
readKeys.add(sessionKey(source, part.read.session.id));
|
|
248
|
+
// A source whose requests mirror another's (OpenCode's claude-agent ones) is totalled once every source is read: a
|
|
249
|
+
// mirrored request counts in the session it mirrors when this call reads that one too.
|
|
250
|
+
if ([...tops, ...children].some(({ read }) => "mirrors" in read && read.mirrors))
|
|
251
|
+
mirroring.push({ source, read });
|
|
252
|
+
else
|
|
253
|
+
out.push(...(await totalsOf(home, source, tops, children, pricer, priceWith, calculateCost, requests)));
|
|
254
|
+
failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
|
|
255
|
+
}
|
|
256
|
+
// A request that mirrors a session this call read is counted in it, not again: each part keeps its own requests alone.
|
|
257
|
+
const mirrored = mirroredIn(readKeys);
|
|
258
|
+
for (const held of mirroring) {
|
|
259
|
+
const { source } = held;
|
|
260
|
+
let { read } = held;
|
|
261
|
+
const own = (all) => {
|
|
262
|
+
for (const part of [...read.tops, ...read.children])
|
|
263
|
+
part.read = ownPart(part.read, mirrored, pricer, all);
|
|
264
|
+
};
|
|
265
|
+
try {
|
|
266
|
+
// Priced as the source's other parts are: Counted when one is (the prices came in while it was read), else AsRead.
|
|
267
|
+
own(whole || ![...read.tops, ...read.children].some((part) => "n" in part.read));
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (!(error instanceof Inexact))
|
|
271
|
+
throw error;
|
|
272
|
+
// As a source read above: again, each request's tokens kept to the totals.
|
|
273
|
+
if (state)
|
|
274
|
+
(state.sources ??= {})[source] = undefined;
|
|
275
|
+
read = await readSource(home, source, readers, env, state, lookups, pricer, true);
|
|
276
|
+
own(true);
|
|
277
|
+
}
|
|
278
|
+
out.push(...(await totalsOf(home, source, read.tops, read.children, pricer, priceWith, calculateCost, requests)));
|
|
279
|
+
}
|
|
280
|
+
if (failed.length && !failures)
|
|
281
|
+
throw new ReadFailures(failed);
|
|
282
|
+
failures?.push(...failed);
|
|
283
|
+
return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
125
284
|
}
|
|
126
|
-
|
|
127
|
-
|
|
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 })));
|
|
285
|
+
finally {
|
|
286
|
+
pool?.close();
|
|
131
287
|
}
|
|
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
288
|
}
|
|
137
|
-
|
|
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);
|
|
289
|
+
async function listSource(home, source, readers, env, sized = false) {
|
|
145
290
|
const listed = await inOrder(await sessionLocators(home, source, { ...(env ? { env } : {}), readers }), source, readers);
|
|
146
|
-
const
|
|
291
|
+
const children = await childrenOf(home, source, { ...(env ? { env } : {}), readers });
|
|
292
|
+
const childList = await Promise.all(children.map(async (child) => ({ ...child, size: sized ? ((await stat(child.locator.file).catch(() => undefined))?.size ?? 0) : 0 })));
|
|
293
|
+
return { listed, childList };
|
|
294
|
+
}
|
|
295
|
+
async function readSource(home, source, readers, env, state, lookups, pricer, whole, listing) {
|
|
296
|
+
const reader = readerOf(source, readers);
|
|
297
|
+
// The pool's listing, when parseHome read this source ahead (pool.ts); each read is taken below in order, or made again.
|
|
298
|
+
const { listed, childList, reads: ahead } = listing ?? (await listSource(home, source, readers, env));
|
|
147
299
|
// Each locator's place in this pass's order of reading.
|
|
148
300
|
const place = new Map([...listed.map(({ locator }) => locatorKey(locator)), ...childList.map(({ locator }) => locatorKey(locator))].map((key, at) => [key, at]));
|
|
149
301
|
// Whether a locator holds a copy of a record that now counts after it: the fresh pass would count it in that locator.
|
|
@@ -154,46 +306,85 @@ async function readSource(home, source, readers, env, state, models) {
|
|
|
154
306
|
// read from its start and its state rebuilt.
|
|
155
307
|
if (kept && ([...kept.cursors.keys()].some((key) => !place.has(key)) || outOfOrder(kept)))
|
|
156
308
|
kept = undefined;
|
|
309
|
+
// A pass from nothing is the last: only its sessions may load the prices (one resumed may be read again).
|
|
310
|
+
const fresh = !kept || kept.cursors.size === 0;
|
|
157
311
|
if (state && !kept)
|
|
158
312
|
kept = state.sources[source] = { cursors: new Map(), owners: recordIndex(), copied: new Map() };
|
|
159
313
|
const { owners, copied } = kept ?? { owners: recordIndex(), copied: new Map() };
|
|
160
314
|
let restarted = false;
|
|
161
315
|
const unread = [];
|
|
162
|
-
const read = async (locator) => {
|
|
316
|
+
const read = async (locator, pooled) => {
|
|
163
317
|
const key = locatorKey(locator);
|
|
164
318
|
const cursor = kept?.cursors.get(key);
|
|
165
|
-
// The records read so far, as the reader asks for them, each new one this locator's, each found one noted.
|
|
166
|
-
//
|
|
167
|
-
//
|
|
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.
|
|
168
324
|
// Records are held by their packed keys (packInto), each packed as it is asked for.
|
|
169
325
|
const me = locatorNumber(owners, key);
|
|
170
|
-
const
|
|
326
|
+
const mark = markOf(owners);
|
|
171
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.
|
|
172
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;
|
|
173
344
|
const seen = {
|
|
174
345
|
has: (record) => {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (owner === -1)
|
|
178
|
-
|
|
179
|
-
|
|
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;
|
|
180
352
|
return false;
|
|
353
|
+
}
|
|
354
|
+
missedCount = -1;
|
|
181
355
|
if (owner !== me)
|
|
182
356
|
found.add(owners.locators[owner]);
|
|
183
357
|
return true;
|
|
184
358
|
},
|
|
185
359
|
add(record) {
|
|
186
|
-
|
|
187
|
-
if (
|
|
188
|
-
|
|
360
|
+
pack(record);
|
|
361
|
+
if (unchanged())
|
|
362
|
+
addNew(owners, at, me);
|
|
363
|
+
else
|
|
364
|
+
addRecord(owners, at, me);
|
|
365
|
+
missedCount = -1;
|
|
189
366
|
return this;
|
|
190
367
|
},
|
|
191
368
|
};
|
|
192
|
-
|
|
369
|
+
if (pooled) {
|
|
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.
|
|
371
|
+
const made = await pooled();
|
|
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.
|
|
374
|
+
ownAll(made.mine, me);
|
|
375
|
+
addDisjoint(owners, made.mine);
|
|
376
|
+
return made.sessions;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
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 }));
|
|
193
382
|
if (!result) {
|
|
194
383
|
// A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
|
|
195
384
|
// would hold none of them: the next pass reads it from its start. A locator that found them already read (a
|
|
196
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);
|
|
197
388
|
if (kept && cursor !== undefined) {
|
|
198
389
|
kept.cursors.delete(key);
|
|
199
390
|
dropOwner(owners, me);
|
|
@@ -203,7 +394,6 @@ async function readSource(home, source, readers, env, state, models) {
|
|
|
203
394
|
}
|
|
204
395
|
return [];
|
|
205
396
|
}
|
|
206
|
-
addAll(owners, mine);
|
|
207
397
|
if (found.size)
|
|
208
398
|
for (const owner of found)
|
|
209
399
|
(copied.get(key) ?? copied.set(key, new Set()).get(key)).add(owner);
|
|
@@ -215,16 +405,33 @@ async function readSource(home, source, readers, env, state, models) {
|
|
|
215
405
|
return result.sessions;
|
|
216
406
|
};
|
|
217
407
|
const tops = [];
|
|
408
|
+
const children = [];
|
|
409
|
+
const sums = new Float64Array(USAGE_FIELDS);
|
|
218
410
|
// Each locator's sessions packed as soon as they are read. A totals read gives each request's counts alone, and its
|
|
219
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
|
|
220
|
-
// reader with no totals read gives its requests whole: only one locator's are held so at a time.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
412
|
+
// reader with no totals read gives its requests whole: only one locator's are held so at a time. Without a requests
|
|
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)) {
|
|
422
|
+
await pricer.load();
|
|
423
|
+
for (const part of [...tops, ...children])
|
|
424
|
+
if ("counts" in part.read && !part.read.mirrors)
|
|
425
|
+
part.read = counted(part.read.session, part.read.counts, pricer, sums);
|
|
426
|
+
}
|
|
427
|
+
return !whole && pricer.ready ? counted(session, requests, pricer, sums) : { session, counts: trimmed(requests) };
|
|
428
|
+
};
|
|
429
|
+
for (const [i, { locator }] of listed.entries())
|
|
430
|
+
for (const session of await read(locator, pass === 0 ? ahead?.[i] : undefined))
|
|
431
|
+
tops.push({ locator: session.locator, read: await pack(session, true) });
|
|
432
|
+
for (const [i, { locator, of }] of childList.entries())
|
|
433
|
+
for (const session of await read(locator, pass === 0 ? ahead?.[listed.length + i] : undefined))
|
|
434
|
+
children.push({ locator: session.locator, read: await pack(session, false), of });
|
|
228
435
|
// A locator its reader could not go on in, or a copy this pass found whose record counts after it: read the source
|
|
229
436
|
// again, from nothing.
|
|
230
437
|
if (pass > 0 || !kept || !(restarted || outOfOrder(kept)))
|
|
@@ -232,7 +439,7 @@ async function readSource(home, source, readers, env, state, models) {
|
|
|
232
439
|
state.sources[source] = undefined;
|
|
233
440
|
}
|
|
234
441
|
}
|
|
235
|
-
async function totalsOf(home, source, tops, children,
|
|
442
|
+
async function totalsOf(home, source, tops, children, pricer, priceWith, calculateCost, sink) {
|
|
236
443
|
// Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
|
|
237
444
|
// parent's, as is each one beside a session's (Claude Code's subagents).
|
|
238
445
|
const sessions = new Map();
|
|
@@ -278,28 +485,59 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
|
|
|
278
485
|
for (const { parts, children: subagents, untied } of sessions.values()) {
|
|
279
486
|
// A session whose every file holds only records an earlier file holds (copies) is no session: its records count where
|
|
280
487
|
// they were first read. serve's import leaves such a file out the same way.
|
|
281
|
-
if (parts.every(({ read }) => read.session
|
|
488
|
+
if (parts.every(({ read }) => copiesAlone(read.session, requestsOf(read))) && subagents.length === 0)
|
|
282
489
|
continue;
|
|
283
490
|
const first = parts[0];
|
|
284
491
|
const tokens = noTokens();
|
|
285
492
|
let reasoning = 0;
|
|
286
493
|
let calls = 0;
|
|
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.
|
|
495
|
+
const all = [...parts, ...subagents].map(({ read }) => read);
|
|
496
|
+
const priced = all.filter((read) => "n" in read);
|
|
497
|
+
if (priced.length && (priced.length !== all.length || sink))
|
|
498
|
+
throw new Error("parts priced and not in one session");
|
|
287
499
|
const requests = [];
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
500
|
+
if (priced.length) {
|
|
501
|
+
// Whole counts summed below 2^53: the same sums in any order.
|
|
502
|
+
for (const read of priced) {
|
|
503
|
+
calls += read.n;
|
|
504
|
+
tokens.input += read.tokens[0];
|
|
505
|
+
tokens.output += read.tokens[1];
|
|
506
|
+
tokens.cacheRead += read.tokens[2];
|
|
507
|
+
tokens.cacheWrite += read.tokens[3];
|
|
508
|
+
tokens.cacheWrite1h += read.tokens[4];
|
|
509
|
+
reasoning += read.tokens[5];
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
else {
|
|
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));
|
|
516
|
+
for (const { usage } of requests) {
|
|
517
|
+
calls += 1;
|
|
518
|
+
if (!usage)
|
|
519
|
+
continue;
|
|
520
|
+
addTokens(tokens, usage);
|
|
521
|
+
reasoning += usage.reasoning ?? 0;
|
|
522
|
+
}
|
|
297
523
|
}
|
|
298
|
-
// The source's own cost, when each of its files wrote one: Claude Code writes the session's running total
|
|
299
|
-
// session's copy goes on from the original's), so the highest; another source prices each
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
524
|
+
// The source's own cost, when each of its files wrote one: Claude Code writes the session's running total, its
|
|
525
|
+
// subagents' with it (a moved session's copy goes on from the original's), so the highest; another source prices each
|
|
526
|
+
// request, so the sum of its files' and its subagents' (OpenCode's subagent is a session of its own).
|
|
527
|
+
const written = parts.map(({ read }) => read.session.costUsd);
|
|
528
|
+
const files = written.some((usd) => usd === undefined) ? undefined : source === "claude-code" ? Math.max(...written) : written.reduce((n, usd) => n + usd, 0);
|
|
529
|
+
let cost = withSubagentCosts(source, files, subagents.map(({ read }) => read.session.costUsd));
|
|
530
|
+
if (cost === undefined && priced.length) {
|
|
531
|
+
// Each request's cost as priced when read, summed in the order priceRequests sums them.
|
|
532
|
+
if (pricer.catalog && pricer.calculate && !priced.some(({ unpriceable }) => unpriceable)) {
|
|
533
|
+
let total = 0;
|
|
534
|
+
for (const { costs, n } of priced)
|
|
535
|
+
for (let i = 0; i < n; i += 1)
|
|
536
|
+
total += costs[i];
|
|
537
|
+
cost = roundUsd(total);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
else if (cost === undefined) {
|
|
303
541
|
const catalog = await priceWith();
|
|
304
542
|
cost = catalog ? await priceRequests(requests, catalog, calculateCost) : undefined;
|
|
305
543
|
}
|
|
@@ -320,8 +558,18 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
|
|
|
320
558
|
};
|
|
321
559
|
out.push(totals);
|
|
322
560
|
if (sink) {
|
|
323
|
-
|
|
324
|
-
|
|
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.
|
|
563
|
+
let started;
|
|
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);
|
|
568
|
+
if (Number.isFinite(at) && (started === undefined || at < started))
|
|
569
|
+
started = at;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
sink(totals, requests, started);
|
|
325
573
|
}
|
|
326
574
|
}
|
|
327
575
|
return out;
|