@parcha/agentrun-import 0.1.0-beta.59 → 0.1.0-beta.61
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 +67 -10
- package/dist/cache.d.ts +90 -0
- package/dist/cache.js +266 -0
- package/dist/cli.js +34 -10
- package/dist/home.d.ts +112 -9
- package/dist/home.js +184 -109
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/internal.d.ts +18 -0
- package/dist/internal.js +12 -0
- package/dist/lines.d.ts +20 -3
- package/dist/lines.js +88 -31
- package/dist/pool-worker.js +22 -34
- package/dist/pool.d.ts +34 -8
- package/dist/pool.js +59 -14
- package/dist/read.js +4 -1
- package/dist/reader.d.ts +3 -0
- package/dist/readers/claude-code.d.ts +24 -0
- package/dist/readers/claude-code.js +77 -37
- package/dist/readers/codex.d.ts +58 -5
- package/dist/readers/codex.js +103 -73
- package/dist/readers/line-readers.d.ts +7 -0
- package/dist/readers/line-readers.js +10 -0
- package/dist/readers/pi.js +9 -2
- package/dist/record-index.d.ts +30 -3
- package/dist/record-index.js +128 -43
- package/dist/scan-wasm.d.ts +1 -0
- package/dist/scan-wasm.js +2 -0
- package/dist/scan.d.ts +21 -0
- package/dist/scan.js +164 -0
- package/dist/text.d.ts +3 -0
- package/dist/text.js +38 -2
- package/dist/types.d.ts +18 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,19 +31,20 @@ const sessions = await parseHome(homedir(), { sources: ["claude-code", "codex"]
|
|
|
31
31
|
it, parseHome throws `ReadFailures`. An unreadable file is never taken for an empty one.
|
|
32
32
|
- `env` names where a source keeps its own directory (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`, OpenCode's `XDG_DATA_HOME` and
|
|
33
33
|
`OPENCODE_DB`); without it the home's.
|
|
34
|
-
- `threads` reads the files on that many worker threads (default: the cores the process may run on
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
- `threads` reads the files on that many worker threads (default: the cores the process may run on less one, two on
|
|
35
|
+
two, at most 16, and no more than the workers whose heaps, 80 MiB each at the default `workerOldMb`, fit in the memory
|
|
36
|
+
still free (the machine's, page cache counted as free, at most its container's limit) once `readAhead` is set aside;
|
|
37
|
+
`1` reads them in order on the calling thread; at most 64). A read is kept only when it is the one the import's order
|
|
38
|
+
would make; any other file is read again in order, so the totals are the same whatever the count. A call with a
|
|
39
|
+
`state`, or with readers of its own, reads on the calling thread; so does OpenCode in any call (its sessions are rows of
|
|
40
|
+
a database, not files of lines).
|
|
38
41
|
- `readAhead` caps the bytes of finished reads waiting to be taken (default 1 GiB, or a sixteenth of the memory the
|
|
39
42
|
process may use, its container's limit when one is set, when that is less: 512 MiB at 8 GiB). Under it, files of 64 MiB and over are read first, largest first, then
|
|
40
43
|
the rest in order; at it, the threads read only the file the import waits on. It is a cap on finished reads waiting,
|
|
41
44
|
plus at most one read in flight per thread (one of those can be a giant file), not on the process's memory.
|
|
42
|
-
- `workerOldMb` caps each worker's old generation (default 64
|
|
45
|
+
- `workerOldMb` caps each worker's old generation (default 64, at least 8, refused with a RangeError under it: at 1 or
|
|
46
|
+
2 MB V8 ends the whole process as a worker starts, and at 3 to 7 the workers run out of memory). A line over an eighth of it, or a file that runs a worker
|
|
43
47
|
out of memory, is read on the calling thread instead; past two such losses a thread, the calling thread reads the rest.
|
|
44
|
-
|
|
45
|
-
On a 73.7 GB home, 8 threads took 90.9 s (median of 5) at a peak of 1.83 GiB, and 1 thread 441.1 s at 1.05 GiB
|
|
46
|
-
(x1); with `readAhead` at 256 MiB, 8 threads took 136.5 s (x1). Measured on a loaded machine (load 17 to 45).
|
|
47
48
|
- A request two sources wrote is counted once. OpenCode's claude-agent provider runs Claude Code, which writes each
|
|
48
49
|
request into its own session file too; OpenCode names that session on the request (`mirrors`). When the same call
|
|
49
50
|
reads that Claude Code session (serve's import: or its store holds it), the request counts there and not in the OpenCode session (tokens, calls and cost),
|
|
@@ -84,6 +85,61 @@ a bundle (`bun build --compile`) carries it, prints the same bytes as under Node
|
|
|
84
85
|
fails instead of pricing nothing. pi-ai is a dependency of the package, so `npx @parcha/agentrun-import` runs the
|
|
85
86
|
CLI as it is; the library loads it only to price.
|
|
86
87
|
|
|
88
|
+
## Cache breaks
|
|
89
|
+
|
|
90
|
+
```js
|
|
91
|
+
import { analyzeCache, cacheHome, readSession } from "@parcha/agentrun-import";
|
|
92
|
+
|
|
93
|
+
const session = await readSession(file, "claude-code", { chain: true });
|
|
94
|
+
const { hitRate, breaks } = await analyzeCache(session);
|
|
95
|
+
// breaks: [{ turn, at, dropPct, rewritten, extraCost, cause, diverged? }]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `hitRate` is the cache read over the whole prompt (`input + cacheRead + cacheWrite`, input already uncached), null for a
|
|
99
|
+
session that sent none.
|
|
100
|
+
- A break is a turn whose cache read dropped more than 80% (`BREAK_DROP`) against the turn before it; the first turn is
|
|
101
|
+
never one, and a drop of exactly 80% is none. A turn compared is a request with usage that sent a prompt. `turn`
|
|
102
|
+
counts the session's requests from 1; `at` is ms since the epoch; `dropPct` the share of the turn before's read lost.
|
|
103
|
+
- `rewritten`: of the read lost, the tokens the turn paid for again, as a cache write or as uncached input. `extraCost`:
|
|
104
|
+
USD, what the turn paid above reading them from the cache, at its model's list prices (pi-ai's catalog, or the
|
|
105
|
+
`catalog` handed in); null when the model is not listed or `catalog: false`.
|
|
106
|
+
- `cause`, the first of `CACHE_CAUSES` the transcript shows evidence of:
|
|
107
|
+
|
|
108
|
+
| Cause | Evidence |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `model` | the turn ran on another model than the turn before |
|
|
111
|
+
| `idle` | the gap since the turn before is past the cache's life: 5 minutes, or an hour when the latest cache write was a 1h one (`cacheWrite1h`) |
|
|
112
|
+
| `compaction` | a compaction since the turn before: Claude Code's `compact_boundary` or `isCompactSummary` record, Codex's `compacted`. It counts in the file that holds it first; across a session's files it carries to the next file's first turn, and a later file's copy of it is never consulted |
|
|
113
|
+
| `edited` | the prompt leaves the chain of the turn before (its prompt and answer) at an earlier message: `diverged` is that message's index |
|
|
114
|
+
| `sidechain` | the turn opens a sidechain after a main-chain turn (Claude Code's `isSidechain`) |
|
|
115
|
+
| `unknown` | none of the above |
|
|
116
|
+
|
|
117
|
+
`chain: true` keeps the session's `chain` beside its turns: each record's id and its parent's (Claude Code's
|
|
118
|
+
`uuid`/`parentUuid`, pi's `id`/`parentId`), a 16-hex sha256 of its content, never the content, and which record opens
|
|
119
|
+
each request. The analyzer finds an edit by comparing the hashes of the two prompts' message chains from the root. A
|
|
120
|
+
sidechain's prompt is a conversation of its own, never an edit of the main one's. A Codex rollout names no record to
|
|
121
|
+
rewind to, so a Codex break is never `edited`; pi writes no compaction or sidechain record in the sessions seen, so a pi
|
|
122
|
+
break is never `compaction` or `sidechain`. A session read without its chain names `model` and `idle` alone.
|
|
123
|
+
|
|
124
|
+
`cacheHome(home, options)` analyzes every session `parseHome` totals (the same options but `state`), keyed the same way,
|
|
125
|
+
of the sources that write a chain (`CACHE_SOURCES`: Claude Code, Codex and pi; another source is refused with a
|
|
126
|
+
`RangeError`, since OpenCode's claude-agent requests mirror a Claude Code session's and would count twice),
|
|
127
|
+
one file at a time: `hitRate` over the session's requests and its subagents', and its breaks. A session's files (a Codex
|
|
128
|
+
thread that goes on in a new rollout) are one conversation in the import's order: a file's first turn is compared with
|
|
129
|
+
the last turn of the file before it (its model, time and cache life carried over), and turns count on across them. Two
|
|
130
|
+
sessions are never compared. Each subagent is a conversation of its own, its breaks with its `subagent` number: a
|
|
131
|
+
subagent's thread that goes on in a new rollout is one, its files joined the same way.
|
|
132
|
+
`analyzeCache` hands back the `last` turn it compared, for the next file's `before`. `cacheTotals(sessions)` counts the breaks and sums their priced extra cost by
|
|
133
|
+
cause.
|
|
134
|
+
|
|
135
|
+
```sh
|
|
136
|
+
node dist/cli.js <home> [--sources claude-code,codex,pi] --cache
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
A JSONL line per session, sorted by key as `--known-answer`'s: `{key, source, hitRate, breaks: [{turn, at, dropPct,
|
|
140
|
+
rewritten, extraCost, cause}]}`, then one line `{totals: {sessions, breaks, extraCost, unpriced}}`. Numbers and cause
|
|
141
|
+
names only.
|
|
142
|
+
|
|
87
143
|
## Usage
|
|
88
144
|
|
|
89
145
|
`normalizeUsage(format, raw, options?)` reads one request's usage as `"anthropic"`, `"openai"`, `"pi"`, `"opencode"` or `"copilot"` writes it:
|
|
@@ -161,8 +217,9 @@ read looks up afresh.
|
|
|
161
217
|
|
|
162
218
|
The cursor is the reader's own: hand it back to the same reader for the same locator. A JSONL source builds its reader
|
|
163
219
|
with `lineReader` from a per-record function; its cursor is the file's device and inode, the byte after the last whole
|
|
164
|
-
line read, and the read's state. A file replaced or truncated since is read from its start,
|
|
165
|
-
|
|
220
|
+
line read, and the read's state. A file replaced or truncated since is read from its start, as is a cursor whose state
|
|
221
|
+
is of another shape than the reader's (its `stateVersion`: a Codex cursor saved by 0.1.0-beta.58 or before), and a last
|
|
222
|
+
line with no newline yet is read but not consumed. A source that keeps many sessions in one file (a SQLite database) implements
|
|
166
223
|
`discover`, `idOf` and `read` itself and returns one locator per session, with its `id`, and `stat`: the session's own size and
|
|
167
224
|
last write, which a caller's size caps and "still being written" check go by (`locatorSize`; without `stat`, the file's).
|
|
168
225
|
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { type ParseOptions } from "./home.js";
|
|
2
|
+
import { type CalculateCost, type Catalog } from "./price.js";
|
|
3
|
+
import { type Source } from "./readers/index.js";
|
|
4
|
+
import type { SessionOf, Usage } from "./types.js";
|
|
5
|
+
/** The causes of a break, in the order they are tried: the first the transcript shows evidence of is the break's. */
|
|
6
|
+
export declare const CACHE_CAUSES: readonly ["model", "idle", "compaction", "edited", "sidechain", "unknown"];
|
|
7
|
+
export type CacheCause = (typeof CACHE_CAUSES)[number];
|
|
8
|
+
/** A break is a drop of more than this part of the turn before's cache read. */
|
|
9
|
+
export declare const BREAK_DROP = 0.8;
|
|
10
|
+
/** How long a cache lives unread: 5 minutes, or an hour where it was written for one (Anthropic's 1h cache). */
|
|
11
|
+
export declare const CACHE_TTL_MS: number;
|
|
12
|
+
export declare const CACHE_TTL_LONG_MS: number;
|
|
13
|
+
/** One break. `turn`: the request's number among the session's assistant turns, from 1 (the first is never a break);
|
|
14
|
+
* `at`: its time (ms since the epoch); `dropPct`: how much of the turn before's cache read it lost, in percent;
|
|
15
|
+
* `rewritten`: the tokens of the read lost that it paid for again, as a cache write or uncached input; `extraCost`: USD,
|
|
16
|
+
* what those cost above reading them from the cache, at the request's model's list prices (null when unpriced);
|
|
17
|
+
* `diverged`: for an edit, the index of the first message where its prompt and the turn before's differ. */
|
|
18
|
+
export type CacheBreak = {
|
|
19
|
+
turn: number;
|
|
20
|
+
at: number;
|
|
21
|
+
dropPct: number;
|
|
22
|
+
rewritten: number;
|
|
23
|
+
extraCost: number | null;
|
|
24
|
+
cause: CacheCause;
|
|
25
|
+
diverged?: number;
|
|
26
|
+
};
|
|
27
|
+
/** `hitRate`: the cache read over the whole prompt (input, cache read and write), null for a session that sent none.
|
|
28
|
+
* `last`: the last turn compared, to carry into the session's next file (CacheOptions.before). `compacted`: whether
|
|
29
|
+
* a compaction this file holds first (no copy) comes after that turn (anywhere in the file when it compared none, or
|
|
30
|
+
* after the carried turn). */
|
|
31
|
+
export type CacheReport = {
|
|
32
|
+
hitRate: number | null;
|
|
33
|
+
breaks: CacheBreak[];
|
|
34
|
+
last?: CacheCarry;
|
|
35
|
+
compacted: boolean;
|
|
36
|
+
};
|
|
37
|
+
/** The turn a file of a session ended on, which the session's next file compares its first turn with: its model, its
|
|
38
|
+
* time, its usage, whether the latest cache write by then was a 1h one, and whether a compaction came after it (the
|
|
39
|
+
* evidence is where the compaction was first read; a later file's copy of it is never consulted). */
|
|
40
|
+
export type CacheCarry = {
|
|
41
|
+
model?: string;
|
|
42
|
+
at: number;
|
|
43
|
+
usage: Usage;
|
|
44
|
+
long: boolean;
|
|
45
|
+
compacted?: boolean;
|
|
46
|
+
};
|
|
47
|
+
export type CacheOptions = {
|
|
48
|
+
/** The catalog to price with; false prices none (every extraCost null). Default: pi-ai's. */
|
|
49
|
+
catalog?: Catalog | false;
|
|
50
|
+
/** pi-ai's calculateCost, when the caller imported pi-ai itself; else priceRequests loads it. */
|
|
51
|
+
calculateCost?: CalculateCost;
|
|
52
|
+
/** The last turn of the session's file before this one (CacheReport.last): this file's first turn is compared with
|
|
53
|
+
* it, and its turns are no session's first. Absent for a session's first file. */
|
|
54
|
+
before?: CacheCarry;
|
|
55
|
+
};
|
|
56
|
+
/** A session's cache, from a read with `chain: true` (readSession(locator, source, { chain: true })). A session read
|
|
57
|
+
* without its chain names a model change or an idle gap; its other breaks are unknown. A turn compared is a request with
|
|
58
|
+
* usage that sent a prompt (a request that failed before it sent any, or whose usage is unknown, is passed over); a
|
|
59
|
+
* break compares it with the one before it. */
|
|
60
|
+
export declare function analyzeCache(session: Pick<SessionOf, "turns" | "chain" | "model">, options?: CacheOptions): Promise<CacheReport>;
|
|
61
|
+
/** One session's cache under a home, keyed as parseHome keys its totals (`key`, `file`, `source`, `id`): `hitRate` over
|
|
62
|
+
* its requests and its subagents' (the tokens parseHome totals), and the breaks in each of its files (`turn` counted
|
|
63
|
+
* across them, in the import's order) and in each subagent's, which is a conversation of its own (`subagent`: its
|
|
64
|
+
* number among the session's, from 1; `turn` counted in it). */
|
|
65
|
+
export type SessionCache = {
|
|
66
|
+
key: string;
|
|
67
|
+
file: string;
|
|
68
|
+
source: string;
|
|
69
|
+
id: string;
|
|
70
|
+
hitRate: number | null;
|
|
71
|
+
breaks: (CacheBreak & {
|
|
72
|
+
subagent?: number;
|
|
73
|
+
})[];
|
|
74
|
+
};
|
|
75
|
+
/** The sources whose sessions cacheHome analyzes: those that write each request's chain (ChainRecord). OpenCode's
|
|
76
|
+
* claude-agent requests mirror a Claude Code session's, so its breaks would count twice in cacheTotals. */
|
|
77
|
+
export declare const CACHE_SOURCES: readonly Source[];
|
|
78
|
+
/** Every session of `sources` under `home` with its cache (SessionCache), sorted by key: the sessions parseHome totals,
|
|
79
|
+
* each file read with its chain, and analyzed as it is read (one at a time: a whole home's turns would not fit). Its
|
|
80
|
+
* options are parseHome's but `state`: each call reads every file from its start. A source not in CACHE_SOURCES is
|
|
81
|
+
* refused (RangeError) before any file is read. */
|
|
82
|
+
export declare function cacheHome(home: string, { sources, readers, catalog, calculateCost, env, failures }?: Omit<ParseOptions, "state">): Promise<SessionCache[]>;
|
|
83
|
+
/** The breaks of `sessions` by cause, each cause there with 0 where none: how many, and their extra cost (USD, of the
|
|
84
|
+
* priced ones); `unpriced`, the breaks whose extra cost is unknown. */
|
|
85
|
+
export declare function cacheTotals(sessions: readonly Pick<SessionCache, "breaks">[]): {
|
|
86
|
+
sessions: number;
|
|
87
|
+
breaks: Record<CacheCause, number>;
|
|
88
|
+
extraCost: Record<CacheCause, number>;
|
|
89
|
+
unpriced: number;
|
|
90
|
+
};
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// The cache analyzer: a session's cache hit rate, and each turn whose cache read dropped more than 80% against the turn
|
|
2
|
+
// before it (a break), with the tokens it paid for again, what that cost, and the cause its transcript shows. It reads
|
|
3
|
+
// the session's chain (ChainRecord: ids, parents and hashes, never text), so it hands back numbers and cause names only.
|
|
4
|
+
import { groupsOf, keyOf, ReadFailures, readSource, requestsIn, requestsOf } from "./home.js";
|
|
5
|
+
import { builtinCatalog, priceRequests } from "./price.js";
|
|
6
|
+
import { locatorKey } from "./reader.js";
|
|
7
|
+
import { READERS } from "./readers/index.js";
|
|
8
|
+
/** The causes of a break, in the order they are tried: the first the transcript shows evidence of is the break's. */
|
|
9
|
+
export const CACHE_CAUSES = ["model", "idle", "compaction", "edited", "sidechain", "unknown"];
|
|
10
|
+
/** A break is a drop of more than this part of the turn before's cache read. */
|
|
11
|
+
export const BREAK_DROP = 0.8;
|
|
12
|
+
/** How long a cache lives unread: 5 minutes, or an hour where it was written for one (Anthropic's 1h cache). */
|
|
13
|
+
export const CACHE_TTL_MS = 5 * 60_000;
|
|
14
|
+
export const CACHE_TTL_LONG_MS = 60 * 60_000;
|
|
15
|
+
const round = (value, places) => Math.round(value * 10 ** places) / 10 ** places;
|
|
16
|
+
const promptOf = ({ input, cacheRead, cacheWrite }) => input + cacheRead + cacheWrite;
|
|
17
|
+
/** A session's cache, from a read with `chain: true` (readSession(locator, source, { chain: true })). A session read
|
|
18
|
+
* without its chain names a model change or an idle gap; its other breaks are unknown. A turn compared is a request with
|
|
19
|
+
* usage that sent a prompt (a request that failed before it sent any, or whose usage is unknown, is passed over); a
|
|
20
|
+
* break compares it with the one before it. */
|
|
21
|
+
export async function analyzeCache(session, options = {}) {
|
|
22
|
+
return analyzed(session, options, options.before?.long ?? false);
|
|
23
|
+
}
|
|
24
|
+
/** analyzeCache, with `long`: whether the latest cache write before the file was a 1h one. A file analyzed alone (no
|
|
25
|
+
* `before`) takes it from the session's earlier files once they are joined: cacheHome analyzes each file both ways. */
|
|
26
|
+
async function analyzed(session, { catalog, calculateCost, before: carried }, written) {
|
|
27
|
+
const answers = session.turns.filter((turn) => turn.role === "assistant");
|
|
28
|
+
const chain = session.chain ?? [];
|
|
29
|
+
// The record that opens each request, by its index among the answers, and each record by id (the first of a repeat).
|
|
30
|
+
const opens = new Map();
|
|
31
|
+
const byId = new Map();
|
|
32
|
+
chain.forEach((record, at) => {
|
|
33
|
+
if (record.request !== undefined && !opens.has(record.request))
|
|
34
|
+
opens.set(record.request, at);
|
|
35
|
+
if (record.id !== undefined && !byId.has(record.id))
|
|
36
|
+
byId.set(record.id, record);
|
|
37
|
+
});
|
|
38
|
+
const prices = catalog === false ? undefined : (catalog ?? (await builtinCatalog()));
|
|
39
|
+
let read = 0;
|
|
40
|
+
let prompt = 0;
|
|
41
|
+
const breaks = [];
|
|
42
|
+
// The turn before, at index -1 when it is the session's previous file's.
|
|
43
|
+
let before = carried ? { index: -1, answer: { at: carried.at, ...(carried.model ? { model: carried.model } : {}) }, usage: carried.usage } : undefined;
|
|
44
|
+
// Whether the latest request that wrote the cache wrote it for an hour.
|
|
45
|
+
let long = written;
|
|
46
|
+
for (const [index, answer] of answers.entries()) {
|
|
47
|
+
const usage = answer.usage;
|
|
48
|
+
if (!usage || promptOf(usage) === 0)
|
|
49
|
+
continue;
|
|
50
|
+
read += usage.cacheRead;
|
|
51
|
+
prompt += promptOf(usage);
|
|
52
|
+
if (before && before.usage.cacheRead > 0 && (before.usage.cacheRead - usage.cacheRead) / before.usage.cacheRead > BREAK_DROP) {
|
|
53
|
+
const lost = before.usage.cacheRead - usage.cacheRead;
|
|
54
|
+
const rewritten = Math.min(lost, usage.cacheWrite + usage.input);
|
|
55
|
+
const { cause, diverged } = causeOf(before.index, before.answer, index, answer, { long, compacted: carried?.compacted === true, chain, opens, byId });
|
|
56
|
+
const model = answer.model ?? session.model;
|
|
57
|
+
breaks.push({
|
|
58
|
+
turn: index + 1,
|
|
59
|
+
at: answer.at,
|
|
60
|
+
dropPct: round((lost / before.usage.cacheRead) * 100, 2),
|
|
61
|
+
rewritten,
|
|
62
|
+
extraCost: prices ? await extraCostOf(model, usage, rewritten, prices, calculateCost) : null,
|
|
63
|
+
cause,
|
|
64
|
+
...(diverged !== undefined ? { diverged } : {}),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
if (usage.cacheWrite > 0)
|
|
68
|
+
long = (usage.cacheWrite1h ?? 0) > 0;
|
|
69
|
+
before = { index, answer, usage };
|
|
70
|
+
}
|
|
71
|
+
// A compaction of this file's own after the last turn compared (the carried one's, or none: the whole file).
|
|
72
|
+
const from = before && before.index >= 0 ? opens.get(before.index) : -1;
|
|
73
|
+
const compacted = (before?.index === -1 && carried?.compacted === true) || (from !== undefined && chain.slice(from + 1).some(isCompaction));
|
|
74
|
+
const last = before ? { ...(before.answer.model ?? session.model ? { model: (before.answer.model ?? session.model) } : {}), at: before.answer.at, usage: before.usage, long, compacted } : undefined;
|
|
75
|
+
return { hitRate: prompt > 0 ? round(read / prompt, 4) : null, breaks, ...(last ? { last } : {}), compacted };
|
|
76
|
+
}
|
|
77
|
+
/** A compaction where it was first read: a copy of one an earlier file holds is that file's evidence, carried from it. */
|
|
78
|
+
const isCompaction = (record) => record.compact === true && !record.copy;
|
|
79
|
+
/** The first cause, in CACHE_CAUSES' order, the transcript shows for the break at request `index` after `last`. */
|
|
80
|
+
function causeOf(lastIndex, last, index, answer, { long, compacted, chain, opens, byId }) {
|
|
81
|
+
if (last.model && answer.model && last.model !== answer.model)
|
|
82
|
+
return { cause: "model" };
|
|
83
|
+
if (answer.at - last.at > (long ? CACHE_TTL_LONG_MS : CACHE_TTL_MS))
|
|
84
|
+
return { cause: "idle" };
|
|
85
|
+
// The turn before in the session's previous file: a compaction after it there (carried), or one this file opens with,
|
|
86
|
+
// is since it; its chain is that file's, so no edit or sidechain is named across the two.
|
|
87
|
+
if (lastIndex < 0 && compacted)
|
|
88
|
+
return { cause: "compaction" };
|
|
89
|
+
const from = lastIndex < 0 ? -1 : opens.get(lastIndex);
|
|
90
|
+
const to = opens.get(index);
|
|
91
|
+
if (from === undefined || to === undefined)
|
|
92
|
+
return { cause: "unknown" };
|
|
93
|
+
if (chain.slice(from + 1, to).some(isCompaction))
|
|
94
|
+
return { cause: "compaction" };
|
|
95
|
+
if (from < 0)
|
|
96
|
+
return { cause: "unknown" };
|
|
97
|
+
const was = chain[from];
|
|
98
|
+
const now = chain[to];
|
|
99
|
+
// A sidechain's prompt is a conversation of its own, never an edit of the main one's.
|
|
100
|
+
if (was.id !== undefined && now.id !== undefined && !was.sidechain === !now.sidechain) {
|
|
101
|
+
// The turn before's prompt with its own answer, and this turn's prompt: this one should go on from all of it.
|
|
102
|
+
const had = hashesTo(was.id, byId);
|
|
103
|
+
const has = now.parent === undefined ? [] : hashesTo(now.parent, byId);
|
|
104
|
+
let same = 0;
|
|
105
|
+
while (same < had.length && same < has.length && had[same] === has[same])
|
|
106
|
+
same += 1;
|
|
107
|
+
if (same < had.length)
|
|
108
|
+
return { cause: "edited", diverged: same };
|
|
109
|
+
}
|
|
110
|
+
if (now.sidechain && !was.sidechain)
|
|
111
|
+
return { cause: "sidechain" };
|
|
112
|
+
return { cause: "unknown" };
|
|
113
|
+
}
|
|
114
|
+
/** The hashes of the chain that ends at `id`, from its root: the conversation as a request held it. */
|
|
115
|
+
function hashesTo(id, byId) {
|
|
116
|
+
const out = [];
|
|
117
|
+
const visited = new Set();
|
|
118
|
+
for (let at = id; at !== undefined && !visited.has(at);) {
|
|
119
|
+
visited.add(at);
|
|
120
|
+
const record = byId.get(at);
|
|
121
|
+
if (!record)
|
|
122
|
+
break;
|
|
123
|
+
out.push(record.hash);
|
|
124
|
+
at = record.parent;
|
|
125
|
+
}
|
|
126
|
+
return out.reverse();
|
|
127
|
+
}
|
|
128
|
+
/** What the request paid for `rewritten` tokens above reading them from the cache: its usage priced as it was, less as
|
|
129
|
+
* it would have been with them read (taken from its cache write first, then its uncached input; the write's 1h part in
|
|
130
|
+
* proportion). */
|
|
131
|
+
async function extraCostOf(model, usage, rewritten, catalog, calculateCost) {
|
|
132
|
+
const fromWrite = Math.min(rewritten, usage.cacheWrite);
|
|
133
|
+
const cacheWrite = usage.cacheWrite - fromWrite;
|
|
134
|
+
const held = {
|
|
135
|
+
...usage,
|
|
136
|
+
input: usage.input - (rewritten - fromWrite),
|
|
137
|
+
cacheRead: usage.cacheRead + rewritten,
|
|
138
|
+
cacheWrite,
|
|
139
|
+
...(usage.cacheWrite1h !== undefined ? { cacheWrite1h: usage.cacheWrite > 0 ? Math.round((usage.cacheWrite1h * cacheWrite) / usage.cacheWrite) : 0 } : {}),
|
|
140
|
+
};
|
|
141
|
+
const paid = await priceRequests([{ ...(model ? { model } : {}), usage }], catalog, calculateCost);
|
|
142
|
+
const would = await priceRequests([{ ...(model ? { model } : {}), usage: held }], catalog, calculateCost);
|
|
143
|
+
return paid === undefined || would === undefined ? null : round(paid - would, 6);
|
|
144
|
+
}
|
|
145
|
+
/** The sources whose sessions cacheHome analyzes: those that write each request's chain (ChainRecord). OpenCode's
|
|
146
|
+
* claude-agent requests mirror a Claude Code session's, so its breaks would count twice in cacheTotals. */
|
|
147
|
+
export const CACHE_SOURCES = ["claude-code", "codex", "pi"];
|
|
148
|
+
/** readSource's prices for a whole read: none, its parts kept with each request's usage (the hit rate's), unpriced. */
|
|
149
|
+
const UNPRICED = { ready: true, load: async () => { } };
|
|
150
|
+
/** Every session of `sources` under `home` with its cache (SessionCache), sorted by key: the sessions parseHome totals,
|
|
151
|
+
* each file read with its chain, and analyzed as it is read (one at a time: a whole home's turns would not fit). Its
|
|
152
|
+
* options are parseHome's but `state`: each call reads every file from its start. A source not in CACHE_SOURCES is
|
|
153
|
+
* refused (RangeError) before any file is read. */
|
|
154
|
+
export async function cacheHome(home, { sources = CACHE_SOURCES, readers = READERS, catalog, calculateCost, env, failures } = {}) {
|
|
155
|
+
const refused = sources.filter((source) => !CACHE_SOURCES.includes(source));
|
|
156
|
+
if (refused.length)
|
|
157
|
+
throw new RangeError(`cacheHome reads ${CACHE_SOURCES.join(", ")}, not ${refused.join(", ")}`);
|
|
158
|
+
const prices = catalog === false ? false : (catalog ?? (await builtinCatalog()) ?? false);
|
|
159
|
+
const priced = { catalog: prices, ...(calculateCost ? { calculateCost } : {}) };
|
|
160
|
+
const out = [];
|
|
161
|
+
const failed = [];
|
|
162
|
+
// One per run, as parseHome keeps one per import: what a reader looks up once (the Codex rollouts index) is shared.
|
|
163
|
+
const lookups = new Map();
|
|
164
|
+
for (const source of sources) {
|
|
165
|
+
// Each file analyzed as it is read, on its own; and its first turn compared, with the chain before it, kept to compare
|
|
166
|
+
// with the last turn of the session's file before it once the files are joined (a Codex thread goes on in a new
|
|
167
|
+
// rollout).
|
|
168
|
+
// Each file alone two ways, the cache before it written for 5 minutes or for an hour (`long`): which holds is known
|
|
169
|
+
// once the session's files before it are joined, and holds until the file writes the cache itself.
|
|
170
|
+
const reports = new Map();
|
|
171
|
+
const { tops, children, unread } = await readSource(home, source, readers, env, undefined, lookups, UNPRICED, true, undefined, async (read) => {
|
|
172
|
+
reports.set(locatorKey(read.locator), { alone: await analyzed(read.session, priced, false), long: await analyzed(read.session, priced, true), ...headOf(read.session) });
|
|
173
|
+
const { turns: _turns, chain: _chain, firstPrompt: _prompt, titleText: _title, sourceTitle: _source, cwd: _cwd, ...session } = read.session;
|
|
174
|
+
return { locator: read.locator, session: { ...session, turns: [] }, requests: read.requests.map(({ at, usage }) => ({ role: "assistant", text: "", calls: [], at, ...(usage ? { usage } : {}) })) };
|
|
175
|
+
});
|
|
176
|
+
failed.push(...unread.map(({ locator, error }) => ({ key: keyOf(home, locator).key, file: locator.file, source, error })));
|
|
177
|
+
for (const { parts, children: subagents } of groupsOf(tops, children)) {
|
|
178
|
+
let read = 0;
|
|
179
|
+
let prompt = 0;
|
|
180
|
+
for (const { usage } of [...parts, ...subagents].flatMap((part) => [...requestsIn(part.read)])) {
|
|
181
|
+
if (!usage)
|
|
182
|
+
continue;
|
|
183
|
+
read += usage.cacheRead;
|
|
184
|
+
prompt += promptOf(usage);
|
|
185
|
+
}
|
|
186
|
+
const breaks = await joined(parts, reports, priced);
|
|
187
|
+
// Each subagent a conversation of its own, numbered from 1 in the import's order: a thread that goes on in another
|
|
188
|
+
// rollout is one, its files joined as the session's are.
|
|
189
|
+
const conversations = new Map();
|
|
190
|
+
for (const part of subagents) {
|
|
191
|
+
const key = conversationOf(part);
|
|
192
|
+
(conversations.get(key) ?? conversations.set(key, []).get(key)).push(part);
|
|
193
|
+
}
|
|
194
|
+
let n = 0;
|
|
195
|
+
for (const files of conversations.values()) {
|
|
196
|
+
n += 1;
|
|
197
|
+
for (const found of await joined(files, reports, priced))
|
|
198
|
+
breaks.push({ ...found, subagent: n });
|
|
199
|
+
}
|
|
200
|
+
const first = parts[0];
|
|
201
|
+
out.push({ ...keyOf(home, first.locator), source, id: first.read.session.id, hitRate: prompt > 0 ? round(read / prompt, 4) : null, breaks });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (failed.length && !failures)
|
|
205
|
+
throw new ReadFailures(failed);
|
|
206
|
+
failures?.push(...failed);
|
|
207
|
+
return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
208
|
+
}
|
|
209
|
+
/** The breaks of one conversation's files, in the import's order: each file's first turn compared with the last turn
|
|
210
|
+
* before it in the files before, its turns counted on from theirs, and a 1h cache write held until a file writes again. */
|
|
211
|
+
async function joined(files, reports, priced) {
|
|
212
|
+
const breaks = [];
|
|
213
|
+
let counted = 0;
|
|
214
|
+
let carry;
|
|
215
|
+
for (const part of files) {
|
|
216
|
+
const report = reports.get(locatorKey(part.locator));
|
|
217
|
+
if (!report)
|
|
218
|
+
continue;
|
|
219
|
+
if (carry && report.head) {
|
|
220
|
+
const { breaks: [edge] } = await analyzeCache(report.head, { ...priced, before: carry });
|
|
221
|
+
if (edge)
|
|
222
|
+
breaks.push({ ...edge, turn: edge.turn + report.skipped + counted });
|
|
223
|
+
}
|
|
224
|
+
// The file as the cache before it was written: a 1h write in an earlier file holds until this one writes.
|
|
225
|
+
const mine = carry?.long ? report.long : report.alone;
|
|
226
|
+
for (const found of mine.breaks)
|
|
227
|
+
breaks.push({ ...found, turn: found.turn + counted });
|
|
228
|
+
// A file with no turn compared passes the carry on, with any compaction of its own.
|
|
229
|
+
carry = mine.last ?? (carry && { ...carry, compacted: carry.compacted === true || mine.compacted });
|
|
230
|
+
counted += requestsOf(part.read);
|
|
231
|
+
}
|
|
232
|
+
return breaks;
|
|
233
|
+
}
|
|
234
|
+
/** Which conversation a subagent's file holds: a thread naming its parent (a Codex subagent, which groupsOf finds by that
|
|
235
|
+
* name) is its thread, in however many rollouts; any other (a Claude Code subagent's file, which names its parent's
|
|
236
|
+
* session) is its own. */
|
|
237
|
+
const conversationOf = (part) => (part.read.session.child && part.read.session.parent ? `thread\0${part.read.session.id}` : `file\0${locatorKey(part.locator)}`);
|
|
238
|
+
/** The breaks of `sessions` by cause, each cause there with 0 where none: how many, and their extra cost (USD, of the
|
|
239
|
+
* priced ones); `unpriced`, the breaks whose extra cost is unknown. */
|
|
240
|
+
export function cacheTotals(sessions) {
|
|
241
|
+
const breaks = Object.fromEntries(CACHE_CAUSES.map((cause) => [cause, 0]));
|
|
242
|
+
const extraCost = Object.fromEntries(CACHE_CAUSES.map((cause) => [cause, 0]));
|
|
243
|
+
let unpriced = 0;
|
|
244
|
+
for (const { cause, extraCost: usd } of sessions.flatMap((session) => session.breaks)) {
|
|
245
|
+
breaks[cause] += 1;
|
|
246
|
+
if (usd === null)
|
|
247
|
+
unpriced += 1;
|
|
248
|
+
else
|
|
249
|
+
extraCost[cause] = round(extraCost[cause] + usd, 6);
|
|
250
|
+
}
|
|
251
|
+
return { sessions: sessions.length, breaks, extraCost, unpriced };
|
|
252
|
+
}
|
|
253
|
+
/** A file's first turn compared (a request with usage that sent a prompt), with the chain up to it, as a session of that
|
|
254
|
+
* turn alone; `skipped`, the turns before it. None for a file with no such turn. */
|
|
255
|
+
function headOf(session) {
|
|
256
|
+
const answers = session.turns.filter((turn) => turn.role === "assistant");
|
|
257
|
+
const index = answers.findIndex(({ usage }) => usage !== undefined && promptOf(usage) > 0);
|
|
258
|
+
if (index < 0)
|
|
259
|
+
return { skipped: 0 };
|
|
260
|
+
const chain = session.chain ?? [];
|
|
261
|
+
const opens = chain.findIndex(({ request }) => request === index);
|
|
262
|
+
const answer = answers[index];
|
|
263
|
+
// Only whether a compaction of this file's own came before it: the chain's ids are this file's alone.
|
|
264
|
+
const compacted = opens > 0 && chain.slice(0, opens).some(isCompaction);
|
|
265
|
+
return { head: { turns: [{ role: "assistant", text: "", calls: [], at: answer.at, ...(answer.model ? { model: answer.model } : {}), usage: answer.usage }], chain: [...(compacted ? [{ compact: true }] : []), { request: 0 }], ...(session.model ? { model: session.model } : {}) }, skipped: index };
|
|
266
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,14 @@
|
|
|
7
7
|
// OpenCode database); turns, the person's user messages; calls, model requests (its subagents' with them); cost, USD,
|
|
8
8
|
// null when unknown. --threads and --read-ahead are parseHome's `threads` and
|
|
9
9
|
// `readAhead` (BYTES: a whole number, or with k, m or g after it for KiB, MiB or GiB); fewer threads or a smaller
|
|
10
|
-
// read-ahead hold less memory.
|
|
10
|
+
// read-ahead hold less memory.
|
|
11
|
+
// node dist/cli.js <home> [--sources claude-code,codex,pi] --cache
|
|
12
|
+
// (the sources that write a chain, CACHE_SOURCES: another is a usage error).
|
|
13
|
+
// The cache analyzer's answer, keyed the same way: a line per session, {key, source, hitRate, breaks: [{turn, at, dropPct,
|
|
14
|
+
// rewritten, extraCost, cause}]} (a subagent's break with its subagent's number), then one totals line: {totals:
|
|
15
|
+
// {sessions, breaks, extraCost, unpriced}}, the breaks and their extra cost by cause. Numbers and cause names only. It
|
|
16
|
+
// reads one file at a time, so --threads and --read-ahead do not apply to it.
|
|
17
|
+
// --help (-h) prints the usage and exits 0; a usage error exits 2.
|
|
11
18
|
// A file that cannot be read makes the answer incomplete: no line is printed, one stderr line names each such file by
|
|
12
19
|
// its source, key and error code (never its path), and the exit is 1.
|
|
13
20
|
//
|
|
@@ -16,10 +23,11 @@
|
|
|
16
23
|
import { parseArgs } from "node:util";
|
|
17
24
|
import { calculateCost } from "@earendil-works/pi-ai";
|
|
18
25
|
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
26
|
+
import { CACHE_SOURCES, cacheHome, cacheTotals } from "./cache.js";
|
|
19
27
|
import { MOST_THREADS, parseHome } from "./home.js";
|
|
20
28
|
import { catalogOf } from "./price.js";
|
|
21
29
|
import { SOURCES } from "./readers/index.js";
|
|
22
|
-
const USAGE = `usage: agentrun-import <home> [--sources ${SOURCES.join(",")}] [--threads N] [--read-ahead BYTES[k|m|g]] --known-answer`;
|
|
30
|
+
const USAGE = `usage: agentrun-import <home> [--sources ${SOURCES.join(",")}] [--threads N] [--read-ahead BYTES[k|m|g]] --known-answer | --cache`;
|
|
23
31
|
const UNITS = { "": 1, k: 2 ** 10, m: 2 ** 20, g: 2 ** 30 };
|
|
24
32
|
/** A flag's whole number (with a unit when `units`), or a usage error. */
|
|
25
33
|
function wholeOf(flag, value, least, units = false, most = Number.MAX_SAFE_INTEGER) {
|
|
@@ -41,7 +49,7 @@ const codeOf = (error) => {
|
|
|
41
49
|
async function main() {
|
|
42
50
|
let parsed;
|
|
43
51
|
try {
|
|
44
|
-
parsed = parseArgs({ allowPositionals: true, options: { sources: { type: "string" }, threads: { type: "string" }, "read-ahead": { type: "string" }, "known-answer": { type: "boolean" }, help: { type: "boolean", short: "h" } } });
|
|
52
|
+
parsed = parseArgs({ allowPositionals: true, options: { sources: { type: "string" }, threads: { type: "string" }, "read-ahead": { type: "string" }, "known-answer": { type: "boolean" }, cache: { type: "boolean" }, help: { type: "boolean", short: "h" } } });
|
|
45
53
|
}
|
|
46
54
|
catch (error) {
|
|
47
55
|
usage(error.message);
|
|
@@ -53,23 +61,39 @@ async function main() {
|
|
|
53
61
|
}
|
|
54
62
|
if (positionals.length !== 1)
|
|
55
63
|
usage("one home directory, please");
|
|
56
|
-
if (!values["known-answer"])
|
|
57
|
-
usage("--known-answer
|
|
64
|
+
if (!values["known-answer"] === !values.cache)
|
|
65
|
+
usage("one output, please: --known-answer or --cache");
|
|
66
|
+
const known = values.cache ? CACHE_SOURCES : SOURCES;
|
|
58
67
|
// A source named twice is read once: a repeat would print its every session twice.
|
|
59
|
-
const sources = values.sources === undefined ?
|
|
60
|
-
const unknown = sources.filter((name) => !
|
|
68
|
+
const sources = values.sources === undefined ? known : [...new Set(values.sources.split(",").map((name) => name.trim()))];
|
|
69
|
+
const unknown = sources.filter((name) => !known.includes(name));
|
|
61
70
|
if (unknown.length || !sources.length)
|
|
62
71
|
usage(`unknown source: ${unknown.join(", ") || "(none)"}`);
|
|
63
72
|
const threads = values.threads === undefined ? undefined : wholeOf("--threads", values.threads, 1, false, MOST_THREADS);
|
|
64
73
|
const readAhead = values["read-ahead"] === undefined ? undefined : wholeOf("--read-ahead", values["read-ahead"], 0, true);
|
|
65
74
|
const failures = [];
|
|
66
|
-
const
|
|
67
|
-
|
|
75
|
+
const options = { sources: sources, catalog: catalogOf(builtinModels().getModels()), calculateCost: calculateCost, failures };
|
|
76
|
+
const failed = () => {
|
|
68
77
|
for (const { source, key, error } of failures)
|
|
69
78
|
process.stderr.write(`agentrun-import: cannot read ${source} ${key} (${codeOf(error)})\n`);
|
|
70
|
-
|
|
79
|
+
if (failures.length)
|
|
80
|
+
process.exitCode = 1;
|
|
81
|
+
return failures.length > 0;
|
|
82
|
+
};
|
|
83
|
+
if (values.cache) {
|
|
84
|
+
const caches = await cacheHome(positionals[0], options);
|
|
85
|
+
if (failed())
|
|
86
|
+
return;
|
|
87
|
+
for (const { key, source, hitRate, breaks } of caches) {
|
|
88
|
+
const listed = breaks.map(({ turn, at, dropPct, rewritten, extraCost, cause, subagent }) => ({ turn, at, dropPct, rewritten, extraCost, cause, ...(subagent !== undefined ? { subagent } : {}) }));
|
|
89
|
+
process.stdout.write(`${JSON.stringify({ key, source, hitRate, breaks: listed })}\n`);
|
|
90
|
+
}
|
|
91
|
+
process.stdout.write(`${JSON.stringify({ totals: cacheTotals(caches) })}\n`);
|
|
71
92
|
return;
|
|
72
93
|
}
|
|
94
|
+
const sessions = await parseHome(positionals[0], { ...options, ...(threads === undefined ? {} : { threads }), ...(readAhead === undefined ? {} : { readAhead }) });
|
|
95
|
+
if (failed())
|
|
96
|
+
return;
|
|
73
97
|
for (const { key, source, tokens, cost, turns, calls } of sessions) {
|
|
74
98
|
const { input, output, cacheRead, cacheWrite, cacheWrite1h } = tokens;
|
|
75
99
|
process.stdout.write(`${JSON.stringify({ key, source, tokens: { input, output, cacheRead, cacheWrite, cacheWrite1h }, cost, turns, calls })}\n`);
|