@bli-cockpit/telemetry-core 0.1.81 → 0.1.82

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/dist/index.d.ts CHANGED
@@ -29,6 +29,7 @@ export * from "./risk-flags.js";
29
29
  export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
+ export * from "./session-facts-delta.js";
32
33
  export * from "./session-facts-skills.js";
33
34
  export * from "./session-facts-spawn.js";
34
35
  export * from "./session-facts-active.js";
package/dist/index.js CHANGED
@@ -29,6 +29,7 @@ export * from "./risk-flags.js";
29
29
  export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
+ export * from "./session-facts-delta.js";
32
33
  export * from "./session-facts-skills.js";
33
34
  export * from "./session-facts-spawn.js";
34
35
  export * from "./session-facts-active.js";
@@ -0,0 +1,45 @@
1
+ /**
2
+ * One file's contribution to a session's facts, remembered so the file need not be read again (BLI-22797).
3
+ *
4
+ * The collector counts a session by feeding its main transcript and each accepted sidecar into ONE accumulator
5
+ * (`session-facts.ts`). That accumulator is not a plain sum: usage is deduped by request id ACROSS files, the
6
+ * Codex totals and the spawn marker are first/last-wins folds, the skill tally keeps first-seen order, and the
7
+ * active-time rule needs every timestamp. So a remembered contribution cannot be a bag of totals. It is what
8
+ * the file would have done to a fresh accumulator, stored in a form that replays onto a live one identically:
9
+ *
10
+ * - `usage`: each request id the file contributed (first occurrence in the file), in file order, so the id
11
+ * dedupe against files already merged is the same decision a fresh read makes;
12
+ * - plain counters add; `timestamps` are sorted and delta-encoded (the active-time rule is order-blind);
13
+ * - `codex_total_usage` / `codex_model_hint` overwrite when set (last file wins); `spawn` fills only an
14
+ * empty slot (first file wins); `skills` merge in first-seen order.
15
+ *
16
+ * Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
17
+ */
18
+ import { type SessionFactsAccumulator, type SessionFactsSource } from "./session-facts.js";
19
+ import type { SessionSpawn } from "./session-facts-spawn.js";
20
+ import type { SkillUseCount } from "./session-facts-skills.js";
21
+ /** `[request id, model, input, output, cache read, cache creation]`. */
22
+ export type SessionFactsDeltaUsage = [string, string, number, number, number, number];
23
+ export interface SessionFactsDelta {
24
+ source: SessionFactsSource;
25
+ usage: SessionFactsDeltaUsage[];
26
+ record_count: number;
27
+ user_prompt_count: number;
28
+ assistant_response_count: number;
29
+ tool_calls_by_name: Record<string, number>;
30
+ /** Sorted ascending: the first value, then the gap to each next one, in ms. */
31
+ timestamps: number[];
32
+ transcript_bytes: number;
33
+ transcript_lines: number;
34
+ transcript_files: number;
35
+ codex_total_usage: Record<string, unknown> | null;
36
+ codex_model_hint: string | null;
37
+ skills: SkillUseCount[];
38
+ spawn: SessionSpawn | null;
39
+ }
40
+ /** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
41
+ export declare function captureSessionFactsDelta(source: SessionFactsSource, feed: (acc: SessionFactsAccumulator) => void): SessionFactsDelta;
42
+ /** Leave `acc` as a fresh read of the same file would have left it. */
43
+ export declare function mergeSessionFactsDelta(acc: SessionFactsAccumulator, delta: SessionFactsDelta): void;
44
+ /** A stored delta read back from disk, or null when it is not one (the caller then reads the file fresh). */
45
+ export declare function parseSessionFactsDelta(value: unknown): SessionFactsDelta | null;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * One file's contribution to a session's facts, remembered so the file need not be read again (BLI-22797).
3
+ *
4
+ * The collector counts a session by feeding its main transcript and each accepted sidecar into ONE accumulator
5
+ * (`session-facts.ts`). That accumulator is not a plain sum: usage is deduped by request id ACROSS files, the
6
+ * Codex totals and the spawn marker are first/last-wins folds, the skill tally keeps first-seen order, and the
7
+ * active-time rule needs every timestamp. So a remembered contribution cannot be a bag of totals. It is what
8
+ * the file would have done to a fresh accumulator, stored in a form that replays onto a live one identically:
9
+ *
10
+ * - `usage`: each request id the file contributed (first occurrence in the file), in file order, so the id
11
+ * dedupe against files already merged is the same decision a fresh read makes;
12
+ * - plain counters add; `timestamps` are sorted and delta-encoded (the active-time rule is order-blind);
13
+ * - `codex_total_usage` / `codex_model_hint` overwrite when set (last file wins); `spawn` fills only an
14
+ * empty slot (first file wins); `skills` merge in first-seen order.
15
+ *
16
+ * Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
17
+ */
18
+ import { addClaudeUsage, newSessionFactsAccumulator, } from "./session-facts.js";
19
+ const finite = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
20
+ /** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
21
+ export function captureSessionFactsDelta(source, feed) {
22
+ const acc = newSessionFactsAccumulator(source);
23
+ acc.usage_log = [];
24
+ feed(acc);
25
+ const sorted = [...acc.timestamps_ms].sort((a, b) => a - b);
26
+ return {
27
+ source,
28
+ usage: acc.usage_log.map(({ id, model, usage }) => [
29
+ id,
30
+ model,
31
+ finite(usage["input_tokens"]),
32
+ finite(usage["output_tokens"]),
33
+ finite(usage["cache_read_input_tokens"]),
34
+ finite(usage["cache_creation_input_tokens"]),
35
+ ]),
36
+ record_count: acc.record_count,
37
+ user_prompt_count: acc.user_prompt_count,
38
+ assistant_response_count: acc.assistant_response_count,
39
+ tool_calls_by_name: { ...acc.tool_calls_by_name },
40
+ timestamps: sorted.map((value, i) => (i === 0 ? value : value - sorted[i - 1])),
41
+ transcript_bytes: acc.transcript_bytes,
42
+ transcript_lines: acc.transcript_lines,
43
+ transcript_files: acc.transcript_files,
44
+ codex_total_usage: acc.codex_total_usage ? { ...acc.codex_total_usage } : null,
45
+ codex_model_hint: acc.codex_model_hint,
46
+ skills: acc.skill_tally.entries(),
47
+ spawn: acc.spawn ? { ...acc.spawn } : null,
48
+ };
49
+ }
50
+ /** Leave `acc` as a fresh read of the same file would have left it. */
51
+ export function mergeSessionFactsDelta(acc, delta) {
52
+ for (const [id, model, input, output, cacheRead, cacheCreation] of delta.usage) {
53
+ if (acc.seen_usage_ids.has(id))
54
+ continue;
55
+ acc.seen_usage_ids.add(id);
56
+ addClaudeUsage(acc, model, {
57
+ input_tokens: input,
58
+ output_tokens: output,
59
+ cache_read_input_tokens: cacheRead,
60
+ cache_creation_input_tokens: cacheCreation,
61
+ });
62
+ }
63
+ acc.record_count += delta.record_count;
64
+ acc.user_prompt_count += delta.user_prompt_count;
65
+ acc.assistant_response_count += delta.assistant_response_count;
66
+ for (const [name, count] of Object.entries(delta.tool_calls_by_name)) {
67
+ acc.tool_calls_by_name[name] = (acc.tool_calls_by_name[name] ?? 0) + count;
68
+ }
69
+ let at = 0;
70
+ delta.timestamps.forEach((value, i) => {
71
+ at = i === 0 ? value : at + value;
72
+ acc.timestamps_ms.push(at);
73
+ acc.first_timestamp_ms = acc.first_timestamp_ms == null ? at : Math.min(acc.first_timestamp_ms, at);
74
+ acc.last_timestamp_ms = acc.last_timestamp_ms == null ? at : Math.max(acc.last_timestamp_ms, at);
75
+ });
76
+ acc.transcript_bytes += delta.transcript_bytes;
77
+ acc.transcript_lines += delta.transcript_lines;
78
+ acc.transcript_files += delta.transcript_files;
79
+ if (delta.codex_total_usage)
80
+ acc.codex_total_usage = { ...delta.codex_total_usage };
81
+ if (delta.codex_model_hint !== null)
82
+ acc.codex_model_hint = delta.codex_model_hint;
83
+ acc.skill_tally.mergeEntries(delta.skills);
84
+ if (!acc.spawn && delta.spawn)
85
+ acc.spawn = { ...delta.spawn };
86
+ }
87
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
88
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
89
+ /** A stored delta read back from disk, or null when it is not one (the caller then reads the file fresh). */
90
+ export function parseSessionFactsDelta(value) {
91
+ if (!isObj(value))
92
+ return null;
93
+ const v = value;
94
+ if (v["source"] !== "claude_code" && v["source"] !== "codex")
95
+ return null;
96
+ const usage = v["usage"];
97
+ if (!Array.isArray(usage) || !usage.every((u) => Array.isArray(u) && u.length === 6 && typeof u[0] === "string" && typeof u[1] === "string" && u.slice(2).every(isNum)))
98
+ return null;
99
+ for (const key of ["record_count", "user_prompt_count", "assistant_response_count", "transcript_bytes", "transcript_lines", "transcript_files"]) {
100
+ if (!isNum(v[key]))
101
+ return null;
102
+ }
103
+ const tools = v["tool_calls_by_name"];
104
+ if (!isObj(tools) || !Object.values(tools).every(isNum))
105
+ return null;
106
+ const stamps = v["timestamps"];
107
+ if (!Array.isArray(stamps) || !stamps.every(isNum))
108
+ return null;
109
+ const skills = v["skills"];
110
+ if (!Array.isArray(skills) || !skills.every((s) => isObj(s) && typeof s["skill"] === "string" && (s["plugin"] === null || typeof s["plugin"] === "string") && isNum(s["by_person"]) && isNum(s["by_agent"])))
111
+ return null;
112
+ const total = v["codex_total_usage"];
113
+ if (total !== null && !isObj(total))
114
+ return null;
115
+ const hint = v["codex_model_hint"];
116
+ if (hint !== null && typeof hint !== "string")
117
+ return null;
118
+ const spawn = v["spawn"];
119
+ if (spawn !== null && !(isObj(spawn) && typeof spawn["kind"] === "string"))
120
+ return null;
121
+ return value;
122
+ }
@@ -45,6 +45,10 @@ export declare class SkillUseTally {
45
45
  private readonly counts;
46
46
  addByPerson(raw: string): void;
47
47
  addByAgent(raw: string): void;
48
+ /** Every tallied skill in first-seen order (unsorted), so a memoized delta merges back identically (BLI-22797). */
49
+ entries(): SkillUseCount[];
50
+ /** Add another tally's counts, creating keys in the given order, exactly as counting those uses here would have. */
51
+ mergeEntries(entries: readonly SkillUseCount[]): void;
48
52
  /** Most used first, ties by name, so the stored list is stable. */
49
53
  toList(): SkillUseCount[];
50
54
  private entry;
@@ -64,6 +64,24 @@ export class SkillUseTally {
64
64
  if (entry)
65
65
  entry.by_agent += 1;
66
66
  }
67
+ /** Every tallied skill in first-seen order (unsorted), so a memoized delta merges back identically (BLI-22797). */
68
+ entries() {
69
+ return [...this.counts.values()].map((c) => ({ ...c }));
70
+ }
71
+ /** Add another tally's counts, creating keys in the given order, exactly as counting those uses here would have. */
72
+ mergeEntries(entries) {
73
+ for (const e of entries) {
74
+ const key = `${e.plugin ?? ""}:${e.skill}`;
75
+ const existing = this.counts.get(key);
76
+ if (existing) {
77
+ existing.by_person += e.by_person;
78
+ existing.by_agent += e.by_agent;
79
+ }
80
+ else {
81
+ this.counts.set(key, { skill: e.skill, plugin: e.plugin, by_person: e.by_person, by_agent: e.by_agent });
82
+ }
83
+ }
84
+ }
67
85
  /** Most used first, ties by name, so the stored list is stable. */
68
86
  toList() {
69
87
  return [...this.counts.values()]
@@ -103,6 +103,12 @@ export interface SessionFactsAccumulator {
103
103
  codex_model_hint: string | null;
104
104
  skill_tally: SkillUseTally;
105
105
  spawn: SessionSpawn | null;
106
+ /** Set only by `session-facts-delta.ts` while it captures one file's contribution (BLI-22797). */
107
+ usage_log?: Array<{
108
+ id: string;
109
+ model: string;
110
+ usage: Record<string, unknown>;
111
+ }>;
106
112
  }
107
113
  export declare function newSessionFactsAccumulator(source: SessionFactsSource): SessionFactsAccumulator;
108
114
  /** One transcript file's size, for callers that never hold its whole text. */
@@ -112,6 +118,7 @@ export declare function observeSessionFactsFile(acc: SessionFactsAccumulator, fi
112
118
  }): void;
113
119
  /** One parsed JSONL record. The caller owns parsing; this owns the rules. */
114
120
  export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): void;
