@parcha/agentrun-import 0.1.0-beta.58 → 0.1.0-beta.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -18
- package/dist/cli.js +23 -8
- package/dist/home.d.ts +22 -1
- package/dist/home.js +324 -131
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -2
- package/dist/lines.d.ts +12 -1
- package/dist/lines.js +66 -8
- 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 +62 -0
- package/dist/pool.d.ts +80 -0
- package/dist/pool.js +243 -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 +37 -6
- package/dist/reader.d.ts +38 -8
- package/dist/readers/claude-code.js +2 -2
- package/dist/readers/codex.d.ts +7 -1
- package/dist/readers/codex.js +429 -9
- 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/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 +4 -0
- package/dist/record-index.js +35 -0
- package/dist/text.d.ts +2 -0
- package/dist/text.js +2 -0
- 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/lines.js
CHANGED
|
@@ -2,12 +2,28 @@
|
|
|
2
2
|
// into a Session, a line that is not JSON, or not a record its source knows, passed over. A read goes on from a cursor:
|
|
3
3
|
// the file's identity (device, inode), the byte after the last whole line read, and the read's state, so a later read
|
|
4
4
|
// takes only the bytes written since.
|
|
5
|
-
import { createReadStream } from "node:fs";
|
|
6
5
|
import { open } from "node:fs/promises";
|
|
7
6
|
import { addRequest, counts, trimmed } from "./counts.js";
|
|
8
7
|
import { rememberUser } from "./reader.js";
|
|
9
8
|
import { isObject, mostEffortOf, timeOf } from "./text.js";
|
|
10
9
|
import { ACTIVE_GAP_MS } from "./types.js";
|
|
10
|
+
/** The bytes a read takes from its file at once. */
|
|
11
|
+
const CHUNK = 1 << 20;
|
|
12
|
+
/** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
|
|
13
|
+
export class LineTooLong extends Error {
|
|
14
|
+
file;
|
|
15
|
+
offset;
|
|
16
|
+
bytes;
|
|
17
|
+
maxLine;
|
|
18
|
+
constructor(file, offset, bytes, maxLine) {
|
|
19
|
+
super(`${file}: a line at byte ${offset} is longer than ${maxLine} bytes (${bytes} so far)`);
|
|
20
|
+
this.file = file;
|
|
21
|
+
this.offset = offset;
|
|
22
|
+
this.bytes = bytes;
|
|
23
|
+
this.maxLine = maxLine;
|
|
24
|
+
this.name = "LineTooLong";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
11
27
|
/** What a listing reads from the session's text: a turns: false cursor keeps none of it, and a read resumed from one
|
|
12
28
|
* gives none (it would describe only what was written since). */
|
|
13
29
|
const withoutText = (session) => {
|
|
@@ -23,19 +39,42 @@ async function markOf(handle, offset) {
|
|
|
23
39
|
const { bytesRead } = await handle.read(bytes, 0, n, offset - n);
|
|
24
40
|
return bytes.subarray(0, bytesRead).toString("base64");
|
|
25
41
|
}
|
|
42
|
+
/** Whether a read from `cursor` of the open file goes on from it: the same source and kind of read, the same file (device
|
|
43
|
+
* and inode), no shorter, and the bytes before its offset as they were. Else it reads the file from its start. */
|
|
44
|
+
async function goesOn(source, keep, totals, cursor, handle, stats) {
|
|
45
|
+
return cursor.source === source && cursor.keep === keep && (cursor.totals ?? false) === totals && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
|
|
46
|
+
}
|
|
47
|
+
/** Whether a read with these options is a totals read: asked for, with no turns kept, from a source that has one. */
|
|
48
|
+
const totalsRead = (spec, keep, asked) => asked && !keep && spec.totals === true;
|
|
49
|
+
/** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it
|
|
50
|
+
* 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. */
|
|
51
|
+
export async function resumes(spec, file, cursor, { turns: keep = true, totals: asked = false } = {}) {
|
|
52
|
+
if (cursor === undefined)
|
|
53
|
+
return false;
|
|
54
|
+
const handle = await open(file, "r").catch(() => undefined);
|
|
55
|
+
if (!handle)
|
|
56
|
+
return false;
|
|
57
|
+
try {
|
|
58
|
+
return await goesOn(spec.source, keep, totalsRead(spec, keep, asked), cursor, handle, await handle.stat());
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
await handle.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
26
64
|
/** The records seen, as a source asks: `extra` over `base`, so a line read that is not kept leaves `base` as it was. */
|
|
27
65
|
const overlay = (base) => {
|
|
28
66
|
const extra = new Set();
|
|
29
67
|
return { has: (key) => extra.has(key) || base.has(key), add: (key) => extra.add(key) };
|
|
30
68
|
};
|
|
31
69
|
/** One session file of `spec`'s source, read from its start or from `cursor`. */
|
|
32
|
-
async function readLines(spec, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true } = {}) {
|
|
70
|
+
async function readLines(spec, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true, maxLine = Infinity } = {}) {
|
|
33
71
|
const { source } = spec;
|
|
34
|
-
const totals =
|
|
72
|
+
const totals = totalsRead(spec, keep, asked);
|
|
35
73
|
const handle = await open(file, "r");
|
|
36
74
|
try {
|
|
37
75
|
const stats = await handle.stat();
|
|
38
|
-
|
|
76
|
+
// The cursor's presence checked here, so `resumed` narrows it where its state and offset are read.
|
|
77
|
+
const resumed = cursor !== undefined && (await goesOn(source, keep, totals, cursor, handle, stats));
|
|
39
78
|
const state = (resumed
|
|
40
79
|
? structuredClone(cursor.state)
|
|
41
80
|
: { session: { source, id: "", file, state: "completed", child: false, turns: [], users: 0, activeMs: 0, copies: 0 }, turns: [], answers: [], names: new Map(), priced: { sum: 0, unknown: false }, activeMs: 0, own: spec.start(), ...(totals ? { counts: counts() } : {}), ...(seen ? {} : { seen: new Set() }) });
|
|
@@ -84,20 +123,38 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
|
|
|
84
123
|
let offset = start;
|
|
85
124
|
let read = 0;
|
|
86
125
|
let rest = [];
|
|
126
|
+
let restBytes = 0;
|
|
127
|
+
const tooLong = (bytes) => {
|
|
128
|
+
if (bytes > maxLine)
|
|
129
|
+
throw new LineTooLong(file, offset, bytes, maxLine);
|
|
130
|
+
};
|
|
87
131
|
if (stats.size > start) {
|
|
88
|
-
// The open handle
|
|
89
|
-
|
|
132
|
+
// The open handle, so the bytes read are the file stat described, whatever the path names now. One buffer for the
|
|
133
|
+
// whole read: a new one a chunk leaves freed native memory behind on every thread that reads (the read pool's).
|
|
134
|
+
const buffer = Buffer.allocUnsafeSlow(CHUNK);
|
|
135
|
+
for (let at = start;;) {
|
|
136
|
+
const { bytesRead } = await handle.read(buffer, 0, CHUNK, at);
|
|
137
|
+
if (!bytesRead)
|
|
138
|
+
break;
|
|
139
|
+
at += bytesRead;
|
|
140
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
90
141
|
read += chunk.length;
|
|
91
142
|
let from = 0;
|
|
92
143
|
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
|
|
144
|
+
tooLong(restBytes + nl - from);
|
|
93
145
|
const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
|
|
94
146
|
rest = [];
|
|
147
|
+
restBytes = 0;
|
|
95
148
|
line(whole.toString("utf8", 0, whole.length && whole[whole.length - 1] === 13 ? whole.length - 1 : whole.length));
|
|
96
149
|
offset += whole.length + 1;
|
|
97
150
|
from = nl + 1;
|
|
98
151
|
}
|
|
99
|
-
|
|
100
|
-
|
|
152
|
+
// The buffer is read into again: a line's start is kept as a copy.
|
|
153
|
+
if (from < chunk.length) {
|
|
154
|
+
restBytes += chunk.length - from;
|
|
155
|
+
tooLong(restBytes);
|
|
156
|
+
rest.push(Buffer.from(chunk.subarray(from)));
|
|
157
|
+
}
|
|
101
158
|
}
|
|
102
159
|
}
|
|
103
160
|
// A last line with no newline yet may be a record still being written: read into this result when it is whole JSON,
|
|
@@ -149,6 +206,7 @@ export function lineReader(spec) {
|
|
|
149
206
|
harness,
|
|
150
207
|
...(order ? { order } : {}),
|
|
151
208
|
discover: async (home, env) => (await spec.files(home, env)).map((file) => ({ file })),
|
|
209
|
+
idOf: ({ file }) => spec.idOf(file),
|
|
152
210
|
read: (locator, cursor, options) => readLines(spec, locator.file, cursor, options),
|
|
153
211
|
...(children ? { children: async (home, env) => (await children(home, env)).map(({ file, of }) => ({ locator: { file }, of: { file: of } })) } : {}),
|
|
154
212
|
};
|
package/dist/mirror.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Answer } from "./types.js";
|
|
2
|
+
/** A session as the rule names it: its source and its id. */
|
|
3
|
+
export declare const sessionKey: (source: string, id: string) => string;
|
|
4
|
+
/** The rule over the sessions counted (each a sessionKey): whether a request is one of theirs, so not its own session's.
|
|
5
|
+
* `kept` maps a session id as the request names it to the id the counted set holds it by, where the two differ (serve
|
|
6
|
+
* keeps an id that holds a key as a hash of it). */
|
|
7
|
+
export declare const mirroredIn: (counted: ReadonlySet<string>, kept?: ReadonlyMap<string, string>) => ({ mirrors }: Pick<Answer, "mirrors">) => boolean;
|
|
8
|
+
/** A session's own requests, those `mirrored` takes left out, and its cost of them: the cost it wrote when it holds none
|
|
9
|
+
* of another's, else its own requests' summed, unknown when one that used tokens is not priced. */
|
|
10
|
+
export declare function ownRequests<A extends Answer>(requests: readonly A[], cost: number | undefined, mirrored: (request: A) => boolean): {
|
|
11
|
+
requests: A[];
|
|
12
|
+
cost: number | undefined;
|
|
13
|
+
};
|
package/dist/mirror.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** A session as the rule names it: its source and its id. */
|
|
2
|
+
export const sessionKey = (source, id) => `${source}:${id}`;
|
|
3
|
+
/** The rule over the sessions counted (each a sessionKey): whether a request is one of theirs, so not its own session's.
|
|
4
|
+
* `kept` maps a session id as the request names it to the id the counted set holds it by, where the two differ (serve
|
|
5
|
+
* keeps an id that holds a key as a hash of it). */
|
|
6
|
+
export const mirroredIn = (counted, kept) => ({ mirrors }) => mirrors !== undefined && counted.has(sessionKey(mirrors.source, kept?.get(mirrors.sessionId) ?? mirrors.sessionId));
|
|
7
|
+
/** A session's own requests, those `mirrored` takes left out, and its cost of them: the cost it wrote when it holds none
|
|
8
|
+
* of another's, else its own requests' summed, unknown when one that used tokens is not priced. */
|
|
9
|
+
export function ownRequests(requests, cost, mirrored) {
|
|
10
|
+
const own = requests.filter((request) => !mirrored(request));
|
|
11
|
+
if (own.length === requests.length)
|
|
12
|
+
return { requests: own, cost };
|
|
13
|
+
const priced = own.every((request) => request.costUsd !== undefined || !request.usage);
|
|
14
|
+
return { requests: own, cost: priced ? own.reduce((n, request) => n + (request.costUsd ?? 0), 0) : undefined };
|
|
15
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// A read pool's worker (pool.ts): reads one locator with the registry's reader as parseHome's totals read does, through a
|
|
2
|
+
// `seen` of the locator's own records alone, and hands back its sessions, the records it added (mine) and the records it
|
|
3
|
+
// asked for, did not hold and never added (missed). parseHome takes the read as its own when no record of either is one
|
|
4
|
+
// an earlier locator holds: its `seen` would then have answered every question alike (a record asked for and then added
|
|
5
|
+
// is in mine), so the read is the one it would have made.
|
|
6
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
7
|
+
import { packed, packInto } from "./record-key.js";
|
|
8
|
+
import { addRecord, ownerOf, recordIndex } from "./record-index.js";
|
|
9
|
+
import { READERS } from "./readers/index.js";
|
|
10
|
+
/** The longest line this worker decodes (pool.ts sets it from the heap cap): a file with a longer one is handed back. */
|
|
11
|
+
const { maxLine } = workerData;
|
|
12
|
+
/** What readers look up once, shared by this worker's reads (ReadOptions.lookups): a pool lives for one parseHome, so
|
|
13
|
+
* this is one import's, and each worker looks up at most once what the import's own thread looks up once. */
|
|
14
|
+
const lookups = new Map();
|
|
15
|
+
const buffers = (index) => [index.uuids.slots, index.uuids.owners, index.uuids.words, index.others.slots, index.others.owners, index.others.ends, index.others.bytes].map((a) => a.buffer);
|
|
16
|
+
parentPort.on("message", async ({ id, source, locator }) => {
|
|
17
|
+
const reader = READERS[source];
|
|
18
|
+
const mine = recordIndex(64);
|
|
19
|
+
const missed = recordIndex(64);
|
|
20
|
+
let asked;
|
|
21
|
+
const at = packed();
|
|
22
|
+
// The last record asked for and not held, kept out of missed until the next question: a reader adds most records just
|
|
23
|
+
// after asking for them, and those are in mine.
|
|
24
|
+
let open = false;
|
|
25
|
+
const settle = () => {
|
|
26
|
+
if (open)
|
|
27
|
+
addRecord(missed, at, 0);
|
|
28
|
+
open = false;
|
|
29
|
+
};
|
|
30
|
+
const pack = (record) => {
|
|
31
|
+
if (record === asked)
|
|
32
|
+
return at;
|
|
33
|
+
settle();
|
|
34
|
+
asked = record;
|
|
35
|
+
return packInto(record, at);
|
|
36
|
+
};
|
|
37
|
+
const seen = {
|
|
38
|
+
has: (record) => {
|
|
39
|
+
pack(record);
|
|
40
|
+
if (ownerOf(mine, at) !== -1)
|
|
41
|
+
return true;
|
|
42
|
+
open = true;
|
|
43
|
+
return false;
|
|
44
|
+
},
|
|
45
|
+
add(record) {
|
|
46
|
+
pack(record);
|
|
47
|
+
open = false;
|
|
48
|
+
addRecord(mine, at, 0);
|
|
49
|
+
return this;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
const result = await reader.read(locator, undefined, { turns: false, totals: true, seen, maxLine, lookups });
|
|
54
|
+
settle();
|
|
55
|
+
const counts = result.sessions.flatMap(({ counts }) => (counts ? [counts.model.buffer, counts.values.buffer, counts.has.buffer] : []));
|
|
56
|
+
parentPort.postMessage({ id, ok: true, sessions: result.sessions, mine, missed }, [...new Set([...buffers(mine), ...buffers(missed), ...counts])]);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// The read is made again in order by parseHome, which records its failure as its own.
|
|
60
|
+
parentPort.postMessage({ id, ok: false });
|
|
61
|
+
}
|
|
62
|
+
});
|
package/dist/pool.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { Locator, SessionRead } from "./reader.js";
|
|
2
|
+
import type { RecordIndex } from "./record-index.js";
|
|
3
|
+
/** A read the pool made: its sessions, the records it added, those it asked for and did not hold. Not ok: make it again. */
|
|
4
|
+
export type PoolRead = {
|
|
5
|
+
ok: true;
|
|
6
|
+
sessions: SessionRead[];
|
|
7
|
+
mine: RecordIndex;
|
|
8
|
+
missed: RecordIndex;
|
|
9
|
+
} | {
|
|
10
|
+
ok: false;
|
|
11
|
+
};
|
|
12
|
+
/** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
|
|
13
|
+
* for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
|
|
14
|
+
export declare const OLD_MB = 64;
|
|
15
|
+
/** A file this large or larger is read ahead of the import's order, the largest first: such files set the time. */
|
|
16
|
+
export declare const BIG_FILE: number;
|
|
17
|
+
/** The most bytes of finished reads that may wait to be taken by default; at the read-ahead, the pool reads only the one
|
|
18
|
+
* parseHome waits for. A cap on finished reads waiting, plus at most one read in flight per thread; not on the process's
|
|
19
|
+
* memory. */
|
|
20
|
+
export declare const READ_AHEAD_BYTES: number;
|
|
21
|
+
/** The memory this process may use: its container's limit (process.constrainedMemory) when one is set below the
|
|
22
|
+
* machine's, else the machine's. A 2 GiB container on a 512 GiB host has 2 GiB. */
|
|
23
|
+
export declare const memoryLimit: (total?: number, constrained?: number) => number;
|
|
24
|
+
/** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
|
|
25
|
+
* at 8 GiB, 128 MiB in a 2 GiB container). */
|
|
26
|
+
export declare const readAheadBytes: (memory?: number) => number;
|
|
27
|
+
/** A session's strings (its first prompt and title can run to megabytes) as V8 holds them. */
|
|
28
|
+
export declare const stringBytes: (session: object) => number;
|
|
29
|
+
export declare class ReadPool {
|
|
30
|
+
private readonly threads;
|
|
31
|
+
private readonly aheadBytes;
|
|
32
|
+
private readonly oldMb;
|
|
33
|
+
private readonly live;
|
|
34
|
+
private readonly idle;
|
|
35
|
+
private readonly running;
|
|
36
|
+
private readonly jobs;
|
|
37
|
+
/** Queued jobs, the largest first (the import's order among equals). */
|
|
38
|
+
private bySize;
|
|
39
|
+
/** The job parseHome waits for (or last took): no job before it is read for it. */
|
|
40
|
+
private cursor;
|
|
41
|
+
/** The first job, in the import's order, that may still be queued. */
|
|
42
|
+
private nextInOrder;
|
|
43
|
+
/** The job parseHome waits for, and how it is handed over. */
|
|
44
|
+
private wanted;
|
|
45
|
+
private waiting;
|
|
46
|
+
private losses;
|
|
47
|
+
private broken;
|
|
48
|
+
/** The most bytes of reads waiting at once, and the workers lost (for measuring). The read-ahead is checked before a
|
|
49
|
+
* read is sent, so the reads in flight then (at most `threads`) may land past it. */
|
|
50
|
+
peakWaiting: number;
|
|
51
|
+
lost: number;
|
|
52
|
+
constructor(threads: number, aheadBytes?: number, oldMb?: number);
|
|
53
|
+
/** The bytes of reads waiting to be taken now. */
|
|
54
|
+
get held(): number;
|
|
55
|
+
/** 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. */
|
|
56
|
+
readAll(items: readonly {
|
|
57
|
+
source: string;
|
|
58
|
+
locator: Locator;
|
|
59
|
+
size: number;
|
|
60
|
+
}[]): number[];
|
|
61
|
+
/** 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,
|
|
62
|
+
* gives a read that is not ok (parseHome makes it itself). */
|
|
63
|
+
take(id: number): Promise<PoolRead>;
|
|
64
|
+
/** Gives up jobs parseHome will not take (a source it reads again whole): their reads waiting are let go, those queued
|
|
65
|
+
* are not read, those running are let go when they end. */
|
|
66
|
+
drop(ids: readonly number[]): void;
|
|
67
|
+
close(): void;
|
|
68
|
+
private spawn;
|
|
69
|
+
/** The next job to read: the one parseHome waits for; else, while the reads waiting are under the budget, the largest
|
|
70
|
+
* file left if it is large, or the first queued past the cursor. */
|
|
71
|
+
private pick;
|
|
72
|
+
private dispatch;
|
|
73
|
+
/** A job's read is made: handed to parseHome if it waits for it, else held until it takes it. */
|
|
74
|
+
private made;
|
|
75
|
+
private finished;
|
|
76
|
+
/** A worker ended (out of memory, or crashed): its file is parseHome's to read, and another worker takes its place. */
|
|
77
|
+
private gone;
|
|
78
|
+
/** The pool stops: no read is taken from it any more; parseHome makes each one itself. */
|
|
79
|
+
private fail;
|
|
80
|
+
}
|
package/dist/pool.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
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 { totalmem } from "node:os";
|
|
11
|
+
import { Worker } from "node:worker_threads";
|
|
12
|
+
/** Each worker's young generation: the default lets eight workers' garbage add up to more than the reads themselves. The
|
|
13
|
+
* workers take none of this process's flags (a caller's `--input-type=module -e` would stop them loading). */
|
|
14
|
+
const YOUNG_MB = 16;
|
|
15
|
+
/** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
|
|
16
|
+
* for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
|
|
17
|
+
export const OLD_MB = 64;
|
|
18
|
+
/** The share of a worker's old generation one line may take: a line past it is read by parseHome. A capped worker
|
|
19
|
+
* whose one native call (a line's decoding, JSON.parse) outgrows its heap does not end alone: V8 ends the process. At a
|
|
20
|
+
* 64 MB heap, a 90 MB line of text, or a 15.9 MB line of empty objects (`[{},{},...]`, parsed to some 13 times its
|
|
21
|
+
* size), ends it; 14 MB of empty objects ends the worker alone. An eighth, 8 MB, leaves that margin. */
|
|
22
|
+
const LINE_SHARE = 8;
|
|
23
|
+
/** A file this large or larger is read ahead of the import's order, the largest first: such files set the time. */
|
|
24
|
+
export const BIG_FILE = 64 * 2 ** 20;
|
|
25
|
+
/** The most bytes of finished reads that may wait to be taken by default; at the read-ahead, the pool reads only the one
|
|
26
|
+
* parseHome waits for. A cap on finished reads waiting, plus at most one read in flight per thread; not on the process's
|
|
27
|
+
* memory. */
|
|
28
|
+
export const READ_AHEAD_BYTES = 2 ** 30;
|
|
29
|
+
/** The memory this process may use: its container's limit (process.constrainedMemory) when one is set below the
|
|
30
|
+
* machine's, else the machine's. A 2 GiB container on a 512 GiB host has 2 GiB. */
|
|
31
|
+
export const memoryLimit = (total = totalmem(), constrained = process.constrainedMemory()) => (constrained > 0 && constrained < total ? constrained : total);
|
|
32
|
+
/** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
|
|
33
|
+
* at 8 GiB, 128 MiB in a 2 GiB container). */
|
|
34
|
+
export const readAheadBytes = (memory = memoryLimit()) => Math.min(READ_AHEAD_BYTES, Math.floor(memory / 16));
|
|
35
|
+
/** Workers lost (out of memory, or ended) past this many times the threads: the pool stops, and parseHome reads the rest. */
|
|
36
|
+
const LOSSES_PER_THREAD = 2;
|
|
37
|
+
/** A session's objects beyond its typed arrays and its strings, as the budget counts them. */
|
|
38
|
+
const SESSION_BYTES = 1024;
|
|
39
|
+
/** A string past U+00FF: V8 holds it at two bytes a UTF-16 code unit, any other at one. */
|
|
40
|
+
const WIDE = /[^\u0000-\u00ff]/;
|
|
41
|
+
/** A session's strings (its first prompt and title can run to megabytes) as V8 holds them. */
|
|
42
|
+
export const stringBytes = (session) => Object.values(session).reduce((sum, value) => sum + (typeof value === "string" ? (WIDE.test(value) ? 2 : 1) * value.length : 0), 0);
|
|
43
|
+
const indexBytes = (index) => [index.uuids.slots, index.uuids.owners, index.uuids.words, index.others.slots, index.others.owners, index.others.ends, index.others.bytes].reduce((sum, a) => sum + a.byteLength, 0);
|
|
44
|
+
/** What a read holds while it waits: its indexes' and counts' arrays, and its sessions with their strings. */
|
|
45
|
+
function heldBytes(read) {
|
|
46
|
+
if (!read.ok)
|
|
47
|
+
return 0;
|
|
48
|
+
let bytes = indexBytes(read.mine) + indexBytes(read.missed);
|
|
49
|
+
for (const { session, counts } of read.sessions)
|
|
50
|
+
bytes += SESSION_BYTES + stringBytes(session) + (counts ? counts.model.byteLength + counts.values.byteLength + counts.has.byteLength : 0);
|
|
51
|
+
return bytes;
|
|
52
|
+
}
|
|
53
|
+
export class ReadPool {
|
|
54
|
+
threads;
|
|
55
|
+
aheadBytes;
|
|
56
|
+
oldMb;
|
|
57
|
+
live = new Set();
|
|
58
|
+
idle = [];
|
|
59
|
+
running = new Map();
|
|
60
|
+
jobs = [];
|
|
61
|
+
/** Queued jobs, the largest first (the import's order among equals). */
|
|
62
|
+
bySize = [];
|
|
63
|
+
/** The job parseHome waits for (or last took): no job before it is read for it. */
|
|
64
|
+
cursor = 0;
|
|
65
|
+
/** The first job, in the import's order, that may still be queued. */
|
|
66
|
+
nextInOrder = 0;
|
|
67
|
+
/** The job parseHome waits for, and how it is handed over. */
|
|
68
|
+
wanted;
|
|
69
|
+
waiting = 0;
|
|
70
|
+
losses = 0;
|
|
71
|
+
broken = false;
|
|
72
|
+
/** The most bytes of reads waiting at once, and the workers lost (for measuring). The read-ahead is checked before a
|
|
73
|
+
* read is sent, so the reads in flight then (at most `threads`) may land past it. */
|
|
74
|
+
peakWaiting = 0;
|
|
75
|
+
lost = 0;
|
|
76
|
+
constructor(threads, aheadBytes = readAheadBytes(), oldMb = OLD_MB) {
|
|
77
|
+
this.threads = threads;
|
|
78
|
+
this.aheadBytes = aheadBytes;
|
|
79
|
+
this.oldMb = oldMb;
|
|
80
|
+
// A worker that cannot start (no file descriptors, no memory) stops the pool: parseHome reads every file itself.
|
|
81
|
+
try {
|
|
82
|
+
for (let i = 0; i < threads; i += 1)
|
|
83
|
+
this.spawn();
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
this.fail();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** The bytes of reads waiting to be taken now. */
|
|
90
|
+
get held() {
|
|
91
|
+
return this.waiting;
|
|
92
|
+
}
|
|
93
|
+
/** 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. */
|
|
94
|
+
readAll(items) {
|
|
95
|
+
const ids = items.map(({ source, locator, size }) => {
|
|
96
|
+
const job = { id: this.jobs.length, source, locator, size, state: this.broken ? "taken" : "queued", bytes: 0 };
|
|
97
|
+
this.jobs.push(job);
|
|
98
|
+
return job.id;
|
|
99
|
+
});
|
|
100
|
+
this.bySize = this.jobs.filter((job) => job.state === "queued").sort((a, b) => b.size - a.size || a.id - b.id);
|
|
101
|
+
this.dispatch();
|
|
102
|
+
return ids;
|
|
103
|
+
}
|
|
104
|
+
/** 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,
|
|
105
|
+
* gives a read that is not ok (parseHome makes it itself). */
|
|
106
|
+
take(id) {
|
|
107
|
+
const job = this.jobs[id];
|
|
108
|
+
if (id > this.cursor)
|
|
109
|
+
this.cursor = id;
|
|
110
|
+
if (job.state === "waiting") {
|
|
111
|
+
const read = job.read;
|
|
112
|
+
job.state = "taken";
|
|
113
|
+
job.read = undefined;
|
|
114
|
+
this.waiting -= job.bytes;
|
|
115
|
+
this.dispatch();
|
|
116
|
+
return Promise.resolve(read);
|
|
117
|
+
}
|
|
118
|
+
if (job.state === "taken")
|
|
119
|
+
return Promise.resolve({ ok: false });
|
|
120
|
+
return new Promise((done) => {
|
|
121
|
+
this.wanted = { job, done };
|
|
122
|
+
this.dispatch();
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/** Gives up jobs parseHome will not take (a source it reads again whole): their reads waiting are let go, those queued
|
|
126
|
+
* are not read, those running are let go when they end. */
|
|
127
|
+
drop(ids) {
|
|
128
|
+
for (const id of ids) {
|
|
129
|
+
const job = this.jobs[id];
|
|
130
|
+
if (job.state === "waiting")
|
|
131
|
+
this.waiting -= job.bytes;
|
|
132
|
+
job.state = "taken";
|
|
133
|
+
job.read = undefined;
|
|
134
|
+
}
|
|
135
|
+
this.dispatch();
|
|
136
|
+
}
|
|
137
|
+
close() {
|
|
138
|
+
this.fail();
|
|
139
|
+
}
|
|
140
|
+
spawn() {
|
|
141
|
+
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 } });
|
|
142
|
+
worker.unref();
|
|
143
|
+
worker.on("message", (read) => this.finished(worker, read));
|
|
144
|
+
worker.on("error", () => this.gone(worker));
|
|
145
|
+
worker.on("exit", () => this.gone(worker));
|
|
146
|
+
this.live.add(worker);
|
|
147
|
+
this.idle.push(worker);
|
|
148
|
+
}
|
|
149
|
+
/** The next job to read: the one parseHome waits for; else, while the reads waiting are under the budget, the largest
|
|
150
|
+
* file left if it is large, or the first queued past the cursor. */
|
|
151
|
+
pick() {
|
|
152
|
+
if (this.wanted?.job.state === "queued")
|
|
153
|
+
return this.wanted.job;
|
|
154
|
+
if (this.waiting >= this.aheadBytes)
|
|
155
|
+
return undefined;
|
|
156
|
+
while (this.bySize.length && this.bySize[0].state !== "queued")
|
|
157
|
+
this.bySize.shift();
|
|
158
|
+
if (this.bySize.length && this.bySize[0].size >= BIG_FILE)
|
|
159
|
+
return this.bySize[0];
|
|
160
|
+
if (this.nextInOrder < this.cursor)
|
|
161
|
+
this.nextInOrder = this.cursor;
|
|
162
|
+
while (this.nextInOrder < this.jobs.length && this.jobs[this.nextInOrder].state !== "queued")
|
|
163
|
+
this.nextInOrder += 1;
|
|
164
|
+
return this.jobs[this.nextInOrder];
|
|
165
|
+
}
|
|
166
|
+
dispatch() {
|
|
167
|
+
while (!this.broken && this.idle.length) {
|
|
168
|
+
const job = this.pick();
|
|
169
|
+
if (!job)
|
|
170
|
+
return;
|
|
171
|
+
const worker = this.idle.pop();
|
|
172
|
+
job.state = "running";
|
|
173
|
+
this.running.set(worker, job);
|
|
174
|
+
// A worker with a read keeps the process alive: parseHome may wait on nothing else.
|
|
175
|
+
worker.ref();
|
|
176
|
+
worker.postMessage({ id: job.id, source: job.source, locator: job.locator });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** A job's read is made: handed to parseHome if it waits for it, else held until it takes it. */
|
|
180
|
+
made(job, read) {
|
|
181
|
+
if (this.wanted?.job === job) {
|
|
182
|
+
const { done } = this.wanted;
|
|
183
|
+
this.wanted = undefined;
|
|
184
|
+
job.state = "taken";
|
|
185
|
+
done(read);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (job.state === "taken")
|
|
189
|
+
return; // dropped while it ran
|
|
190
|
+
job.state = "waiting";
|
|
191
|
+
job.read = read;
|
|
192
|
+
job.bytes = heldBytes(read);
|
|
193
|
+
this.waiting += job.bytes;
|
|
194
|
+
if (this.waiting > this.peakWaiting)
|
|
195
|
+
this.peakWaiting = this.waiting;
|
|
196
|
+
}
|
|
197
|
+
finished(worker, read) {
|
|
198
|
+
const job = this.running.get(worker);
|
|
199
|
+
this.running.delete(worker);
|
|
200
|
+
this.idle.push(worker);
|
|
201
|
+
worker.unref();
|
|
202
|
+
if (job)
|
|
203
|
+
this.made(job, read);
|
|
204
|
+
this.dispatch();
|
|
205
|
+
}
|
|
206
|
+
/** A worker ended (out of memory, or crashed): its file is parseHome's to read, and another worker takes its place. */
|
|
207
|
+
gone(worker) {
|
|
208
|
+
if (!this.live.delete(worker) || this.broken)
|
|
209
|
+
return;
|
|
210
|
+
this.lost += 1;
|
|
211
|
+
const at = this.idle.indexOf(worker);
|
|
212
|
+
if (at !== -1)
|
|
213
|
+
this.idle.splice(at, 1);
|
|
214
|
+
const job = this.running.get(worker);
|
|
215
|
+
this.running.delete(worker);
|
|
216
|
+
if (job)
|
|
217
|
+
this.made(job, { ok: false });
|
|
218
|
+
if ((this.losses += 1) > LOSSES_PER_THREAD * this.threads)
|
|
219
|
+
return this.fail();
|
|
220
|
+
try {
|
|
221
|
+
this.spawn();
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return this.fail();
|
|
225
|
+
}
|
|
226
|
+
this.dispatch();
|
|
227
|
+
}
|
|
228
|
+
/** The pool stops: no read is taken from it any more; parseHome makes each one itself. */
|
|
229
|
+
fail() {
|
|
230
|
+
this.broken = true;
|
|
231
|
+
for (const worker of this.live)
|
|
232
|
+
void worker.terminate();
|
|
233
|
+
for (const job of this.jobs) {
|
|
234
|
+
job.state = "taken";
|
|
235
|
+
job.read = undefined;
|
|
236
|
+
}
|
|
237
|
+
this.running.clear();
|
|
238
|
+
this.waiting = 0;
|
|
239
|
+
const wanted = this.wanted;
|
|
240
|
+
this.wanted = undefined;
|
|
241
|
+
wanted?.done({ ok: false });
|
|
242
|
+
}
|
|
243
|
+
}
|
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
|
}
|