@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/pool.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// A pool of worker threads that read a home's locators ahead of parseHome, each through a `seen` of its own
|
|
2
|
+
// (pool-worker.ts). parseHome still takes each read in the import's order and keeps it only when it is the read it would
|
|
3
|
+
// have made itself; any other it makes again, so the totals are the same whatever the pool does.
|
|
4
|
+
//
|
|
5
|
+
// A read made ahead of the import's order waits, whole, until parseHome takes it, so what the pool reads ahead is what it
|
|
6
|
+
// holds. The read parseHome waits for is always made next. Past it, while the reads waiting stay under the read-ahead
|
|
7
|
+
// (readAheadBytes()), the pool reads large files first (BIG_FILE and over, the largest first: they set the time), then
|
|
8
|
+
// the rest in the import's order; at the read-ahead it reads only the one parseHome waits for. A worker's heap is bounded (OLD_MB): one that
|
|
9
|
+
// runs out gives up its file, which parseHome reads itself, and another worker takes its place.
|
|
10
|
+
import { availableParallelism, freemem, totalmem } from "node:os";
|
|
11
|
+
import { Worker } from "node:worker_threads";
|
|
12
|
+
import { indexArrays } from "./record-index.js";
|
|
13
|
+
/** Each worker's young generation: the default lets eight workers' garbage add up to more than the reads themselves. The
|
|
14
|
+
* workers take none of this process's flags (a caller's `--input-type=module -e` would stop them loading). */
|
|
15
|
+
const YOUNG_MB = 16;
|
|
16
|
+
/** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
|
|
17
|
+
* for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
|
|
18
|
+
export const OLD_MB = 64;
|
|
19
|
+
/** The smallest old generation a worker may be given (parseHome's workerOldMb). On node 24.22.3, one pool worker started
|
|
20
|
+
* at N MB to read a synthetic home of four files (one of 1.2 MB), each N in a process of its own: at 1 and 2 MB V8 ends
|
|
21
|
+
* the whole process as the worker starts ("Fatal JavaScript out of memory: GC during deserialization"); from 3 to 6 MB
|
|
22
|
+
* no worker read a file (5 processes each, 29 at 6); at 7, 28 of 29 processes lost a worker; at 8 to 10 (29 processes
|
|
23
|
+
* each) and at 11 and 12 (5 each), every worker read every file. A worker under it can only end the process or lose
|
|
24
|
+
* every read, so it is refused. */
|
|
25
|
+
export const MIN_OLD_MB = 8;
|
|
26
|
+
/** The share of a worker's old generation one line may take: a line past it is read by parseHome. A capped worker
|
|
27
|
+
* whose one native call (a line's decoding, JSON.parse) outgrows its heap does not end alone: V8 ends the process. At a
|
|
28
|
+
* 64 MB heap, a 90 MB line of text, or a 15.9 MB line of empty objects (`[{},{},...]`, parsed to some 13 times its
|
|
29
|
+
* size), ends it; 14 MB of empty objects ends the worker alone. An eighth, 8 MB, leaves that margin. */
|
|
30
|
+
const LINE_SHARE = 8;
|
|
31
|
+
/** A file this large or larger is read ahead of the import's order, the largest first: such files set the time. */
|
|
32
|
+
export const BIG_FILE = 64 * 2 ** 20;
|
|
33
|
+
/** The most bytes of finished reads that may wait to be taken by default; at the read-ahead, the pool reads only the one
|
|
34
|
+
* parseHome waits for. A cap on finished reads waiting, plus at most one read in flight per thread; not on the process's
|
|
35
|
+
* memory. */
|
|
36
|
+
export const READ_AHEAD_BYTES = 2 ** 30;
|
|
37
|
+
/** The memory this process may use: its container's limit (process.constrainedMemory) when one is set below the
|
|
38
|
+
* machine's, else the machine's. A 2 GiB container on a 512 GiB host has 2 GiB. */
|
|
39
|
+
export const memoryLimit = (total = totalmem(), constrained = process.constrainedMemory()) => (constrained > 0 && constrained < total ? constrained : total);
|
|
40
|
+
/** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
|
|
41
|
+
* at 8 GiB, 128 MiB in a 2 GiB container). */
|
|
42
|
+
export const readAheadBytes = (memory = memoryLimit()) => Math.min(READ_AHEAD_BYTES, Math.floor(memory / 16));
|
|
43
|
+
/** The default threads' ceiling. On a 48-core machine, a 23 GB home (pooled, median of 2) took 27.5 s at 8 threads
|
|
44
|
+
* (peak 1.13 GiB), 20.3 s at 16 (1.77 GiB), 17.2 s at 24 (2.39 GiB) and 23.3 s at 32 (2.87 GiB): 16 takes most of 24's
|
|
45
|
+
* gain for three quarters of its memory, and past 24 the threads slow each other down. */
|
|
46
|
+
export const DEFAULT_THREADS_CEILING = 16;
|
|
47
|
+
/** The most a worker's heap holds: its young generation (YOUNG_MB) and its old one (`oldMb`), both capped at its start.
|
|
48
|
+
* The pool's peak grew by about this, 80 MiB a worker at the default, from 8 threads to 24 (the runs DEFAULT_THREADS_CEILING cites). */
|
|
49
|
+
export const workerBytes = (oldMb = OLD_MB) => (YOUNG_MB + oldMb) * 2 ** 20;
|
|
50
|
+
/** The memory still free to this process: the machine's (os.freemem, MemAvailable on Linux: page cache it may reclaim
|
|
51
|
+
* counts as free), at most its container's limit (memoryLimit). Not process.availableMemory: under a cgroup it takes the
|
|
52
|
+
* limit less memory.current, which counts the page cache as used. On a 503 GiB machine with 345 GiB free, in a cgroup
|
|
53
|
+
* of 350 GiB whose 346 GiB in use were 250 GiB of page cache, it read 130 MiB to 3.6 GiB from one second to the next. */
|
|
54
|
+
export const freeMemory = (free = freemem(), limit = memoryLimit()) => Math.min(free, limit);
|
|
55
|
+
/** parseHome's default threads: the fewest of
|
|
56
|
+
* - the cores this process may run on, one left for the thread that takes the reads and totals them (two cores keep
|
|
57
|
+
* two threads: one worker would read no faster than the calling thread alone);
|
|
58
|
+
* - DEFAULT_THREADS_CEILING;
|
|
59
|
+
* - the workers whose heaps (workerBytes) fit in the memory still free (freeMemory) once the read-ahead (`aheadBytes`)
|
|
60
|
+
* is set aside, since the reads waiting are held on the calling thread;
|
|
61
|
+
* and at least 1 (every file read on the calling thread). A caller's `threads` is taken as given, up to MOST_THREADS. */
|
|
62
|
+
export const defaultThreads = (cores = availableParallelism(), available = freeMemory(), aheadBytes = readAheadBytes(), oldMb = OLD_MB) => {
|
|
63
|
+
const byCores = cores <= 2 ? cores : cores - 1;
|
|
64
|
+
const byMemory = Math.floor(Math.max(0, available - aheadBytes) / workerBytes(oldMb));
|
|
65
|
+
return Math.max(1, Math.min(byCores, DEFAULT_THREADS_CEILING, byMemory));
|
|
66
|
+
};
|
|
67
|
+
/** Workers lost (out of memory, or ended) past this many times the threads: the pool stops, and parseHome reads the rest. */
|
|
68
|
+
const LOSSES_PER_THREAD = 2;
|
|
69
|
+
/** A session's objects beyond its typed arrays and its strings, as the budget counts them. */
|
|
70
|
+
const SESSION_BYTES = 1024;
|
|
71
|
+
/** A string past U+00FF: V8 holds it at two bytes a UTF-16 code unit, any other at one. */
|
|
72
|
+
const WIDE = /[^\u0000-\u00ff]/;
|
|
73
|
+
/** A read's strings as V8 holds them (a session's first prompt and title can run to megabytes), wherever they are in its
|
|
74
|
+
* objects and arrays (a session's turns, a read's requests and paths): each object once, on a stack of its own, so no
|
|
75
|
+
* depth runs the call stack out and a cycle ends. A typed array holds none: heldBytes counts its bytes apart. */
|
|
76
|
+
export function stringBytes(read) {
|
|
77
|
+
let bytes = 0;
|
|
78
|
+
const visited = new Set();
|
|
79
|
+
const stack = [read];
|
|
80
|
+
while (stack.length) {
|
|
81
|
+
const value = stack.pop();
|
|
82
|
+
if (typeof value === "string")
|
|
83
|
+
bytes += (WIDE.test(value) ? 2 : 1) * value.length;
|
|
84
|
+
else if (typeof value === "object" && value !== null && !ArrayBuffer.isView(value) && !visited.has(value)) {
|
|
85
|
+
visited.add(value);
|
|
86
|
+
for (const inner of Array.isArray(value) ? value : Object.values(value))
|
|
87
|
+
stack.push(inner);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return bytes;
|
|
91
|
+
}
|
|
92
|
+
const indexBytes = (index) => indexArrays(index).reduce((sum, a) => sum + a.byteLength, 0);
|
|
93
|
+
/** What a read holds while it waits: its indexes' and counts' arrays, and its sessions with their strings. */
|
|
94
|
+
function heldBytes(read) {
|
|
95
|
+
if (!read.ok)
|
|
96
|
+
return 0;
|
|
97
|
+
let bytes = indexBytes(read.mine) + indexBytes(read.missed);
|
|
98
|
+
for (const sessionRead of read.sessions) {
|
|
99
|
+
const { counts } = sessionRead;
|
|
100
|
+
bytes += SESSION_BYTES + stringBytes(sessionRead) + (counts ? counts.model.byteLength + counts.values.byteLength + counts.has.byteLength : 0);
|
|
101
|
+
}
|
|
102
|
+
return bytes;
|
|
103
|
+
}
|
|
104
|
+
export class ReadPool {
|
|
105
|
+
threads;
|
|
106
|
+
aheadBytes;
|
|
107
|
+
oldMb;
|
|
108
|
+
live = new Set();
|
|
109
|
+
idle = [];
|
|
110
|
+
running = new Map();
|
|
111
|
+
jobs = [];
|
|
112
|
+
/** Queued jobs, the largest first (the import's order among equals). */
|
|
113
|
+
bySize = [];
|
|
114
|
+
/** The job parseHome waits for (or last took): no job before it is read for it. */
|
|
115
|
+
cursor = 0;
|
|
116
|
+
/** The first job, in the import's order, that may still be queued. */
|
|
117
|
+
nextInOrder = 0;
|
|
118
|
+
/** The job parseHome waits for, and how it is handed over. */
|
|
119
|
+
wanted;
|
|
120
|
+
waiting = 0;
|
|
121
|
+
losses = 0;
|
|
122
|
+
broken = false;
|
|
123
|
+
/** The most bytes of reads waiting at once, read by the lane's measuring script alone. The read-ahead is checked before
|
|
124
|
+
* a read is sent, so the reads in flight then (at most `threads`) may land past it. */
|
|
125
|
+
peakWaiting = 0;
|
|
126
|
+
constructor(threads, aheadBytes = readAheadBytes(), oldMb = OLD_MB) {
|
|
127
|
+
this.threads = threads;
|
|
128
|
+
this.aheadBytes = aheadBytes;
|
|
129
|
+
this.oldMb = oldMb;
|
|
130
|
+
// A worker that cannot start (no file descriptors, no memory) stops the pool: parseHome reads every file itself.
|
|
131
|
+
try {
|
|
132
|
+
for (let i = 0; i < threads; i += 1)
|
|
133
|
+
this.spawn();
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
this.fail();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Queues each locator; a job's id is its place in the import's order, so `items` come in that order. The ids, for take. */
|
|
140
|
+
readAll(items) {
|
|
141
|
+
const ids = items.map(({ source, locator, size }) => {
|
|
142
|
+
const job = { id: this.jobs.length, source, locator, size, state: this.broken ? "taken" : "queued", bytes: 0 };
|
|
143
|
+
this.jobs.push(job);
|
|
144
|
+
return job.id;
|
|
145
|
+
});
|
|
146
|
+
this.bySize = this.jobs.filter((job) => job.state === "queued").sort((a, b) => b.size - a.size || a.id - b.id);
|
|
147
|
+
this.dispatch();
|
|
148
|
+
return ids;
|
|
149
|
+
}
|
|
150
|
+
/** The read of job `id`, made next when it is not made yet. Each id is taken once; a second take, or a pool that broke,
|
|
151
|
+
* gives a read that is not ok (parseHome makes it itself). */
|
|
152
|
+
take(id) {
|
|
153
|
+
const job = this.jobs[id];
|
|
154
|
+
if (id > this.cursor)
|
|
155
|
+
this.cursor = id;
|
|
156
|
+
if (job.state === "waiting") {
|
|
157
|
+
const read = job.read;
|
|
158
|
+
job.state = "taken";
|
|
159
|
+
job.read = undefined;
|
|
160
|
+
this.waiting -= job.bytes;
|
|
161
|
+
this.dispatch();
|
|
162
|
+
return Promise.resolve(read);
|
|
163
|
+
}
|
|
164
|
+
if (job.state === "taken")
|
|
165
|
+
return Promise.resolve({ ok: false });
|
|
166
|
+
return new Promise((done) => {
|
|
167
|
+
this.wanted = { job, done };
|
|
168
|
+
this.dispatch();
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Gives up jobs parseHome will not take (a source it reads again whole): their reads waiting are let go, those queued
|
|
172
|
+
* are not read, those running are let go when they end. */
|
|
173
|
+
drop(ids) {
|
|
174
|
+
for (const id of ids) {
|
|
175
|
+
const job = this.jobs[id];
|
|
176
|
+
if (job.state === "waiting")
|
|
177
|
+
this.waiting -= job.bytes;
|
|
178
|
+
job.state = "taken";
|
|
179
|
+
job.read = undefined;
|
|
180
|
+
}
|
|
181
|
+
this.dispatch();
|
|
182
|
+
}
|
|
183
|
+
close() {
|
|
184
|
+
this.fail();
|
|
185
|
+
}
|
|
186
|
+
spawn() {
|
|
187
|
+
const worker = new Worker(new URL("./pool-worker.js", import.meta.url), { execArgv: [], workerData: { maxLine: Math.floor((this.oldMb * 2 ** 20) / LINE_SHARE) }, resourceLimits: { maxYoungGenerationSizeMb: YOUNG_MB, maxOldGenerationSizeMb: this.oldMb } });
|
|
188
|
+
worker.unref();
|
|
189
|
+
worker.on("message", (read) => this.finished(worker, read));
|
|
190
|
+
worker.on("error", () => this.gone(worker));
|
|
191
|
+
worker.on("exit", () => this.gone(worker));
|
|
192
|
+
this.live.add(worker);
|
|
193
|
+
this.idle.push(worker);
|
|
194
|
+
}
|
|
195
|
+
/** The next job to read: the one parseHome waits for; else, while the reads waiting are under the budget, the largest
|
|
196
|
+
* file left if it is large, or the first queued past the cursor. */
|
|
197
|
+
pick() {
|
|
198
|
+
if (this.wanted?.job.state === "queued")
|
|
199
|
+
return this.wanted.job;
|
|
200
|
+
if (this.waiting >= this.aheadBytes)
|
|
201
|
+
return undefined;
|
|
202
|
+
while (this.bySize.length && this.bySize[0].state !== "queued")
|
|
203
|
+
this.bySize.shift();
|
|
204
|
+
if (this.bySize.length && this.bySize[0].size >= BIG_FILE)
|
|
205
|
+
return this.bySize[0];
|
|
206
|
+
if (this.nextInOrder < this.cursor)
|
|
207
|
+
this.nextInOrder = this.cursor;
|
|
208
|
+
while (this.nextInOrder < this.jobs.length && this.jobs[this.nextInOrder].state !== "queued")
|
|
209
|
+
this.nextInOrder += 1;
|
|
210
|
+
return this.jobs[this.nextInOrder];
|
|
211
|
+
}
|
|
212
|
+
dispatch() {
|
|
213
|
+
while (!this.broken && this.idle.length) {
|
|
214
|
+
const job = this.pick();
|
|
215
|
+
if (!job)
|
|
216
|
+
return;
|
|
217
|
+
const worker = this.idle.pop();
|
|
218
|
+
job.state = "running";
|
|
219
|
+
this.running.set(worker, job);
|
|
220
|
+
// A worker with a read keeps the process alive: parseHome may wait on nothing else.
|
|
221
|
+
worker.ref();
|
|
222
|
+
worker.postMessage({ id: job.id, source: job.source, locator: job.locator });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** A job's read is made: handed to parseHome if it waits for it, else held until it takes it. */
|
|
226
|
+
made(job, read) {
|
|
227
|
+
if (this.wanted?.job === job) {
|
|
228
|
+
const { done } = this.wanted;
|
|
229
|
+
this.wanted = undefined;
|
|
230
|
+
job.state = "taken";
|
|
231
|
+
done(read);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (job.state === "taken")
|
|
235
|
+
return; // dropped while it ran
|
|
236
|
+
job.state = "waiting";
|
|
237
|
+
job.read = read;
|
|
238
|
+
job.bytes = heldBytes(read);
|
|
239
|
+
this.waiting += job.bytes;
|
|
240
|
+
if (this.waiting > this.peakWaiting)
|
|
241
|
+
this.peakWaiting = this.waiting;
|
|
242
|
+
}
|
|
243
|
+
finished(worker, read) {
|
|
244
|
+
const job = this.running.get(worker);
|
|
245
|
+
this.running.delete(worker);
|
|
246
|
+
this.idle.push(worker);
|
|
247
|
+
worker.unref();
|
|
248
|
+
if (job)
|
|
249
|
+
this.made(job, read);
|
|
250
|
+
this.dispatch();
|
|
251
|
+
}
|
|
252
|
+
/** A worker ended (out of memory, or crashed): its file is parseHome's to read, and another worker takes its place. */
|
|
253
|
+
gone(worker) {
|
|
254
|
+
if (!this.live.delete(worker) || this.broken)
|
|
255
|
+
return;
|
|
256
|
+
const at = this.idle.indexOf(worker);
|
|
257
|
+
if (at !== -1)
|
|
258
|
+
this.idle.splice(at, 1);
|
|
259
|
+
const job = this.running.get(worker);
|
|
260
|
+
this.running.delete(worker);
|
|
261
|
+
if (job)
|
|
262
|
+
this.made(job, { ok: false });
|
|
263
|
+
if ((this.losses += 1) > LOSSES_PER_THREAD * this.threads)
|
|
264
|
+
return this.fail();
|
|
265
|
+
try {
|
|
266
|
+
this.spawn();
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
return this.fail();
|
|
270
|
+
}
|
|
271
|
+
this.dispatch();
|
|
272
|
+
}
|
|
273
|
+
/** The pool stops: no read is taken from it any more; parseHome makes each one itself. */
|
|
274
|
+
fail() {
|
|
275
|
+
this.broken = true;
|
|
276
|
+
for (const worker of this.live)
|
|
277
|
+
void worker.terminate();
|
|
278
|
+
for (const job of this.jobs) {
|
|
279
|
+
job.state = "taken";
|
|
280
|
+
job.read = undefined;
|
|
281
|
+
}
|
|
282
|
+
this.running.clear();
|
|
283
|
+
this.waiting = 0;
|
|
284
|
+
const wanted = this.wanted;
|
|
285
|
+
this.wanted = undefined;
|
|
286
|
+
wanted?.done({ ok: false });
|
|
287
|
+
}
|
|
288
|
+
}
|
package/dist/price.d.ts
CHANGED
|
@@ -19,9 +19,9 @@ export declare function catalogOf(models: readonly {
|
|
|
19
19
|
provider: string;
|
|
20
20
|
cost?: Partial<ModelCost>;
|
|
21
21
|
}[]): Catalog;
|
|
22
|
-
/** pi-ai's built-in catalog, by model id
|
|
23
|
-
*
|
|
24
|
-
export declare function builtinCatalog(): Promise<Catalog
|
|
22
|
+
/** pi-ai's built-in catalog, by model id. serve prices with its own catalog (pi-ai's, with serve's overrides and added
|
|
23
|
+
* models), which it passes in; the CLI imports pi-ai itself. */
|
|
24
|
+
export declare function builtinCatalog(): Promise<Catalog>;
|
|
25
25
|
/** pi-ai's calculateCost: what one request's usage costs at a model's price. */
|
|
26
26
|
export type CalculateCost = (model: {
|
|
27
27
|
cost: ModelCost;
|
|
@@ -42,8 +42,16 @@ export type Priced = {
|
|
|
42
42
|
model?: string;
|
|
43
43
|
usage?: Usage;
|
|
44
44
|
};
|
|
45
|
+
/** pi-ai's calculateCost, loaded. */
|
|
46
|
+
export declare const loadCalculateCost: () => Promise<CalculateCost>;
|
|
47
|
+
/** What one request costs at `catalog`'s list prices, unrounded: undefined when its tokens are unknown or its provider
|
|
48
|
+
* does not list its model; 0 for a request of no tokens, at any price. */
|
|
49
|
+
export declare function priceRequest({ model, usage }: Priced, catalog: Catalog, calculate: CalculateCost): number | undefined;
|
|
50
|
+
/** A sum of requests' costs rounded to a millionth of a dollar. */
|
|
51
|
+
export declare const roundUsd: (usd: number) => number;
|
|
45
52
|
/** What `requests` cost at `catalog`'s list prices, each at its own provider's entry for its model, rounded to a
|
|
46
53
|
* millionth of a dollar: undefined when one request's tokens are unknown or its provider does not list its model (the
|
|
47
|
-
* request was served at a price no one lists here)
|
|
48
|
-
*
|
|
54
|
+
* request was served at a price no one lists here). A provider's $0 entry is $0. A request of no tokens costs nothing
|
|
55
|
+
* at any price. The sum is taken in the requests' order, adding a request of no tokens as 0
|
|
56
|
+
* (which leaves any sum as it is). */
|
|
49
57
|
export declare function priceRequests(requests: readonly Priced[], catalog: Catalog, calculateCost?: CalculateCost): Promise<number | undefined>;
|
package/dist/price.js
CHANGED
|
@@ -8,33 +8,43 @@ export function catalogOf(models) {
|
|
|
8
8
|
}
|
|
9
9
|
return out;
|
|
10
10
|
}
|
|
11
|
-
/** pi-ai's built-in catalog, by model id
|
|
12
|
-
*
|
|
11
|
+
/** pi-ai's built-in catalog, by model id. serve prices with its own catalog (pi-ai's, with serve's overrides and added
|
|
12
|
+
* models), which it passes in; the CLI imports pi-ai itself. */
|
|
13
13
|
export async function builtinCatalog() {
|
|
14
|
-
|
|
15
|
-
return loaded ? catalogOf(loaded.builtinModels().getModels()) : undefined;
|
|
14
|
+
return catalogOf((await import("@earendil-works/pi-ai/providers/all")).builtinModels().getModels());
|
|
16
15
|
}
|
|
16
|
+
/** pi-ai's calculateCost, loaded. */
|
|
17
|
+
export const loadCalculateCost = async () => (await import("@earendil-works/pi-ai")).calculateCost;
|
|
18
|
+
/** What one request costs at `catalog`'s list prices, unrounded: undefined when its tokens are unknown or its provider
|
|
19
|
+
* does not list its model; 0 for a request of no tokens, at any price. */
|
|
20
|
+
export function priceRequest({ model, usage }, catalog, calculate) {
|
|
21
|
+
if (!usage)
|
|
22
|
+
return undefined;
|
|
23
|
+
const { input, output, cacheRead, cacheWrite, cacheWrite1h } = usage;
|
|
24
|
+
if (input + output + cacheRead + cacheWrite === 0)
|
|
25
|
+
return 0;
|
|
26
|
+
const at = model?.indexOf("/") ?? -1;
|
|
27
|
+
const cost = model && at > 0 ? catalog.get(model.slice(at + 1))?.find((entry) => entry.provider === model.slice(0, at))?.cost : undefined;
|
|
28
|
+
if (!cost)
|
|
29
|
+
return undefined;
|
|
30
|
+
const counted = { input, output, cacheRead, cacheWrite, ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}), totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
31
|
+
return calculate({ cost }, counted).total;
|
|
32
|
+
}
|
|
33
|
+
/** A sum of requests' costs rounded to a millionth of a dollar. */
|
|
34
|
+
export const roundUsd = (usd) => Math.round(usd * 1e6) / 1e6;
|
|
17
35
|
/** What `requests` cost at `catalog`'s list prices, each at its own provider's entry for its model, rounded to a
|
|
18
36
|
* millionth of a dollar: undefined when one request's tokens are unknown or its provider does not list its model (the
|
|
19
|
-
* request was served at a price no one lists here)
|
|
20
|
-
*
|
|
37
|
+
* request was served at a price no one lists here). A provider's $0 entry is $0. A request of no tokens costs nothing
|
|
38
|
+
* at any price. The sum is taken in the requests' order, adding a request of no tokens as 0
|
|
39
|
+
* (which leaves any sum as it is). */
|
|
21
40
|
export async function priceRequests(requests, catalog, calculateCost) {
|
|
22
|
-
const calculate = calculateCost ?? (await
|
|
23
|
-
if (!calculate)
|
|
24
|
-
return undefined;
|
|
41
|
+
const calculate = calculateCost ?? (await loadCalculateCost());
|
|
25
42
|
let total = 0;
|
|
26
|
-
for (const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const { input, output, cacheRead, cacheWrite, cacheWrite1h } = usage;
|
|
30
|
-
if (input + output + cacheRead + cacheWrite === 0)
|
|
31
|
-
continue;
|
|
32
|
-
const at = model?.indexOf("/") ?? -1;
|
|
33
|
-
const cost = model && at > 0 ? catalog.get(model.slice(at + 1))?.find((entry) => entry.provider === model.slice(0, at))?.cost : undefined;
|
|
34
|
-
if (!cost)
|
|
43
|
+
for (const request of requests) {
|
|
44
|
+
const usd = priceRequest(request, catalog, calculate);
|
|
45
|
+
if (usd === undefined)
|
|
35
46
|
return undefined;
|
|
36
|
-
|
|
37
|
-
total += calculate({ cost }, counted).total;
|
|
47
|
+
total += usd;
|
|
38
48
|
}
|
|
39
|
-
return
|
|
49
|
+
return roundUsd(total);
|
|
40
50
|
}
|
package/dist/read.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Stats } from "node:fs";
|
|
2
|
-
import type { Env, Locator, Reader, ReadOptions } from "./reader.js";
|
|
2
|
+
import type { Env, Locator, LocatorSize, Reader, ReadOptions } from "./reader.js";
|
|
3
3
|
import { type Source } from "./readers/index.js";
|
|
4
4
|
import type { SessionOf } from "./types.js";
|
|
5
5
|
export type Session = SessionOf<Source>;
|
|
@@ -12,12 +12,22 @@ export declare function sessionLocators(home: string, source: string, { env, rea
|
|
|
12
12
|
env?: Env;
|
|
13
13
|
readers?: Readers;
|
|
14
14
|
}): Promise<Locator[]>;
|
|
15
|
-
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
/** What the session at `locator` takes and when it was last written: the reader's stat, else its file's size and mtime.
|
|
16
|
+
* null when it is gone (the reader says so, or its file is). Any other error (a database locked or damaged, no access)
|
|
17
|
+
* is thrown: a session whose size cannot be had is not one that is gone. */
|
|
18
|
+
export declare function locatorSize(locator: Locator, source: string, readers?: Readers): Promise<LocatorSize | null>;
|
|
19
|
+
/** The session the one at `locator` ran under, as its reader tells it without reading the session (locatorSize's
|
|
20
|
+
* `parent`, else the reader's bounded head read, parentOf): what ties a subagent too large to read to its run. */
|
|
21
|
+
export declare function locatorParent(locator: Locator, source: string, readers?: Readers): Promise<string | undefined>;
|
|
22
|
+
/** The locators of `source`, each with its file's stats and its own size (locatorSize; one gone since it was listed is
|
|
23
|
+
* passed over), in the import's order: the reader's (Claude Code's by project folder, oldest written first: the first
|
|
24
|
+
* file holding a copied record keeps it), else as they were listed. One whose size cannot be had is kept, `failed` with
|
|
25
|
+
* why and its file's size: the caller reads it (its read fails as it did) or says it is left out, never drops it unsaid. */
|
|
18
26
|
export declare function inOrder(locators: readonly Locator[], source: string, readers?: Readers): Promise<{
|
|
19
27
|
locator: Locator;
|
|
20
28
|
stats: Stats;
|
|
29
|
+
size: LocatorSize;
|
|
30
|
+
failed?: unknown;
|
|
21
31
|
}[]>;
|
|
22
32
|
/** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
|
|
23
33
|
* (Claude Code's <session id>/subagents/). */
|
package/dist/read.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { lstat, stat } from "node:fs/promises";
|
|
2
|
+
import { DROPS_CURSOR } from "./internal.js";
|
|
2
3
|
import { READERS } from "./readers/index.js";
|
|
3
4
|
/** The reader of `source` among `readers`; one that is not there throws. */
|
|
4
5
|
export function readerOf(source, readers = READERS) {
|
|
@@ -17,19 +18,50 @@ export async function sessionLocators(home, source, { env, readers } = {}) {
|
|
|
17
18
|
out.push(locator);
|
|
18
19
|
return out;
|
|
19
20
|
}
|
|
20
|
-
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
21
|
+
/** What the session at `locator` takes and when it was last written: the reader's stat, else its file's size and mtime.
|
|
22
|
+
* null when it is gone (the reader says so, or its file is). Any other error (a database locked or damaged, no access)
|
|
23
|
+
* is thrown: a session whose size cannot be had is not one that is gone. */
|
|
24
|
+
export async function locatorSize(locator, source, readers) {
|
|
25
|
+
const own = readerOf(source, readers).stat;
|
|
26
|
+
if (own)
|
|
27
|
+
return own(locator);
|
|
28
|
+
const stats = await stat(locator.file).catch((error) => {
|
|
29
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
30
|
+
return null;
|
|
31
|
+
throw error;
|
|
32
|
+
});
|
|
33
|
+
return stats && { bytes: stats.size, mtimeMs: stats.mtimeMs };
|
|
34
|
+
}
|
|
35
|
+
/** The session the one at `locator` ran under, as its reader tells it without reading the session (locatorSize's
|
|
36
|
+
* `parent`, else the reader's bounded head read, parentOf): what ties a subagent too large to read to its run. */
|
|
37
|
+
export async function locatorParent(locator, source, readers) {
|
|
38
|
+
const reader = readerOf(source, readers);
|
|
39
|
+
const size = reader.stat ? await locatorSize(locator, source, readers).catch(() => null) : null;
|
|
40
|
+
return size?.parent ?? (await reader.parentOf?.(locator).catch(() => undefined));
|
|
41
|
+
}
|
|
42
|
+
/** The locators of `source`, each with its file's stats and its own size (locatorSize; one gone since it was listed is
|
|
43
|
+
* passed over), in the import's order: the reader's (Claude Code's by project folder, oldest written first: the first
|
|
44
|
+
* file holding a copied record keeps it), else as they were listed. One whose size cannot be had is kept, `failed` with
|
|
45
|
+
* why and its file's size: the caller reads it (its read fails as it did) or says it is left out, never drops it unsaid. */
|
|
23
46
|
export async function inOrder(locators, source, readers) {
|
|
24
47
|
const out = [];
|
|
25
48
|
for (const locator of locators) {
|
|
26
49
|
const stats = await stat(locator.file).catch(() => null);
|
|
27
|
-
if (stats)
|
|
28
|
-
|
|
50
|
+
if (!stats)
|
|
51
|
+
continue;
|
|
52
|
+
const file = { bytes: stats.size, mtimeMs: stats.mtimeMs };
|
|
53
|
+
if (!readerOf(source, readers).stat) {
|
|
54
|
+
out.push({ locator, stats, size: file });
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const size = await locatorSize(locator, source, readers).then((size) => size && { size }, (failed) => ({ size: file, failed }));
|
|
58
|
+
if (size)
|
|
59
|
+
out.push({ locator, stats, ...size });
|
|
29
60
|
}
|
|
30
61
|
const order = readerOf(source, readers).order;
|
|
62
|
+
const key = ({ locator, stats, size }) => ({ file: locator.file, mtimeMs: stats.mtimeMs, ...(locator.id !== undefined ? { id: locator.id } : {}), ...(size.created !== undefined ? { created: size.created } : {}) });
|
|
31
63
|
if (order)
|
|
32
|
-
out.sort((a, b) => order(
|
|
64
|
+
out.sort((a, b) => order(key(a), key(b)));
|
|
33
65
|
return out;
|
|
34
66
|
}
|
|
35
67
|
/** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
|
|
@@ -41,7 +73,9 @@ export async function childrenOf(home, source, { env, readers } = {}) {
|
|
|
41
73
|
* listing shows. A locator whose session is not there throws. */
|
|
42
74
|
export async function readSession(locator, source, { readers, ...options } = {}) {
|
|
43
75
|
const at = typeof locator === "string" ? { file: locator } : locator;
|
|
44
|
-
|
|
76
|
+
// The cursor is dropped: the read makes no copy for it.
|
|
77
|
+
const read = { ...options, keepsCursor: false, [DROPS_CURSOR]: true };
|
|
78
|
+
const { sessions } = await readerOf(source, readers).read(at, undefined, read);
|
|
45
79
|
const found = at.id === undefined ? sessions[0] : sessions.find(({ locator }) => locator.id === at.id);
|
|
46
80
|
if (!found)
|
|
47
81
|
throw new Error(`no session ${at.id ?? ""} in ${at.file}`);
|
package/dist/reader.d.ts
CHANGED
|
@@ -10,6 +10,25 @@ export type Locator = {
|
|
|
10
10
|
};
|
|
11
11
|
/** A locator as one string: the file, with `#id` after it when it names one. */
|
|
12
12
|
export declare const locatorKey: ({ file, id }: Locator) => string;
|
|
13
|
+
/** What a locator's session takes: its bytes, and when it was last written (ms). A file's size and mtime for a file of
|
|
14
|
+
* one session; for one session of many in a file (a database), that session's own. */
|
|
15
|
+
export type LocatorSize = {
|
|
16
|
+
bytes: number;
|
|
17
|
+
mtimeMs: number;
|
|
18
|
+
/** The session it ran under, when the reader knows it without reading the session (a database row's parent): a caller
|
|
19
|
+
* that leaves a subagent out (still written, too large) leaves the session it ran under out with it. */
|
|
20
|
+
parent?: string;
|
|
21
|
+
/** When the session began (ms), when the reader knows it without reading the session (a database row's): what its
|
|
22
|
+
* order of reading may go by. */
|
|
23
|
+
created?: number;
|
|
24
|
+
};
|
|
25
|
+
/** What a reader's order of locators goes by. */
|
|
26
|
+
export type OrderKey = {
|
|
27
|
+
file: string;
|
|
28
|
+
mtimeMs: number;
|
|
29
|
+
id?: string;
|
|
30
|
+
created?: number;
|
|
31
|
+
};
|
|
13
32
|
/** One session a read found: where it is, what it is, and every request read (each counted once), whether turns are kept
|
|
14
33
|
* or not: what a total counts. A totals read (ReadOptions.totals) has them as `counts` alone, `requests` empty. */
|
|
15
34
|
export type SessionRead<S extends string = string> = {
|
|
@@ -43,6 +62,13 @@ export type ReadOptions = {
|
|
|
43
62
|
* `seen` like any other, as no later read takes it again. Default true: it is left out of `seen` until a read from
|
|
44
63
|
* the cursor takes it whole. */
|
|
45
64
|
keepsCursor?: boolean;
|
|
65
|
+
/** The longest line, in bytes, the read takes: a longer one ends it with a LineTooLong error, before the line is
|
|
66
|
+
* decoded. The read pool's workers set it to an eighth of their heap (pool.ts), so that no one line can end the
|
|
67
|
+
* process; parseHome then reads the file on its own thread, with no such bound. Default: none. */
|
|
68
|
+
maxLine?: number;
|
|
69
|
+
/** What a reader looks up once for a whole import, shared across its files: one map per import, each reader keying
|
|
70
|
+
* its own entries. Without one, each read looks up afresh. */
|
|
71
|
+
lookups?: Map<string, unknown>;
|
|
46
72
|
};
|
|
47
73
|
export type Reader<S extends string = string, C = unknown> = {
|
|
48
74
|
source: S;
|
|
@@ -52,17 +78,21 @@ export type Reader<S extends string = string, C = unknown> = {
|
|
|
52
78
|
harness: string;
|
|
53
79
|
/** The candidate locators of the source under `home`, any order (`env`: where the source's own directory is named). */
|
|
54
80
|
discover: (home: string, env?: Env) => Promise<Locator[]>;
|
|
81
|
+
/** The id the read gives the locator's session when no record of it names one (Claude Code's always: its file's
|
|
82
|
+
* name). A caller that names a session without reading it (a listing's probe) takes the same id. */
|
|
83
|
+
idOf: (locator: Locator) => string;
|
|
55
84
|
/** One locator read, from its start or from `cursor` (one this reader returned for the same locator). A cursor that no
|
|
56
85
|
* longer fits (the file replaced, truncated, rewritten) is read from the start, `resumed` false. */
|
|
57
86
|
read: (locator: Locator, cursor?: C, options?: ReadOptions) => Promise<ReadResult<S, C>>;
|
|
58
|
-
/** The import's order of the listed locators, when not their path's (a record copied into two files is the first's)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
87
|
+
/** The import's order of the listed locators, when not their path's (a record copied into two files is the first's):
|
|
88
|
+
* each with its file's mtime, its id in the file, and when its session began where the reader's stat says. */
|
|
89
|
+
order?: (a: OrderKey, b: OrderKey) => number;
|
|
90
|
+
/** The locator's own size and last write, when it is not its file's (a session in a database of many): what a caller's
|
|
91
|
+
* size caps and liveness go by. null: the session is not there. Without it, the file's (locatorSize). */
|
|
92
|
+
stat?: (locator: Locator) => Promise<LocatorSize | null>;
|
|
93
|
+
/** The session the locator's ran under, from a bounded head of its file, never the rest (Codex's first line): what ties
|
|
94
|
+
* a subagent a caller will not read (over its cap) to its run. None: no parent named there. */
|
|
95
|
+
parentOf?: (locator: Locator) => Promise<string | undefined>;
|
|
66
96
|
/** Subagents' sessions that name no parent themselves, each with the session it ran under (`of`). */
|
|
67
97
|
children?: (home: string, env?: Env) => Promise<{
|
|
68
98
|
locator: Locator;
|
|
@@ -1,4 +1,25 @@
|
|
|
1
|
+
import { type LineSource } from "../lines.js";
|
|
1
2
|
import { type Env } from "../reader.js";
|
|
3
|
+
import { type RecordIndex } from "../record-index.js";
|
|
4
|
+
import type { Answer } from "../types.js";
|
|
5
|
+
type Own = {
|
|
6
|
+
/** This file's requests by key (keyOf), each a turn its later lines join. */
|
|
7
|
+
keyed: Map<string, Answer>;
|
|
8
|
+
/** A totals read's instead: each request's index in its counts, by its key packed (packInto). */
|
|
9
|
+
indexes?: RecordIndex;
|
|
10
|
+
/** The calls of requests that were copies, whose results are copies too. */
|
|
11
|
+
copied: Set<string>;
|
|
12
|
+
/** Its titles (titleRecord), and its records' uuids, for the summaries' leaves. */
|
|
13
|
+
titles: {
|
|
14
|
+
custom?: string;
|
|
15
|
+
ai?: string;
|
|
16
|
+
summaries: {
|
|
17
|
+
title: string;
|
|
18
|
+
leaf?: string;
|
|
19
|
+
}[];
|
|
20
|
+
uuids: Set<string>;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
2
23
|
/** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
|
|
3
24
|
* with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
|
|
4
25
|
* folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
|
|
@@ -8,3 +29,6 @@ export declare function childFiles(home: string, env?: Env): Promise<{
|
|
|
8
29
|
of: string;
|
|
9
30
|
}[]>;
|
|
10
31
|
export declare const claudeCode: import("../reader.js").Reader<"claude-code", import("../lines.js").FileCursor>;
|
|
32
|
+
/** The source as lineReader takes it (a test reads with it, its fields or not). */
|
|
33
|
+
export declare const claudeCodeLines: LineSource<"claude-code", Own>;
|
|
34
|
+
export {};
|