@bli-cockpit/telemetry-core 0.1.95 → 0.1.97

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.
@@ -16,6 +16,7 @@
16
16
  * Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
17
17
  */
18
18
  import { type SessionFactsAccumulator, type SessionFactsSource } from "./session-facts.js";
19
+ import type { HandsOnDelta } from "./session-facts-hands-on.js";
19
20
  import type { SessionSpawn } from "./session-facts-spawn.js";
20
21
  import type { SkillUseCount } from "./session-facts-skills.js";
21
22
  /** `[request id, model, input, output, cache read, cache creation]`. */
@@ -36,6 +37,8 @@ export interface SessionFactsDelta {
36
37
  codex_model_hint: string | null;
37
38
  skills: SkillUseCount[];
38
39
  spawn: SessionSpawn | null;
40
+ /** BLI-23623: this file's human events and classification counts. */
41
+ hands_on: HandsOnDelta;
39
42
  }
40
43
  /** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
41
44
  export declare function captureSessionFactsDelta(source: SessionFactsSource, feed: (acc: SessionFactsAccumulator) => void): SessionFactsDelta;
@@ -45,6 +45,7 @@ export function captureSessionFactsDelta(source, feed) {
45
45
  codex_model_hint: acc.codex_model_hint,
46
46
  skills: acc.skill_tally.entries(),
47
47
  spawn: acc.spawn ? { ...acc.spawn } : null,
48
+ hands_on: acc.hands_on.toDelta(),
48
49
  };
49
50
  }
50
51
  /** Leave `acc` as a fresh read of the same file would have left it. */
@@ -83,6 +84,7 @@ export function mergeSessionFactsDelta(acc, delta) {
83
84
  acc.skill_tally.mergeEntries(delta.skills);
84
85
  if (!acc.spawn && delta.spawn)
85
86
  acc.spawn = { ...delta.spawn };
87
+ acc.hands_on.mergeDelta(delta.hands_on);
86
88
  }
87
89
  const isNum = (v) => typeof v === "number" && Number.isFinite(v);
88
90
  const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
