@parcha/agentrun-import 0.1.0-beta.56 → 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
@@ -85,7 +85,7 @@ type Reader<S extends string, C> = {
85
85
  name: string;
86
86
  harness: string;
87
87
  discover(home: string, env?: Env): Promise<Locator[]>;
88
- 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 }>;
89
89
  order?(a, b): number;
90
90
  children?(home: string, env?: Env): Promise<{ locator: Locator; of: Locator }[]>;
91
91
  };
@@ -97,5 +97,31 @@ line read, and the read's state. A file replaced or truncated since is read from
97
97
  newline yet is read but not consumed. A source that keeps many sessions in one file (a SQLite database) implements
98
98
  `discover` and `read` itself and returns one locator per session, with its `id`.
99
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
+
100
126
  `readSession(locator, source)`, `sessionLocators(home, source)`, `inOrder(locators, source)` and
101
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
@@ -30,10 +30,12 @@ export type SessionTotals = {
30
30
  };
31
31
  /** What parseHome keeps between passes, when handed one: each locator's cursor (its reader's own), the records each
32
32
  * source has read with the locator that read each first, and which locators found a record another read first, so a
33
- * second pass reads only what was written since. It holds no session text (its reads are turns: false: counts, ids and
34
- * paths alone), so it can be kept with v8.serialize. Its contents are the package's; `read` is the last pass's bytes. A
35
- * 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. */
36
37
  export type HomeState = {
38
+ version?: number;
37
39
  read?: number;
38
40
  sources?: Partial<Record<string, SourceState>>;
39
41
  };
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,13 +29,37 @@ 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
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) {
@@ -89,8 +116,13 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
89
116
  const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
90
117
  const out = [];
91
118
  const failed = [];
92
- if (state)
119
+ if (state) {
120
+ if (state.version !== STATE_VERSION) {
121
+ state.version = STATE_VERSION;
122
+ state.sources = {};
123
+ }
93
124
  state.read = 0;
125
+ }
94
126
  for (const source of sources) {
95
127
  const models = { names: [], index: new Map() };
96
128
  const { tops, children, unread } = await readSource(home, source, readers, env, state, models);
@@ -118,9 +150,9 @@ async function readSource(home, source, readers, env, state, models) {
118
150
  const outOfOrder = (kept) => [...kept.copied].some(([key, owners]) => [...owners].some((owner) => place.get(owner) > place.get(key)));
119
151
  for (let pass = 0;; pass += 1) {
120
152
  let kept = state ? (state.sources ??= {})[source] : undefined;
121
- // A source's state of another shape (an earlier version's, its records in a Map) is set aside like one whose files
122
- // changed: the source is read from its start and its state rebuilt.
123
- 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)))
124
156
  kept = undefined;
125
157
  if (state && !kept)
126
158
  kept = state.sources[source] = { cursors: new Map(), owners: recordIndex(), copied: new Map() };
@@ -133,16 +165,14 @@ async function readSource(home, source, readers, env, state, models) {
133
165
  // The records read so far, as the reader asks for them, each new one this locator's, each found one noted. Both are
134
166
  // staged and kept only when the read succeeds: a read that fails partway leaves no record owned that no cursor
135
167
  // holds, which a retry would take for a copy.
136
- // 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.
137
169
  const me = locatorNumber(owners, key);
138
170
  const mine = recordIndex(64);
139
171
  const found = new Set();
140
- let asked;
141
172
  const at = packed();
142
- const pack = (record) => (record === asked ? at : ((asked = record), packInto(record, at)));
143
173
  const seen = {
144
174
  has: (record) => {
145
- pack(record);
175
+ packInto(record, at);
146
176
  let owner = ownerOf(owners, at);
147
177
  if (owner === -1)
148
178
  owner = ownerOf(mine, at);
@@ -153,13 +183,13 @@ async function readSource(home, source, readers, env, state, models) {
153
183
  return true;
154
184
  },
155
185
  add(record) {
156
- pack(record);
186
+ packInto(record, at);
157
187
  if (ownerOf(owners, at) === -1)
158
188
  addRecord(mine, at, me);
159
189
  return this;
160
190
  },
161
191
  };
162
- 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 }));
163
193
  if (!result) {
164
194
  // A locator read before that cannot be read now gives up its cursor and the records it held, as a fresh pass
165
195
  // would hold none of them: the next pass reads it from its start. A locator that found them already read (a
@@ -185,7 +215,9 @@ async function readSource(home, source, readers, env, state, models) {
185
215
  return result.sessions;
186
216
  };
187
217
  const tops = [];
188
- // 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.
189
221
  for (const { locator } of listed)
190
222
  for (const session of await read(locator))
191
223
  tops.push({ locator: session.locator, read: compact(session, models) });
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
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";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
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";
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-import",
3
- "version": "0.1.0-beta.56",
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",