@bli-cockpit/telemetry-core 0.1.96 → 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.
Files changed (49) hide show
  1. package/dist/agent-artifacts.d.ts +3 -0
  2. package/dist/agent-artifacts.js +1 -1
  3. package/dist/codex-record-copies.d.ts +7 -0
  4. package/dist/codex-record-copies.js +58 -0
  5. package/dist/evidence-completeness.d.ts +2 -2
  6. package/dist/evidence-rules-fingerprint.js +2 -1
  7. package/dist/evidence-stubs.d.ts +1 -1
  8. package/dist/evidence-stubs.js +2 -2
  9. package/dist/evidence-transcripts.d.ts +1 -1
  10. package/dist/evidence-transcripts.js +2 -2
  11. package/dist/evidence-upload.d.ts +72 -0
  12. package/dist/evidence-upload.js +1 -1
  13. package/dist/image-byte-scan.js +5 -5
  14. package/dist/image-descriptions.d.ts +4 -1
  15. package/dist/image-descriptions.js +3 -1
  16. package/dist/image-store.d.ts +1 -0
  17. package/dist/image-store.js +1 -1
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.js +4 -0
  20. package/dist/ingest-dto.d.ts +2 -2
  21. package/dist/local-config.d.ts +1 -1
  22. package/dist/opencode-transcript.d.ts +9 -0
  23. package/dist/opencode-transcript.js +97 -0
  24. package/dist/pi-transcript-extract.d.ts +58 -0
  25. package/dist/pi-transcript-extract.js +56 -0
  26. package/dist/pi-transcript-lineage.d.ts +14 -0
  27. package/dist/pi-transcript-lineage.js +20 -0
  28. package/dist/pi-transcript-usage.d.ts +27 -0
  29. package/dist/pi-transcript-usage.js +31 -0
  30. package/dist/pi-transcript.d.ts +38 -0
  31. package/dist/pi-transcript.js +105 -0
  32. package/dist/session-facts-delta.d.ts +3 -0
  33. package/dist/session-facts-delta.js +11 -0
  34. package/dist/session-facts-hands-on.d.ts +98 -0
  35. package/dist/session-facts-hands-on.js +208 -0
  36. package/dist/session-facts-schema.d.ts +109 -0
  37. package/dist/session-facts-schema.js +63 -0
  38. package/dist/session-facts-spawn.d.ts +2 -1
  39. package/dist/session-facts-spawn.js +3 -1
  40. package/dist/session-facts-usage-math.d.ts +6 -0
  41. package/dist/session-facts-usage-math.js +27 -0
  42. package/dist/session-facts.d.ts +24 -108
  43. package/dist/session-facts.js +38 -88
  44. package/dist/shelf.d.ts +28 -16
  45. package/dist/shelf.js +18 -8
  46. package/dist/t3-projection-message.d.ts +39 -0
  47. package/dist/t3-projection-message.js +125 -0
  48. package/dist/transcript-images.js +2 -2
  49. package/package.json +1 -1
@@ -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,18 +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";
38
+ import { includeCodexRevisionRecord, observeCodexCumulativeUsage, codexRevisionUsageModel } from "./codex-record-copies.js";
35
39
  import { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText } from "./session-facts-text.js";
36
40
  import { activeSeconds } from "./session-facts-active.js";
37
- import { claudeSpawn, codexSpawn, SessionSpawnSchema } from "./session-facts-spawn.js";
38
- import { observeClaudeSkillUse, observeCodexSkillUse, SKILL_USE_MAX_SKILLS, SkillUseCountSchema, SkillUseTally } from "./session-facts-skills.js";
41
+ import { byteLength, emptyUsage, sumUsage, usageTotal } from "./session-facts-usage-math.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";
39
45
  /** Bump when a counting rule changes, never when a field is added. */
40
46
  export const SESSION_FACTS_VERSION = "det.v6";