@@ -118,5 +120,14 @@ export function parseSessionFactsDelta(value) {
118
120
  const spawn = v["spawn"];
119
121
  if (spawn !== null && !(isObj(spawn) && typeof spawn["kind"] === "string"))
120
122
  return null;
123
+ const handsOn = v["hands_on"];
124
+ if (!isObj(handsOn) || !Array.isArray(handsOn["events"]))
125
+ return null;
126
+ if (!handsOn["events"].every((e) => Array.isArray(e) && e.length === 2 && typeof e[0] === "string" && isNum(e[1])))
127
+ return null;
128
+ for (const key of ["human_count", "not_human_count", "unknown_count", "turn_starts"]) {
129
+ if (!isNum(handsOn[key]))
130
+ return null;
131
+ }
121
132
  return value;
122
133
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Hands-on time estimate (BLI-23623, rule `hands_on.v1`): an ESTIMATE of how long a person was engaged with a
3
+ * session, computed only from the timestamps of the messages THEY sent. It does not measure attention and makes
4
+ * no accuracy claim until it is compared with independently timed real activity.
5
+ *
6
+ * The rule, immutable per rule id:
7
+ * - Every confirmed human event (a Claude prompt `uuid`, a Codex human root `turn_id`) credits the fixed window
8
+ * [t - 3 min, t + 5 min]. Windows do not depend on what the agent did in between.
9
+ * - Windows are unioned inside a session; the server unions again across a person's sessions after deduping
10
+ * replayed events by identity (forks and resumes copy history).
11
+ *
12
+ * Classification is provisional ("v1") until validated on captured real records of known actions. Precedence:
13
+ * Claude: (0) compaction summary: not human, whatever tags it carries (machine-written);
14
+ * (1) `origin.kind` or `turnOrigin` == human: human;
15
+ * (2) `promptSource` typed | queued | suggestion_accepted: human;
16
+ * (3) task-notification / peer / scheduled / system / coordinator origin, isMeta, isSidechain,
17
+ * tool_result-only: not human;
18
+ * (4) anything else (untagged records of an older client, `sdk`): UNKNOWN. Counted in coverage, never
19
+ * silently treated as "no human".
20
+ * Codex: `task_started.turn_attribution.turn_trigger` user | composer | queue with a null `parent_turn_id` and
21
+ * a null `initiating_agent_path`: human; exec | guardian_review (or a nested turn): not human; missing
22
+ * attribution or any other trigger: unknown.
23
+ *
24
+ * Pure. Metadata out: event ids, timestamps, counts. No text is returned.
25
+ */
26
+ import { z } from "zod";
27
+ export declare const HANDS_ON_RULE_ID = "hands_on.v1";
28
+ export declare const HANDS_ON_BEFORE_MS: number;
29
+ export declare const HANDS_ON_AFTER_MS: number;
30
+ /** One session reports at most this many human events; `events_truncated` says how many were dropped. */
31
+ export declare const HANDS_ON_MAX_EVENTS = 10000;
32
+ export type HandsOnLabel = "human" | "not_human" | "unknown";
33
+ export interface HandsOnClassification {
34
+ label: HandsOnLabel;
35
+ /** A short constant naming the rule that decided (for tests and logs, never content). */
36
+ reason: string;
37
+ }
38
+ /** Decide whether one Claude `type:"user"` record is a message the person sent. */
39
+ export declare function classifyClaudeUserRecord(record: Record<string, unknown>): HandsOnClassification;
40
+ /** Decide whether one Codex `task_started` payload opened a turn the person started. */
41
+ export declare function classifyCodexTaskStarted(payload: Record<string, unknown>): HandsOnClassification;
42
+ /** Codex's identity for a human event: the root turn id. */
43
+ export declare function codexTurnId(payload: Record<string, unknown>): string | null;
44
+ /** Merge `[start, end]` ms intervals (sorted by start, touching intervals join). */
45
+ export declare function mergeIntervals(intervals: ReadonlyArray<readonly [number, number]>): Array<[number, number]>;
46
+ export declare function handsOnWindow(tsMs: number): [number, number];
47
+ export declare function intervalsMs(intervals: ReadonlyArray<readonly [number, number]>): number;
48
+ /** One file's contribution, in the form `session-facts-delta.ts` remembers and replays. */
49
+ export interface HandsOnDelta {
50
+ /** `[event id, ts ms]` per human event, first seen of an id wins, sorted by ts. */
51
+ events: Array<[string, number]>;
52
+ human_count: number;
53
+ not_human_count: number;
54
+ unknown_count: number;
55
+ /** Codex `task_started` records seen, so a Codex file with none can report its prompts as unknown. */
56
+ turn_starts: number;
57
+ }
58
+ export declare function emptyHandsOnDelta(): HandsOnDelta;
59
+ /** Collects a session's classified events record by record. */
60
+ export declare class HandsOnTally {
61
+ private readonly byId;
62
+ human: number;
63
+ notHuman: number;
64
+ unknown: number;
65
+ turnStarts: number;
66
+ /** Count one classified record. A human record with no usable timestamp cannot credit a window, so it counts as unknown. */
67
+ observe(classification: HandsOnClassification, id: string | null, tsMs: number | null): void;
68
+ mergeDelta(delta: HandsOnDelta): void;
69
+ toDelta(): HandsOnDelta;
70
+ }
71
+ export declare const HandsOnFactsSchema: z.ZodObject<{
72
+ rule_id: z.ZodLiteral<"hands_on.v1">;
73
+ seconds: z.ZodNumber;
74
+ events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
75
+ intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
76
+ human_count: z.ZodNumber;
77
+ not_human_count: z.ZodNumber;
78
+ unknown_count: z.ZodNumber;
79
+ events_truncated: z.ZodNumber;
80
+ }, z.core.$strict>;
81
+ export type HandsOnFacts = z.infer<typeof HandsOnFactsSchema>;
82
+ /**
83
+ * The finished answer. `codexUserPrompts` lets a Codex file with no `task_started` records at all (an older
84
+ * client) report its prompts as unknown instead of reporting nothing.
85
+ */
86
+ export declare function finalizeHandsOn(tally: HandsOnTally, codexUserPrompts: number): HandsOnFacts;
87
+ /** Counts only, for one scan's log line: how many sessions carried the estimate and how the records classified. */
88
+ export declare function summarizeHandsOn(facts: ReadonlyArray<{
89
+ hands_on?: HandsOnFacts;
90
+ } | null | undefined>): {
91
+ rule_id: string;
92
+ sessions: number;
93
+ sessions_with_events: number;
94
+ human: number;
95
+ not_human: number;
96
+ unknown: number;
97
+ seconds: number;
98
+ };
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Hands-on time estimate (BLI-23623, rule `hands_on.v1`): an ESTIMATE of how long a person was engaged with a
3
+ * session, computed only from the timestamps of the messages THEY sent. It does not measure attention and makes
4
+ * no accuracy claim until it is compared with independently timed real activity.
5
+ *
6
+ * The rule, immutable per rule id:
7
+ * - Every confirmed human event (a Claude prompt `uuid`, a Codex human root `turn_id`) credits the fixed window
8
+ * [t - 3 min, t + 5 min]. Windows do not depend on what the agent did in between.
9
+ * - Windows are unioned inside a session; the server unions again across a person's sessions after deduping
10
+ * replayed events by identity (forks and resumes copy history).
11
+ *
12
+ * Classification is provisional ("v1") until validated on captured real records of known actions. Precedence:
13
+ * Claude: (0) compaction summary: not human, whatever tags it carries (machine-written);
14
+ * (1) `origin.kind` or `turnOrigin` == human: human;
15
+ * (2) `promptSource` typed | queued | suggestion_accepted: human;
16
+ * (3) task-notification / peer / scheduled / system / coordinator origin, isMeta, isSidechain,
17
+ * tool_result-only: not human;
18
+ * (4) anything else (untagged records of an older client, `sdk`): UNKNOWN. Counted in coverage, never
19
+ * silently treated as "no human".
20
+ * Codex: `task_started.turn_attribution.turn_trigger` user | composer | queue with a null `parent_turn_id` and
21
+ * a null `initiating_agent_path`: human; exec | guardian_review (or a nested turn): not human; missing
22
+ * attribution or any other trigger: unknown.
23
+ *
24
+ * Pure. Metadata out: event ids, timestamps, counts. No text is returned.
25
+ */
26
+ import { z } from "zod";
27
+ export const HANDS_ON_RULE_ID = "hands_on.v1";
28
+ export const HANDS_ON_BEFORE_MS = 3 * 60 * 1000;
29
+ export const HANDS_ON_AFTER_MS = 5 * 60 * 1000;
30
+ /** One session reports at most this many human events; `events_truncated` says how many were dropped. */
31
+ export const HANDS_ON_MAX_EVENTS = 10_000;
32
+ const MAX_EVENT_ID_CHARS = 80;
33
+ const HUMAN_PROMPT_SOURCES = new Set(["typed", "queued", "suggestion_accepted"]);
34
+ const NOT_HUMAN_TURN_ORIGINS = new Set(["task_notification", "peer", "scheduled", "system"]);
35
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
36
+ const str = (v) => (typeof v === "string" && v ? v : null);
37
+ /** Is this user record's content only tool results (the agent's tool output echoed back)? */
38
+ function toolResultOnly(record) {
39
+ if (record["toolUseResult"] !== undefined)
40
+ return true;
41
+ const message = record["message"];
42
+ const content = isObj(message) ? message["content"] : undefined;
43
+ return Array.isArray(content) && content.length > 0 && content.every((b) => isObj(b) && b["type"] === "tool_result");
44
+ }
45
+ /** Decide whether one Claude `type:"user"` record is a message the person sent. */
46
+ export function classifyClaudeUserRecord(record) {
47
+ if (record["isCompactSummary"] === true)
48
+ return { label: "not_human", reason: "compact_summary" };
49
+ const origin = isObj(record["origin"]) ? str(record["origin"]["kind"]) : null;
50
+ const turnOrigin = str(record["turnOrigin"]);
51
+ if (origin === "human")
52
+ return { label: "human", reason: "origin_human" };
53
+ if (turnOrigin === "human")
54
+ return { label: "human", reason: "turn_origin_human" };
55
+ const promptSource = str(record["promptSource"]);
56
+ if (promptSource && HUMAN_PROMPT_SOURCES.has(promptSource))
57
+ return { label: "human", reason: "prompt_source_human" };
58
+ if (origin)
59
+ return { label: "not_human", reason: "origin_" + origin.slice(0, 30) };
60
+ if (turnOrigin && NOT_HUMAN_TURN_ORIGINS.has(turnOrigin))
61
+ return { label: "not_human", reason: "turn_origin_" + turnOrigin };
62
+ if (promptSource === "system")
63
+ return { label: "not_human", reason: "prompt_source_system" };
64
+ if (record["isMeta"] === true)
65
+ return { label: "not_human", reason: "meta" };
66
+ if (record["isSidechain"] === true)
67
+ return { label: "not_human", reason: "sidechain" };
68
+ if (toolResultOnly(record))
69
+ return { label: "not_human", reason: "tool_result_only" };
70
+ return { label: "unknown", reason: "untagged" };
71
+ }
72
+ const HUMAN_CODEX_TRIGGERS = new Set(["user", "composer", "queue"]);
73
+ const MACHINE_CODEX_TRIGGERS = new Set(["exec", "guardian_review"]);
74
+ /** Decide whether one Codex `task_started` payload opened a turn the person started. */
75
+ export function classifyCodexTaskStarted(payload) {
76
+ const attribution = payload["turn_attribution"];
77
+ if (!isObj(attribution))
78
+ return { label: "unknown", reason: "no_attribution" };
79
+ const trigger = str(attribution["turn_trigger"]);
80
+ if (!trigger)
81
+ return { label: "unknown", reason: "no_trigger" };
82
+ if (MACHINE_CODEX_TRIGGERS.has(trigger))
83
+ return { label: "not_human", reason: "trigger_" + trigger };
84
+ if (HUMAN_CODEX_TRIGGERS.has(trigger)) {
85
+ const nested = str(attribution["parent_turn_id"]) !== null || str(attribution["initiating_agent_path"]) !== null;
86
+ return nested ? { label: "not_human", reason: "nested_turn" } : { label: "human", reason: "trigger_" + trigger };
87
+ }
88
+ return { label: "unknown", reason: "trigger_other" };
89
+ }
90
+ /** Codex's identity for a human event: the root turn id. */
91
+ export function codexTurnId(payload) {
92
+ const attribution = isObj(payload["turn_attribution"]) ? payload["turn_attribution"] : {};
93
+ return str(attribution["turn_id"]) ?? str(payload["turn_id"]);
94
+ }
95
+ /** Merge `[start, end]` ms intervals (sorted by start, touching intervals join). */
96
+ export function mergeIntervals(intervals) {
97
+ const sorted = [...intervals].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
98
+ const out = [];
99
+ for (const [start, end] of sorted) {
100
+ const last = out[out.length - 1];
101
+ if (last && start <= last[1])
102
+ last[1] = Math.max(last[1], end);
103
+ else
104
+ out.push([start, end]);
105
+ }
106
+ return out;
107
+ }
108
+ export function handsOnWindow(tsMs) {
109
+ return [tsMs - HANDS_ON_BEFORE_MS, tsMs + HANDS_ON_AFTER_MS];
110
+ }
111
+ export function intervalsMs(intervals) {
112
+ return intervals.reduce((sum, [start, end]) => sum + Math.max(0, end - start), 0);
113
+ }
114
+ export function emptyHandsOnDelta() {
115
+ return { events: [], human_count: 0, not_human_count: 0, unknown_count: 0, turn_starts: 0 };
116
+ }
117
+ /** Collects a session's classified events record by record. */
118
+ export class HandsOnTally {
119
+ byId = new Map();
120
+ human = 0;
121
+ notHuman = 0;
122
+ unknown = 0;
123
+ turnStarts = 0;
124
+ /** Count one classified record. A human record with no usable timestamp cannot credit a window, so it counts as unknown. */
125
+ observe(classification, id, tsMs) {
126
+ if (classification.label === "not_human")
127
+ return void (this.notHuman += 1);
128
+ if (classification.label === "unknown")
129
+ return void (this.unknown += 1);
130
+ if (tsMs == null)
131
+ return void (this.unknown += 1);
132
+ this.human += 1;
133
+ // A record with no identity gets one from its timestamp: replays of it dedupe, two distinct ones in a ms collapse.
134
+ const key = (id ?? "ts-" + tsMs).slice(0, MAX_EVENT_ID_CHARS);
135
+ const seen = this.byId.get(key);
136
+ if (seen === undefined || tsMs < seen)
137
+ this.byId.set(key, tsMs);
138
+ }
139
+ mergeDelta(delta) {
140
+ this.human += delta.human_count;
141
+ this.notHuman += delta.not_human_count;
142
+ this.unknown += delta.unknown_count;
143
+ this.turnStarts += delta.turn_starts;
144
+ for (const [id, ts] of delta.events) {
145
+ const seen = this.byId.get(id);
146
+ if (seen === undefined || ts < seen)
147
+ this.byId.set(id, ts);
148
+ }
149
+ }
150
+ toDelta() {
151
+ return {
152
+ events: [...this.byId.entries()].sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0])),
153
+ human_count: this.human,
154
+ not_human_count: this.notHuman,
155
+ unknown_count: this.unknown,
156
+ turn_starts: this.turnStarts,
157
+ };
158
+ }
159
+ }
160
+ export const HandsOnFactsSchema = z
161
+ .object({
162
+ rule_id: z.literal(HANDS_ON_RULE_ID),
163
+ seconds: z.number().int().nonnegative(),
164
+ events: z.array(z.tuple([z.string().min(1).max(MAX_EVENT_ID_CHARS), z.number().int()])).max(HANDS_ON_MAX_EVENTS),
165
+ intervals: z.array(z.tuple([z.number().int(), z.number().int()])).max(HANDS_ON_MAX_EVENTS),
166
+ human_count: z.number().int().nonnegative(),
167
+ not_human_count: z.number().int().nonnegative(),
168
+ unknown_count: z.number().int().nonnegative(),
169
+ events_truncated: z.number().int().nonnegative(),
170
+ })
171
+ .strict();
172
+ /**
173
+ * The finished answer. `codexUserPrompts` lets a Codex file with no `task_started` records at all (an older
174
+ * client) report its prompts as unknown instead of reporting nothing.
175
+ */
176
+ export function finalizeHandsOn(tally, codexUserPrompts) {
177
+ const delta = tally.toDelta();
178
+ const unknown = delta.unknown_count + (delta.turn_starts === 0 && codexUserPrompts > 0 && delta.human_count === 0 ? codexUserPrompts : 0);
179
+ const intervals = mergeIntervals(delta.events.map(([, ts]) => handsOnWindow(ts)));
180
+ const kept = delta.events.slice(0, HANDS_ON_MAX_EVENTS);
181
+ return {
182
+ rule_id: HANDS_ON_RULE_ID,
183
+ seconds: Math.round(intervalsMs(intervals) / 1000),
184
+ events: kept,
185
+ intervals: intervals.slice(0, HANDS_ON_MAX_EVENTS),
186
+ human_count: delta.human_count,
187
+ not_human_count: delta.not_human_count,
188
+ unknown_count: unknown,
189
+ events_truncated: delta.events.length - kept.length,
190
+ };
191
+ }
192
+ /** Counts only, for one scan's log line: how many sessions carried the estimate and how the records classified. */
193
+ export function summarizeHandsOn(facts) {
194
+ const out = { rule_id: HANDS_ON_RULE_ID, sessions: 0, sessions_with_events: 0, human: 0, not_human: 0, unknown: 0, seconds: 0 };
195
+ for (const f of facts) {
196
+ const h = f?.hands_on;
197
+ if (!h)
198
+ continue;
199
+ out.sessions += 1;
200
+ if (h.events.length > 0)
201
+ out.sessions_with_events += 1;
202
+ out.human += h.human_count;
203
+ out.not_human += h.not_human_count;
204
+ out.unknown += h.unknown_count;
205
+ out.seconds += h.seconds;
206
+ }
207
+ return out;
208
+ }
@@ -17,7 +17,7 @@ export type SessionSpawnKind = "interactive" | "worker" | "subagent";
17
17
  * `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
18
18
  * `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
