@bli-cockpit/telemetry-core 0.1.97 → 0.1.98

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.
@@ -0,0 +1,109 @@
1
+ /** Wire validation and bounded cardinalities shared by collector and server facts. */
2
+ import { z } from "zod";
3
+ export declare const SESSION_FACTS_MAX_MODELS = 50;
4
+ export declare const SESSION_FACTS_MAX_TOOL_NAMES = 200;
5
+ export declare const MAX_MODEL_NAME_CHARS = 200;
6
+ export declare const MAX_TOOL_NAME_CHARS = 120;
7
+ export declare const SessionFactsUsageSchema: z.ZodObject<{
8
+ input_tokens: z.ZodNumber;
9
+ output_tokens: z.ZodNumber;
10
+ cache_read_input_tokens: z.ZodNumber;
11
+ cache_creation_input_tokens: z.ZodNumber;
12
+ }, z.core.$strict>;
13
+ /**
14
+ * The wire shape. Optional wherever it rides an envelope: a CLI published
15
+ * before this change sends no block at all, and its uploads must still
16
+ * validate.
17
+ */
18
+ export declare const SessionFactsSchema: z.ZodObject<{
19
+ extractor_version: z.ZodString;
20
+ source: z.ZodEnum<{
21
+ codex: "codex";
22
+ claude_code: "claude_code";
23
+ opencode: "opencode";
24
+ }>;
25
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
26
+ complete: "complete";
27
+ partial: "partial";
28
+ unavailable: "unavailable";
29
+ }>>;
30
+ usage_identity_scope: z.ZodOptional<z.ZodEnum<{
31
+ machine: "machine";
32
+ operator: "operator";
33
+ }>>;
34
+ usage_claims: z.ZodOptional<z.ZodArray<z.ZodObject<{
35
+ identity: z.ZodString;
36
+ model: z.ZodString;
37
+ usage: z.ZodObject<{
38
+ input_tokens: z.ZodNumber;
39
+ output_tokens: z.ZodNumber;
40
+ cache_read_input_tokens: z.ZodNumber;
41
+ cache_creation_input_tokens: z.ZodNumber;
42
+ }, z.core.$strict>;
43
+ }, z.core.$strict>>>;
44
+ unknown_usage_records: z.ZodOptional<z.ZodNumber>;
45
+ copied_usage_records: z.ZodOptional<z.ZodNumber>;
46
+ usage_by_model: z.ZodRecord<z.ZodString, z.ZodObject<{
47
+ input_tokens: z.ZodNumber;
48
+ output_tokens: z.ZodNumber;
49
+ cache_read_input_tokens: z.ZodNumber;
50
+ cache_creation_input_tokens: z.ZodNumber;
51
+ }, z.core.$strict>>;
52
+ models: z.ZodArray<z.ZodString>;
53
+ input_tokens: z.ZodNumber;
54
+ output_tokens: z.ZodNumber;
55
+ cache_read_tokens: z.ZodNumber;
56
+ cache_creation_tokens: z.ZodNumber;
57
+ total_tokens: z.ZodNumber;
58
+ record_count: z.ZodNumber;
59
+ turn_count: z.ZodNumber;
60
+ user_prompt_count: z.ZodNumber;
61
+ assistant_response_count: z.ZodNumber;
62
+ tool_calls_by_name: z.ZodRecord<z.ZodString, z.ZodNumber>;
63
+ tool_call_count: z.ZodNumber;
64
+ first_timestamp: z.ZodNullable<z.ZodString>;
65
+ last_timestamp: z.ZodNullable<z.ZodString>;
66
+ wall_duration_seconds: z.ZodNullable<z.ZodNumber>;
67
+ active_seconds: z.ZodOptional<z.ZodNumber>;
68
+ transcript_bytes: z.ZodNumber;
69
+ transcript_lines: z.ZodNumber;
70
+ transcript_files: z.ZodNumber;
71
+ truncated_models: z.ZodNumber;
72
+ truncated_tool_names: z.ZodNumber;
73
+ skill_use: z.ZodOptional<z.ZodArray<z.ZodObject<{
74
+ skill: z.ZodString;
75
+ plugin: z.ZodNullable<z.ZodString>;
76
+ by_person: z.ZodNumber;
77
+ by_agent: z.ZodNumber;
78
+ }, z.core.$strict>>>;
79
+ spawn: z.ZodOptional<z.ZodObject<{
80
+ kind: z.ZodEnum<{
81
+ interactive: "interactive";
82
+ worker: "worker";
83
+ subagent: "subagent";
84
+ }>;
85
+ client_app: z.ZodOptional<z.ZodEnum<{
86
+ unknown: "unknown";
87
+ claude_cli: "claude_cli";
88
+ claude_desktop: "claude_desktop";
89
+ claude_ide: "claude_ide";
90
+ codex_cli: "codex_cli";
91
+ codex_desktop: "codex_desktop";
92
+ codex_ide: "codex_ide";
93
+ codex_exec: "codex_exec";
94
+ t3_code: "t3_code";
95
+ }>>;
96
+ parent_session_id: z.ZodOptional<z.ZodString>;
97
+ }, z.core.$strict>>;
98
+ hands_on: z.ZodOptional<z.ZodObject<{
99
+ rule_id: z.ZodLiteral<"hands_on.v1">;
100
+ seconds: z.ZodNumber;
101
+ events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
102
+ intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
103
+ human_count: z.ZodNumber;
104
+ not_human_count: z.ZodNumber;
105
+ unknown_count: z.ZodNumber;
106
+ events_truncated: z.ZodNumber;
107
+ }, z.core.$strict>>;
108
+ }, z.core.$strict>;
109
+ export type SessionFactsWire = z.infer<typeof SessionFactsSchema>;
@@ -0,0 +1,63 @@
1
+ /** Wire validation and bounded cardinalities shared by collector and server facts. */
2
+ import { z } from "zod";
3
+ import { HandsOnFactsSchema } from "./session-facts-hands-on.js";
4
+ import { SessionSpawnSchema } from "./session-facts-spawn.js";
5
+ import { SKILL_USE_MAX_SKILLS, SkillUseCountSchema } from "./session-facts-skills.js";
6
+ export const SESSION_FACTS_MAX_MODELS = 50;
7
+ export const SESSION_FACTS_MAX_TOOL_NAMES = 200;
8
+ export const MAX_MODEL_NAME_CHARS = 200;
9
+ export const MAX_TOOL_NAME_CHARS = 120;
10
+ const TokenCountSchema = z.number().int().nonnegative().max(1_000_000_000_000);
11
+ export const SessionFactsUsageSchema = z
12
+ .object({
13
+ input_tokens: TokenCountSchema,
14
+ output_tokens: TokenCountSchema,
15
+ cache_read_input_tokens: TokenCountSchema,
16
+ cache_creation_input_tokens: TokenCountSchema,
17
+ })
18
+ .strict();
19
+ /**
20
+ * The wire shape. Optional wherever it rides an envelope: a CLI published
21
+ * before this change sends no block at all, and its uploads must still
22
+ * validate.
23
+ */
24
+ export const SessionFactsSchema = z
25
+ .object({
26
+ extractor_version: z.string().trim().min(1).max(40),
27
+ source: z.enum(["codex", "claude_code", "opencode"]),
28
+ usage_accounting: z.enum(["complete", "partial", "unavailable"]).optional(),
29
+ usage_identity_scope: z.enum(["machine", "operator"]).optional(),
30
+ usage_claims: z.array(z.object({ identity: z.string().regex(/^[a-f0-9]{64}$/), model: z.string().min(1).max(200), usage: z.object({ input_tokens: z.number().nonnegative(), output_tokens: z.number().nonnegative(), cache_read_input_tokens: z.number().nonnegative(), cache_creation_input_tokens: z.number().nonnegative() }).strict() }).strict()).max(1000).optional(),
31
+ unknown_usage_records: z.number().int().nonnegative().optional(),
32
+ copied_usage_records: z.number().int().nonnegative().optional(),
33
+ usage_by_model: z
34
+ .record(z.string().min(1).max(MAX_MODEL_NAME_CHARS), SessionFactsUsageSchema)
35
+ .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_MODELS, { message: "too many models" }),
36
+ models: z.array(z.string().min(1).max(MAX_MODEL_NAME_CHARS)).max(SESSION_FACTS_MAX_MODELS),
37
+ input_tokens: TokenCountSchema,
38
+ output_tokens: TokenCountSchema,
39
+ cache_read_tokens: TokenCountSchema,
40
+ cache_creation_tokens: TokenCountSchema,
41
+ total_tokens: TokenCountSchema,
42
+ record_count: z.number().int().nonnegative(),
43
+ turn_count: z.number().int().nonnegative(),
44
+ user_prompt_count: z.number().int().nonnegative(),
45
+ assistant_response_count: z.number().int().nonnegative(),
46
+ tool_calls_by_name: z
47
+ .record(z.string().min(1).max(MAX_TOOL_NAME_CHARS), z.number().int().nonnegative())
48
+ .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_TOOL_NAMES, { message: "too many tool names" }),
49
+ tool_call_count: z.number().int().nonnegative(),
50
+ first_timestamp: z.string().datetime({ offset: true }).nullable(),
51
+ last_timestamp: z.string().datetime({ offset: true }).nullable(),
52
+ wall_duration_seconds: z.number().int().nonnegative().nullable(),
53
+ active_seconds: z.number().int().nonnegative().optional(),
54
+ transcript_bytes: z.number().int().nonnegative(),
55
+ transcript_lines: z.number().int().nonnegative(),
56
+ transcript_files: z.number().int().nonnegative(),
57
+ truncated_models: z.number().int().nonnegative(),
58
+ truncated_tool_names: z.number().int().nonnegative(),
59
+ skill_use: z.array(SkillUseCountSchema).max(SKILL_USE_MAX_SKILLS).optional(),
60
+ spawn: SessionSpawnSchema.optional(),
61
+ hands_on: HandsOnFactsSchema.optional(),
62
+ })
63
+ .strict();
@@ -1,37 +1,4 @@
1
- /**
2
- * Session facts: everything deterministic about one transcript, counted once,
3
- * where the file already is.
4
- *
5
- * BLI-4341 part A. Token totals used to be computed only on the server, which downloaded the transcript back out of
6
- * Storage and summed it (`det.v5`), though the collector holds the same bytes at harvest time and had already read
7
- * every line; a session with no analysis run had no token count at all.
8
- *
9
- * This module is the ONE implementation of those rules. The collector feeds it
10
- * at upload; the server extractor feeds it the same records during its own
11
- * pass, so both sides count identically by construction rather than by review.
12
- * `det.v6` is `det.v5`'s rules with one owner.
13
- *
14
- * Contract:
15
- * - Pure. No filesystem, no network, no clock. Content in, numbers out.
16
- * - METADATA ONLY on the way out: token counts, turn counts, tool NAMES and
17
- * their counts, timestamps, byte/line sizes. Text is read in-process to
18
- * decide whether a turn counted; it is never returned.
19
- * - Two feeds, one rulebook: `observeSessionFactsRecord` for a caller that
20
- * is already parsing the JSONL (the server extractor), and
21
- * `computeSessionFacts` for a caller holding whole file contents (the
22
- * collector).
23
- *
24
- * Counting rules, both verified against real transcripts:
25
- * - Claude Code writes PER-TURN usage on each assistant record, repeated
26
- * across the several records of one API request, so usage is summed with a
27
- * dedupe on `message.id` (fallback `requestId`).
28
- * - Codex writes a CUMULATIVE `total_token_usage` on every `token_count`
29
- * event, so the last one wins, attributed to the `turn_context` model. Its
30
- * `input_tokens` includes cached input and its `output_tokens` already
31
- * includes reasoning, so input is normalized to fresh-only, matching the
32
- * Anthropic-shaped usage the price table expects.
33
- */
34
- import { z } from "zod";
1
+ export { SESSION_FACTS_MAX_MODELS, SESSION_FACTS_MAX_TOOL_NAMES } from "./session-facts-schema.js";
35
2
  import { HandsOnTally, type HandsOnFacts } from "./session-facts-hands-on.js";
