@parcha/agentrun-import 0.0.0-bootstrap.0 → 0.1.0-beta.55

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/dist/home.js ADDED
@@ -0,0 +1,289 @@
1
+ // Every session under a home, as totals: what each used, its subagents' requests with it, and what it cost. A session is
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.
4
+ import { createHash } from "node:crypto";
5
+ import { relative, sep } from "node:path";
6
+ import { builtinCatalog, priceRequests } from "./price.js";
7
+ import { childrenOf, inOrder, readerOf, sessionLocators } from "./read.js";
8
+ import { locatorKey } from "./reader.js";
9
+ import { READERS, SOURCES } from "./readers/index.js";
10
+ import { addAll, addRecord, dropOwner, isRecordIndex, locatorNumber, ownerOf, recordIndex } from "./record-index.js";
11
+ import { packed, packInto } from "./record-key.js";
12
+ import { addTokens, noTokens } from "./usage.js";
13
+ /** What parseHome throws when a locator could not be read and the caller took no failures list. Its message names no
14
+ * path; `failures` holds them. */
15
+ export class ReadFailures extends Error {
16
+ failures;
17
+ constructor(failures) {
18
+ super(`${failures.length} session ${failures.length === 1 ? "file" : "files"} could not be read`);
19
+ this.failures = failures;
20
+ this.name = "ReadFailures";
21
+ }
22
+ }
23
+ /** A session's key: the sha256 of its file's path relative to the home, "/" between its parts, `#<id>` after it when its
24
+ * locator names one. */
25
+ const keyOf = (home, { file, id }) => {
26
+ const path = relative(home, file).split(sep).join("/");
27
+ return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
28
+ };
29
+ const USAGE_FIELDS = 6;
30
+ const HAS_USAGE = 1;
31
+ const HAS_LONG = 2;
32
+ const HAS_REASONING = 4;
33
+ /** `read` as a total takes it (Compact), each request's model the one totalsOf prices it at. */
34
+ function compact(read, models) {
35
+ const { id, child, parent, users, copies, costUsd, model } = read.session;
36
+ const n = read.requests.length;
37
+ 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) };
38
+ for (let i = 0; i < n; i += 1) {
39
+ const request = read.requests[i];
40
+ const name = request.model ?? model;
41
+ let at = -1;
42
+ if (name !== undefined) {
43
+ at = models.index.get(name) ?? -1;
44
+ if (at === -1)
45
+ models.index.set(name, (at = models.names.push(name) - 1));
46
+ }
47
+ out.models[i] = at;
48
+ const { usage } = request;
49
+ if (!usage)
50
+ continue;
51
+ const o = i * USAGE_FIELDS;
52
+ out.usage[o] = usage.input;
53
+ out.usage[o + 1] = usage.output;
54
+ out.usage[o + 2] = usage.cacheRead;
55
+ out.usage[o + 3] = usage.cacheWrite;
56
+ let has = HAS_USAGE;
57
+ if (usage.cacheWrite1h !== undefined) {
58
+ out.usage[o + 4] = usage.cacheWrite1h;
59
+ has |= HAS_LONG;
60
+ }
61
+ if (usage.reasoning !== undefined) {
62
+ out.usage[o + 5] = usage.reasoning;
63
+ has |= HAS_REASONING;
64
+ }
65
+ out.has[i] = has;
66
+ }
67
+ return out;
68
+ }
69
+ /** The i-th request of `read` as priceRequests takes it. */
70
+ function requestAt(read, i, models) {
71
+ const at = read.models[i];
72
+ const model = at === -1 ? undefined : models.names[at];
73
+ const has = read.has[i];
74
+ if (!(has & HAS_USAGE))
75
+ return { model, usage: undefined };
76
+ const o = i * USAGE_FIELDS;
77
+ const usage = { input: read.usage[o], output: read.usage[o + 1], cacheRead: read.usage[o + 2], cacheWrite: read.usage[o + 3] };
78
+ if (has & HAS_LONG)
79
+ usage.cacheWrite1h = read.usage[o + 4];
80
+ if (has & HAS_REASONING)
81
+ usage.reasoning = read.usage[o + 5];
82
+ return { model, usage };
83
+ }
84
+ /** Every session of `sources` under `home`, as totals, sorted by key. */
85
+ export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures } = {}) {
86
+ let prices;
87
+ const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
88
+ const out = [];
89
+ const failed = [];
90
+ if (state)
91
+ state.read = 0;
92
+ for (const source of sources) {
93
+ const models = { names: [], index: new Map() };
94
+ const { tops, children, unread } = await readSource(home, source, readers, env, state, models);
95
+ out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost)));
96
+ failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
97
+ }
98
+ if (failed.length && !failures)
99
+ throw new ReadFailures(failed);
100
+ failures?.push(...failed);
101
+ return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
102
+ }
103
+ /** `source`'s locators read in the import's order, sessions first, then the subagents beside them, through one `seen`.
104
+ * A pass handed a state goes on from its cursors, and comes out as a fresh pass would: a record copied into many files
105
+ * 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
106
+ * gone, when its reader could not go on from its cursor (a new inode, truncated, rewritten), or when a locator holding a
107
+ * copy now comes before the one its record counts in (an append moved an older file after its resumed copy, a new file
108
+ * sorts before one it shares records with). A change of order among locators that share no record reads nothing again. */
109
+ async function readSource(home, source, readers, env, state, models) {
110
+ const reader = readerOf(source, readers);
111
+ const listed = await inOrder(await sessionLocators(home, source, { ...(env ? { env } : {}), readers }), source, readers);
112
+ const childList = await childrenOf(home, source, { ...(env ? { env } : {}), readers });
113
+ // Each locator's place in this pass's order of reading.
114
+ const place = new Map([...listed.map(({ locator }) => locatorKey(locator)), ...childList.map(({ locator }) => locatorKey(locator))].map((key, at) => [key, at]));
115
+ // Whether a locator holds a copy of a record that now counts after it: the fresh pass would count it in that locator.
116
+ const outOfOrder = (kept) => [...kept.copied].some(([key, owners]) => [...owners].some((owner) => place.get(owner) > place.get(key)));
117
+ for (let pass = 0;; pass += 1) {
118
+ let kept = state ? (state.sources ??= {})[source] : undefined;
119
+ // A source's state of another shape (an earlier version's, its records in a Map) is set aside like one whose files
120
+ // changed: the source is read from its start and its state rebuilt.
121
+ if (kept && (!isRecordIndex(kept.owners) || [...kept.cursors.keys()].some((key) => !place.has(key)) || outOfOrder(kept)))
122
+ kept = undefined;
123
+ if (state && !kept)
124
+ kept = state.sources[source] = { cursors: new Map(), owners: recordIndex(), copied: new Map() };
125
+ const { owners, copied } = kept ?? { owners: recordIndex(), copied: new Map() };
126
+ let restarted = false;
127
+ const unread = [];
128
+ const read = async (locator) => {
129
+ const key = locatorKey(locator);
130
+ const cursor = kept?.cursors.get(key);
131
+ // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. Both are
132
+ // staged and kept only when the read succeeds: a read that fails partway leaves no record owned that no cursor
133
+ // holds, which a retry would take for a copy.
134
+ // Records are held by their packed keys (packInto): a reader asks has, then add, of one record, packed once.
135
+ const me = locatorNumber(owners, key);
136
+ const mine = recordIndex(64);
137
+ const found = new Set();
138
+ let asked;
139
+ const at = packed();
140
+ const pack = (record) => (record === asked ? at : ((asked = record), packInto(record, at)));
141
+ const seen = {
142
+ has: (record) => {
143
+ pack(record);
144
+ let owner = ownerOf(owners, at);
145
+ if (owner === -1)
146
+ owner = ownerOf(mine, at);
147
+ if (owner === -1)
148
+ return false;
149
+ if (owner !== me)
150
+ found.add(owners.locators[owner]);
151
+ return true;
152
+ },
153
+ add(record) {
154
+ pack(record);
155
+ if (ownerOf(owners, at) === -1)
156
+ addRecord(mine, at, me);
157
+ return this;
158
+ },
159
+ };
160
+ const result = await reader.read(locator, cursor, { turns: false, seen }).catch((error) => void unread.push({ locator, error }));
161
+ if (!result) {
162
+ // A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
163
+ // would hold none of them: the next pass reads it from its start. A locator that found them already read (a
164
+ // copy) skipped them, though the fresh pass counts them there: the source is read again.
165
+ if (kept && cursor !== undefined) {
166
+ kept.cursors.delete(key);
167
+ dropOwner(owners, me);
168
+ copied.delete(key);
169
+ if ([...copied.values()].some((owners) => owners.has(key)))
170
+ restarted = true;
171
+ }
172
+ return [];
173
+ }
174
+ addAll(owners, mine);
175
+ if (found.size)
176
+ for (const owner of found)
177
+ (copied.get(key) ?? copied.set(key, new Set()).get(key)).add(owner);
178
+ if (cursor !== undefined && !result.resumed)
179
+ restarted = true;
180
+ if (state)
181
+ state.read += result.read;
182
+ kept?.cursors.set(key, result.cursor);
183
+ return result.sessions;
184
+ };
185
+ const tops = [];
186
+ // Each locator's sessions packed as soon as they are read: only one locator's requests are ever held whole.
187
+ for (const { locator } of listed)
188
+ for (const session of await read(locator))
189
+ tops.push({ locator: session.locator, read: compact(session, models) });
190
+ const children = [];
191
+ for (const { locator, of } of childList)
192
+ for (const session of await read(locator))
193
+ children.push({ locator: session.locator, read: compact(session, models), of });
194
+ // A locator its reader could not go on in, or a copy this pass found whose record counts after it: read the source
195
+ // again, from nothing.
196
+ if (pass > 0 || !kept || !(restarted || outOfOrder(kept)))
197
+ return { tops, children, unread };
198
+ state.sources[source] = undefined;
199
+ }
200
+ }
201
+ async function totalsOf(home, source, tops, children, models, priceWith, calculateCost) {
202
+ // Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
203
+ // parent's, as is each one beside a session's (Claude Code's subagents).
204
+ const sessions = new Map();
205
+ const named = [];
206
+ for (const part of tops) {
207
+ const { session } = part.read;
208
+ if (session.child && session.parent) {
209
+ named.push({ part, parent: session.parent });
210
+ continue;
211
+ }
212
+ const held = sessions.get(session.id) ?? sessions.set(session.id, { parts: [], children: [] }).get(session.id);
213
+ held.parts.push(part);
214
+ }
215
+ const byLocator = new Map(tops.map((part) => [locatorKey(part.locator), part.read.session.id]));
216
+ const untied = [];
217
+ for (const child of children) {
218
+ const id = byLocator.get(locatorKey(child.of));
219
+ const held = id !== undefined ? sessions.get(id) : undefined;
220
+ if (held)
221
+ held.children.push(child);
222
+ else
223
+ untied.push(child);
224
+ }
225
+ // A thread's parent is a session, or another thread that names its own parent: up the chain to the session.
226
+ const parentOf = new Map(named.map(({ part, parent }) => [part.read.session.id, parent]));
227
+ for (const { part, parent } of named) {
228
+ let at = parent;
229
+ const visited = new Set();
230
+ while (at !== undefined && !sessions.has(at) && !visited.has(at)) {
231
+ visited.add(at);
232
+ at = parentOf.get(at);
233
+ }
234
+ const held = at !== undefined ? sessions.get(at) : undefined;
235
+ if (held)
236
+ held.children.push(part);
237
+ else
238
+ untied.push(part);
239
+ }
240
+ // A subagent whose session is not under the home: a line of its own, but its prompts are its parent agent's.
241
+ for (const part of untied)
242
+ sessions.set(`\0${locatorKey(part.locator)}`, { parts: [part], children: [], untied: true });
243
+ const out = [];
244
+ for (const { parts, children: subagents, untied } of sessions.values()) {
245
+ // A session whose every file holds only records an earlier file holds (copies) is no session: its records count where
246
+ // they were first read. serve's import leaves such a file out the same way.
247
+ if (parts.every(({ read }) => read.session.copies > 0 && read.session.users === 0 && read.models.length === 0) && subagents.length === 0)
248
+ continue;
249
+ const first = parts[0];
250
+ const tokens = noTokens();
251
+ let reasoning = 0;
252
+ let calls = 0;
253
+ const requests = [];
254
+ for (const { read } of [...parts, ...subagents])
255
+ for (let i = 0; i < read.models.length; i += 1)
256
+ requests.push(requestAt(read, i, models));
257
+ for (const { usage } of requests) {
258
+ calls += 1;
259
+ if (!usage)
260
+ continue;
261
+ addTokens(tokens, usage);
262
+ reasoning += usage.reasoning ?? 0;
263
+ }
264
+ // The source's own cost, when each of its files wrote one: Claude Code writes the session's running total (a moved
265
+ // session's copy goes on from the original's), so the highest; another source prices each request, so their sum.
266
+ const written = parts.flatMap(({ read }) => (read.session.costUsd !== undefined ? [read.session.costUsd] : []));
267
+ let cost = written.length === parts.length ? (source === "claude-code" ? Math.max(...written) : written.reduce((n, usd) => n + usd, 0)) : undefined;
268
+ if (cost === undefined) {
269
+ const catalog = await priceWith();
270
+ cost = catalog ? await priceRequests(requests, catalog, calculateCost) : undefined;
271
+ }
272
+ const { key, file } = keyOf(home, first.locator);
273
+ out.push({
274
+ key,
275
+ file,
276
+ source,
277
+ id: first.read.session.id,
278
+ tokens,
279
+ reasoning,
280
+ cost: cost ?? null,
281
+ // A subagent's session counted on its own line (its parent not under the home, or named nowhere: Codex's
282
+ // source.subagent alone, a Claude Code sidechain file): its prompts are its parent agent's, as serve takes it.
283
+ turns: untied || parts.every(({ read }) => read.session.child) ? 0 : parts.reduce((n, { read }) => n + read.session.users, 0),
284
+ calls,
285
+ subagents: subagents.length,
286
+ });
287
+ }
288
+ return out;
289
+ }
@@ -0,0 +1,10 @@
1
+ export type { Answer, Ended, ToolCall, Turn, Usage } from "./types.js";
2
+ export { ACTIVE_GAP_MS } from "./types.js";
3
+ export { mostEffortOf, personsWords } from "./text.js";
4
+ export { addTokens, noTokens, normalizeUsage, type Tokens, type UsageFormat } from "./usage.js";
5
+ export { type Env, type Locator, locatorKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
6
+ export { type FileCursor, type LineSource, lineReader, type ReadContext, type ReadState } from "./lines.js";
7
+ export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES, type Source } from "./readers/index.js";
8
+ export { childrenOf, inOrder, locatorOf, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
9
+ export { builtinCatalog, type CalculateCost, type Catalog, catalogOf, type Listed, type ModelCost, type Priced, priceRequests } from "./price.js";
10
+ export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionTotals } from "./home.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { ACTIVE_GAP_MS } from "./types.js";
2
+ export { mostEffortOf, personsWords } from "./text.js";
3
+ export { addTokens, noTokens, normalizeUsage } from "./usage.js";
4
+ export { locatorKey } from "./reader.js";
5
+ export { lineReader } from "./lines.js";
6
+ export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES } from "./readers/index.js";
7
+ export { childrenOf, inOrder, locatorOf, readerOf, readSession, sessionLocators } from "./read.js";
8
+ export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
9
+ export { parseHome, ReadFailures } from "./home.js";
@@ -0,0 +1,74 @@
1
+ import { type Env, type Reader } from "./reader.js";
2
+ import { type Answer, type SessionOf, type Turn } from "./types.js";
3
+ /** One file's read so far, all of it plain data (no function, Maps and Sets allowed), so a cursor can carry it and
4
+ * structuredClone or v8.serialize can copy it. `answers` holds every request read, whether turns are kept or not: what
5
+ * a total counts. `own` is the source's own (LineSource.start). A turns: true read's holds the session's text (its
6
+ * turns, prompts, titles, tool output, working directory); a turns: false read's cursor holds none of it, only counts,
7
+ * ids and the like (see LineSource.forget). */
8
+ export type ReadState<O = unknown> = {
9
+ session: SessionOf;
10
+ turns: Turn[];
11
+ answers: Answer[];
12
+ /** Tool names by call id, for the results that name none. */
13
+ names: Map<string, string>;
14
+ /** The sum of the requests the source priced, and whether one was not. */
15
+ priced: {
16
+ sum: number;
17
+ unknown: boolean;
18
+ };
19
+ /** The effort in force (Codex's turn_context, pi's thinking level). */
20
+ effort?: string;
21
+ first?: number;
22
+ last?: number;
23
+ activeMs: number;
24
+ own: O;
25
+ /** The records seen, when the caller shares none across files. */
26
+ seen?: Set<string>;
27
+ };
28
+ /** What a source's record and finish are handed: the file's state, the records seen across the import's files ("u:"
29
+ * a record's uuid, "m:" a request's key, "l:" a bare message id a store imported before keys had request ids), whether turns are kept, and `add`, which keeps a turn (and counts a user's). */
30
+ export type ReadContext<O = unknown> = {
31
+ state: ReadState<O>;
32
+ seen: Set<string>;
33
+ keep: boolean;
34
+ add: (turn: Turn) => void;
35
+ };
36
+ /** A JSONL source: where its files are, and how it reads one record of one into the session. */
37
+ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name" | "harness" | "order"> & {
38
+ /** The candidate session files under `home`, any order; links are dropped by the caller. */
39
+ files: (home: string, env?: Env) => Promise<string[]>;
40
+ /** Subagents' session files that name no parent themselves, each with the session file it ran under (`of`). */
41
+ children?: (home: string, env?: Env) => Promise<{
42
+ file: string;
43
+ of: string;
44
+ }[]>;
45
+ /** The source's own state for a new file. */
46
+ start: () => O;
47
+ /** One record read: false for one read already (a copy), which moves no time. */
48
+ record: (value: Record<string, unknown>, at: number, context: ReadContext<O>) => boolean | void;
49
+ /** The session as the file ends, from `out` (a copy of the state's session, its turns `turns`): it may set more of
50
+ * `out` and return the turns in their order. It never changes the state, which a later read goes on from. */
51
+ finish?: (out: SessionOf, turns: Turn[], context: ReadContext<O>) => Turn[];
52
+ /** The session's id when no record named one. */
53
+ idOf: (file: string) => string;
54
+ /** `own` without the session's text (prompts, titles, tool output), for the cursor of a turns: false read. */
55
+ forget?: (own: O) => O;
56
+ };
57
+ /** Where a read of a file stopped, and what it had read. Plain data (Maps, Sets and shared objects, no function):
58
+ * structuredClone or v8.serialize keeps it whole. Read it through its reader alone. A turns: true read's cursor
59
+ * holds the session's text, as its state does (ReadState); keep or send it as you would the session. */
60
+ export type FileCursor = {
61
+ source: string;
62
+ dev: number;
63
+ ino: number;
64
+ /** The byte after the last newline read: a last line with none is read again next time. */
65
+ offset: number;
66
+ /** The last bytes before `offset` (up to 64, base64): a file rewritten in place to at least the same length no longer
67
+ * has them there, and is read from its start. */
68
+ mark: string;
69
+ /** Whether the read kept turns: a cursor of the other kind is no place to go on from. */
70
+ keep: boolean;
71
+ state: ReadState;
72
+ };
73
+ /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
74
+ export declare function lineReader<S extends string, O>(spec: LineSource<S, O>): Reader<S, FileCursor>;
package/dist/lines.js ADDED
@@ -0,0 +1,149 @@
1
+ // A Reader for a source that writes each session as a JSONL file (Claude Code, Codex, pi): the file read a line at a time
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
+ // the file's identity (device, inode), the byte after the last whole line read, and the read's state, so a later read
4
+ // takes only the bytes written since.
5
+ import { createReadStream } from "node:fs";
6
+ import { open } from "node:fs/promises";
7
+ import { rememberUser } from "./reader.js";
8
+ import { isObject, mostEffortOf, timeOf } from "./text.js";
9
+ import { ACTIVE_GAP_MS } from "./types.js";
10
+ /** What a listing reads from the session's text: a turns: false cursor keeps none of it, and a read resumed from one
11
+ * gives none (it would describe only what was written since). */
12
+ const withoutText = (session) => {
13
+ const { firstPrompt: _prompt, titleText: _title, cwd: _cwd, sourceTitle: _source, ...rest } = session;
14
+ return rest;
15
+ };
16
+ /** The up to 64 bytes before `offset` in the open file, base64. */
17
+ async function markOf(handle, offset) {
18
+ const n = Math.min(64, offset);
19
+ if (n === 0)
20
+ return "";
21
+ const bytes = Buffer.alloc(n);
22
+ const { bytesRead } = await handle.read(bytes, 0, n, offset - n);
23
+ return bytes.subarray(0, bytesRead).toString("base64");
24
+ }
25
+ /** The records seen, as a source asks: `extra` over `base`, so a line read that is not kept leaves `base` as it was. */
26
+ const overlay = (base) => {
27
+ const extra = new Set();
28
+ return { has: (key) => extra.has(key) || base.has(key), add: (key) => extra.add(key) };
29
+ };
30
+ /** One session file of `spec`'s source, read from its start or from `cursor`. */
31
+ async function readLines(spec, file, cursor, { turns: keep = true, seen, keepsCursor = true } = {}) {
32
+ const { source } = spec;
33
+ const handle = await open(file, "r");
34
+ try {
35
+ const stats = await handle.stat();
36
+ const resumed = cursor !== undefined && cursor.source === source && cursor.keep === keep && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
37
+ const state = (resumed
38
+ ? structuredClone(cursor.state)
39
+ : { 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(), ...(seen ? {} : { seen: new Set() }) });
40
+ const context = {
41
+ state,
42
+ seen: seen ?? (state.seen ??= new Set()),
43
+ keep,
44
+ add: (turn) => {
45
+ rememberUser(state.session, turn);
46
+ if (keep)
47
+ state.turns.push(turn);
48
+ if (turn.role === "assistant")
49
+ state.answers.push(turn);
50
+ },
51
+ };
52
+ const line = (text) => {
53
+ let value;
54
+ try {
55
+ value = JSON.parse(text);
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ if (!isObject(value))
61
+ return;
62
+ const at = timeOf(value.timestamp);
63
+ // A copy of a record read already moves no time: its time was counted where it was first read.
64
+ const copy = spec.record(value, at ?? state.last ?? 0, context) === false;
65
+ if (copy)
66
+ state.session.copies += 1;
67
+ if (at !== undefined && !copy) {
68
+ state.first ??= at;
69
+ // A record older than the latest (a block a resumed file repeats) moves no time either.
70
+ if (state.last === undefined || at >= state.last) {
71
+ if (state.last !== undefined && at - state.last <= ACTIVE_GAP_MS)
72
+ state.activeMs += at - state.last;
73
+ state.last = at;
74
+ }
75
+ }
76
+ };
77
+ const start = resumed ? cursor.offset : 0;
78
+ let offset = start;
79
+ let read = 0;
80
+ let rest = [];
81
+ if (stats.size > start) {
82
+ // The open handle's descriptor, so the bytes streamed are the file stat described, whatever the path names now.
83
+ for await (const chunk of createReadStream(file, { fd: handle.fd, start, autoClose: false, highWaterMark: 1 << 20 })) {
84
+ read += chunk.length;
85
+ let from = 0;
86
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
87
+ const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
88
+ rest = [];
89
+ line(whole.toString("utf8", 0, whole.length && whole[whole.length - 1] === 13 ? whole.length - 1 : whole.length));
90
+ offset += whole.length + 1;
91
+ from = nl + 1;
92
+ }
93
+ if (from < chunk.length)
94
+ rest.push(chunk.subarray(from));
95
+ }
96
+ }
97
+ // A last line with no newline yet may be a record still being written: read into this result when it is whole JSON,
98
+ // but the cursor stays before it, its state without it. A caller that keeps the cursor reads the line again from it,
99
+ // so its `seen` is left untouched by it; one that keeps none (readSession) has it in `seen` like any other line.
100
+ let kept = state;
101
+ if (rest.length) {
102
+ kept = structuredClone(state);
103
+ if (keepsCursor)
104
+ context.seen = overlay(context.seen);
105
+ line(Buffer.concat(rest).toString("utf8"));
106
+ }
107
+ const mark = await markOf(handle, offset);
108
+ let session = finish(spec, file, state, context);
109
+ if (!keep) {
110
+ kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own };
111
+ if (resumed)
112
+ session = withoutText(session);
113
+ }
114
+ return { sessions: [{ locator: { file }, session, requests: state.answers }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, state: kept }, read, resumed };
115
+ }
116
+ finally {
117
+ await handle.close();
118
+ }
119
+ }
120
+ /** The session as read so far, the state left as it is. */
121
+ function finish(spec, file, state, context) {
122
+ const out = { ...state.session, file };
123
+ const turns = spec.finish ? spec.finish(out, context.keep ? [...state.turns] : [], context) : context.keep ? [...state.turns] : [];
124
+ if (!out.id)
125
+ out.id = spec.idOf(file);
126
+ if (state.first !== undefined)
127
+ out.startedAt = new Date(state.first).toISOString();
128
+ if (state.last !== undefined)
129
+ out.endedAt = new Date(state.last).toISOString();
130
+ out.activeMs = Math.round(state.activeMs);
131
+ out.turns = turns;
132
+ const effort = mostEffortOf(turns);
133
+ if (effort)
134
+ out.effort = effort;
135
+ return out;
136
+ }
137
+ /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
138
+ export function lineReader(spec) {
139
+ const { source, name, harness, order, children } = spec;
140
+ return {
141
+ source,
142
+ name,
143
+ harness,
144
+ ...(order ? { order } : {}),
145
+ discover: async (home, env) => (await spec.files(home, env)).map((file) => ({ file })),
146
+ read: (locator, cursor, options) => readLines(spec, locator.file, cursor, options),
147
+ ...(children ? { children: async (home, env) => (await children(home, env)).map(({ file, of }) => ({ locator: { file }, of: { file: of } })) } : {}),
148
+ };
149
+ }
@@ -0,0 +1,49 @@
1
+ import type { Usage } from "./types.js";
2
+ export type ModelCost = {
3
+ input: number;
4
+ output: number;
5
+ cacheRead: number;
6
+ cacheWrite: number;
7
+ tiers?: unknown;
8
+ };
9
+ /** A model's entry in a catalog: its provider, and its price in USD per million tokens. */
10
+ export type Listed = {
11
+ provider: string;
12
+ cost: ModelCost;
13
+ };
14
+ /** Catalog entries by model id, every provider's. */
15
+ export type Catalog = ReadonlyMap<string, readonly Listed[]>;
16
+ /** A catalog of pi-ai's models (builtinModels().getModels()), by model id. */
17
+ export declare function catalogOf(models: readonly {
18
+ id: string;
19
+ provider: string;
20
+ cost?: Partial<ModelCost>;
21
+ }[]): Catalog;
22
+ /** pi-ai's built-in catalog, by model id; undefined when pi-ai is not installed. serve prices with its own catalog
23
+ * (pi-ai's, with serve's overrides and added models), which it passes in; the CLI imports pi-ai itself. */
24
+ export declare function builtinCatalog(): Promise<Catalog | undefined>;
25
+ /** pi-ai's calculateCost: what one request's usage costs at a model's price. */
26
+ export type CalculateCost = (model: {
27
+ cost: ModelCost;
28
+ }, usage: Usage & {
29
+ totalTokens: number;
30
+ cost: {
31
+ input: number;
32
+ output: number;
33
+ cacheRead: number;
34
+ cacheWrite: number;
35
+ total: number;
36
+ };
37
+ }) => {
38
+ total: number;
39
+ };
40
+ /** A request to price: the model it ran on ("provider/model"), and its tokens. */
41
+ export type Priced = {
42
+ model?: string;
43
+ usage?: Usage;
44
+ };
45
+ /** What `requests` cost at `catalog`'s list prices, each at its own provider's entry for its model, rounded to a
46
+ * 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), or pi-ai is not installed (no `calculateCost` handed in). A provider's $0 entry is $0. A request of
48
+ * no tokens costs nothing at any price. */
49
+ export declare function priceRequests(requests: readonly Priced[], catalog: Catalog, calculateCost?: CalculateCost): Promise<number | undefined>;
package/dist/price.js ADDED
@@ -0,0 +1,40 @@
1
+ /** A catalog of pi-ai's models (builtinModels().getModels()), by model id. */
2
+ export function catalogOf(models) {
3
+ const out = new Map();
4
+ for (const model of models) {
5
+ const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, tiers } = model.cost ?? {};
6
+ const listed = out.get(model.id) ?? out.set(model.id, []).get(model.id);
7
+ listed.push({ provider: model.provider, cost: { input, output, cacheRead, cacheWrite, ...(tiers ? { tiers } : {}) } });
8
+ }
9
+ return out;
10
+ }
11
+ /** pi-ai's built-in catalog, by model id; undefined when pi-ai is not installed. serve prices with its own catalog
12
+ * (pi-ai's, with serve's overrides and added models), which it passes in; the CLI imports pi-ai itself. */
13
+ export async function builtinCatalog() {
14
+ const loaded = await import("@earendil-works/pi-ai/providers/all").catch(() => undefined);
15
+ return loaded ? catalogOf(loaded.builtinModels().getModels()) : undefined;
16
+ }
17
+ /** What `requests` cost at `catalog`'s list prices, each at its own provider's entry for its model, rounded to a
18
+ * 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), or pi-ai is not installed (no `calculateCost` handed in). A provider's $0 entry is $0. A request of
20
+ * no tokens costs nothing at any price. */
21
+ export async function priceRequests(requests, catalog, calculateCost) {
22
+ const calculate = calculateCost ?? (await import("@earendil-works/pi-ai").catch(() => undefined))?.calculateCost;
23
+ if (!calculate)
24
+ return undefined;
25
+ let total = 0;
26
+ for (const { model, usage } of requests) {
27
+ if (!usage)
28
+ return undefined;
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)
35
+ return undefined;
36
+ const counted = { input, output, cacheRead, cacheWrite, ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}), totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
37
+ total += calculate({ cost }, counted).total;
38
+ }
39
+ return Math.round(total * 1e6) / 1e6;
40
+ }
package/dist/read.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Stats } from "node:fs";
2
+ import type { Env, Locator, Reader, ReadOptions } from "./reader.js";
3
+ import { type Source } from "./readers/index.js";
4
+ import type { SessionOf } from "./types.js";
5
+ export type Session = SessionOf<Source>;
6
+ /** The readers a call reads with: the registry's, or one a caller hands in (a test's, a source not yet registered). */
7
+ export type Readers = Readonly<Record<string, Reader<string, any>>>;
8
+ /** The reader of `source` among `readers`; one that is not there throws. */
9
+ export declare function readerOf(source: string, readers?: Readers): Reader<string, unknown>;
10
+ /** The locators of `source` under `home`, by path, never through a link (a file that is not a regular file is dropped). */
11
+ export declare function sessionLocators(home: string, source: string, { env, readers }?: {
12
+ env?: Env;
13
+ readers?: Readers;
14
+ }): Promise<Locator[]>;
15
+ /** The locators of `source`, each with its file's stats (one gone since it was listed is passed over), in the import's
16
+ * order: the reader's (Claude Code's by project folder, oldest written first: the first file holding a copied record
17
+ * keeps it), else as they were listed. */
18
+ export declare function inOrder(locators: readonly Locator[], source: string, readers?: Readers): Promise<{
19
+ locator: Locator;
20
+ stats: Stats;
21
+ }[]>;
22
+ /** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
23
+ * (Claude Code's <session id>/subagents/). */
24
+ export declare function childrenOf(home: string, source: string, { env, readers }?: {
25
+ env?: Env;
26
+ readers?: Readers;
27
+ }): Promise<{
28
+ locator: Locator;
29
+ of: Locator;
30
+ }[]>;
31
+ /** The one session at `locator` (a file alone is its first session), read whole; `turns: false` keeps only what a
32
+ * listing shows. A locator whose session is not there throws. */
33
+ export declare function readSession(locator: Locator | string, source: string, { readers, ...options }?: ReadOptions & {
34
+ readers?: Readers;
35
+ }): Promise<Session>;
36
+ /** Where a session read by readSession is: its file, and its id there when the file holds many. */
37
+ export declare const locatorOf: ({ file, within }: Pick<Session, "file" | "within">) => Locator;