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

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.
@@ -2,7 +2,7 @@
2
2
  import { basename, join } from "node:path";
3
3
  import { lineReader } from "../lines.js";
4
4
  import { entries } from "../reader.js";
5
- import { argsOf, effortOf, isObject, str, textOf, timeOf } from "../text.js";
5
+ import { argsOf, effortOf, FAILED, isObject, str, textOf, timeOf } from "../text.js";
6
6
  import { normalizeUsage } from "../usage.js";
7
7
  function record(value, at, { state, keep, add }) {
8
8
  const { session, priced } = state;
@@ -72,7 +72,7 @@ function record(value, at, { state, keep, add }) {
72
72
  ...(session.model ? { model: session.model } : {}),
73
73
  ...(state.effort ? { effort: state.effort } : {}),
74
74
  ...(tokens ? { usage: tokens } : {}),
75
- ...(message.stopReason === "error" ? { error: str(message.errorMessage) ?? "unknown error" } : {}),
75
+ ...(message.stopReason === "error" ? { error: keep ? (str(message.errorMessage) ?? "unknown error") : FAILED } : {}),
76
76
  });
77
77
  }
78
78
  }
@@ -36,4 +36,8 @@ export declare function addRecord(index: RecordIndex, key: Packed, owner: number
36
36
  export declare function addAll(into: RecordIndex, from: RecordIndex): void;
37
37
  /** `index` without the records `owner` owns: the rest kept in their order. */
38
38
  export declare function dropOwner(index: RecordIndex, owner: number): void;
39
+ /** Each record of `from` packed, in the order taken, until `stop` returns true for one: whether one did. */
40
+ export declare function someRecord(from: RecordIndex, stop: (key: Packed) => boolean): boolean;
41
+ /** Every record of `index` now owned by `owner`. */
42
+ export declare function ownAll(index: RecordIndex, owner: number): void;
39
43
  export {};
@@ -183,3 +183,38 @@ export function dropOwner(index, owner) {
183
183
  index.uuids = kept.uuids;
184
184
  index.others = kept.others;
185
185
  }
186
+ /** Each record of `from` packed, in the order taken, until `stop` returns true for one: whether one did. */
187
+ export function someRecord(from, stop) {
188
+ const key = { bytes: new Uint8Array(64), length: 0 };
189
+ const u = from.uuids;
190
+ key.bytes[0] = UUID;
191
+ key.length = 17;
192
+ for (let i = 0; i < u.count; i += 1) {
193
+ for (let k = 0; k < 4; k += 1) {
194
+ const w = u.words[i * 4 + k];
195
+ key.bytes[1 + k * 4] = w & 0xff;
196
+ key.bytes[2 + k * 4] = (w >>> 8) & 0xff;
197
+ key.bytes[3 + k * 4] = (w >>> 16) & 0xff;
198
+ key.bytes[4 + k * 4] = (w >>> 24) & 0xff;
199
+ }
200
+ if (stop(key))
201
+ return true;
202
+ }
203
+ const o = from.others;
204
+ for (let i = 0; i < o.count; i += 1) {
205
+ const start = i === 0 ? 0 : o.ends[i - 1];
206
+ const end = o.ends[i];
207
+ if (key.bytes.length < end - start)
208
+ key.bytes = new Uint8Array((end - start) * 2);
209
+ key.bytes.set(o.bytes.subarray(start, end));
210
+ key.length = end - start;
211
+ if (stop(key))
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ /** Every record of `index` now owned by `owner`. */
217
+ export function ownAll(index, owner) {
218
+ index.uuids.owners.fill(owner, 0, index.uuids.count);
219
+ index.others.owners.fill(owner, 0, index.others.count);
220
+ }
package/dist/text.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { Turn } from "./types.js";
2
+ /** What a request read without turns keeps of its error: that it failed, never the message (a path, a provider's text). */
3
+ export declare const FAILED = "failed";
2
4
  export declare const isObject: (value: unknown) => value is Record<string, unknown>;
3
5
  export declare const str: (value: unknown) => string | undefined;
4
6
  export declare const timeOf: (value: unknown) => number | undefined;
package/dist/text.js CHANGED
@@ -1,3 +1,5 @@
1
+ /** What a request read without turns keeps of its error: that it failed, never the message (a path, a provider's text). */
2
+ export const FAILED = "failed";
1
3
  export const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
4
  export const str = (value) => (typeof value === "string" && value !== "" ? value : undefined);
3
5
  export const timeOf = (value) => {
package/dist/types.d.ts CHANGED
@@ -15,10 +15,19 @@ export type Usage = {
15
15
  cacheWrite1h?: number;
16
16
  reasoning?: number;
17
17
  };
18
+ /** Another source's session that holds the same request: OpenCode's claude-agent provider runs Claude Code, which writes
19
+ * each request into its own session file too. A total of both sources counts the request once, in `source`'s. */
20
+ export type Mirror = {
21
+ source: string;
22
+ sessionId: string;
23
+ };
18
24
  /** An assistant turn is one model request: `model` the one it ran on ("provider/model"), `effort` the effort or
19
25
  * thinking level it ran at, `usage` its tokens, each absent when the source does not say; `key`, the source's own id of
20
- * the request (Claude Code's message id with its request id, Codex's response id); `error`, why it failed. A note is a
21
- * line the harness itself wrote in the conversation: no request, nor the person's. */
26
+ * the request (Claude Code's message id with its request id, Codex's response id); `error`, why it failed; `mirrors`, the
27
+ * other source's session that holds the same request (Mirror). `folded`: its usage
28
+ * (zeros) is counted in a later request of the same session, where its source wrote a total, not each request's own
29
+ * (Droid): its zeros are no unknown. A note is a line the harness itself wrote in the conversation: no request, nor the
30
+ * person's. */
22
31
  export type Turn = ({
23
32
  role: "user";
24
33
  text: string;
@@ -35,10 +44,15 @@ export type Turn = ({
35
44
  at: number;
36
45
  costUsd?: number;
37
46
  key?: string;
47
+ /** The source's own ids of the request's later parts, each a key of its own (Copilot's later chunks of a split
48
+ * response, each a message with its own messageId): a later import counts them once too. */
49
+ keys?: string[];
38
50
  model?: string;
39
51
  effort?: string;
40
52
  usage?: Usage;
41
53
  error?: string;
54
+ folded?: true;
55
+ mirrors?: Mirror;
42
56
  } | {
43
57
  role: "toolResult";
44
58
  callId: string;
@@ -47,7 +61,8 @@ export type Turn = ({
47
61
  isError: boolean;
48
62
  at: number;
49
63
  }) & {
50
- /** The source's own ids of the records the turn was read from (Claude Code's uuids): a later import counts them once. */
64
+ /** The source's own ids of the records the turn was read from (Claude Code's uuids, an OpenCode prompt's fingerprint): a
65
+ * later import counts them once. */
51
66
  uuids?: string[];
52
67
  };
53
68
  export type Answer = Extract<Turn, {
@@ -92,4 +107,6 @@ export type SessionOf<S extends string = string> = {
92
107
  copies: number;
93
108
  /** The effort or thinking level most of its requests ran at, as the source names it; with its turns only. */
94
109
  effort?: string;
110
+ /** Each other source's session its requests' mirrors name, in the order first named (with or without its turns). */
111
+ mirrors?: Mirror[];
95
112
  };
package/dist/usage.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import type { Usage } from "./types.js";
2
- export type UsageFormat = "anthropic" | "openai" | "pi" | "openrouter";
2
+ export type UsageFormat = "anthropic" | "openai" | "pi" | "openrouter" | "opencode" | "copilot";
3
+ /** What a format's reading may need beyond the counts: the version of the program that wrote them (OpenCode's). */
4
+ export type UsageOptions = {
5
+ version?: string;
6
+ };
3
7
  /** A request's usage as `format` writes it, as Usage; undefined unless input and output are counts (an absent cache
4
8
  * 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
9
  * is kept only when it is a count of at most the whole. */
6
- export declare function normalizeUsage(format: UsageFormat, raw: unknown): Usage | undefined;
10
+ export declare function normalizeUsage(format: UsageFormat, raw: unknown, options?: UsageOptions): Usage | undefined;
7
11
  /** A request's tokens as an OpenTelemetry GenAI span carries them: `input` INCLUSIVE of the cache (the uncached input, the
8
12
  * cache read and the cache write together), as gen_ai.usage.input_tokens is defined and as Sentry reads it (it takes
9
13
  * the cache counts out of it again, so an exclusive figure would go negative). The other counts as Usage has them. */
package/dist/usage.js CHANGED
@@ -6,8 +6,32 @@
6
6
  // pi already split as Usage is, cacheWrite1h included.
7
7
  // openrouter Chat Completions' names: prompt_tokens holds prompt_tokens_details.cached_tokens and .cache_write_tokens,
8
8
  // subtracted; completion_tokens holds completion_tokens_details.reasoning_tokens, kept beside it.
9
+ // opencode {input, output, reasoning, cache: {read, write}, total?}: input already leaves the cache out. Since
10
+ // OpenCode 1.3.16 output leaves the reasoning out (anomalyco/opencode 280eb16e77, #21047: "ensure reasoning
11
+ // tokens arent double counted"; AI SDK 6 came in 1.3.4, and output was still the SDK's whole outputTokens
12
+ // until then), so output is output + reasoning (reasoning kept beside it, as OpenAI's). Before it, output
13
+ // held the reasoning already: a session's `version` older than 1.3.16 keeps output as it is. Where a step
14
+ // records its `total`, output is what the total leaves after the input and the cache, when that is at
15
+ // least the output, whatever the version. All nought is no usage: a request cut before its usage came.
16
+ // copilot GitHub Copilot CLI's {inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens}:
17
+ // inputTokens holds the cache read and write (github/copilot-sdk docs/features/usage-and-billing.md),
18
+ // subtracted; reasoningTokens is part of outputTokens, kept as `reasoning` beside it.
9
19
  // A trace exporter's figure is otelUsage's: the same counts, its input inclusive of the cache.
10
20
  import { isObject } from "./text.js";
21
+ /** The first OpenCode whose output leaves the reasoning out. */
22
+ const OPENCODE_SPLIT = [1, 3, 16];
23
+ /** Whether `version` ("1.2.3", a pre-release after it) is an OpenCode older than 1.3.16; unknown is not. */
24
+ function beforeSplit(version) {
25
+ const parts = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version ?? "");
26
+ if (!parts)
27
+ return false;
28
+ for (let i = 0; i < 3; i += 1) {
29
+ const [at, split] = [Number(parts[i + 1]), OPENCODE_SPLIT[i]];
30
+ if (at !== split)
31
+ return at < split;
32
+ }
33
+ return false;
34
+ }
11
35
  /** Each format's names for input, cache read, cache write, output and the reasoning part of the output (a dotted name is
12
36
  * a nested one), and whether its input holds its cache counts. */
13
37
  const NAMES = {
@@ -15,6 +39,7 @@ const NAMES = {
15
39
  openai: { input: "input_tokens", cacheRead: "cached_input_tokens", cacheWrite: "cache_write_input_tokens", output: "output_tokens", reasoning: "reasoning_output_tokens", cachedIn: true },
16
40
  pi: { input: "input", cacheRead: "cacheRead", cacheWrite: "cacheWrite", output: "output", cachedIn: false },
17
41
  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 },
42
+ copilot: { input: "inputTokens", cacheRead: "cacheReadTokens", cacheWrite: "cacheWriteTokens", output: "outputTokens", reasoning: "reasoningTokens", cachedIn: true },
18
43
  };
19
44
  const count = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : undefined);
20
45
  /** The value at a dotted name in `raw`, undefined where any part is missing. */
@@ -22,9 +47,11 @@ const at = (raw, name) => name.split(".").reduce((value, part) => (isObject(valu
22
47
  /** A request's usage as `format` writes it, as Usage; undefined unless input and output are counts (an absent cache
23
48
  * count is 0) and the input left is not negative. The 1h part of the cache write, or the reasoning part of the output,
24
49
  * is kept only when it is a count of at most the whole. */
25
- export function normalizeUsage(format, raw) {
50
+ export function normalizeUsage(format, raw, options = {}) {
26
51
  if (!isObject(raw))
27
52
  return undefined;
53
+ if (format === "opencode")
54
+ return openCodeUsage(raw, beforeSplit(options.version));
28
55
  const names = NAMES[format];
29
56
  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) };
30
57
  if (usage.input === undefined || usage.output === undefined || usage.cacheRead === undefined || usage.cacheWrite === undefined)
@@ -42,6 +69,20 @@ export function normalizeUsage(format, raw) {
42
69
  out.reasoning = reasoning;
43
70
  return out;
44
71
  }
72
+ function openCodeUsage(raw, holdsReasoning) {
73
+ const cache = isObject(raw.cache) ? raw.cache : {};
74
+ const [input, output, reasoning, cacheRead, cacheWrite] = [raw.input, raw.output, raw.reasoning ?? 0, cache.read ?? 0, cache.write ?? 0].map(count);
75
+ if (input === undefined || output === undefined || reasoning === undefined || cacheRead === undefined || cacheWrite === undefined)
76
+ return undefined;
77
+ const total = count(raw.total);
78
+ const left = total === undefined ? -1 : total - input - cacheRead - cacheWrite;
79
+ const usage = { input, output: left >= output ? left : holdsReasoning ? output : output + reasoning, cacheRead, cacheWrite };
80
+ if (usage.input + usage.output + usage.cacheRead + usage.cacheWrite === 0)
81
+ return undefined;
82
+ if (raw.reasoning !== undefined && reasoning <= usage.output)
83
+ usage.reasoning = reasoning;
84
+ return usage;
85
+ }
45
86
  export function otelUsage(usage) {
46
87
  return { input: usage.input + usage.cacheRead + usage.cacheWrite, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, ...(usage.reasoning === undefined ? {} : { reasoning: usage.reasoning }) };
47
88
  }
package/dist/wrapped.d.ts CHANGED
@@ -31,11 +31,13 @@ export type Wrapped = {
31
31
  requests: number;
32
32
  tokens: number;
33
33
  }[];
34
+ /** `unpricedRequests` per model: of its requests, those its `cost` leaves out (all of them: no price was known). */
34
35
  models: {
35
36
  model: string;
36
37
  requests: number;
37
38
  tokens: Tokens;
38
39
  cost: number;
40
+ unpricedRequests: number;
39
41
  }[];
40
42
  sources: {
41
43
  source: string;
package/dist/wrapped.js CHANGED
@@ -49,7 +49,7 @@ export async function wrappedHome(home, year, options = {}) {
49
49
  const h = by(harnesses, harnessOf(totals.source), () => ({ sessions: 0, requests: 0, tokens: 0 }));
50
50
  h.requests += 1;
51
51
  h.tokens += held;
52
- const m = by(models, r.model ?? "unknown", () => ({ requests: 0, tokens: noTokens(), cost: 0 }));
52
+ const m = by(models, r.model ?? "unknown", () => ({ requests: 0, tokens: noTokens(), cost: 0, unpricedRequests: 0 }));
53
53
  m.requests += 1;
54
54
  if (r.usage)
55
55
  addTokens(m.tokens, r.usage);
@@ -58,8 +58,10 @@ export async function wrappedHome(home, year, options = {}) {
58
58
  // A request with no usage (pi leaves it off an aborted request) is unpriced; known zero usage is free and priced.
59
59
  if (r.usage)
60
60
  by(usages, r.model ?? "unknown", () => []).push(r.usage);
61
- else
61
+ else {
62
62
  out.unpricedRequests += 1;
63
+ m.unpricedRequests += 1;
64
+ }
63
65
  }
64
66
  },
65
67
  });
@@ -78,8 +80,10 @@ export async function wrappedHome(home, year, options = {}) {
78
80
  // The caller's price answers per request: one it cannot price is left out alone.
79
81
  for (const usage of paid) {
80
82
  const one = await options.price(known, usage);
81
- if (one === undefined)
83
+ if (one === undefined) {
82
84
  out.unpricedRequests += 1;
85
+ models.get(model).unpricedRequests += 1;
86
+ }
83
87
  else
84
88
  usd = (usd ?? 0) + one;
85
89
  }
@@ -88,8 +92,10 @@ export async function wrappedHome(home, year, options = {}) {
88
92
  }
89
93
  else if (prices)
90
94
  usd = await priceRequests(paid.map((usage) => ({ ...(known ? { model: known } : {}), usage })), prices);
91
- if (usd === undefined)
95
+ if (usd === undefined) {
92
96
  out.unpricedRequests += paid.length;
97
+ models.get(model).unpricedRequests += paid.length;
98
+ }
93
99
  else {
94
100
  out.cost += usd;
95
101
  models.get(model).cost = usd;
package/package.json CHANGED
@@ -1,12 +1,14 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-import",
3
- "version": "0.1.0-beta.57",
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.",
3
+ "version": "0.1.0-beta.59",
4
+ "description": "Reads the coding-agent sessions under a home (Claude Code, Codex, pi, OpenCode, GitHub Copilot CLI) 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",
7
7
  "claude-code",
8
8
  "codex",
9
+ "copilot",
9
10
  "pi",
11
+ "opencode",
10
12
  "sessions",
11
13
  "usage"
12
14
  ],