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

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
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
@@ -60,6 +61,17 @@ export type ParseOptions = {
60
61
  /** Where each locator its reader could not read goes (unopenable, an I/O error midway); the rest are totalled. Without
61
62
  * it, parseHome throws ReadFailures instead: an unreadable file is never taken for an empty one. */
62
63
  failures?: ReadFailure[];
64
+ /** Called with each session as it is totalled: its totals, and its requests (its subagents' with them, each once) with
65
+ * their times and models, text-free as the totals are. `started`: the time (ms) of the first request of the session's
66
+ * own files (not its subagents'), absent when it has none. For a caller that buckets the same numbers (wrapped.ts). */
67
+ requests?: (totals: SessionTotals, requests: readonly SessionRequest[], started: number | undefined) => void;
68
+ };
69
+ /** One model request of a session: when (ms), by which model ("provider/model", the session's when the request names none),
70
+ * and its tokens where the source counted them. */
71
+ export type SessionRequest = {
72
+ at: number;
73
+ model?: string;
74
+ usage?: Usage;
63
75
  };
64
76
  /** A locator its reader could not read: its key (as SessionTotals'), its file, and the reader's error. */
65
77
  export type ReadFailure = {
@@ -75,5 +87,5 @@ export declare class ReadFailures extends Error {
75
87
  constructor(failures: ReadFailure[]);
76
88
  }
77
89
  /** 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[]>;
90
+ export declare function parseHome(home: string, { sources, readers, state, catalog, calculateCost, env, failures, requests }?: ParseOptions): Promise<SessionTotals[]>;
79
91
  export {};
package/dist/home.js CHANGED
@@ -34,9 +34,10 @@ const HAS_REASONING = 4;
34
34
  function compact(read, models) {
35
35
  const { id, child, parent, users, copies, costUsd, model } = read.session;
36
36
  const n = read.requests.length;
37
- const out = { session: { id, child, users, copies, ...(parent !== undefined ? { parent } : {}), ...(costUsd !== undefined ? { costUsd } : {}), ...(model !== undefined ? { model } : {}) }, models: new Int32Array(n), usage: new Float64Array(n * USAGE_FIELDS), has: new Uint8Array(n) };
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), at: new Float64Array(n) };
38
38
  for (let i = 0; i < n; i += 1) {
39
39
  const request = read.requests[i];
40
+ out.at[i] = request.at;
40
41
  const name = request.model ?? model;
41
42
  let at = -1;
42
43
  if (name !== undefined) {
@@ -66,23 +67,24 @@ function compact(read, models) {
66
67
  }
67
68
  return out;
68
69
  }
69
- /** The i-th request of `read` as priceRequests takes it. */
70
+ /** The i-th request of `read` as priceRequests and the requests sink take it. */
70
71
  function requestAt(read, i, models) {
71
- const at = read.models[i];
72
- const model = at === -1 ? undefined : models.names[at];
72
+ const index = read.models[i];
73
+ const model = index === -1 ? undefined : models.names[index];
74
+ const request = { at: read.at[i], ...(model !== undefined ? { model } : {}) };
73
75
  const has = read.has[i];
74
76
  if (!(has & HAS_USAGE))
75
- return { model, usage: undefined };
77
+ return request;
76
78
  const o = i * USAGE_FIELDS;
77
79
  const usage = { input: read.usage[o], output: read.usage[o + 1], cacheRead: read.usage[o + 2], cacheWrite: read.usage[o + 3] };
78
80
  if (has & HAS_LONG)
79
81
  usage.cacheWrite1h = read.usage[o + 4];
80
82
  if (has & HAS_REASONING)
81
83
  usage.reasoning = read.usage[o + 5];
82
- return { model, usage };
84
+ return { ...request, usage };
83
85
  }
84
86
  /** 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 } = {}) {
87
+ export async function parseHome(home, { sources = SOURCES, readers = READERS, state, catalog, calculateCost, env, failures, requests } = {}) {
86
88
  let prices;
87
89
  const priceWith = () => (catalog === false ? Promise.resolve(undefined) : catalog ? Promise.resolve(catalog) : (prices ??= builtinCatalog()));
88
90
  const out = [];
@@ -92,7 +94,7 @@ export async function parseHome(home, { sources = SOURCES, readers = READERS, st
92
94
  for (const source of sources) {
93
95
  const models = { names: [], index: new Map() };
94
96
  const { tops, children, unread } = await readSource(home, source, readers, env, state, models);
95
- out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost)));
97
+ out.push(...(await totalsOf(home, source, tops, children, models, priceWith, calculateCost, requests)));
96
98
  failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
97
99
  }
98
100
  if (failed.length && !failures)
@@ -198,7 +200,7 @@ async function readSource(home, source, readers, env, state, models) {
198
200
  state.sources[source] = undefined;
199
201
  }
200
202
  }
201
- async function totalsOf(home, source, tops, children, models, priceWith, calculateCost) {
203
+ async function totalsOf(home, source, tops, children, models, priceWith, calculateCost, sink) {
202
204
  // Sessions by id, their locators in the import's order; one naming its parent (a Codex subagent's thread) is the
203
205
  // parent's, as is each one beside a session's (Claude Code's subagents).
204
206
  const sessions = new Map();
@@ -270,7 +272,7 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
270
272
  cost = catalog ? await priceRequests(requests, catalog, calculateCost) : undefined;
271
273
  }
272
274
  const { key, file } = keyOf(home, first.locator);
273
- out.push({
275
+ const totals = {
274
276
  key,
275
277
  file,
276
278
  source,
@@ -283,7 +285,12 @@ async function totalsOf(home, source, tops, children, models, priceWith, calcula
283
285
  turns: untied || parts.every(({ read }) => read.session.child) ? 0 : parts.reduce((n, { read }) => n + read.session.users, 0),
284
286
  calls,
285
287
  subagents: subagents.length,
286
- });
288
+ };
289
+ out.push(totals);
290
+ if (sink) {
291
+ const times = parts.flatMap(({ read }) => Array.from(read.at)).filter(Number.isFinite);
292
+ sink(totals, requests, times.reduce((least, at) => (least === undefined || at < least ? at : least), undefined));
293
+ }
287
294
  }
288
295
  return out;
289
296
  }
package/dist/index.d.ts CHANGED
@@ -7,4 +7,5 @@ export { type FileCursor, type LineSource, lineReader, type ReadContext, type Re
7
7
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES, type Source } from "./readers/index.js";
8
8
  export { childrenOf, inOrder, locatorOf, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
9
9
  export { builtinCatalog, type CalculateCost, type Catalog, catalogOf, type Listed, type ModelCost, type Priced, priceRequests } from "./price.js";
10
- export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionTotals } from "./home.js";
10
+ export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals } from "./home.js";
11
+ export { type Wrapped, wrappedHome } from "./wrapped.js";
package/dist/index.js CHANGED
@@ -7,3 +7,4 @@ export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES } from "./readers/index.js";
7
7
  export { childrenOf, inOrder, locatorOf, readerOf, readSession, sessionLocators } from "./read.js";
8
8
  export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
9
9
  export { parseHome, ReadFailures } from "./home.js";
10
+ export { wrappedHome } from "./wrapped.js";
@@ -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.56",
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",