121
+ export declare function addClaudeUsage(acc: SessionFactsAccumulator, model: string, usage: Record<string, unknown>): void;
115
122
  /**
116
123
  * OpenAI semantics differ from the Anthropic-shaped usage the price table
117
124
  * assumes: `input_tokens` INCLUDES `cached_input_tokens` and `output_tokens`
@@ -106,13 +106,13 @@ function observeClaudeRecord(acc, record) {
106
106
  const msg = message;
107
107
  const model = typeof msg["model"] === "string" ? msg["model"] : null;
108
108
  const usage = msg["usage"];
109
- // One API request emits several records repeating the same usage; the id is
110
- // what makes summing them safe.
109
+ // One API request emits several records repeating the same usage; the id makes summing safe.
111
110
  const usageId = (typeof msg["id"] === "string" && msg["id"]) ||
112
111
  (typeof record["requestId"] === "string" && record["requestId"]) ||
113
112
  null;
114
113
  if (model && usage && typeof usage === "object" && usageId && !acc.seen_usage_ids.has(usageId)) {
115
114
  acc.seen_usage_ids.add(usageId);
115
+ acc.usage_log?.push({ id: usageId, model, usage: usage });
116
116
  addClaudeUsage(acc, model, usage);
117
117
  }
118
118
  if (claudeAssistantText(record)?.trim())
@@ -177,7 +177,7 @@ function countTool(acc, name) {
177
177
  const key = name.slice(0, MAX_TOOL_NAME_CHARS) || "unknown";
178
178
  acc.tool_calls_by_name[key] = (acc.tool_calls_by_name[key] ?? 0) + 1;
179
179
  }
180
- function addClaudeUsage(acc, model, usage) {
180
+ export function addClaudeUsage(acc, model, usage) {
181
181
  const key = model.slice(0, MAX_MODEL_NAME_CHARS);
182
182
  const current = acc.usage_by_model[key] ?? emptyUsage();
183
183
  current.input_tokens += num(usage["input_tokens"]);
@@ -203,9 +203,7 @@ export function codexUsageFromCumulativeTotal(total) {
203
203
  };
204
204
  }
205
205
  export function finalizeSessionFacts(acc) {
206
- // A Codex session whose usage never named a model is left uncounted rather
207
- // than filed under a guess: det.v5 did the same, and a token total on the
208
- // wrong model is money attributed to the wrong place.
206
+ // A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
209
207
  if (acc.codex_total_usage && acc.codex_model_hint) {
210
208
  acc.usage_by_model[acc.codex_model_hint.slice(0, MAX_MODEL_NAME_CHARS)] =
211
209
  codexUsageFromCumulativeTotal(acc.codex_total_usage);
@@ -264,9 +262,7 @@ export function observeSessionFactsContent(acc, content) {
264
262
  record = JSON.parse(line);
265
263
  }
266
264
  catch {
267
- // Silent by design: the parser's message quotes the offending line,
268
- // which is transcript content. The line still counts toward the file's
269
- // line total, so the loss is visible as a number.
265
+ // Silent by design: the parser's message quotes the line (transcript content); the line still counts in the total.
270
266
  continue;
271
267
  }
272
268
  if (!record || typeof record !== "object" || Array.isArray(record))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.81",
3
+ "version": "0.1.82",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",