41
- /** How many distinct models and tool names one session may report. */
42
- export const SESSION_FACTS_MAX_MODELS = 50;
43
- export const SESSION_FACTS_MAX_TOOL_NAMES = 200;
44
- const MAX_MODEL_NAME_CHARS = 200;
45
- const MAX_TOOL_NAME_CHARS = 120;
46
47
  export function newSessionFactsAccumulator(source) {
47
48
  return {
48
49
  source,
@@ -62,6 +63,7 @@ export function newSessionFactsAccumulator(source) {
62
63
  codex_model_hint: null,
63
64
  skill_tally: new SkillUseTally(),
64
65
  spawn: null,
66
+ hands_on: new HandsOnTally(),
65
67
  };
66
68
  }
67
69
  /** One transcript file's size, for callers that never hold its whole text. */
@@ -72,8 +74,10 @@ export function observeSessionFactsFile(acc, file) {
72
74
  }
73
75
  /** One parsed JSONL record. The caller owns parsing; this owns the rules. */
74
76
  export function observeSessionFactsRecord(acc, record) {
77
+ if (acc.source === "codex" && !includeCodexRevisionRecord(acc, record))
78
+ return false;
75
79
  acc.record_count += 1;
76
- const ms = parseTimestampMs(record["timestamp"]);
80
+ const ms = parseTimestampMs(acc.source === "codex" ? readT3ProjectionMessage(record)?.created_at ?? record["timestamp"] : record["timestamp"]);
77
81
  if (ms != null) {
78
82
  acc.timestamps_ms.push(ms);
79
83
  acc.first_timestamp_ms =
@@ -81,15 +85,19 @@ export function observeSessionFactsRecord(acc, record) {
81
85
  acc.last_timestamp_ms =
82
86
  acc.last_timestamp_ms == null ? ms : Math.max(acc.last_timestamp_ms, ms);
83
87
  }
84
- if (acc.source === "claude_code")
88
+ if (acc.source === "opencode")
89
+ observeOpenCodeFacts(acc, record);
90
+ else if (acc.source === "claude_code")
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);
@@ -131,6 +139,12 @@ function observeClaudeRecord(acc, record) {
131
139
  observeClaudeSkillUse(acc.skill_tally, record);
132
140
  }
133
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
+ }
134
148
  const type = String(record["type"] ?? "");
135
149
  const payload = record["payload"];
136
150
  const p = payload && typeof payload === "object" ? payload : {};
@@ -162,6 +176,11 @@ function observeCodexRecord(acc, record) {
162
176
  }
163
177
  if (type !== "event_msg")
164
178
  return;
179
+ if (String(p["type"] ?? "") === "task_started") {
180
+ acc.hands_on.turnStarts += 1;
181
+ acc.hands_on.observe(classifyCodexTaskStarted(p), codexTurnId(p), parseTimestampMs(record["timestamp"]));
182
+ return;
183
+ }
165
184
  if (String(p["type"] ?? "") !== "token_count")
166
185
  return;
167
186
  const info = p["info"];
@@ -170,7 +189,7 @@ function observeCodexRecord(acc, record) {
170
189
  const total = info["total_token_usage"];
171
190
  // Cumulative: the last event of the session is the session total.
172
191
  if (total && typeof total === "object") {
173
- acc.codex_total_usage = total;
192
+ observeCodexCumulativeUsage(acc, record, total);
174
193
  }
175
194
  }
176
195
  function countTool(acc, name) {
@@ -203,9 +222,12 @@ export function codexUsageFromCumulativeTotal(total) {
203
222
  };
204
223
  }
205
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));
206
227
  // 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)] =
228
+ const usageModel = codexRevisionUsageModel(acc);
229
+ if (acc.codex_total_usage && usageModel) {
230
+ acc.usage_by_model[usageModel.slice(0, MAX_MODEL_NAME_CHARS)] =
209
231
  codexUsageFromCumulativeTotal(acc.codex_total_usage);
210
232
  }
211
233
  const usageEntries = Object.entries(acc.usage_by_model).sort((a, b) => usageTotal(b[1]) - usageTotal(a[1]) || a[0].localeCompare(b[0]));