19
19
  */
20
- export declare const CLIENT_APPS: readonly ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
20
+ export declare const CLIENT_APPS: readonly ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "t3_code", "unknown"];
21
21
  export type ClientApp = (typeof CLIENT_APPS)[number];
22
22
  export interface SessionSpawn {
23
23
  kind: SessionSpawnKind;
@@ -41,6 +41,7 @@ export declare const SessionSpawnSchema: z.ZodObject<{
41
41
  codex_desktop: "codex_desktop";
42
42
  codex_ide: "codex_ide";
43
43
  codex_exec: "codex_exec";
44
+ t3_code: "t3_code";
44
45
  }>>;
45
46
  parent_session_id: z.ZodOptional<z.ZodString>;
46
47
  }, z.core.$strict>;
@@ -15,7 +15,7 @@ import { z } from "zod";
15
15
  * `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
16
16
  * `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
17
17
  */
18
- export const CLIENT_APPS = ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
18
+ export const CLIENT_APPS = ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "t3_code", "unknown"];
19
19
  const SPAWN_ID = /^[A-Za-z0-9._-]{1,80}$/u;
20
20
  const spawnId = (value) => typeof value === "string" && SPAWN_ID.test(value) ? value : undefined;
21
21
  export const SessionSpawnSchema = z
