@bli-cockpit/telemetry-core 0.1.97 → 0.1.99

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 (40) hide show
  1. package/dist/agent-artifacts.d.ts +6 -0
  2. package/dist/agent-artifacts.js +1 -1
  3. package/dist/codex-record-copies.js +11 -6
  4. package/dist/evidence-completeness.d.ts +2 -2
  5. package/dist/evidence-rules-fingerprint.js +3 -1
  6. package/dist/evidence-stubs.d.ts +1 -1
  7. package/dist/evidence-stubs.js +2 -2
  8. package/dist/evidence-transcripts.d.ts +1 -1
  9. package/dist/evidence-transcripts.js +2 -2
  10. package/dist/evidence-upload-abort.d.ts +1 -1
  11. package/dist/evidence-upload.d.ts +61 -3
  12. package/dist/evidence-upload.js +1 -1
  13. package/dist/image-byte-scan.js +35 -6
  14. package/dist/image-descriptions.d.ts +5 -1
  15. package/dist/image-descriptions.js +3 -1
  16. package/dist/image-store.d.ts +2 -0
  17. package/dist/image-store.js +1 -1
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +6 -0
  20. package/dist/ingest-dto.d.ts +2 -2
  21. package/dist/local-config.d.ts +1 -1
  22. package/dist/memory-hook-stats.d.ts +1 -1
  23. package/dist/native-usage-facts.d.ts +8 -0
  24. package/dist/native-usage-facts.js +28 -0
  25. package/dist/opencode-transcript.d.ts +8 -0
  26. package/dist/opencode-transcript.js +72 -0
  27. package/dist/pi-session-facts.d.ts +2 -0
  28. package/dist/pi-session-facts.js +37 -0
  29. package/dist/pi-transcript-usage.js +2 -0
  30. package/dist/session-facts-schema.d.ts +110 -0
  31. package/dist/session-facts-schema.js +63 -0
  32. package/dist/session-facts-spawn.js +2 -0
  33. package/dist/session-facts.d.ts +19 -118
  34. package/dist/session-facts.js +24 -60
  35. package/dist/shelf.d.ts +31 -16
  36. package/dist/shelf.js +18 -8
  37. package/dist/t3-projection-message.d.ts +39 -0
  38. package/dist/t3-projection-message.js +125 -0
  39. package/dist/transcript-images.js +14 -2
  40. package/package.json +1 -1
package/dist/shelf.d.ts CHANGED
@@ -53,17 +53,22 @@ 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";
71
+ pi: "pi";
67
72
  claude: "claude";
68
73
  }>>;
69
74
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -87,17 +92,22 @@ export declare const ShelfReportSchema: z.ZodObject<{
87
92
  user_prompt_count: z.ZodNumber;
88
93
  assistant_response_count: z.ZodNumber;
89
94
  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;
95
+ input_tokens: z.ZodNullable<z.ZodNumber>;
96
+ output_tokens: z.ZodNullable<z.ZodNumber>;
97
+ cache_read_tokens: z.ZodNullable<z.ZodNumber>;
98
+ cache_creation_tokens: z.ZodNullable<z.ZodNumber>;
99
+ total_tokens: z.ZodNullable<z.ZodNumber>;
95
100
  transcript_bytes: z.ZodNumber;
96
101
  transcript_lines: z.ZodNumber;
97
102
  transcript_files: z.ZodNumber;
98
103
  day: z.ZodOptional<z.ZodString>;
104
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
105
+ unavailable: "unavailable";
106
+ }>>;
99
107
  tool: z.ZodOptional<z.ZodEnum<{
100
108
  codex: "codex";
109
+ opencode: "opencode";
110
+ pi: "pi";
101
111
  claude: "claude";
102
112
  }>>;
103
113
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -132,17 +142,22 @@ export declare const ShelfReportsEnvelopeSchema: z.ZodObject<{
132
142
  user_prompt_count: z.ZodNumber;
133
143
  assistant_response_count: z.ZodNumber;
134
144
  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;
145
+ input_tokens: z.ZodNullable<z.ZodNumber>;
146
+ output_tokens: z.ZodNullable<z.ZodNumber>;
147
+ cache_read_tokens: z.ZodNullable<z.ZodNumber>;
148
+ cache_creation_tokens: z.ZodNullable<z.ZodNumber>;
149
+ total_tokens: z.ZodNullable<z.ZodNumber>;
140
150
  transcript_bytes: z.ZodNumber;
141
151
  transcript_lines: z.ZodNumber;
142
152
  transcript_files: z.ZodNumber;
143
153
  day: z.ZodOptional<z.ZodString>;
154
+ usage_accounting: z.ZodOptional<z.ZodEnum<{
155
+ unavailable: "unavailable";
156
+ }>>;
144
157
  tool: z.ZodOptional<z.ZodEnum<{
145
158
  codex: "codex";
159
+ opencode: "opencode";
160
+ pi: "pi";
146
161
  claude: "claude";
147
162
  }>>;
148
163
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -167,7 +182,7 @@ export declare function shelfRequestHeaders(options: {
167
182
  }): Record<string, string>;
168
183
  /** The fields of a counted session the bare record is projected from (a subset of `SessionFacts`). */
169
184
  export interface ShelfMetricsFacts {
170
- source: "codex" | "claude_code";
185
+ source: "codex" | "claude_code" | "opencode" | "pi";
171
186
  usage_by_model: Record<string, {
172
187
  input_tokens: number;
173
188
  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", "pi"]).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 === "pi" ? "pi" : facts.source === "opencode" ? "opencode" : facts.source === "codex" ? "codex" : "claude";
165
+ if ((facts.source === "opencode" || facts.source === "pi")) {
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" && facts.source !== "pi")) {
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
@@ -67,6 +67,18 @@ export function findEmbeddedImages(text) {
67
67
  byteSize: bytes.byteLength,
68
68
  });
69
69
  }
70
+ // Pi stores explicit image blocks as data/mimeType, including valid tiny images.
71
+ for (const match of text.matchAll(/"data"\s*:\s*"([A-Za-z0-9+/=]{4,})"/g)) {
72
+ const run = match[1];
73
+ const base64Start = match.index + match[0].indexOf(run);
74
+ if (found.some(image => image.base64Start === base64Start))
75
+ continue;
76
+ const bytes = Buffer.from(run, "base64"), mediaType = sniffImageMediaType(bytes);
77
+ if (!mediaType)
78
+ continue;
79
+ found.push({ replaceStart: base64Start, replaceEnd: base64Start + run.length, base64Start, base64End: base64Start + run.length, sha256: createHash("sha256").update(bytes).digest("hex"), mediaType, byteSize: bytes.length });
80
+ }
81
+ found.sort((a, b) => a.replaceStart - b.replaceStart);
70
82
  return found;
71
83
  }
72
84
  /** The base64 text of one found image, sliced from the transcript only when it is about to be sent. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.97",
3
+ "version": "0.1.99",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",