@@ -220,6 +242,7 @@ export function finalizeSessionFacts(acc) {
220
242
  return {
221
243
  extractor_version: SESSION_FACTS_VERSION,
222
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 } : {}),
223
246
  usage_by_model,
224
247
  models: keptUsage.map(([model]) => model).sort((a, b) => a.localeCompare(b)),
225
248
  input_tokens: totals.input_tokens,
@@ -244,6 +267,7 @@ export function finalizeSessionFacts(acc) {
244
267
  skill_use: acc.skill_tally.toList().slice(0, SKILL_USE_MAX_SKILLS),
245
268
  ...(acc.spawn ? { spawn: acc.spawn } : {}),
246
269
  active_seconds: activeSeconds(acc.timestamps_ms),
270
+ hands_on: finalizeHandsOn(acc.hands_on, acc.source === "codex" ? acc.user_prompt_count : 0),
247
271
  };
248
272
  }
249
273
  /**
@@ -285,33 +309,6 @@ export function computeSessionFacts(options) {
285
309
  }
286
310
  return finalizeSessionFacts(acc);
287
311
  }
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
312
  function parseTimestampMs(value) {
316
313
  if (typeof value !== "string")
317
314
  return null;
@@ -321,52 +318,5 @@ function parseTimestampMs(value) {
321
318
  function num(value) {
322
319
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
323
320
  }
324
- const TokenCountSchema = z.number().int().nonnegative().max(1_000_000_000_000);
325
- export const SessionFactsUsageSchema = z
326
- .object({
327
- input_tokens: TokenCountSchema,
328
- output_tokens: TokenCountSchema,
329
- cache_read_input_tokens: TokenCountSchema,
330
- cache_creation_input_tokens: TokenCountSchema,
331
- })
332
- .strict();
333
- /**
334
- * The wire shape. Optional wherever it rides an envelope: a CLI published
335
- * before this change sends no block at all, and its uploads must still
336
- * validate.
337
- */
338
- export const SessionFactsSchema = z
339
- .object({
340
- extractor_version: z.string().trim().min(1).max(40),
341
- source: z.enum(["codex", "claude_code"]),
342
- usage_by_model: z
343
- .record(z.string().min(1).max(MAX_MODEL_NAME_CHARS), SessionFactsUsageSchema)
344
- .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_MODELS, { message: "too many models" }),
345
- models: z.array(z.string().min(1).max(MAX_MODEL_NAME_CHARS)).max(SESSION_FACTS_MAX_MODELS),
346
- input_tokens: TokenCountSchema,
347
- output_tokens: TokenCountSchema,
348
- cache_read_tokens: TokenCountSchema,
349
- cache_creation_tokens: TokenCountSchema,
350
- total_tokens: TokenCountSchema,
351
- record_count: z.number().int().nonnegative(),
352
- turn_count: z.number().int().nonnegative(),
353
- user_prompt_count: z.number().int().nonnegative(),
354
- assistant_response_count: z.number().int().nonnegative(),
355
- tool_calls_by_name: z
356
- .record(z.string().min(1).max(MAX_TOOL_NAME_CHARS), z.number().int().nonnegative())
357
- .refine((value) => Object.keys(value).length <= SESSION_FACTS_MAX_TOOL_NAMES, { message: "too many tool names" }),
358
- tool_call_count: z.number().int().nonnegative(),
359
- first_timestamp: z.string().datetime({ offset: true }).nullable(),
360
- last_timestamp: z.string().datetime({ offset: true }).nullable(),
361
- wall_duration_seconds: z.number().int().nonnegative().nullable(),
362
- active_seconds: z.number().int().nonnegative().optional(),
363
- transcript_bytes: z.number().int().nonnegative(),
364
- transcript_lines: z.number().int().nonnegative(),
365
- transcript_files: z.number().int().nonnegative(),
366
- truncated_models: z.number().int().nonnegative(),
367
- truncated_tool_names: z.number().int().nonnegative(),
368
- skill_use: z.array(SkillUseCountSchema).max(SKILL_USE_MAX_SKILLS).optional(),
369
- spawn: SessionSpawnSchema.optional(),
370
- })
371
- .strict();
321
+ export { SessionFactsSchema, SessionFactsUsageSchema } from "./session-facts-schema.js";
372
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;
@@ -0,0 +1,125 @@
1
+ /** Explicit host evidence, never a counterfeit native Codex response or usage record. */
2
+ import { createHash } from "node:crypto";
3
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
4
+ const isHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/u.test(v);
5
+ const object = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
6
+ /** Decode only the observed assistant projection; unknown tags/roles remain raw evidence. */
7
+ export function readT3ProjectionMessage(record) {
8
+ if (record["type"] !== "tower_t3_message")
9
+ return null;
10
+ const p = object(record["payload"]);
11
+ if (p["schema_version"] !== "t3-message.v1" || p["role"] !== "assistant" ||
12
+ p["provenance"] !== "t3-0.1.7:orchestration_v2_projection_messages" || !isHash(p["text_sha256"]) || typeof p["text"] !== "string")
13
+ return null;
14
+ for (const key of ["native_session_id", "native_turn_id", "native_item_id", "t3_thread_id", "t3_message_id", "created_at", "updated_at"]) {
15
+ if (typeof p[key] !== "string" || !p[key])
16
+ return null;
17
+ }
18
+ if (!Number.isFinite(Date.parse(p["created_at"])) || !Number.isFinite(Date.parse(p["updated_at"])))
19
+ return null;
20
+ // Never validate source hash against masked text: the sanitizer legitimately changes it.
21
+ const decoded = { ...p };
22
+ const copy = object(p["native_copy"]);
23
+ if (!isHash(copy["record_sha256"]) || copy["text_sha256"] !== p["text_sha256"])
24
+ delete decoded.native_copy;
25
+ return decoded;
26
+ }
27
+ /** Match only native IDs and exact source text. Missing IDs never imply a copy. */
28
+ export function createNativeT3MessageIndex() {
29
+ let sessionId = null, turnId = null;
30
+ const copies = new Map();
31
+ const cwds = new Map();
32
+ let cwd = null;
33
+ let metadataBytes = 0;
34
+ const reserve = (key) => {
35
+ metadataBytes += Buffer.byteLength(key) + 64;
36
+ if (copies.size + cwds.size >= 100_000 || metadataBytes > 16 * 1024 * 1024)
37
+ throw new Error("t3_native_identity_index_capped");
38
+ };
39
+ const key = (session, turn, item, textHash) => JSON.stringify([session, turn, item, textHash]);
40
+ return {
41
+ observe(record, recordHash) {
42
+ const p = object(record["payload"]);
43
+ if (record["type"] === "session_meta") {
44
+ sessionId = typeof p["id"] === "string" ? p["id"] : null;
45
+ turnId = null;
46
+ cwd = typeof p["cwd"] === "string" ? p["cwd"] : null;
47
+ }
48
+ if (record["type"] === "turn_context") {
49
+ if (typeof p["turn_id"] === "string")
50
+ turnId = p["turn_id"];
51
+ if (typeof p["cwd"] === "string")
52
+ cwd = p["cwd"];
53
+ }
54
+ if (record["type"] === "event_msg" && p["type"] === "task_started")
55
+ turnId = typeof p["turn_id"] === "string" ? p["turn_id"] : null;
56
+ const explicitTurn = typeof p["turn_id"] === "string" ? p["turn_id"] : turnId;
57
+ if (sessionId && explicitTurn && cwd) {
58
+ const k = JSON.stringify([sessionId, explicitTurn]), seen = cwds.get(k) ?? new Set();
59
+ if (!seen.has(cwd)) {
60
+ reserve(k + cwd);
61
+ seen.add(cwd);
62
+ }
63
+ cwds.set(k, seen);
64
+ }
65
+ if (sessionId && explicitTurn && record["type"] === "response_item" && p["type"] === "message" && p["role"] === "assistant" && typeof p["id"] === "string" && Array.isArray(p["content"])) {
66
+ const blocks = p["content"].map(object);
67
+ // Unknown/non-text blocks cannot prove a text copy.
68
+ if (blocks.every(b => typeof b["text"] === "string")) {
69
+ const text = blocks.map(b => b["text"]).join("\n");
70
+ const identity = key(sessionId, explicitTurn, p["id"], hash(text));
71
+ if (!copies.has(identity))
72
+ reserve(identity);
73
+ copies.set(identity, recordHash);
74
+ }
75
+ }
76
+ if (record["type"] === "event_msg" && ["task_complete", "turn_aborted"].includes(String(p["type"])))
77
+ turnId = null;
78
+ },
79
+ copyOf(message) {
80
+ const recordHash = copies.get(key(message.native_session_id, message.native_turn_id, message.native_item_id, message.text_sha256));
81
+ return recordHash ? { record_sha256: recordHash, text_sha256: message.text_sha256 } : undefined;
82
+ },
83
+ turnCwds(message) {
84
+ return [...(cwds.get(JSON.stringify([message.native_session_id, message.native_turn_id])) ?? [null])];
85
+ },
86
+ };
87
+ }
88
+ /** Consumers use this after their native-copy selector; divergent source revisions stay distinct. */
89
+ export function t3ProjectionMessageSelector() {
90
+ const seen = new Set();
91
+ return record => {
92
+ if (record["type"] !== "tower_t3_message")
93
+ return true;
94
+ const message = readT3ProjectionMessage(record);
95
+ if (!message)
96
+ return false;
97
+ const identity = JSON.stringify([message.native_session_id, message.native_turn_id, message.native_item_id,
98
+ message.t3_thread_id, message.t3_message_id, message.text_sha256]);
99
+ if (seen.has(identity))
100
+ return false;
101
+ seen.add(identity);
102
+ return !message.native_copy;
103
+ };
104
+ }
105
+ /**
106
+ * Insert a late host supplement into a candidate view, never into retained bytes or native tool order.
107
+ * Native order stays authoritative. Missing clocks and ties place the supplement before native candidates,
108
+ * so an appended historical omission cannot displace a native closing response on an invented clock.
109
+ */
110
+ export function placeLateT3Projection(entries, candidate) {
111
+ if (!candidate.t3Projection) {
112
+ entries.push(candidate);
113
+ return;
114
+ }
115
+ const at = candidate.occurredAt === null ? NaN : Date.parse(candidate.occurredAt);
116
+ const before = entries.findIndex(entry => {
117
+ const existing = entry.occurredAt === null ? NaN : Date.parse(entry.occurredAt);
118
+ if (!Number.isFinite(at))
119
+ return !entry.t3Projection;
120
+ if (!Number.isFinite(existing))
121
+ return !entry.t3Projection;
122
+ return existing > at || (existing === at && !entry.t3Projection);
123
+ });
124
+ entries.splice(before < 0 ? entries.length : before, 0, candidate);
125
+ }
@@ -20,8 +20,8 @@
20
20
  * in. So every parser that read the line before still reads it.
21
21
  */
22
22
  import { createHash } from "node:crypto";
23
- import { IMAGE_MIN_BASE64_CHARS, formatImageMarker, sniffImageMediaType, } from "./image-descriptions.js";
24
- const BASE64_RUN = `[A-Za-z0-9+/=]{${IMAGE_MIN_BASE64_CHARS},}`;
23
+ import { IMAGE_MIN_BASE64_CHARS, IMAGE_DATA_URL_MIN_BASE64_CHARS, formatImageMarker, sniffImageMediaType, } from "./image-descriptions.js";
24
+ const BASE64_RUN = `[A-Za-z0-9+/=]{${IMAGE_DATA_URL_MIN_BASE64_CHARS},}`;
25
25
  /**
26
26
  * What the first characters of a base64 run look like for each type we accept: PNG `iVBOR`, JPEG
27
27
  * `/9j/`, GIF `R0lGO`, WebP (RIFF) `UklGR`. Anchoring the whole-string form on these keeps the scan
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.96",
3
+ "version": "0.1.98",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",