@@ -88,6 +88,8 @@ export function codexSpawn(current, meta) {
88
88
  * run, not a Codex client a person used, so it is `unknown`.
89
89
  */
90
90
  export function codexClientApp(originator, source) {
91
+ if (originator === "T3 Code")
92
+ return "t3_code";
91
93
  if (originator === "codex_exec")
92
94
  return "codex_exec";
93
95
  if (originator === "Codex Desktop" || originator === "codex_work_desktop")
@@ -0,0 +1,6 @@
1
+ /** Small pure helpers of `session-facts.ts` (moved out so that file stays under the readability band, BLI-23623). */
2
+ import type { SessionFactsUsage } from "./session-facts.js";
3
+ export declare function usageTotal(usage: SessionFactsUsage): number;
4
+ export declare function emptyUsage(): SessionFactsUsage;
5
+ export declare function sumUsage(usages: readonly SessionFactsUsage[]): SessionFactsUsage;
6
+ export declare function byteLength(value: string): number;
@@ -0,0 +1,27 @@
1
+ export function usageTotal(usage) {
2
+ return (usage.input_tokens +
3
+ usage.output_tokens +
4
+ usage.cache_read_input_tokens +
5
+ usage.cache_creation_input_tokens);
6
+ }
7
+ export function emptyUsage() {
8
+ return {
9
+ input_tokens: 0,
10
+ output_tokens: 0,
11
+ cache_read_input_tokens: 0,
12
+ cache_creation_input_tokens: 0,
13
+ };
14
+ }
15
+ export function sumUsage(usages) {
16
+ return usages.reduce((sum, usage) => ({
17
+ input_tokens: sum.input_tokens + usage.input_tokens,
18
+ output_tokens: sum.output_tokens + usage.output_tokens,
19
+ cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
20
+ cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
21
+ }), emptyUsage());
22
+ }
23
+ export function byteLength(value) {
24
+ return typeof Buffer === "undefined"
25
+ ? new TextEncoder().encode(value).length
26
+ : Buffer.byteLength(value, "utf8");
27
+ }
@@ -32,6 +32,7 @@
32
32
  * Anthropic-shaped usage the price table expects.
33
33
  */
34
34
  import { z } from "zod";
35
+ import { HandsOnTally, type HandsOnFacts } from "./session-facts-hands-on.js";
35
36
  import { type SessionSpawn } from "./session-facts-spawn.js";
36
37
  import { SkillUseTally } from "./session-facts-skills.js";
37
38
  import type { SkillUseCount } from "./session-facts-skills.js";
@@ -83,6 +84,8 @@ export interface SessionFacts {
83
84
  skill_use?: SkillUseCount[];
84
85
  /** BLI-13066: who started the session (`session-facts-spawn.ts`). Absent from a block a CLI published before this field. */
85
86
  spawn?: SessionSpawn;
87
+ /** BLI-23623: hands-on estimate from the person's own message timestamps (`session-facts-hands-on.ts`). Absent from a block a CLI published before this field. */
88
+ hands_on?: HandsOnFacts;
86
89
  }
87
90
  export interface SessionFactsAccumulator {
88
91
  source: SessionFactsSource;
@@ -103,6 +106,7 @@ export interface SessionFactsAccumulator {
103
106
  codex_model_hint: string | null;
104
107
  skill_tally: SkillUseTally;
105
108
  spawn: SessionSpawn | null;
109
+ hands_on: HandsOnTally;
106
110
  /** Set only by `session-facts-delta.ts` while it captures one file's contribution (BLI-22797). */
107
111
  usage_log?: Array<{
108
112
  id: string;
@@ -117,7 +121,7 @@ export declare function observeSessionFactsFile(acc: SessionFactsAccumulator, fi
117
121
  lines: number;
118
122
  }): void;
119
123
  /** One parsed JSONL record. The caller owns parsing; this owns the rules. */
120
- export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): void;
124
+ export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): boolean;
121
125
  export declare function addClaudeUsage(acc: SessionFactsAccumulator, model: string, usage: Record<string, unknown>): void;
122
126
  /**
123
127
  * OpenAI semantics differ from the Anthropic-shaped usage the price table
@@ -210,9 +214,20 @@ export declare const SessionFactsSchema: z.ZodObject<{
210
214
  codex_desktop: "codex_desktop";
211
215
  codex_ide: "codex_ide";
212
216
  codex_exec: "codex_exec";
217
+ t3_code: "t3_code";
213
218
  }>>;
214
219
  parent_session_id: z.ZodOptional<z.ZodString>;
215
220
  }, z.core.$strict>>;
221
+ hands_on: z.ZodOptional<z.ZodObject<{
222
+ rule_id: z.ZodLiteral<"hands_on.v1">;
223
+ seconds: z.ZodNumber;
224
+ events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
225
+ intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
226
+ human_count: z.ZodNumber;
227
+ not_human_count: z.ZodNumber;
228
+ unknown_count: z.ZodNumber;
229
+ events_truncated: z.ZodNumber;
230
+ }, z.core.$strict>>;
216
231
  }, z.core.$strict>;
217
232
  export type SessionFactsWire = z.infer<typeof SessionFactsSchema>;
218
233
  export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
@@ -32,8 +32,11 @@
32
32
  * Anthropic-shaped usage the price table expects.
33
33
  */
34
34
  import { z } from "zod";
35
+ import { includeCodexRevisionRecord, observeCodexCumulativeUsage, codexRevisionUsageModel } from "./codex-record-copies.js";
35
36
  import { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText } from "./session-facts-text.js";
36
37
  import { activeSeconds } from "./session-facts-active.js";
38
+ import { byteLength, emptyUsage, sumUsage, usageTotal } from "./session-facts-usage-math.js";
39
+ import { classifyClaudeUserRecord, classifyCodexTaskStarted, codexTurnId, finalizeHandsOn, HandsOnFactsSchema, HandsOnTally, } from "./session-facts-hands-on.js";
37
40
  import { claudeSpawn, codexSpawn, SessionSpawnSchema } from "./session-facts-spawn.js";
38
41
  import { observeClaudeSkillUse, observeCodexSkillUse, SKILL_USE_MAX_SKILLS, SkillUseCountSchema, SkillUseTally } from "./session-facts-skills.js";
39
42
  /** Bump when a counting rule changes, never when a field is added. */
@@ -62,6 +65,7 @@ export function newSessionFactsAccumulator(source) {
62
65
  codex_model_hint: null,
63
66
  skill_tally: new SkillUseTally(),
64
67
  spawn: null,
68
+ hands_on: new HandsOnTally(),
65
69
  };
66
70
  }
67
71
  /** One transcript file's size, for callers that never hold its whole text. */
@@ -72,6 +76,8 @@ export function observeSessionFactsFile(acc, file) {
72
76
  }
73
77
  /** One parsed JSONL record. The caller owns parsing; this owns the rules. */
74
78
  export function observeSessionFactsRecord(acc, record) {
79
+ if (acc.source === "codex" && !includeCodexRevisionRecord(acc, record))
80
+ return false;
75
81
  acc.record_count += 1;
76
82
  const ms = parseTimestampMs(record["timestamp"]);
77
83
  if (ms != null) {
@@ -85,11 +91,13 @@ export function observeSessionFactsRecord(acc, record) {
85
91
  observeClaudeRecord(acc, record);
86
92
  else
87
93
  observeCodexRecord(acc, record);
94
+ return true;
88
95
  }
89
96
  function observeClaudeRecord(acc, record) {
90
97
  const type = typeof record["type"] === "string" ? record["type"] : "";
91
98
  acc.spawn = claudeSpawn(acc.spawn, record);
92
99
  if (type === "user") {
100
+ acc.hands_on.observe(classifyClaudeUserRecord(record), typeof record["uuid"] === "string" ? record["uuid"] : null, parseTimestampMs(record["timestamp"]));
93
101
  if (record["isMeta"] === true)
94
102
  return;
95
103
  const text = claudeUserTurnText(record);
@@ -162,6 +170,11 @@ function observeCodexRecord(acc, record) {
162
170
  }
163
171
  if (type !== "event_msg")
164
172
  return;
173
+ if (String(p["type"] ?? "") === "task_started") {
174
+ acc.hands_on.turnStarts += 1;
175
+ acc.hands_on.observe(classifyCodexTaskStarted(p), codexTurnId(p), parseTimestampMs(record["timestamp"]));
176
+ return;
177
+ }
165
178
  if (String(p["type"] ?? "") !== "token_count")
166
179
  return;
167
180
  const info = p["info"];
@@ -170,7 +183,7 @@ function observeCodexRecord(acc, record) {
170
183
  const total = info["total_token_usage"];
171
184
  // Cumulative: the last event of the session is the session total.
172
185
  if (total && typeof total === "object") {
173
- acc.codex_total_usage = total;
186
+ observeCodexCumulativeUsage(acc, record, total);
174
187
  }
175
188
  }
176
189
  function countTool(acc, name) {
@@ -204,8 +217,9 @@ export function codexUsageFromCumulativeTotal(total) {
204
217
  }
205
218
  export function finalizeSessionFacts(acc) {
206
219
  // A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
207
- if (acc.codex_total_usage && acc.codex_model_hint) {
208
- acc.usage_by_model[acc.codex_model_hint.slice(0, MAX_MODEL_NAME_CHARS)] =
220
+ const usageModel = codexRevisionUsageModel(acc);
221
+ if (acc.codex_total_usage && usageModel) {
222
+ acc.usage_by_model[usageModel.slice(0, MAX_MODEL_NAME_CHARS)] =
209
223
  codexUsageFromCumulativeTotal(acc.codex_total_usage);
210
224
  }
211
225
  const usageEntries = Object.entries(acc.usage_by_model).sort((a, b) => usageTotal(b[1]) - usageTotal(a[1]) || a[0].localeCompare(b[0]));
@@ -244,6 +258,7 @@ export function finalizeSessionFacts(acc) {
244
258
  skill_use: acc.skill_tally.toList().slice(0, SKILL_USE_MAX_SKILLS),
245
259
  ...(acc.spawn ? { spawn: acc.spawn } : {}),
246
260
  active_seconds: activeSeconds(acc.timestamps_ms),
261
+ hands_on: finalizeHandsOn(acc.hands_on, acc.source === "codex" ? acc.user_prompt_count : 0),
247
262
  };
248
263
  }
249
264
  /**
@@ -285,33 +300,6 @@ export function computeSessionFacts(options) {
285
300
  }
286
301
  return finalizeSessionFacts(acc);
287
302
  }
288
- function usageTotal(usage) {
289
- return (usage.input_tokens +
290
- usage.output_tokens +
291
- usage.cache_read_input_tokens +
292
- usage.cache_creation_input_tokens);
293
- }
294
- function sumUsage(usages) {
295
- return usages.reduce((sum, usage) => ({
296
- input_tokens: sum.input_tokens + usage.input_tokens,
297
- output_tokens: sum.output_tokens + usage.output_tokens,
298
- cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
299
- cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
300
- }), emptyUsage());
301
- }
302
- function emptyUsage() {
303
- return {
304
- input_tokens: 0,
305
- output_tokens: 0,
306
- cache_read_input_tokens: 0,
307
- cache_creation_input_tokens: 0,
308
- };
309
- }
310
- function byteLength(value) {
311
- return typeof Buffer === "undefined"
312
- ? new TextEncoder().encode(value).length
313
- : Buffer.byteLength(value, "utf8");
314
- }
315
303
  function parseTimestampMs(value) {
316
304
  if (typeof value !== "string")
317
305
  return null;
@@ -367,6 +355,7 @@ export const SessionFactsSchema = z
367
355
  truncated_tool_names: z.number().int().nonnegative(),
368
356
  skill_use: z.array(SkillUseCountSchema).max(SKILL_USE_MAX_SKILLS).optional(),
369
357
  spawn: SessionSpawnSchema.optional(),
358
+ hands_on: HandsOnFactsSchema.optional(),
370
359
  })
371
360
  .strict();
372
361
  export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
@@ -112,7 +112,9 @@ export function setupReceiptPieces(receipt, memory) {
112
112
  const reason = memory?.reasons?.[key];
113
113
  return {
114
114
  status: word,
115
- ...(word !== "ok" && reason ? { reason } : {}),
115
+ // BLI-24349: `ok` keeps one reason, `managed_by_system`, so a machine
116
+ // card can say HOW Codex runs the hooks (no trust step needed).
117
+ ...((word !== "ok" || reason === "managed_by_system") && reason ? { reason } : {}),
116
118
  };
117
119
  };
118
120
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.95",
3
+ "version": "0.1.97",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",