@parcha/agentrun-import 0.1.0-beta.55 → 0.1.0-beta.57

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 CHANGED
@@ -28,6 +28,22 @@ const sessions = await parseHome(homedir(), { sources: ["claude-code", "codex"]
28
28
  totalled; without it, parseHome throws `ReadFailures`. An unreadable file is never taken for an empty one.
29
29
  - `env` names where a source keeps its own directory (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`); without it the home's.
30
30
 
31
+ ## A year of work
32
+
33
+ ```js
34
+ import { wrappedHome } from "@parcha/agentrun-import";
35
+
36
+ const year = await wrappedHome(homedir(), 2026); // the same options as parseHome, but `state`
37
+ ```
38
+
39
+ `wrappedHome(home, year)` buckets by each request's time, in the machine's local zone, so a session that spans New Year
40
+ splits: `tokens`, `requests`, `days` (`{day, requests, tokens}`), `hours` (24) and `weekdays` (7, Sunday first),
41
+ `activeMs` (the gaps between a session's requests of the year, each counted when under 15 minutes), `models`,
42
+ `harnesses` and `sources`. A session counts in `sessions` (and its prompts in `turns`) for the year its first request is in.
43
+ `cost` is the catalog's list price of the requests it could price; `unpricedRequests` counts the rest. Like the totals, it
44
+ holds counts, names and times only: no prompt, title, path or project. `parseHome`'s `requests` option is the hook it is
45
+ built on: each session's totals and its requests, as they are totalled.
46
+
31
47
  ## Known answer
32
48
 
33
49
  ```sh
@@ -69,7 +85,7 @@ type Reader<S extends string, C> = {
69
85
  name: string;
70
86
  harness: string;
71
87
  discover(home: string, env?: Env): Promise<Locator[]>;
72
- read(locator: Locator, cursor?: C, options?: { turns?: boolean; seen?: Set<string> }): Promise<{ sessions: SessionRead<S>[]; cursor: C; read: number; resumed: boolean }>;
88
+ read(locator: Locator, cursor?: C, options?: { turns?: boolean; totals?: boolean; seen?: Set<string> }): Promise<{ sessions: SessionRead<S>[]; cursor: C; read: number; resumed: boolean }>;
73
89
  order?(a, b): number;
74
90
  children?(home: string, env?: Env): Promise<{ locator: Locator; of: Locator }[]>;
75
91
  };
@@ -81,5 +97,31 @@ line read, and the read's state. A file replaced or truncated since is read from
81
97
  newline yet is read but not consumed. A source that keeps many sessions in one file (a SQLite database) implements
82
98
  `discover` and `read` itself and returns one locator per session, with its `id`.
83
99
 
100
+ With `turns: false`, `totals: true` asks for only what `parseHome` totals: each session read then has `counts` set and
101
+ `requests` empty. Only a `lineReader` whose source sets `totals: true` (one that sets no turn's model, usage or time after
102
+ adding it) reads so; Claude Code's, Codex's and pi's do. Any other reader ignores the option, and its sessions have
103
+ `requests` whole and no `counts`. `Counts` holds the requests in typed arrays, in order:
104
+
105
+ - `n`: the number of requests.
106
+ - `models`: each model name once; `model[i]` is request `i`'s index into it, or -1 for none named.
107
+ - `values`: seven numbers a request, from `i * 7`: input, output, cacheRead, cacheWrite, cacheWrite1h and reasoning
108
+ tokens, then the request's time (the `at` a read of turns gives it, in ms since the epoch).
109
+ - `has[i]`: which usage request `i` has, as bits: 1 its usage at all, 2 cacheWrite1h, 4 reasoning.
110
+
111
+ `atOf(counts, i)` reads request `i`'s time:
112
+
113
+ ```ts
114
+ import { atOf, READERS } from "@parcha/agentrun-import";
115
+
116
+ const reader = READERS["claude-code"];
117
+ for (const locator of await reader.discover(home)) {
118
+ const { sessions } = await reader.read(locator, undefined, { turns: false, totals: true });
119
+ for (const read of sessions) {
120
+ if (!read.counts) continue; // a reader with no totals read: read.requests holds its requests whole
121
+ for (let i = 0; i < read.counts.n; i++) console.log(read.session.id, new Date(atOf(read.counts, i)).toISOString());
122
+ }
123
+ }
124
+ ```
125
+
84
126
  `readSession(locator, source)`, `sessionLocators(home, source)`, `inOrder(locators, source)` and
85
127
  `childrenOf(home, source)` are what serve's import reads through.
@@ -0,0 +1,30 @@
1
+ import type { Usage } from "./types.js";
2
+ /** A request's usage numbers: input, output, cacheRead, cacheWrite, cacheWrite1h, reasoning. */
3
+ export declare const USAGE_FIELDS = 6;
4
+ /** Where a request's time is in its stride, after its usage numbers. */
5
+ export declare const AT = 6;
6
+ /** A request's numbers in Counts.values: its usage numbers, then its time. */
7
+ export declare const STRIDE: number;
8
+ export declare const HAS_USAGE = 1;
9
+ export declare const HAS_LONG = 2;
10
+ export declare const HAS_REASONING = 4;
11
+ /** Request i's model is models[model[i]] (-1: none named). Its numbers are values[i * STRIDE, (i + 1) * STRIDE): its
12
+ * usage (USAGE_FIELDS of them, has[i]'s HAS_* bits saying which it has), then its time (AT: atOf). */
13
+ export type Counts = {
14
+ n: number;
15
+ models: string[];
16
+ model: Int32Array;
17
+ values: Float64Array;
18
+ has: Uint8Array;
19
+ };
20
+ export declare const counts: () => Counts;
21
+ /** Request i's time: its Answer's `at` in a read of turns. */
22
+ export declare const atOf: (c: Counts, i: number) => number;
23
+ /** A request added, its model `model` and its usage `usage` (either absent), at `at` (the time a read of turns gives
24
+ * its Answer): its index. */
25
+ export declare function addRequest(c: Counts, model: string | undefined, usage: Usage | undefined, at: number): number;
26
+ /** Request i's usage, now `usage`. */
27
+ export declare function setUsage(c: Counts, i: number, usage: Usage): void;
28
+ /** `c` with room for its requests alone, as a cursor keeps it: no slots to grow into (a file of a few requests would
29
+ * carry 16), which a read resumed from it makes again as it adds. */
30
+ export declare const trimmed: (c: Counts) => Counts;
package/dist/counts.js ADDED
@@ -0,0 +1,55 @@
1
+ /** A request's usage numbers: input, output, cacheRead, cacheWrite, cacheWrite1h, reasoning. */
2
+ export const USAGE_FIELDS = 6;
3
+ /** Where a request's time is in its stride, after its usage numbers. */
4
+ export const AT = USAGE_FIELDS;
5
+ /** A request's numbers in Counts.values: its usage numbers, then its time. */
6
+ export const STRIDE = USAGE_FIELDS + 1;
7
+ export const HAS_USAGE = 1;
8
+ export const HAS_LONG = 2;
9
+ export const HAS_REASONING = 4;
10
+ export const counts = () => ({ n: 0, models: [], model: new Int32Array(16), values: new Float64Array(16 * STRIDE), has: new Uint8Array(16) });
11
+ /** Request i's time: its Answer's `at` in a read of turns. */
12
+ export const atOf = (c, i) => c.values[i * STRIDE + AT];
13
+ /** A request added, its model `model` and its usage `usage` (either absent), at `at` (the time a read of turns gives
14
+ * its Answer): its index. */
15
+ export function addRequest(c, model, usage, at) {
16
+ if (c.n === c.model.length) {
17
+ // Doubled; from 16 when it held none, or was trimmed to its requests (a cursor's, trimmed).
18
+ const size = Math.max(16, c.n * 2);
19
+ const models = new Int32Array(size);
20
+ models.set(c.model);
21
+ c.model = models;
22
+ const values = new Float64Array(size * STRIDE);
23
+ values.set(c.values);
24
+ c.values = values;
25
+ const has = new Uint8Array(size);
26
+ has.set(c.has);
27
+ c.has = has;
28
+ }
29
+ const i = c.n++;
30
+ let m = -1;
31
+ if (model !== undefined) {
32
+ m = c.models.indexOf(model);
33
+ if (m === -1)
34
+ m = c.models.push(model) - 1;
35
+ }
36
+ c.model[i] = m;
37
+ c.values[i * STRIDE + AT] = at;
38
+ if (usage)
39
+ setUsage(c, i, usage);
40
+ return i;
41
+ }
42
+ /** Request i's usage, now `usage`. */
43
+ export function setUsage(c, i, usage) {
44
+ const o = i * STRIDE;
45
+ c.values[o] = usage.input;
46
+ c.values[o + 1] = usage.output;
47
+ c.values[o + 2] = usage.cacheRead;
48
+ c.values[o + 3] = usage.cacheWrite;
49
+ c.values[o + 4] = usage.cacheWrite1h ?? 0;
50
+ c.values[o + 5] = usage.reasoning ?? 0;
51
+ c.has[i] = HAS_USAGE | (usage.cacheWrite1h !== undefined ? HAS_LONG : 0) | (usage.reasoning !== undefined ? HAS_REASONING : 0);
52
+ }
53
+ /** `c` with room for its requests alone, as a cursor keeps it: no slots to grow into (a file of a few requests would
54
+ * carry 16), which a read resumed from it makes again as it adds. */
55
+ export const trimmed = (c) => ({ n: c.n, models: c.models, model: c.model.slice(0, c.n), values: c.values.slice(0, c.n * STRIDE), has: c.has.slice(0, c.n) });
package/dist/home.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type Readers } from "./read.js";
3
3
  import { type Env } from "./reader.js";
4
4
  import { type Source } from "./readers/index.js";
5
5
  import { type RecordIndex } from "./record-index.js";
6
+ import type { Usage } from "./types.js";
6
7
  import { type Tokens } from "./usage.js";
7
8
  export type SessionTotals = {
8
9
  /** The sha256 (hex) of the session's first file's path relative to the home, with "/" between its parts, and
@@ -29,10 +30,12 @@ export type SessionTotals = {
29
30
  };
30
31
  /** What parseHome keeps between passes, when handed one: each locator's cursor (its reader's own), the records each
31
32
  * source has read with the locator that read each first, and which locators found a record another read first, so a
32
- * second pass reads only what was written since. It holds no session text (its reads are turns: false: counts, ids and
33
- * paths alone), so it can be kept with v8.serialize. Its contents are the package's; `read` is the last pass's bytes. A
34
- * source's part kept by an earlier version of another shape is set aside, and that source read again from its start. */
33
+ * second pass reads only what was written since. It holds no session text (its reads are turns: false and totals: counts,
34
+ * ids and paths alone, each request as its model, usage and time), so it can be kept with v8.serialize. Its contents are the
35
+ * package's; `read` is the last pass's bytes, `version` the shape's. A state of another version (or of none, an earlier
36
+ * one's) is set aside, and every source read again from its start. */
35
37
  export type HomeState = {
38
+ version?: number;
36
39
  read?: number;
37
40
  sources?: Partial<Record<string, SourceState>>;
38
41
  };
@@ -60,6 +63,17 @@ export type ParseOptions = {
60
63
  /** Where each locator its reader could not read goes (unopenable, an I/O error midway); the rest are totalled. Without
61
64
  * it, parseHome throws ReadFailures instead: an unreadable file is never taken for an empty one. */
62
65
  failures?: ReadFailure[];
66
+ /** Called with each session as it is totalled: its totals, and its requests (its subagents' with them, each once) with
67
+ * their times and models, text-free as the totals are. `started`: the time (ms) of the first request of the session's
68
+ * own files (not its subagents'), absent when it has none. For a caller that buckets the same numbers (wrapped.ts). */
69
+ requests?: (totals: SessionTotals, requests: readonly SessionRequest[], started: number | undefined) => void;
70
+ };
71
+ /** One model request of a session: when (ms), by which model ("provider/model", the session's when the request names none),
72
+ * and its tokens where the source counted them. */
73
+ export type SessionRequest = {
74
+ at: number;
75
+ model?: string;
76
+ usage?: Usage;
63
77
  };
64
78
  /** A locator its reader could not read: its key (as SessionTotals'), its file, and the reader's error. */
65
79
  export type ReadFailure = {
@@ -75,5 +89,5 @@ export declare class ReadFailures extends Error {
75
89
  constructor(failures: ReadFailure[]);
76
90
  }
77
91
  /** Every session of `sources` under `home`, as totals, sorted by key. */
78
- export declare function parseHome(home: string, { sources, readers, state, catalog, calculateCost, env, failures }?: ParseOptions): Promise<SessionTotals[]>;
92
+ export declare function parseHome(home: string, { sources, readers, state, catalog, calculateCost, env, failures, requests }?: ParseOptions): Promise<SessionTotals[]>;
79
93
  export {};
package/dist/home.js CHANGED
@@ -7,9 +7,12 @@ import { builtinCatalog, priceRequests } from "./price.js";
7
7
  import { childrenOf, inOrder, readerOf, sessionLocators } from "./read.js";
8
8
  import { locatorKey } from "./reader.js";
9
9
  import { READERS, SOURCES } from "./readers/index.js";
10
- import { addAll, addRecord, dropOwner, isRecordIndex, locatorNumber, ownerOf, recordIndex } from "./record-index.js";
10
+ import { AT, HAS_LONG, HAS_REASONING, HAS_USAGE, STRIDE, USAGE_FIELDS } from "./counts.js";
11
+ import { addAll, addRecord, dropOwner, locatorNumber, ownerOf, recordIndex } from "./record-index.js";
11
12
  import { packed, packInto } from "./record-key.js";
12
13
  import { addTokens, noTokens } from "./usage.js";
14
+ /** The shape of the HomeState this version keeps: a state of any other is set aside. */
15
+ const STATE_VERSION = 1;
13
16
  /** What parseHome throws when a locator could not be read and the caller took no failures list. Its message names no
14
17
  * path; `failures` holds them. */
15
18
  export class ReadFailures extends Error {
@@ -26,17 +29,42 @@ const keyOf = (home, { file, id }) => {
26
29
  const path = relative(home, file).split(sep).join("/");
27
30
  return { key: createHash("sha256").update(id === undefined ? path : `${path}#${id}`).digest("hex"), file: path };
28
31
  };
29
- const USAGE_FIELDS = 6;
30
- const HAS_USAGE = 1;
31
- const HAS_LONG = 2;
32
- const HAS_REASONING = 4;
33
32
  /** `read` as a total takes it (Compact), each request's model the one totalsOf prices it at. */
34
33
  function compact(read, models) {
35
34
  const { id, child, parent, users, copies, costUsd, model } = read.session;
35
+ const { counts } = read;
36
+ if (counts) {
37
+ // A totals read's requests, as read: each one's model mapped to the pass's (its own, else the session's).
38
+ const intern = (name) => {
39
+ if (name === undefined)
40
+ return -1;
41
+ let at = models.index.get(name);
42
+ if (at === undefined)
43
+ models.index.set(name, (at = models.names.push(name) - 1));
44
+ return at;
45
+ };
46
+ const names = counts.models.map(intern);
47
+ const fallback = intern(model);
48
+ // Each request's usage numbers, and apart from them its time (counts' stride is STRIDE, the time at AT).
49
+ const usage = new Float64Array(counts.n * USAGE_FIELDS);
50
+ const at = new Float64Array(counts.n);
51
+ for (let i = 0; i < counts.n; i += 1) {
52
+ usage.set(counts.values.subarray(i * STRIDE, i * STRIDE + USAGE_FIELDS), i * USAGE_FIELDS);
53
+ at[i] = counts.values[i * STRIDE + AT];
54
+ }
55
+ return {
56
+ session: { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) },
57
+ models: counts.model.slice(0, counts.n).map((at) => (at === -1 ? fallback : names[at])),
58
+ usage,
59
+ has: counts.has.slice(0, counts.n),
60
+ at,
61
+ };
62
+ }
36
63
  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) };
64
+ const out = { session: { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) }, models: new Int32Array(n), usage: new Float64Array(n * USAGE_FIELDS), has: new Uint8Array(n), at: new Float64Array(n) };
38
65
  for (let i = 0; i < n; i += 1) {
39
66
  const request = read.requests[i];
67
+ out.at[i] = request.at;
40
68
  const name = request.model ?? model;
41
69
  let at = -1;
42
70
  if (name !== undefined) {
@@ -66,33 +94,39 @@ function compact(read, models) {
66
94
  }
67
95
  return out;
68
96
  }
69
- /** The i-th request of `read` as priceRequests takes it. */
97
+ /** The i-th request of `read` as priceRequests and the requests sink take it. */
70
98
  function requestAt(read, i, models) {
71
- const at = read.models[i];
72
- const model = at === -1 ? undefined : models.names[at];
99
+ const index = read.models[i];
100
+ const model = index === -1 ? undefined : models.names[index];
101
+ const request = { at: read.at[i], ...(model !== undefined ? { model } : {}) };
73
102
  const has = read.has[i];
74
103
  if (!(has & HAS_USAGE))
75
- return { model, usage: undefined };
104
+ return request;
76
105
  const o = i * USAGE_FIELDS;
77
106
  const usage = { input: read.usage[o], output: read.usage[o + 1], cacheRead: read.usage[o + 2], cacheWrite: read.usage[o + 3] };
78
107
  if (has & HAS_LONG)
79
108
  usage.cacheWrite1h = read.usage[o + 4];
80
109
  if (has & HAS_REASONING)
81
110
  usage.reasoning = read.usage[o + 5];
82
- return { model, usage };
111
+ return { ...request, usage };
83
112
  }
84
113
  /** 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 } = {}) {
114
+ export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests } = {}) {
86
115
  let prices;
87
116
  const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
88
117
  const out = [];
89
118
  const failed = [];
90
- if (state)
119
+ if (state) {
120
+ if (state.version !== STATE_VERSION) {
121
+ state.version = STATE_VERSION;
122
+ state.sources = {};
123
+ }
91
124
  state.read = 0;
125
+ }
92
126
  for (const source of sources) {
93
127
  const models = { names: [], index: new Map() };
94
128
  const { tops, children, unread } = await readSource(home, source, readers, env, state, models);
95
- out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost)));
129
+ out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost, requests)));
96
130
  failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
97
131
  }
98
132
  if (failed.length && !failures)
@@ -116,9 +150,9 @@ async function readSource(home, source, readers, env, state, models) {
116
150
  const outOfOrder = (kept) => [...kept.copied].some(([key, owners]) => [...owners].some((owner) => place.get(owner) > place.get(key)));
117
151
  for (let pass = 0;; pass += 1) {
118
152
  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)))
153
+ // A source's state whose files changed so (a locator gone, a copy now before its record's) is set aside: the source is
154
+ // read from its start and its state rebuilt.
155
+ if (kept && ([...kept.cursors.keys()].some((key) => !place.has(key)) || outOfOrder(kept)))
122
156
  kept = undefined;
123
157
  if (state && !kept)
124
158
  kept = state.sources[source] = { cursors: new Map(), owners: recordIndex(), copied: new Map() };
@@ -131,16 +165,14 @@ async function readSource(home, source, readers, env, state, models) {
131
165
  // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. Both are
132
166
  // staged and kept only when the read succeeds: a read that fails partway leaves no record owned that no cursor
133
167
  // 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.
168
+ // Records are held by their packed keys (packInto), each packed as it is asked for.
135
169
  const me = locatorNumber(owners, key);
136
170
  const mine = recordIndex(64);
137
171
  const found = new Set();
138
- let asked;
139
172
  const at = packed();
140
- const pack = (record) => (record === asked ? at : ((asked = record), packInto(record, at)));
141
173
  const seen = {
142
174
  has: (record) => {
143
- pack(record);
175
+ packInto(record, at);
144
176
  let owner = ownerOf(owners, at);
145
177
  if (owner === -1)
146
178
  owner = ownerOf(mine, at);
@@ -151,13 +183,13 @@ async function readSource(home, source, readers, env, state, models) {
151
183
  return true;
152
184
  },
153
185
  add(record) {
154
- pack(record);
186
+ packInto(record, at);
155
187
  if (ownerOf(owners, at) === -1)
156
188
  addRecord(mine, at, me);
157
189
  return this;
158
190
  },
159
191
  };
160
- const result = await reader.read(locator, cursor, { turns: false, seen }).catch((error) => void unread.push({ locator, error }));
192
+ const result = await reader.read(locator, cursor, { turns: false, totals: true, seen }).catch((error) => void unread.push({ locator, error }));
161
193
  if (!result) {
162
194
  // A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
163
195
  // would hold none of them: the next pass reads it from its start. A locator that found them already read (a
@@ -183,7 +215,9 @@ async function readSource(home, source, readers, env, state, models) {
183
215
  return result.sessions;
184
216
  };
185
217
  const tops = [];
186
- // Each locator's sessions packed as soon as they are read: only one locator's requests are ever held whole.
218
+ // Each locator's sessions packed as soon as they are read. A totals read gives each request's counts alone, and its
219
+ // cursor, kept in a state between passes, holds those too: no request is held as an object, by a pass or a state. A
220
+ // reader with no totals read gives its requests whole: only one locator's are held so at a time.
187
221
  for (const { locator } of listed)
188
222
  for (const session of await read(locator))
189
223
  tops.push({ locator: session.locator, read: compact(session, models) });
@@ -198,7 +232,7 @@ async function readSource(home, source, readers, env, state, models) {
198
232
  state.sources[source] = undefined;
199
233
  }
200
234
  }
201
- async function totalsOf(home, source, tops, children, models, priceWith, calculateCost) {
235
+ async function totalsOf(home, source, tops, children, models, priceWith, calculateCost, sink) {
202
236
  // Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
203
237
  // parent's, as is each one beside a session's (Claude Code's subagents).
204
238
  const sessions = new Map();
@@ -270,7 +304,7 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
270
304
  cost = catalog ? await priceRequests(requests, catalog, calculateCost) : undefined;
271
305
  }
272
306
  const { key, file } = keyOf(home, first.locator);
273
- out.push({
307
+ const totals = {
274
308
  key,
275
309
  file,
276
310
  source,
@@ -283,7 +317,12 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
283
317
  turns: untied || parts.every(({ read }) => read.session.child) ? 0 : parts.reduce((n, { read }) => n + read.session.users, 0),
284
318
  calls,
285
319
  subagents: subagents.length,
286
- });
320
+ };
321
+ out.push(totals);
322
+ if (sink) {
323
+ const times = parts.flatMap(({ read }) => Array.from(read.at)).filter(Number.isFinite);
324
+ sink(totals, requests, times.reduce((least, at) => (least === undefined || at < least ? at : least), undefined));
325
+ }
287
326
  }
288
327
  return out;
289
328
  }
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  export type { Answer, Ended, ToolCall, Turn, Usage } from "./types.js";
2
2
  export { ACTIVE_GAP_MS } from "./types.js";
3
3
  export { mostEffortOf, personsWords } from "./text.js";
4
- export { addTokens, noTokens, normalizeUsage, type Tokens, type UsageFormat } from "./usage.js";
4
+ export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat } from "./usage.js";
5
+ export { atOf, type Counts } from "./counts.js";
5
6
  export { type Env, type Locator, locatorKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
6
7
  export { type FileCursor, type LineSource, lineReader, type ReadContext, type ReadState } from "./lines.js";
7
8
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES, type Source } from "./readers/index.js";
8
9
  export { childrenOf, inOrder, locatorOf, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
9
10
  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";
11
+ export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals } from "./home.js";
12
+ export { type Wrapped, wrappedHome } from "./wrapped.js";
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  export { ACTIVE_GAP_MS } from "./types.js";
2
2
  export { mostEffortOf, personsWords } from "./text.js";
3
- export { addTokens, noTokens, normalizeUsage } from "./usage.js";
3
+ export { addTokens, noTokens, normalizeUsage, otelUsage } from "./usage.js";
4
+ export { atOf } from "./counts.js";
4
5
  export { locatorKey } from "./reader.js";
5
6
  export { lineReader } from "./lines.js";
6
7
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES } from "./readers/index.js";
7
8
  export { childrenOf, inOrder, locatorOf, readerOf, readSession, sessionLocators } from "./read.js";
8
9
  export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
9
10
  export { parseHome, ReadFailures } from "./home.js";
11
+ export { wrappedHome } from "./wrapped.js";
package/dist/lines.d.ts CHANGED
@@ -1,8 +1,9 @@
1
+ import { type Counts } from "./counts.js";
1
2
  import { type Env, type Reader } from "./reader.js";
2
3
  import { type Answer, type SessionOf, type Turn } from "./types.js";
3
4
  /** 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
5
  * 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
+ * a total counts; a totals read's are in `counts` instead, each its model, usage and time alone. `own` is the source's own (LineSource.start). A turns: true read's holds the session's text (its
6
7
  * turns, prompts, titles, tool output, working directory); a turns: false read's cursor holds none of it, only counts,
7
8
  * ids and the like (see LineSource.forget). */
8
9
  export type ReadState<O = unknown> = {
@@ -22,6 +23,8 @@ export type ReadState<O = unknown> = {
22
23
  last?: number;
23
24
  activeMs: number;
24
25
  own: O;
26
+ /** A totals read's requests (ReadOptions.totals), in place of `answers`. */
27
+ counts?: Counts;
25
28
  /** The records seen, when the caller shares none across files. */
26
29
  seen?: Set<string>;
27
30
  };
@@ -53,6 +56,10 @@ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name"
53
56
  idOf: (file: string) => string;
54
57
  /** `own` without the session's text (prompts, titles, tool output), for the cursor of a turns: false read. */
55
58
  forget?: (own: O) => O;
59
+ /** true when a totals read (ReadOptions.totals) may keep each request's model, usage and time alone, as it is
60
+ * added: the source sets no turn's model, usage or time after adding it, or keeps its requests in `counts` itself. Without it a totals
61
+ * read is a turns: false read, its requests whole. */
62
+ totals?: true;
56
63
  };
57
64
  /** Where a read of a file stopped, and what it had read. Plain data (Maps, Sets and shared objects, no function):
58
65
  * structuredClone or v8.serialize keeps it whole. Read it through its reader alone. A turns: true read's cursor
@@ -66,8 +73,9 @@ export type FileCursor = {
66
73
  /** The last bytes before `offset` (up to 64, base64): a file rewritten in place to at least the same length no longer
67
74
  * has them there, and is read from its start. */
68
75
  mark: string;
69
- /** Whether the read kept turns: a cursor of the other kind is no place to go on from. */
76
+ /** Whether the read kept turns, and whether it was a totals read: a cursor of another kind is no place to go on from. */
70
77
  keep: boolean;
78
+ totals?: boolean;
71
79
  state: ReadState;
72
80
  };
73
81
  /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
package/dist/lines.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // takes only the bytes written since.
5
5
  import { createReadStream } from "node:fs";
6
6
  import { open } from "node:fs/promises";
7
+ import { addRequest, counts, trimmed } from "./counts.js";
7
8
  import { rememberUser } from "./reader.js";
8
9
  import { isObject, mostEffortOf, timeOf } from "./text.js";
9
10
  import { ACTIVE_GAP_MS } from "./types.js";
@@ -28,15 +29,16 @@ const overlay = (base) => {
28
29
  return { has: (key) => extra.has(key) || base.has(key), add: (key) => extra.add(key) };
29
30
  };
30
31
  /** 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
+ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true } = {}) {
32
33
  const { source } = spec;
34
+ const totals = asked && !keep && spec.totals === true;
33
35
  const handle = await open(file, "r");
34
36
  try {
35
37
  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;
38
+ const resumed = cursor !== undefined && 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;
37
39
  const state = (resumed
38
40
  ? 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() }) });
41
+ : { 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() }) });
40
42
  const context = {
41
43
  state,
42
44
  seen: seen ?? (state.seen ??= new Set()),
@@ -45,7 +47,11 @@ async function readLines(spec, file, cursor, { turns: keep = true, seen, keepsCu
45
47
  rememberUser(state.session, turn);
46
48
  if (keep)
47
49
  state.turns.push(turn);
48
- if (turn.role === "assistant")
50
+ if (turn.role !== "assistant")
51
+ return;
52
+ if (state.counts)
53
+ addRequest(state.counts, turn.model, turn.usage, turn.at);
54
+ else
49
55
  state.answers.push(turn);
50
56
  },
51
57
  };
@@ -107,11 +113,11 @@ async function readLines(spec, file, cursor, { turns: keep = true, seen, keepsCu
107
113
  const mark = await markOf(handle, offset);
108
114
  let session = finish(spec, file, state, context);
109
115
  if (!keep) {
110
- kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own };
116
+ kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own, ...(kept.counts ? { counts: trimmed(kept.counts) } : {}) };
111
117
  if (resumed)
112
118
  session = withoutText(session);
113
119
  }
114
- return { sessions: [{ locator: { file }, session, requests: state.answers }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, state: kept }, read, resumed };
120
+ return { sessions: [{ locator: { file }, session, requests: state.answers, ...(state.counts ? { counts: state.counts } : {}) }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, ...(totals ? { totals } : {}), state: kept }, read, resumed };
115
121
  }
116
122
  finally {
117
123
  await handle.close();
package/dist/reader.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Dirent } from "node:fs";
2
+ import type { Counts } from "./counts.js";
2
3
  import type { Answer, SessionOf, Turn } from "./types.js";
3
4
  /** The environment a reader may look in for its source's own directories (CLAUDE_CONFIG_DIR, CODEX_HOME). */
4
5
  export type Env = Readonly<Record<string, string | undefined>>;
@@ -10,11 +11,12 @@ export type Locator = {
10
11
  /** A locator as one string: the file, with `#id` after it when it names one. */
11
12
  export declare const locatorKey: ({ file, id }: Locator) => string;
12
13
  /** One session a read found: where it is, what it is, and every request read (each counted once), whether turns are kept
13
- * or not: what a total counts. */
14
+ * or not: what a total counts. A totals read (ReadOptions.totals) has them as `counts` alone, `requests` empty. */
14
15
  export type SessionRead<S extends string = string> = {
15
16
  locator: Locator;
16
17
  session: SessionOf<S>;
17
18
  requests: Answer[];
19
+ counts?: Counts;
18
20
  };
19
21
  export type ReadResult<S extends string = string, C = unknown> = {
20
22
  /** The locator's sessions: one for a file of one session; each in the file, or the one its id names, for a file of
@@ -30,6 +32,10 @@ export type ReadResult<S extends string = string, C = unknown> = {
30
32
  export type ReadOptions = {
31
33
  /** false keeps only what a listing shows: no turns, nor a request's text or call arguments. */
32
34
  turns?: boolean;
35
+ /** With turns false, true keeps only what parseHome totals: each request's model, usage and time, as `counts`
36
+ * (no calls, ids or keys), and no title. A reader that has no such read gives its requests as ever: a lineReader's has one when
37
+ * its LineSource says `totals: true` (Claude Code's, Codex's and pi's do). */
38
+ totals?: boolean;
33
39
  /** The records and requests an import has read already, across its files: a record in it (a copy a resumed session's
34
40
  * file carries) adds nothing, and this read's are added to it. A cursor read with one is resumed with the same one. */
35
41
  seen?: Set<string>;
@@ -1,8 +1,11 @@
1
1
  // Claude Code: ~/.claude/projects/<cwd slug>/<session id>.jsonl, its subagents' in <session id>/subagents/ (children).
2
2
  import { lstat } from "node:fs/promises";
3
3
  import { basename, dirname, join } from "node:path";
4
+ import { addRequest, setUsage } from "../counts.js";
4
5
  import { lineReader } from "../lines.js";
5
6
  import { entries } from "../reader.js";
7
+ import { addRecord, ownerOf, recordIndex } from "../record-index.js";
8
+ import { packed, packInto } from "../record-key.js";
6
9
  import { argsOf, effortOf, INTERRUPTED, isObject, str, textOf } from "../text.js";
7
10
  import { normalizeUsage } from "../usage.js";
8
11
  // The titles Claude Code writes into a session's file, each again as it changes, and the field each holds it in.
@@ -32,9 +35,10 @@ const keyOf = (message, value) => {
32
35
  const request = str(value.requestId);
33
36
  return id && request ? `${id}:${request}` : id;
34
37
  };
38
+ const PACKED = packed();
35
39
  /** Claude Code's record; false for one read already (the import's earlier file, or this file's own repeat). */
36
40
  function record(value, at, { state, seen, keep, add }) {
37
- const { session, names, own } = state;
41
+ const { session, names, own, counts } = state;
38
42
  // Claude Code names a session's file for its id (<id>.jsonl): the file's own, whatever a record in it says. A resumed
39
43
  // session's file can open with records copied from the session it resumed, each still naming that one.
40
44
  if (!session.id)
@@ -43,9 +47,10 @@ function record(value, at, { state, seen, keep, add }) {
43
47
  session.cwd = value.cwd;
44
48
  if (value.isSidechain === true)
45
49
  session.child = true;
50
+ // A totals read keeps no title, nor the uuids a summary's is checked against.
46
51
  if (TITLES.has(value.type))
47
- return titleRecord(value, session, own.titles);
48
- if (str(value.uuid))
52
+ return counts ? undefined : titleRecord(value, session, own.titles);
53
+ if (str(value.uuid) && !counts)
49
54
  own.titles.uuids.add(value.uuid);
50
55
  if (value.type === "cost-state") {
51
56
  // The last one is the session's: unknown when the CLI could not price a model it used.
@@ -83,8 +88,10 @@ function record(value, at, { state, seen, keep, add }) {
83
88
  name: String(b.name ?? ""),
84
89
  arguments: keep ? argsOf(b.input) : {},
85
90
  }));
86
- for (const call of calls)
87
- names.set(call.id, call.name);
91
+ // A tool's name is for its result's turn: none is kept without turns.
92
+ if (keep)
93
+ for (const call of calls)
94
+ names.set(call.id, call.name);
88
95
  // The CLI's own turns (model <synthetic>): one marked an API error is a request that failed; any other ("No response
89
96
  // requested.") is no request, kept as the CLI's note.
90
97
  const failed = value.isApiErrorMessage === true;
@@ -99,6 +106,31 @@ function record(value, at, { state, seen, keep, add }) {
99
106
  // stream's start): the last line's usage is the request's.
100
107
  const key = keyOf(message, value);
101
108
  const usage = normalizeUsage("anthropic", message.usage);
109
+ if (counts) {
110
+ // A totals read: the request's model, usage and time alone, its later lines' usage over it, as below.
111
+ // Started small: a session's file often holds a request or two, and its cursor keeps the index.
112
+ const indexes = (own.indexes ??= recordIndex(2));
113
+ const packed = key ? packInto(key, PACKED) : undefined;
114
+ const index = packed ? ownerOf(indexes, packed) : -1;
115
+ if (index !== -1) {
116
+ if (usage)
117
+ setUsage(counts, index, usage);
118
+ return;
119
+ }
120
+ if (key && (seen.has(`m:${key}`) || (str(message.id) && seen.has(`l:${message.id}`)))) {
121
+ for (const call of calls)
122
+ own.copied.add(call.id);
123
+ return false;
124
+ }
125
+ if (!key && !text && calls.length === 0)
126
+ return;
127
+ const added = addRequest(counts, session.model, usage, at);
128
+ if (packed) {
129
+ addRecord(indexes, packed, added);
130
+ seen.add(`m:${key}`);
131
+ }
132
+ return;
133
+ }
102
134
  const held = key ? own.keyed.get(key) : undefined;
103
135
  if (held) {
104
136
  if (keep)
@@ -225,6 +257,7 @@ const spec = {
225
257
  children: childFiles,
226
258
  start: () => ({ keyed: new Map(), copied: new Set(), titles: { summaries: [], uuids: new Set() } }),
227
259
  record,
260
+ totals: true,
228
261
  finish(out, turns, { state: { own } }) {
229
262
  const { titles } = own;
230
263
  const sourceTitle = titles.custom ?? titles.ai ?? titles.summaries.findLast(({ leaf }) => leaf === undefined || titles.uuids.has(leaf))?.title;
@@ -1,5 +1,6 @@
1
1
  // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. A subagent's thread names its parent in its session_meta.
2
2
  import { basename, join } from "node:path";
3
+ import { addRequest, setUsage } from "../counts.js";
3
4
  import { lineReader } from "../lines.js";
4
5
  import { entries, rememberUser } from "../reader.js";
5
6
  import { argsOf, effortOf, isObject, str, textOf } from "../text.js";
@@ -50,7 +51,7 @@ function codexFailed(output) {
50
51
  return undefined;
51
52
  }
52
53
  function record(value, at, { state, keep, add }) {
53
- const { session, names, turns, own: codex } = state;
54
+ const { session, names, turns, own: codex, counts } = state;
54
55
  const payload = isObject(value.payload) ? value.payload : {};
55
56
  // One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
56
57
  // compaction's, one whose output is no item read here) is a turn of its own.
@@ -70,6 +71,22 @@ function record(value, at, { state, keep, add }) {
70
71
  turn.key = response;
71
72
  codex.open = codex.unpaid = undefined;
72
73
  };
74
+ // A totals read's: the same, each request its model, usage and time alone.
75
+ const answerAt = () => addRequest(counts, session.model, undefined, at);
76
+ const requestAt = () => {
77
+ if (codex.openAt === undefined) {
78
+ codex.openAt = codex.unpaidAt = answerAt();
79
+ codex.openCalls = [];
80
+ }
81
+ return codex.openAt;
82
+ };
83
+ const answeredAt = (usage) => {
84
+ const tokens = normalizeUsage("openai", usage);
85
+ const index = codex.unpaidAt ?? answerAt();
86
+ if (tokens)
87
+ setUsage(counts, index, tokens);
88
+ codex.openAt = codex.unpaidAt = undefined;
89
+ };
73
90
  if (value.type === "session_meta") {
74
91
  if (str(payload.id))
75
92
  session.id = payload.id;
@@ -94,6 +111,7 @@ function record(value, at, { state, keep, add }) {
94
111
  state.effort = effortOf(payload.effort);
95
112
  // A new turn: a request left open (aborted) has no usage to come.
96
113
  codex.open = codex.unpaid = undefined;
114
+ codex.openAt = codex.unpaidAt = undefined;
97
115
  return;
98
116
  }
99
117
  // Each request's usage: a token_usage_record per response where the rollout has them (they also count requests no
@@ -106,7 +124,7 @@ function record(value, at, { state, keep, add }) {
106
124
  return;
107
125
  if (id)
108
126
  codex.responses.add(id);
109
- return answered(payload.usage, id);
127
+ return counts ? answeredAt(payload.usage) : answered(payload.usage, id);
110
128
  }
111
129
  if (value.type === "event_msg") {
112
130
  if (payload.type === "user_message") {
@@ -122,9 +140,15 @@ function record(value, at, { state, keep, add }) {
122
140
  if (total !== undefined && total === codex.total)
123
141
  return;
124
142
  codex.total = total;
125
- answered(info.last_token_usage);
143
+ if (counts)
144
+ answeredAt(info.last_token_usage);
145
+ else
146
+ answered(info.last_token_usage);
126
147
  }
127
148
  else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
149
+ // Whether a call failed is its result's turn's: none is kept without turns.
150
+ if (!keep)
151
+ return;
128
152
  // An item's id is its call's in some Codex versions: its status then says whether the call failed.
129
153
  const { id, status, exit_code: code } = payload.item;
130
154
  const failed = status === "failed" || (typeof code === "number" && code !== 0) ? true : status === "completed" ? false : undefined;
@@ -152,19 +176,28 @@ function record(value, at, { state, keep, add }) {
152
176
  }
153
177
  else if (payload.type === "message" && payload.role === "assistant") {
154
178
  const text = textOf(payload.content);
155
- if (text) {
179
+ if (text && counts)
180
+ requestAt();
181
+ else if (text) {
156
182
  const turn = request();
157
183
  if (keep)
158
184
  turn.text = [turn.text, text].filter(Boolean).join("\n");
159
185
  }
160
186
  }
187
+ else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type) && counts) {
188
+ requestAt();
189
+ if (payload.type === "function_call" || payload.type === "custom_tool_call")
190
+ codex.openCalls.push(String(payload.call_id ?? payload.id ?? ""));
191
+ }
161
192
  else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
162
193
  const turn = request();
163
194
  if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
164
195
  return;
165
196
  const id = String(payload.call_id ?? payload.id ?? "");
166
197
  const name = String(payload.name ?? "");
167
- names.set(id, name);
198
+ // A tool's name is for its result's turn: none is kept without turns.
199
+ if (keep)
200
+ names.set(id, name);
168
201
  turn.calls.push({
169
202
  type: "toolCall",
170
203
  id,
@@ -174,11 +207,16 @@ function record(value, at, { state, keep, add }) {
174
207
  }
175
208
  else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
176
209
  const id = String(payload.call_id ?? "");
177
- const output = isObject(payload.output) && "content" in payload.output ? payload.output.content : payload.output;
178
- const stated = codexFailed(payload.output);
179
210
  // The model saw a result: what it writes next is another request.
180
211
  if (codex.open?.calls.some((call) => call.id === id))
181
212
  codex.open = undefined;
213
+ if (codex.openAt !== undefined && codex.openCalls.includes(id))
214
+ codex.openAt = undefined;
215
+ // A result is a turn alone (no count): none is kept without turns.
216
+ if (!keep)
217
+ return;
218
+ const output = isObject(payload.output) && "content" in payload.output ? payload.output.content : payload.output;
219
+ const stated = codexFailed(payload.output);
182
220
  const turn = {
183
221
  role: "toolResult",
184
222
  callId: id,
@@ -212,6 +250,7 @@ const spec = {
212
250
  },
213
251
  start: () => ({ events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() }),
214
252
  record,
253
+ totals: true,
215
254
  // Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
216
255
  // writes the user message alone. One source per file, so no turn counts twice.
217
256
  finish(out, turns, { state: { own }, keep }) {
@@ -94,6 +94,7 @@ const spec = {
94
94
  },
95
95
  start: () => undefined,
96
96
  record,
97
+ totals: true,
97
98
  idOf: (file) => basename(file, ".jsonl").split("_").pop(),
98
99
  };
99
100
  export const pi = lineReader(spec);
@@ -25,12 +25,8 @@ export type RecordIndex = {
25
25
  };
26
26
  /** An empty index, its slots `slots` (a power of 2) to start with. */
27
27
  export declare const recordIndex: (slots?: number) => RecordIndex;
28
- /** Whether `value` is a RecordIndex: a HomeState kept by an earlier version holds its records in a Map instead. */
29
- export declare function isRecordIndex(value: unknown): value is RecordIndex;
30
28
  /** The number of `locator` in `index`, given one when it has none. */
31
29
  export declare function locatorNumber(index: RecordIndex, locator: string): number;
32
- /** How many records `index` holds. */
33
- export declare const recordCount: (index: RecordIndex) => number;
34
30
  /** The owner (its number) of the record packed as `key`, else -1. */
35
31
  export declare function ownerOf(index: RecordIndex, { bytes, length }: Packed): number;
36
32
  /** The record packed as `key` added, owned by `owner` (a number of the index the owners refer to); one held already is
@@ -13,11 +13,6 @@ export const recordIndex = (slots = 1024) => ({
13
13
  locators: [],
14
14
  numbers: new Map(),
15
15
  });
16
- /** Whether `value` is a RecordIndex: a HomeState kept by an earlier version holds its records in a Map instead. */
17
- export function isRecordIndex(value) {
18
- const index = value;
19
- return typeof index === "object" && index !== null && index.uuids?.slots instanceof Int32Array && index.others?.bytes instanceof Uint8Array && Array.isArray(index.locators) && index.numbers instanceof Map;
20
- }
21
16
  /** The number of `locator` in `index`, given one when it has none. */
22
17
  export function locatorNumber(index, locator) {
23
18
  let n = index.numbers.get(locator);
@@ -25,8 +20,6 @@ export function locatorNumber(index, locator) {
25
20
  index.numbers.set(locator, (n = index.locators.push(locator) - 1));
26
21
  return n;
27
22
  }
28
- /** How many records `index` holds. */
29
- export const recordCount = (index) => index.uuids.count + index.others.count;
30
23
  // murmur3's finalizer: every bit of the input moves the slot.
31
24
  const mix = (h) => {
32
25
  h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
@@ -7,5 +7,3 @@ export type Packed = {
7
7
  export declare const packed: () => Packed;
8
8
  /** `key` packed into `out`, its buffer grown when the key needs more. */
9
9
  export declare function packInto(key: string, out: Packed): Packed;
10
- /** `key` packed, as bytes of its own. */
11
- export declare const packKey: (key: string) => Uint8Array;
@@ -91,8 +91,3 @@ export function packInto(key, out) {
91
91
  out.length = 1 + key.length * 2;
92
92
  return out;
93
93
  }
94
- /** `key` packed, as bytes of its own. */
95
- export const packKey = (key) => {
96
- const { bytes, length } = packInto(key, packed());
97
- return bytes.slice(0, length);
98
- };
package/dist/usage.d.ts CHANGED
@@ -1,9 +1,20 @@
1
1
  import type { Usage } from "./types.js";
2
- export type UsageFormat = "anthropic" | "openai" | "pi";
2
+ export type UsageFormat = "anthropic" | "openai" | "pi" | "openrouter";
3
3
  /** A request's usage as `format` writes it, as Usage; undefined unless input and output are counts (an absent cache
4
4
  * count is 0) and the input left is not negative. The 1h part of the cache write, or the reasoning part of the output,
5
5
  * is kept only when it is a count of at most the whole. */
6
6
  export declare function normalizeUsage(format: UsageFormat, raw: unknown): Usage | undefined;
7
+ /** A request's tokens as an OpenTelemetry GenAI span carries them: `input` INCLUSIVE of the cache (the uncached input, the
8
+ * cache read and the cache write together), as gen_ai.usage.input_tokens is defined and as Sentry reads it (it takes
9
+ * the cache counts out of it again, so an exclusive figure would go negative). The other counts as Usage has them. */
10
+ export type OtelUsage = {
11
+ input: number;
12
+ output: number;
13
+ cacheRead: number;
14
+ cacheWrite: number;
15
+ reasoning?: number;
16
+ };
17
+ export declare function otelUsage(usage: Usage): OtelUsage;
7
18
  /** The buckets a total of requests keeps, each a sum; cacheWrite1h is 0 when no request named one. */
8
19
  export type Tokens = {
9
20
  input: number;
package/dist/usage.js CHANGED
@@ -4,14 +4,21 @@
4
4
  // openai input_tokens holds cached_input_tokens (and a cache write where one is counted): subtracted. output_tokens
5
5
  // holds reasoning_output_tokens, kept as `reasoning` beside it. Codex writes OpenAI's counts.
6
6
  // pi already split as Usage is, cacheWrite1h included.
7
+ // openrouter Chat Completions' names: prompt_tokens holds prompt_tokens_details.cached_tokens and .cache_write_tokens,
8
+ // subtracted; completion_tokens holds completion_tokens_details.reasoning_tokens, kept beside it.
9
+ // A trace exporter's figure is otelUsage's: the same counts, its input inclusive of the cache.
7
10
  import { isObject } from "./text.js";
8
- /** Each format's names for input, cache read, cache write and output, and whether its input holds its cache counts. */
11
+ /** Each format's names for input, cache read, cache write, output and the reasoning part of the output (a dotted name is
12
+ * a nested one), and whether its input holds its cache counts. */
9
13
  const NAMES = {
10
14
  anthropic: { input: "input_tokens", cacheRead: "cache_read_input_tokens", cacheWrite: "cache_creation_input_tokens", output: "output_tokens", cachedIn: false },
11
- openai: { input: "input_tokens", cacheRead: "cached_input_tokens", cacheWrite: "cache_write_input_tokens", output: "output_tokens", cachedIn: true },
15
+ openai: { input: "input_tokens", cacheRead: "cached_input_tokens", cacheWrite: "cache_write_input_tokens", output: "output_tokens", reasoning: "reasoning_output_tokens", cachedIn: true },
12
16
  pi: { input: "input", cacheRead: "cacheRead", cacheWrite: "cacheWrite", output: "output", cachedIn: false },
17
+ openrouter: { input: "prompt_tokens", cacheRead: "prompt_tokens_details.cached_tokens", cacheWrite: "prompt_tokens_details.cache_write_tokens", output: "completion_tokens", reasoning: "completion_tokens_details.reasoning_tokens", cachedIn: true },
13
18
  };
14
19
  const count = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : undefined);
20
+ /** The value at a dotted name in `raw`, undefined where any part is missing. */
21
+ const at = (raw, name) => name.split(".").reduce((value, part) => (isObject(value) ? value[part] : undefined), raw);
15
22
  /** A request's usage as `format` writes it, as Usage; undefined unless input and output are counts (an absent cache
16
23
  * count is 0) and the input left is not negative. The 1h part of the cache write, or the reasoning part of the output,
17
24
  * is kept only when it is a count of at most the whole. */
@@ -19,7 +26,7 @@ export function normalizeUsage(format, raw) {
19
26
  if (!isObject(raw))
20
27
  return undefined;
21
28
  const names = NAMES[format];
22
- const usage = { input: count(raw[names.input]), output: count(raw[names.output]), cacheRead: count(raw[names.cacheRead] ?? 0), cacheWrite: count(raw[names.cacheWrite] ?? 0) };
29
+ const usage = { input: count(at(raw, names.input)), output: count(at(raw, names.output)), cacheRead: count(at(raw, names.cacheRead) ?? 0), cacheWrite: count(at(raw, names.cacheWrite) ?? 0) };
23
30
  if (usage.input === undefined || usage.output === undefined || usage.cacheRead === undefined || usage.cacheWrite === undefined)
24
31
  return undefined;
25
32
  if (names.cachedIn)
@@ -30,11 +37,14 @@ export function normalizeUsage(format, raw) {
30
37
  const long = count(format === "anthropic" ? (isObject(raw.cache_creation) ? raw.cache_creation.ephemeral_1h_input_tokens : undefined) : format === "pi" ? raw.cacheWrite1h : undefined);
31
38
  if (long !== undefined && long <= out.cacheWrite)
32
39
  out.cacheWrite1h = long;
33
- const reasoning = format === "openai" ? count(raw.reasoning_output_tokens) : undefined;
40
+ const reasoning = names.reasoning === undefined ? undefined : count(at(raw, names.reasoning));
34
41
  if (reasoning !== undefined && reasoning <= out.output)
35
42
  out.reasoning = reasoning;
36
43
  return out;
37
44
  }
45
+ export function otelUsage(usage) {
46
+ return { input: usage.input + usage.cacheRead + usage.cacheWrite, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, ...(usage.reasoning === undefined ? {} : { reasoning: usage.reasoning }) };
47
+ }
38
48
  export const noTokens = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cacheWrite1h: 0 });
39
49
  export function addTokens(into, usage) {
40
50
  into.input += usage.input;
@@ -0,0 +1,49 @@
1
+ import { type ParseOptions } from "./home.js";
2
+ import { type Usage } from "./types.js";
3
+ import { type Tokens } from "./usage.js";
4
+ export type Wrapped = {
5
+ year: number;
6
+ /** Sessions whose first request is in the year, their prompts (`turns`, the person's own) with them. */
7
+ sessions: number;
8
+ turns: number;
9
+ /** Requests in the year, each once, subagents' with them. */
10
+ requests: number;
11
+ tokens: Tokens;
12
+ /** List price (the catalog's) of the requests it could price, USD; `unpricedRequests` counts those it could not (an
13
+ * unlisted model, no usage), so a sum that left some out says so. */
14
+ cost: number;
15
+ unpricedRequests: number;
16
+ /** Local days with a request, ascending: that day's requests and tokens (input, output and cache together). */
17
+ days: {
18
+ day: string;
19
+ requests: number;
20
+ tokens: number;
21
+ }[];
22
+ /** Requests by local hour of the day (24) and by weekday (7, Sunday first). */
23
+ hours: number[];
24
+ weekdays: number[];
25
+ /** Time at work: the gaps between a session's requests of the year, each counted when it is under ACTIVE_GAP_MS. */
26
+ activeMs: number;
27
+ /** By reader's harness, the way serve runs it, and by model ("provider/model", "unknown" for a request naming none). */
28
+ harnesses: {
29
+ harness: string;
30
+ sessions: number;
31
+ requests: number;
32
+ tokens: number;
33
+ }[];
34
+ models: {
35
+ model: string;
36
+ requests: number;
37
+ tokens: Tokens;
38
+ cost: number;
39
+ }[];
40
+ sources: {
41
+ source: string;
42
+ sessions: number;
43
+ requests: number;
44
+ }[];
45
+ };
46
+ /** `year` under `home`, from parseHome's reads: its options (`state` and `requests` aside). */
47
+ export declare function wrappedHome(home: string, year: number, options?: Omit<ParseOptions, "state" | "requests"> & {
48
+ price?: (model: string | undefined, usage: Usage) => Promise<number | undefined> | number | undefined;
49
+ }): Promise<Wrapped>;
@@ -0,0 +1,104 @@
1
+ // A year of work under a home, as numbers: what the year used, by which harnesses and models, and when. Every figure is
2
+ // bucketed by its REQUEST's time in the machine's local zone (a session that spans New Year splits); a session counts in
3
+ // `sessions` for the year its first request falls in. Text-free as parseHome's totals are: counts, names and times only,
4
+ // never a prompt, a title, a path or a project.
5
+ import { builtinCatalog, priceRequests } from "./price.js";
6
+ import { parseHome } from "./home.js";
7
+ import { READERS } from "./readers/index.js";
8
+ import { ACTIVE_GAP_MS } from "./types.js";
9
+ import { addTokens, noTokens } from "./usage.js";
10
+ const all = (t) => t.input + t.output + t.cacheRead + t.cacheWrite;
11
+ const day = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
12
+ const by = (map, key, make) => map.get(key) ?? map.set(key, make()).get(key);
13
+ /** `year` under `home`, from parseHome's reads: its options (`state` and `requests` aside). */
14
+ export async function wrappedHome(home, year, options = {}) {
15
+ const prices = options.catalog === false ? undefined : (options.catalog ?? (await builtinCatalog()));
16
+ const out = { year, sessions: 0, turns: 0, requests: 0, tokens: noTokens(), cost: 0, unpricedRequests: 0, days: [], hours: new Array(24).fill(0), weekdays: new Array(7).fill(0), activeMs: 0, harnesses: [], models: [], sources: [] };
17
+ const days = new Map();
18
+ const harnesses = new Map();
19
+ const models = new Map();
20
+ const sources = new Map();
21
+ // The usage of each model's requests of the year, priced once the read is over (a rejection of the price then rejects
22
+ // this call, with no promise left floating), and each request that carries none, which no price can cover.
23
+ const usages = new Map();
24
+ const harnessOf = (source) => (options.readers ?? READERS)[source]?.harness ?? source;
25
+ await parseHome(home, {
26
+ ...options,
27
+ requests: (totals, requests, started) => {
28
+ const mine = requests.filter((r) => Number.isFinite(r.at) && new Date(r.at).getFullYear() === year).sort((a, b) => a.at - b.at);
29
+ const counted = started !== undefined && new Date(started).getFullYear() === year;
30
+ if (counted) {
31
+ out.sessions += 1;
32
+ out.turns += totals.turns;
33
+ by(sources, totals.source, () => ({ sessions: 0, requests: 0 })).sessions += 1;
34
+ by(harnesses, harnessOf(totals.source), () => ({ sessions: 0, requests: 0, tokens: 0 })).sessions += 1;
35
+ }
36
+ for (let i = 0; i < mine.length; i++) {
37
+ const r = mine[i];
38
+ const when = new Date(r.at);
39
+ const held = all(addTokens(noTokens(), r.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }));
40
+ out.requests += 1;
41
+ if (r.usage)
42
+ addTokens(out.tokens, r.usage);
43
+ out.hours[when.getHours()] += 1;
44
+ out.weekdays[when.getDay()] += 1;
45
+ const d = by(days, day(when), () => ({ requests: 0, tokens: 0 }));
46
+ d.requests += 1;
47
+ d.tokens += held;
48
+ by(sources, totals.source, () => ({ sessions: 0, requests: 0 })).requests += 1;
49
+ const h = by(harnesses, harnessOf(totals.source), () => ({ sessions: 0, requests: 0, tokens: 0 }));
50
+ h.requests += 1;
51
+ h.tokens += held;
52
+ const m = by(models, r.model ?? "unknown", () => ({ requests: 0, tokens: noTokens(), cost: 0 }));
53
+ m.requests += 1;
54
+ if (r.usage)
55
+ addTokens(m.tokens, r.usage);
56
+ if (i > 0 && r.at - mine[i - 1].at < ACTIVE_GAP_MS)
57
+ out.activeMs += r.at - mine[i - 1].at;
58
+ // A request with no usage (pi leaves it off an aborted request) is unpriced; known zero usage is free and priced.
59
+ if (r.usage)
60
+ by(usages, r.model ?? "unknown", () => []).push(r.usage);
61
+ else
62
+ out.unpricedRequests += 1;
63
+ }
64
+ },
65
+ });
66
+ const round = (n) => Math.round(n * 1e6) / 1e6;
67
+ // One price per model: the caller's per request, or the catalog's over all of the model's requests at once (one rounding
68
+ // of the model's sum, so many requests of a fraction of a cent each still add up). A model it cannot price leaves only
69
+ // its own requests out, counted in `unpricedRequests`.
70
+ for (const [model, list] of usages) {
71
+ const known = model === "unknown" ? undefined : model;
72
+ let usd;
73
+ // A request of known zero tokens is free at any price: it is neither priced nor counted as unpriced.
74
+ const paid = list.filter((usage) => usage.input + usage.output + usage.cacheRead + usage.cacheWrite > 0);
75
+ if (paid.length === 0)
76
+ continue;
77
+ if (options.price) {
78
+ // The caller's price answers per request: one it cannot price is left out alone.
79
+ for (const usage of paid) {
80
+ const one = await options.price(known, usage);
81
+ if (one === undefined)
82
+ out.unpricedRequests += 1;
83
+ else
84
+ usd = (usd ?? 0) + one;
85
+ }
86
+ if (usd === undefined)
87
+ continue;
88
+ }
89
+ else if (prices)
90
+ usd = await priceRequests(paid.map((usage) => ({ ...(known ? { model: known } : {}), usage })), prices);
91
+ if (usd === undefined)
92
+ out.unpricedRequests += paid.length;
93
+ else {
94
+ out.cost += usd;
95
+ models.get(model).cost = usd;
96
+ }
97
+ }
98
+ out.cost = round(out.cost);
99
+ out.days = [...days].sort(([a], [b]) => (a < b ? -1 : 1)).map(([d, v]) => ({ day: d, ...v }));
100
+ out.harnesses = [...harnesses].map(([harness, v]) => ({ harness, ...v })).sort((a, b) => b.tokens - a.tokens || (a.harness < b.harness ? -1 : 1));
101
+ out.models = [...models].map(([model, v]) => ({ model, ...v, cost: round(v.cost) })).sort((a, b) => all(b.tokens) - all(a.tokens) || (a.model < b.model ? -1 : 1));
102
+ out.sources = [...sources].map(([source, v]) => ({ source, ...v })).sort((a, b) => b.requests - a.requests || (a.source < b.source ? -1 : 1));
103
+ return out;
104
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-import",
3
- "version": "0.1.0-beta.55",
3
+ "version": "0.1.0-beta.57",
4
4
  "description": "Reads the coding-agent sessions under a home (Claude Code, Codex, pi) into one Session shape, with normalized token usage, subagents under their parent, byte-offset cursors for re-reads, and per-session totals.",
5
5
  "keywords": [
6
6
  "agentrun",