36
3
  import { type SessionSpawn } from "./session-facts-spawn.js";
37
4
  import { SkillUseTally } from "./session-facts-skills.js";
@@ -39,19 +6,27 @@ import type { SkillUseCount } from "./session-facts-skills.js";
39
6
  /** Bump when a counting rule changes, never when a field is added. */
40
7
  export declare const SESSION_FACTS_VERSION = "det.v6";
41
8
  /** How many distinct models and tool names one session may report. */
42
- export declare const SESSION_FACTS_MAX_MODELS = 50;
43
- export declare const SESSION_FACTS_MAX_TOOL_NAMES = 200;
44
- export type SessionFactsSource = "codex" | "claude_code";
9
+ export type SessionFactsSource = "codex" | "claude_code" | "opencode";
45
10
  export interface SessionFactsUsage {
46
11
  input_tokens: number;
47
12
  output_tokens: number;
48
13
  cache_read_input_tokens: number;
49
14
  cache_creation_input_tokens: number;
50
15
  }
16
+ export interface NativeUsageClaim {
17
+ identity: string;
18
+ model: string;
19
+ usage: SessionFactsUsage;
20
+ }
51
21
  export interface SessionFacts {
52
22
  /** The rules that produced these numbers. */
53
23
  extractor_version: string;
54
24
  source: SessionFactsSource;
25
+ usage_accounting?: "complete" | "partial" | "unavailable";
26
+ usage_identity_scope?: "machine" | "operator";
27
+ usage_claims?: NativeUsageClaim[];
28
+ unknown_usage_records?: number;
29
+ copied_usage_records?: number;
55
30
  usage_by_model: Record<string, SessionFactsUsage>;
56
31
  models: string[];
57
32
  input_tokens: number;
@@ -88,7 +63,12 @@ export interface SessionFacts {
88
63
  hands_on?: HandsOnFacts;
89
64
  }
90
65
  export interface SessionFactsAccumulator {
66
+ opencode_usage_messages?: number;
67
+ opencode_usage_records?: number;
68
+ opencode_usage_claims?: Map<string, NativeUsageClaim>;
91
69
  source: SessionFactsSource;
70
+ unknown_usage_records?: number;
71
+ copied_usage_records?: number;
92
72
  usage_by_model: Record<string, SessionFactsUsage>;
93
73
  seen_usage_ids: Set<string>;
94
74
  record_count: number;
@@ -149,85 +129,6 @@ export declare function computeSessionFacts(options: {
149
129
  source: SessionFactsSource;
150
130
  contents: readonly string[];
151
131
  }): SessionFacts;
152
- export declare const SessionFactsUsageSchema: z.ZodObject<{
153
- input_tokens: z.ZodNumber;
154
- output_tokens: z.ZodNumber;
155
- cache_read_input_tokens: z.ZodNumber;
156
- cache_creation_input_tokens: z.ZodNumber;
157
- }, z.core.$strict>;
158
- /**
159
- * The wire shape. Optional wherever it rides an envelope: a CLI published
160
- * before this change sends no block at all, and its uploads must still
161
- * validate.
162
- */
163
- export declare const SessionFactsSchema: z.ZodObject<{
164
- extractor_version: z.ZodString;
165
- source: z.ZodEnum<{
166
- codex: "codex";
167
- claude_code: "claude_code";
168
- }>;
169
- usage_by_model: z.ZodRecord<z.ZodString, z.ZodObject<{
170
- input_tokens: z.ZodNumber;
171
- output_tokens: z.ZodNumber;
172
- cache_read_input_tokens: z.ZodNumber;
173
- cache_creation_input_tokens: z.ZodNumber;
174
- }, z.core.$strict>>;
175
- models: z.ZodArray<z.ZodString>;
176
- input_tokens: z.ZodNumber;
177
- output_tokens: z.ZodNumber;
178
- cache_read_tokens: z.ZodNumber;
179
- cache_creation_tokens: z.ZodNumber;
180
- total_tokens: z.ZodNumber;
181
- record_count: z.ZodNumber;
182
- turn_count: z.ZodNumber;
183
- user_prompt_count: z.ZodNumber;
184
- assistant_response_count: z.ZodNumber;
185
- tool_calls_by_name: z.ZodRecord<z.ZodString, z.ZodNumber>;
186
- tool_call_count: z.ZodNumber;
187
- first_timestamp: z.ZodNullable<z.ZodString>;
188
- last_timestamp: z.ZodNullable<z.ZodString>;
189
- wall_duration_seconds: z.ZodNullable<z.ZodNumber>;
190
- active_seconds: z.ZodOptional<z.ZodNumber>;
191
- transcript_bytes: z.ZodNumber;
192
- transcript_lines: z.ZodNumber;
193
- transcript_files: z.ZodNumber;
194
- truncated_models: z.ZodNumber;
195
- truncated_tool_names: z.ZodNumber;
196
- skill_use: z.ZodOptional<z.ZodArray<z.ZodObject<{
197
- skill: z.ZodString;
198
- plugin: z.ZodNullable<z.ZodString>;
199
- by_person: z.ZodNumber;
200
- by_agent: z.ZodNumber;
201
- }, z.core.$strict>>>;
202
- spawn: z.ZodOptional<z.ZodObject<{
203
- kind: z.ZodEnum<{
204
- interactive: "interactive";
205
- worker: "worker";
206
- subagent: "subagent";
207
- }>;
208
- client_app: z.ZodOptional<z.ZodEnum<{
209
- unknown: "unknown";
210
- claude_cli: "claude_cli";
211
- claude_desktop: "claude_desktop";
212
- claude_ide: "claude_ide";
213
- codex_cli: "codex_cli";
214
- codex_desktop: "codex_desktop";
215
- codex_ide: "codex_ide";
216
- codex_exec: "codex_exec";
217
- t3_code: "t3_code";
218
- }>>;
219
- parent_session_id: z.ZodOptional<z.ZodString>;
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>>;
231
- }, z.core.$strict>;
232
- export type SessionFactsWire = z.infer<typeof SessionFactsSchema>;
132
+ export { SessionFactsSchema, SessionFactsUsageSchema } from "./session-facts-schema.js";
133
+ export type { SessionFactsWire } from "./session-facts-schema.js";
233
134
  export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
@@ -1,3 +1,4 @@
1
+ import { readT3ProjectionMessage } from "./t3-projection-message.js";
1
2
  /**
2
3
  * Session facts: everything deterministic about one transcript, counted once,
3
4
  * where the file already is.
@@ -31,21 +32,18 @@
31
32
  * includes reasoning, so input is normalized to fresh-only, matching the
32
33
  * Anthropic-shaped usage the price table expects.
33
34
  */
34
- import { z } from "zod";
35
+ import { MAX_MODEL_NAME_CHARS, MAX_TOOL_NAME_CHARS, SESSION_FACTS_MAX_MODELS, SESSION_FACTS_MAX_TOOL_NAMES } from "./session-facts-schema.js";
36
+ export { SESSION_FACTS_MAX_MODELS, SESSION_FACTS_MAX_TOOL_NAMES } from "./session-facts-schema.js";
37
+ import { observeOpenCodeFacts } from "./opencode-transcript.js";
35
38
  import { includeCodexRevisionRecord, observeCodexCumulativeUsage, codexRevisionUsageModel } from "./codex-record-copies.js";
36
39
  import { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText } from "./session-facts-text.js";
37
40
  import { activeSeconds } from "./session-facts-active.js";
38
41
  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";
40
- import { claudeSpawn, codexSpawn, SessionSpawnSchema } from "./session-facts-spawn.js";
41
- import { observeClaudeSkillUse, observeCodexSkillUse, SKILL_USE_MAX_SKILLS, SkillUseCountSchema, SkillUseTally } from "./session-facts-skills.js";
42
+ import { classifyClaudeUserRecord, classifyCodexTaskStarted, codexTurnId, finalizeHandsOn, HandsOnTally, } from "./session-facts-hands-on.js";
43
+ import { claudeSpawn, codexSpawn } from "./session-facts-spawn.js";
44
+ import { observeClaudeSkillUse, observeCodexSkillUse, SKILL_USE_MAX_SKILLS, SkillUseTally } from "./session-facts-skills.js";
42
45
  /** Bump when a counting rule changes, never when a field is added. */
43
46
  export const SESSION_FACTS_VERSION = "det.v6";
44
- /** How many distinct models and tool names one session may report. */
45
- export const SESSION_FACTS_MAX_MODELS = 50;
46
- export const SESSION_FACTS_MAX_TOOL_NAMES = 200;
47
- const MAX_MODEL_NAME_CHARS = 200;
48
- const MAX_TOOL_NAME_CHARS = 120;
49
47
  export function newSessionFactsAccumulator(source) {
50
48
  return {
51
49
  source,
@@ -79,7 +77,7 @@ export function observeSessionFactsRecord(acc, record) {
79
77
  if (acc.source === "codex" && !includeCodexRevisionRecord(acc, record))
80
78
  return false;
81
79
  acc.record_count += 1;
82
- const ms = parseTimestampMs(record["timestamp"]);
80
+ const ms = parseTimestampMs(acc.source === "codex" ? readT3ProjectionMessage(record)?.created_at ?? record["timestamp"] : record["timestamp"]);
83
81
  if (ms != null) {
84
82
  acc.timestamps_ms.push(ms);
85
83
  acc.first_timestamp_ms =
@@ -87,7 +85,9 @@ export function observeSessionFactsRecord(acc, record) {
87
85
  acc.last_timestamp_ms =
88
86
  acc.last_timestamp_ms == null ? ms : Math.max(acc.last_timestamp_ms, ms);
89
87
  }
90
- if (acc.source === "claude_code")
88
+ if (acc.source === "opencode")
89
+ observeOpenCodeFacts(acc, record);
90
+ else if (acc.source === "claude_code")
91
91
  observeClaudeRecord(acc, record);
92
92
  else
93
93
  observeCodexRecord(acc, record);
@@ -139,6 +139,12 @@ function observeClaudeRecord(acc, record) {
139
139
  observeClaudeSkillUse(acc.skill_tally, record);
140
140
  }
141
141
  function observeCodexRecord(acc, record) {
142
+ const projection = readT3ProjectionMessage(record);
143
+ if (projection) {
144
+ if (projection.text.trim())
145
+ acc.assistant_response_count += 1;
146
+ return;
147
+ }
142
148
  const type = String(record["type"] ?? "");
143
149
  const payload = record["payload"];
144
150
  const p = payload && typeof payload === "object" ? payload : {};
@@ -216,6 +222,8 @@ export function codexUsageFromCumulativeTotal(total) {
216
222
  };
217
223
  }
218
224
  export function finalizeSessionFacts(acc) {
225
+ if (acc.source === "opencode")
226
+ acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + Math.max(0, (acc.opencode_usage_messages ?? 0) - (acc.opencode_usage_records ?? 0));
219
227
  // A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
220
228
  const usageModel = codexRevisionUsageModel(acc);
221
229
  if (acc.codex_total_usage && usageModel) {
@@ -234,6 +242,7 @@ export function finalizeSessionFacts(acc) {
234
242
  return {
235
243
  extractor_version: SESSION_FACTS_VERSION,
236
244
  source: acc.source,
245
+ ...(acc.source === "opencode" ? { usage_identity_scope: "machine", usage_claims: [...(acc.opencode_usage_claims?.values() ?? [])], usage_accounting: acc.unknown_usage_records ? (Object.keys(acc.usage_by_model).length ? "partial" : "unavailable") : "complete", unknown_usage_records: acc.unknown_usage_records ?? 0, copied_usage_records: acc.copied_usage_records ?? 0 } : {}),
237
246
  usage_by_model,
238
247
  models: keptUsage.map(([model]) => model).sort((a, b) => a.localeCompare(b)),
239
248
  input_tokens: totals.input_tokens,
@@ -309,53 +318,5 @@ function parseTimestampMs(value) {
309
318
  function num(value) {
310
319
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
311
320
  }
312
- const TokenCountSchema = z.number().int().nonnegative().max(1_000_000_000_000);
313
- export const SessionFactsUsageSchema = z
314
- .object({
315
- input_tokens: TokenCountSchema,
316
- output_tokens: TokenCountSchema,
317
- cache_read_input_tokens: TokenCountSchema,
318
- cache_creation_input_tokens: TokenCountSchema,
319
- })
320
- .strict();
321
- /**
322
- * The wire shape. Optional wherever it rides an envelope: a CLI published
323
- * before this change sends no block at all, and its uploads must still
324
- * validate.
325
- */
326
- export const SessionFactsSchema = z
327
- .object({
328
- extractor_version: z.string().trim().min(1).max(40),
329
- source: z.enum(["codex", "claude_code"]),
330
- usage_by_model: z
331
- .record(z.string().min(1).max(MAX_MODEL_NAME_CHARS), SessionFactsUsageSchema)
332
- .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_MODELS, { message: "too many models" }),
333
- models: z.array(z.string().min(1).max(MAX_MODEL_NAME_CHARS)).max(SESSION_FACTS_MAX_MODELS),
334
- input_tokens: TokenCountSchema,
335
- output_tokens: TokenCountSchema,
336
- cache_read_tokens: TokenCountSchema,
337
- cache_creation_tokens: TokenCountSchema,
338
- total_tokens: TokenCountSchema,
339
- record_count: z.number().int().nonnegative(),
340
- turn_count: z.number().int().nonnegative(),
341
- user_prompt_count: z.number().int().nonnegative(),
342
- assistant_response_count: z.number().int().nonnegative(),
343
- tool_calls_by_name: z
344
- .record(z.string().min(1).max(MAX_TOOL_NAME_CHARS), z.number().int().nonnegative())
345
- .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_TOOL_NAMES, { message: "too many tool names" }),
346
- tool_call_count: z.number().int().nonnegative(),
347
- first_timestamp: z.string().datetime({ offset: true }).nullable(),
348
- last_timestamp: z.string().datetime({ offset: true }).nullable(),
349
- wall_duration_seconds: z.number().int().nonnegative().nullable(),
350
- active_seconds: z.number().int().nonnegative().optional(),
351
- transcript_bytes: z.number().int().nonnegative(),
352
- transcript_lines: z.number().int().nonnegative(),
353
- transcript_files: z.number().int().nonnegative(),
354
- truncated_models: z.number().int().nonnegative(),
355
- truncated_tool_names: z.number().int().nonnegative(),
356
- skill_use: z.array(SkillUseCountSchema).max(SKILL_USE_MAX_SKILLS).optional(),
357
- spawn: SessionSpawnSchema.optional(),
358
- hands_on: HandsOnFactsSchema.optional(),
359
- })
360
- .strict();
321
+ export { SessionFactsSchema, SessionFactsUsageSchema } from "./session-facts-schema.js";
361
322
  export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
package/dist/shelf.d.ts CHANGED
@@ -53,17 +53,21 @@ export declare const ShelfSessionMetricsSchema: z.ZodObject<{
53
53
  user_prompt_count: z.ZodNumber;
54
54
  assistant_response_count: z.ZodNumber;
55
55
  tool_call_count: z.ZodNumber;
56
- input_tokens: z.ZodNumber;
57
- output_tokens: z.ZodNumber;
58
- cache_read_tokens: z.ZodNumber;
59
- cache_creation_tokens: z.ZodNumber;
60
- total_tokens: z.ZodNumber;
56
+ input_tokens: z.ZodNullable<z.ZodNumber>;
57
+ output_tokens: z.ZodNullable<z.ZodNumber>;
58
+ cache_read_tokens: z.ZodNullable<z.ZodNumber>;
59
+ cache_creation_tokens: z.ZodNullable<z.ZodNumber>;
60
+ total_tokens: z.ZodNullable<z.ZodNumber>;
61
61
  transcript_bytes: z.ZodNumber;
62
62
  transcript_lines: z.ZodNumber;
63
63
  transcript_files: z.ZodNumber;
64
64
  day: z.ZodOptional<z.ZodString>;
65
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
66
+ unavailable: "unavailable";
67
+ }>>;
65
68
  tool: z.ZodOptional<z.ZodEnum<{
66
69
  codex: "codex";
70
+ opencode: "opencode";
67
71
  claude: "claude";
68
72
  }>>;
69
73
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -87,17 +91,21 @@ export declare const ShelfReportSchema: z.ZodObject<{
87
91
  user_prompt_count: z.ZodNumber;
88
92
  assistant_response_count: z.ZodNumber;
89
93
  tool_call_count: z.ZodNumber;
90
- input_tokens: z.ZodNumber;
91
- output_tokens: z.ZodNumber;
92
- cache_read_tokens: z.ZodNumber;
93
- cache_creation_tokens: z.ZodNumber;
94
- total_tokens: z.ZodNumber;
94
+ input_tokens: z.ZodNullable<z.ZodNumber>;
95
+ output_tokens: z.ZodNullable<z.ZodNumber>;
96
+ cache_read_tokens: z.ZodNullable<z.ZodNumber>;
97
+ cache_creation_tokens: z.ZodNullable<z.ZodNumber>;
98
+ total_tokens: z.ZodNullable<z.ZodNumber>;
95
99
  transcript_bytes: z.ZodNumber;
96
100
  transcript_lines: z.ZodNumber;
97
101
  transcript_files: z.ZodNumber;
98
102
  day: z.ZodOptional<z.ZodString>;
103
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
104
+ unavailable: "unavailable";
105
+ }>>;
99
106
  tool: z.ZodOptional<z.ZodEnum<{
100
107
  codex: "codex";
108
+ opencode: "opencode";
101
109
  claude: "claude";
102
110
  }>>;
103
111
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -132,17 +140,21 @@ export declare const ShelfReportsEnvelopeSchema: z.ZodObject<{
132
140
  user_prompt_count: z.ZodNumber;
133
141
  assistant_response_count: z.ZodNumber;
134
142
  tool_call_count: z.ZodNumber;
135
- input_tokens: z.ZodNumber;
136
- output_tokens: z.ZodNumber;
137
- cache_read_tokens: z.ZodNumber;
138
- cache_creation_tokens: z.ZodNumber;
139
- total_tokens: z.ZodNumber;
143
+ input_tokens: z.ZodNullable<z.ZodNumber>;
144
+ output_tokens: z.ZodNullable<z.ZodNumber>;
145
+ cache_read_tokens: z.ZodNullable<z.ZodNumber>;
146
+ cache_creation_tokens: z.ZodNullable<z.ZodNumber>;
147
+ total_tokens: z.ZodNullable<z.ZodNumber>;
140
148
  transcript_bytes: z.ZodNumber;
141
149
  transcript_lines: z.ZodNumber;
142
150
  transcript_files: z.ZodNumber;
143
151
  day: z.ZodOptional<z.ZodString>;
152
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
153
+ unavailable: "unavailable";
154
+ }>>;
144
155
  tool: z.ZodOptional<z.ZodEnum<{
145
156
  codex: "codex";
157
+ opencode: "opencode";
146
158
  claude: "claude";
147
159
  }>>;
148
160
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -167,7 +179,7 @@ export declare function shelfRequestHeaders(options: {
167
179
  }): Record<string, string>;
168
180
  /** The fields of a counted session the bare record is projected from (a subset of `SessionFacts`). */
169
181
  export interface ShelfMetricsFacts {
170
- source: "codex" | "claude_code";
182
+ source: "codex" | "claude_code" | "opencode";
171
183
  usage_by_model: Record<string, {
172
184
  input_tokens: number;
173
185
  output_tokens: number;
package/dist/shelf.js CHANGED
@@ -52,17 +52,18 @@ export const ShelfSessionMetricsSchema = z
52
52
  user_prompt_count: Count,
53
53
  assistant_response_count: Count,
54
54
  tool_call_count: Count,
55
- input_tokens: Count,
56
- output_tokens: Count,
57
- cache_read_tokens: Count,
58
- cache_creation_tokens: Count,
59
- total_tokens: Count,
55
+ input_tokens: Count.nullable(),
56
+ output_tokens: Count.nullable(),
57
+ cache_read_tokens: Count.nullable(),
58
+ cache_creation_tokens: Count.nullable(),
59
+ total_tokens: Count.nullable(),
60
60
  transcript_bytes: Count,
61
61
  transcript_lines: Count,
62
62
  transcript_files: Count,
63
63
  // Opt-in categories (A-D), off unless the founder allowed them on that laptop.
64
64
  day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
65
- tool: z.enum(["claude", "codex"]).optional(),
65
+ usage_accounting: z.enum(["unavailable"]).optional(),
66
+ tool: z.enum(["claude", "codex", "opencode"]).optional(),
66
67
  model_tokens: z.record(z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9._:/-]+$/), Count).optional(),
67
68
  spawn_kind: z.enum(["human", "automated", "subagent"]).optional(),
68
69
  })
@@ -160,8 +161,17 @@ export function projectShelfMetrics(facts, allow = []) {
160
161
  metrics.day = day.toISOString().slice(0, 10);
161
162
  }
162
163
  if (allowed.has("tool"))
163
- metrics.tool = facts.source === "codex" ? "codex" : "claude";
164
- if (allowed.has("model")) {
164
+ metrics.tool = facts.source === "opencode" ? "opencode" : facts.source === "codex" ? "codex" : "claude";
165
+ if (facts.source === "opencode") {
166
+ // Drawer privacy excludes native request identities, so global copied usage cannot be settled here.
167
+ metrics.usage_accounting = "unavailable";
168
+ metrics.input_tokens = null;
169
+ metrics.output_tokens = null;
170
+ metrics.cache_read_tokens = null;
171
+ metrics.cache_creation_tokens = null;
172
+ metrics.total_tokens = null;
173
+ }
174
+ if (allowed.has("model") && facts.source !== "opencode") {
165
175
  const byModel = {};
166
176
  for (const [model, usage] of Object.entries(facts.usage_by_model)) {
167
177
  const key = model.trim().slice(0, 80);
@@ -0,0 +1,39 @@
1
+ export interface T3ProjectionMessage {
2
+ schema_version: "t3-message.v1";
3
+ native_session_id: string;
4
+ native_turn_id: string;
5
+ native_item_id: string;
6
+ t3_thread_id: string;
7
+ t3_message_id: string;
8
+ role: "assistant";
9
+ created_at: string;
10
+ updated_at: string;
11
+ /** Original source text revision. Redaction may change text without changing this opaque identity. */
12
+ text_sha256: string;
13
+ text: string;
14
+ provenance: "t3-0.1.7:orchestration_v2_projection_messages";
15
+ /** Source-time exact native identity AND original text match, before wrapper-specific redaction. */
16
+ native_copy?: {
17
+ record_sha256: string;
18
+ text_sha256: string;
19
+ };
20
+ }
21
+ /** Decode only the observed assistant projection; unknown tags/roles remain raw evidence. */
22
+ export declare function readT3ProjectionMessage(record: Record<string, unknown>): T3ProjectionMessage | null;
23
+ /** Match only native IDs and exact source text. Missing IDs never imply a copy. */
24
+ export declare function createNativeT3MessageIndex(): {
25
+ observe(record: Record<string, unknown>, recordHash: string): void;
26
+ copyOf(message: T3ProjectionMessage): T3ProjectionMessage["native_copy"];
27
+ turnCwds(message: T3ProjectionMessage): Array<string | null>;
28
+ };
29
+ /** Consumers use this after their native-copy selector; divergent source revisions stay distinct. */
30
+ export declare function t3ProjectionMessageSelector(): (record: Record<string, unknown>) => boolean;
31
+ /**
32
+ * Insert a late host supplement into a candidate view, never into retained bytes or native tool order.
33
+ * Native order stays authoritative. Missing clocks and ties place the supplement before native candidates,
34
+ * so an appended historical omission cannot displace a native closing response on an invented clock.
35
+ */
36
+ export declare function placeLateT3Projection<T extends {
37
+ occurredAt: string | null;
38
+ t3Projection?: boolean;
39
+ }>(entries: T[], candidate: T): void;