@bli-cockpit/telemetry-core 0.1.98 → 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.
@@ -5,6 +5,7 @@ export declare const AgentArtifactSourceSchema: z.ZodEnum<{
5
5
  codex: "codex";
6
6
  claude_code: "claude_code";
7
7
  opencode: "opencode";
8
+ pi: "pi";
8
9
  }>;
9
10
  export type AgentArtifactSource = z.infer<typeof AgentArtifactSourceSchema>;
10
11
  export declare const AgentArtifactKindSchema: z.ZodEnum<{
@@ -88,6 +89,7 @@ export declare const AgentImageArtifactSchema: z.ZodObject<{
88
89
  codex: "codex";
89
90
  claude_code: "claude_code";
90
91
  opencode: "opencode";
92
+ pi: "pi";
91
93
  }>;
92
94
  source_session_id: z.ZodString;
93
95
  source_message_id: z.ZodOptional<z.ZodString>;
@@ -182,6 +184,7 @@ export declare const AgentImageArtifactReportRequestSchema: z.ZodObject<{
182
184
  codex: "codex";
183
185
  claude_code: "claude_code";
184
186
  opencode: "opencode";
187
+ pi: "pi";
185
188
  }>;
186
189
  source_session_id: z.ZodString;
187
190
  source_message_id: z.ZodOptional<z.ZodString>;
@@ -3,7 +3,7 @@ import { CaptureProvenanceSchema, IsoDateTimeSchema, NonEmptyStringSchema, Sha25
3
3
  export const AGENT_IMAGE_ARTIFACT_MAX_FILE_BYTES = 10 * 1024 * 1024;
4
4
  export const AGENT_IMAGE_ARTIFACT_MAX_REPORT_ITEMS = 100;
5
5
  const UuidSchema = z.string().uuid();
6
- export const AgentArtifactSourceSchema = z.enum(["codex", "claude_code", "opencode"]);
6
+ export const AgentArtifactSourceSchema = z.enum(["codex", "claude_code", "opencode", "pi"]);
7
7
  export const AgentArtifactKindSchema = z.enum([
8
8
  "screenshot",
9
9
  "image_attachment",
@@ -45,6 +45,7 @@ export function evidenceRulesFingerprint() {
45
45
  pdf_rules_version: PDF_RULES_VERSION,
46
46
  pdf_marker_sample: formatPdfMarker({ sha256: "0123456789abcdef".repeat(4), pages: 3, byteSize: 412 * 1024, method: "text-layer", notes: ["sample"] }, "body"),
47
47
  pdf_reference_sample: formatPdfReference({ sha256: "0123456789abcdef".repeat(4), byteSize: 412 * 1024 }),
48
+ explicit_image_data_payloads: "magic-checked-native-data.v1",
48
49
  image_detector_probe: findEmbeddedImages(probe).map((image) => [image.replaceStart, image.replaceEnd, image.mediaType, image.byteSize]),
49
50
  };
50
51
  cached = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
@@ -55,6 +55,6 @@ export type EvidenceStubsResponse = z.infer<typeof EvidenceStubsResponseSchema>;
55
55
  * `raw-evidence-claude-reader.ts`); anything else is null, never a guess.
56
56
  */
57
57
  export declare function transcriptSessionFromObjectKey(objectKey: string): {
58
- source: "codex" | "claude_code" | "opencode";
58
+ source: "codex" | "claude_code" | "opencode" | "pi";
59
59
  session_id: string;
60
60
  } | null;
@@ -56,11 +56,11 @@ export const EvidenceStubsResponseSchema = z
56
56
  * `raw-evidence-claude-reader.ts`); anything else is null, never a guess.
57
57
  */
58
58
  export function transcriptSessionFromObjectKey(objectKey) {
59
- const match = /(?:^|\/)(codex|claude|opencode)\/([A-Za-z0-9._-]{1,80})\/[0-9a-f]{16}\.jsonl$/u.exec(objectKey);
59
+ const match = /(?:^|\/)(codex|claude|opencode|pi)\/([A-Za-z0-9._-]{1,80})\/[0-9a-f]{16}\.jsonl$/u.exec(objectKey);
60
60
  if (!match)
61
61
  return null;
62
62
  return {
63
- source: match[1] === "opencode" ? "opencode" : match[1] === "codex" ? "codex" : "claude_code",
63
+ source: match[1] === "pi" ? "pi" : match[1] === "opencode" ? "opencode" : match[1] === "codex" ? "codex" : "claude_code",
64
64
  session_id: match[2],
65
65
  };
66
66
  }
@@ -48,7 +48,7 @@ export declare const EvidenceTranscriptsResponseSchema: z.ZodObject<{
48
48
  }, z.core.$strict>;
49
49
  export type EvidenceTranscriptsResponse = z.infer<typeof EvidenceTranscriptsResponseSchema>;
50
50
  export interface TranscriptFileIdentity {
51
- source: "codex" | "claude_code" | "opencode";
51
+ source: "codex" | "claude_code" | "opencode" | "pi";
52
52
  session_id: string;
53
53
  /** The Claude subagent file's key segment, or null for the session's main transcript. */
54
54
  sidecar: string | null;
@@ -60,10 +60,10 @@ export const EvidenceTranscriptsResponseSchema = z
60
60
  * `raw-evidence-claude-reader.ts`); anything else is null, never a guess.
61
61
  */
62
62
  export function transcriptFileFromObjectKey(objectKey) {
63
- const main = /(?:^|\/)(codex|claude|opencode)\/([A-Za-z0-9._-]{1,80})\/[0-9a-f]{16}\.jsonl$/u.exec(objectKey);
63
+ const main = /(?:^|\/)(codex|claude|opencode|pi)\/([A-Za-z0-9._-]{1,80})\/[0-9a-f]{16}\.jsonl$/u.exec(objectKey);
64
64
  if (main) {
65
65
  return {
66
- source: main[1] === "opencode" ? "opencode" : main[1] === "codex" ? "codex" : "claude_code",
66
+ source: main[1] === "pi" ? "pi" : main[1] === "opencode" ? "opencode" : main[1] === "codex" ? "codex" : "claude_code",
67
67
  session_id: main[2],
68
68
  sidecar: null,
69
69
  };
@@ -60,8 +60,8 @@ export type RawEvidenceUploadAbortRequest = z.infer<typeof RawEvidenceUploadAbor
60
60
  export declare const RawEvidenceUploadAbortResponseSchema: z.ZodObject<{
61
61
  ok: z.ZodLiteral<true>;
62
62
  status: z.ZodEnum<{
63
- reason_recorded: "reason_recorded";
64
63
  aborted: "aborted";
64
+ reason_recorded: "reason_recorded";
65
65
  already_terminal: "already_terminal";
66
66
  }>;
67
67
  upload_id: z.ZodString;
@@ -142,6 +142,7 @@ export declare const RawEvidenceUploadBeginObjectSchema: z.ZodObject<{
142
142
  codex: "codex";
143
143
  claude_code: "claude_code";
144
144
  opencode: "opencode";
145
+ pi: "pi";
145
146
  }>;
146
147
  }, z.core.$strict>>;
147
148
  }, z.core.$strict>;
@@ -260,6 +261,7 @@ export declare const RawEvidenceUploadBeginRequestSchema: z.ZodObject<{
260
261
  codex: "codex";
261
262
  claude_code: "claude_code";
262
263
  opencode: "opencode";
264
+ pi: "pi";
263
265
  }>;
264
266
  }, z.core.$strict>>;
265
267
  }, z.core.$strict>>;
@@ -267,9 +269,9 @@ export declare const RawEvidenceUploadBeginRequestSchema: z.ZodObject<{
267
269
  export type RawEvidenceUploadBeginRequest = z.infer<typeof RawEvidenceUploadBeginRequestSchema>;
268
270
  export declare const RawEvidenceUploadDispositionSchema: z.ZodEnum<{
269
271
  resume: "resume";
272
+ conflict: "conflict";
270
273
  new: "new";
271
274
  already_committed: "already_committed";
272
- conflict: "conflict";
273
275
  }>;
274
276
  export type RawEvidenceUploadDisposition = z.infer<typeof RawEvidenceUploadDispositionSchema>;
275
277
  /** How a chunk's bytes are compressed on the wire (BLI-23334). `gzip` is what every collector speaks today; the door decodes all three. */
@@ -289,9 +291,9 @@ export declare const RawEvidenceUploadBeginResponseObjectSchema: z.ZodObject<{
289
291
  raw_evidence_pointer_id: z.ZodString;
290
292
  disposition: z.ZodEnum<{
291
293
  resume: "resume";
294
+ conflict: "conflict";
292
295
  new: "new";
293
296
  already_committed: "already_committed";
294
- conflict: "conflict";
295
297
  }>;
296
298
  upload_id: z.ZodOptional<z.ZodString>;
297
299
  received_chunk_indexes: z.ZodDefault<z.ZodArray<z.ZodNumber>>;
@@ -324,9 +326,9 @@ export declare const RawEvidenceUploadBeginResponseSchema: z.ZodObject<{
324
326
  raw_evidence_pointer_id: z.ZodString;
325
327
  disposition: z.ZodEnum<{
326
328
  resume: "resume";
329
+ conflict: "conflict";
327
330
  new: "new";
328
331
  already_committed: "already_committed";
329
- conflict: "conflict";
330
332
  }>;
331
333
  upload_id: z.ZodOptional<z.ZodString>;
332
334
  received_chunk_indexes: z.ZodDefault<z.ZodArray<z.ZodNumber>>;
@@ -458,6 +460,7 @@ export declare const RawEvidenceUploadCommitRequestSchema: z.ZodObject<{
458
460
  codex: "codex";
459
461
  claude_code: "claude_code";
460
462
  opencode: "opencode";
463
+ pi: "pi";
461
464
  }>;
462
465
  }, z.core.$strict>>;
463
466
  }, z.core.$strict>;
@@ -554,6 +557,7 @@ export declare const AgentSessionSourceSchema: z.ZodDefault<z.ZodEnum<{
554
557
  codex: "codex";
555
558
  claude_code: "claude_code";
556
559
  opencode: "opencode";
560
+ pi: "pi";
557
561
  }>>;
558
562
  export type AgentSessionSource = z.infer<typeof AgentSessionSourceSchema>;
559
563
  export declare const CodexSessionAttributionSchema: z.ZodObject<{
@@ -564,6 +568,7 @@ export declare const CodexSessionAttributionSchema: z.ZodObject<{
564
568
  codex: "codex";
565
569
  claude_code: "claude_code";
566
570
  opencode: "opencode";
571
+ pi: "pi";
567
572
  }>>;
568
573
  observed_at: z.ZodString;
569
574
  attribution_state: z.ZodEnum<{
@@ -585,6 +590,7 @@ export declare const CodexSessionAttributionSchema: z.ZodObject<{
585
590
  codex: "codex";
586
591
  claude_code: "claude_code";
587
592
  opencode: "opencode";
593
+ pi: "pi";
588
594
  }>;
589
595
  usage_accounting: z.ZodOptional<z.ZodEnum<{
590
596
  complete: "complete";
@@ -733,6 +739,7 @@ export declare const CodexSessionAttributionReportRequestSchema: z.ZodObject<{
733
739
  codex: "codex";
734
740
  claude_code: "claude_code";
735
741
  opencode: "opencode";
742
+ pi: "pi";
736
743
  }>>;
737
744
  observed_at: z.ZodString;
738
745
  attribution_state: z.ZodEnum<{
@@ -754,6 +761,7 @@ export declare const CodexSessionAttributionReportRequestSchema: z.ZodObject<{
754
761
  codex: "codex";
755
762
  claude_code: "claude_code";
756
763
  opencode: "opencode";
764
+ pi: "pi";
757
765
  }>;
758
766
  usage_accounting: z.ZodOptional<z.ZodEnum<{
759
767
  complete: "complete";
@@ -251,7 +251,7 @@ export const RootScopeSchema = z.enum(["inside", "outside"]);
251
251
  * working unchanged after this schema lands.
252
252
  */
253
253
  export const AgentSessionSourceSchema = z
254
- .enum(["codex", "claude_code", "opencode"])
254
+ .enum(["codex", "claude_code", "opencode", "pi"])
255
255
  .default("codex");
256
256
  export const CodexSessionAttributionSchema = z
257
257
  .object({
@@ -117,6 +117,34 @@ function nextQuotedStart(line, anchor, from, current) {
117
117
  at = line.indexOf(anchor, at + 1);
118
118
  return at;
119
119
  }
120
+ /** Match the reference's "data" whitespace/colon prefix without copying earlier image payloads. */
121
+ function followsExplicitDataKey(line, payloadStart) {
122
+ const skipWhitespace = (end) => {
123
+ while (end > 0) {
124
+ const byte = line[end - 1];
125
+ if (byte === 0x20 || (byte >= 0x09 && byte <= 0x0d)) {
126
+ end--;
127
+ continue;
128
+ }
129
+ // JavaScript \s also admits these UTF-8 whitespace code points (all at most three bytes).
130
+ let width = 0;
131
+ for (const size of [2, 3])
132
+ if (end >= size && /^\s$/u.test(line.toString("utf8", end - size, end))) {
133
+ width = size;
134
+ break;
135
+ }
136
+ if (!width)
137
+ break;
138
+ end -= width;
139
+ }
140
+ return end;
141
+ };
142
+ let cursor = skipWhitespace(payloadStart - 1); // The quote directly before the payload.
143
+ if (line[cursor - 1] !== 0x3a)
144
+ return false;
145
+ cursor = skipWhitespace(cursor - 1);
146
+ return cursor >= 6 && line.toString("latin1", cursor - 6, cursor) === '"data"';
147
+ }
120
148
  /**
121
149
  * Every embedded image in `line` (one physical line, no `\n` inside), in order, with byte offsets inside
122
150
  * the line. Equal to `findEmbeddedImages` on the decoded text in everything but the unit of the offsets.
@@ -153,7 +181,8 @@ export function scanImagesInLine(line) {
153
181
  const startLength = STARTS[kind].length;
154
182
  const end = runEnd(line, candidate);
155
183
  const closed = end < line.length && (line[end] === QUOTE || (line[end] === BACKSLASH && line[end + 1] === QUOTE));
156
- if (!closed || end - candidate < startLength + (IMAGE_MIN_BASE64_CHARS - 5)) {
184
+ const explicitData = line[end] === QUOTE && followsExplicitDataKey(line, candidate);
185
+ if (!closed || end - candidate < (explicitData ? IMAGE_DATA_URL_MIN_BASE64_CHARS : startLength + (IMAGE_MIN_BASE64_CHARS - 5))) {
157
186
  position = candidate + 1;
158
187
  continue;
159
188
  }
@@ -99,6 +99,7 @@ export declare const ImageDescribeRequestSchema: z.ZodObject<{
99
99
  codex: "codex";
100
100
  claude_code: "claude_code";
101
101
  opencode: "opencode";
102
+ pi: "pi";
102
103
  manual: "manual";
103
104
  }>>;
104
105
  session_id: z.ZodOptional<z.ZodString>;
@@ -127,7 +127,7 @@ export const ImageDescribeRequestSchema = z
127
127
  byte_size: z.number().int().min(1).max(IMAGE_DESCRIBE_MAX_BYTES),
128
128
  content_base64: z.string().min(8).max(Math.ceil((IMAGE_DESCRIBE_MAX_BYTES * 4) / 3) + 16),
129
129
  /** Which agent wrote the transcript the image came from. */
130
- source: z.enum(["codex", "claude_code", "opencode", "manual"]).optional(),
130
+ source: z.enum(["codex", "claude_code", "opencode", "pi", "manual"]).optional(),
131
131
  /** The agent's session id, an id only, for "where did this image appear". */
132
132
  session_id: z.string().min(1).max(200).optional(),
133
133
  })
@@ -31,6 +31,7 @@ export declare const ImageUseSchema: z.ZodObject<{
31
31
  codex: "codex";
32
32
  claude_code: "claude_code";
33
33
  opencode: "opencode";
34
+ pi: "pi";
34
35
  }>;
35
36
  }, z.core.$strict>;
36
37
  export type ImageUse = z.infer<typeof ImageUseSchema>;
@@ -35,7 +35,7 @@ export const IMAGE_USE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
35
35
  export const ImageUseSchema = z
36
36
  .object({
37
37
  session_id: z.string().regex(IMAGE_USE_SESSION_ID, "session_id must be an agent session id"),
38
- source: z.enum(["codex", "claude_code", "opencode"]),
38
+ source: z.enum(["codex", "claude_code", "opencode", "pi"]),
39
39
  })
40
40
  .strict();
41
41
  const IMAGE_KEY = /^([A-Za-z0-9._-]+)\/images\/([0-9a-f]{64})\.(png|jpg|gif|webp)$/;
package/dist/index.d.ts CHANGED
@@ -55,3 +55,7 @@ export * from "./trace-sink.js";
55
55
  export * from "./upload-failure-class.js";
56
56
  export * from "./work-context.js";
57
57
  export { openCodeTurnText, openCodeProviderIdentity, nativeObject } from "./opencode-transcript.js";
58
+ export * from "./pi-transcript.js";
59
+ export * from "./pi-transcript-usage.js";
60
+ export * from "./pi-transcript-extract.js";
61
+ export * from "./pi-transcript-lineage.js";
package/dist/index.js CHANGED
@@ -55,3 +55,7 @@ export * from "./trace-sink.js";
55
55
  export * from "./upload-failure-class.js";
56
56
  export * from "./work-context.js";
57
57
  export { openCodeTurnText, openCodeProviderIdentity, nativeObject } from "./opencode-transcript.js";
58
+ export * from "./pi-transcript.js";
59
+ export * from "./pi-transcript-usage.js";
60
+ export * from "./pi-transcript-extract.js";
61
+ export * from "./pi-transcript-lineage.js";
@@ -93,9 +93,9 @@ export declare const MEMORY_HOOK_BUCKET_PATTERN: RegExp;
93
93
  export declare const MemoryHookStatsFileSchema: z.ZodObject<{
94
94
  schema_version: z.ZodLiteral<"memory-hook-stats.v1">;
95
95
  buckets: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodEnum<{
96
+ stop: "stop";
96
97
  prompt: "prompt";
97
98
  "session-start": "session-start";
98
- stop: "stop";
99
99
  }> & z.core.$partial, z.ZodObject<{
100
100
  runs: z.ZodNumber;
101
101
  printed: z.ZodNumber;
@@ -0,0 +1,8 @@
1
+ /** Shared native usage claims reach operator ownership only after the existing evidence acknowledgment. */
2
+ import type { SessionFactsAccumulator, SessionFactsUsage } from './session-facts.js';
3
+ export declare function observeNativeUsageFacts(acc: SessionFactsAccumulator, claim: {
4
+ status: unknown;
5
+ identity: unknown;
6
+ model: unknown;
7
+ usage: SessionFactsUsage;
8
+ }): void;
@@ -0,0 +1,28 @@
1
+ export function observeNativeUsageFacts(acc, claim) {
2
+ acc.opencode_usage_records = (acc.opencode_usage_records ?? 0) + 1;
3
+ if (claim.status === 'unknown') {
4
+ acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
5
+ return;
6
+ }
7
+ if (typeof claim.identity !== 'string' || !/^[a-f0-9]{64}$/.test(claim.identity) || typeof claim.model !== 'string') {
8
+ acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
9
+ return;
10
+ }
11
+ acc.opencode_usage_claims ??= new Map();
12
+ if (!acc.opencode_usage_claims.has(claim.identity) && acc.opencode_usage_claims.size >= 1000) {
13
+ acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
14
+ return;
15
+ }
16
+ acc.opencode_usage_claims.set(claim.identity, { identity: claim.identity, model: claim.model.slice(0, 200), usage: claim.usage });
17
+ if (claim.status === 'copied') {
18
+ acc.copied_usage_records = (acc.copied_usage_records ?? 0) + 1;
19
+ return;
20
+ }
21
+ if (claim.status !== 'known' || acc.seen_usage_ids.has(claim.identity))
22
+ return;
23
+ acc.seen_usage_ids.add(claim.identity);
24
+ const usage = acc.usage_by_model[claim.model] ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
25
+ for (const key of Object.keys(usage))
26
+ usage[key] += claim.usage[key];
27
+ acc.usage_by_model[claim.model] = usage;
28
+ }
@@ -1,4 +1,3 @@
1
- /** Native OpenCode semantics, shared by collection and downloaded-evidence readers. */
2
1
  import type { SessionFactsAccumulator } from "./session-facts.js";
3
2
  export declare function nativeObject(value: unknown): Record<string, unknown>;
4
3
  /** Text comes from native text parts; reasoning, tool output and unknown parts remain separate evidence. */
@@ -1,3 +1,5 @@
1
+ /** Native OpenCode semantics, shared by collection and downloaded-evidence readers. */
2
+ import { observeNativeUsageFacts } from "./native-usage-facts.js";
1
3
  export function nativeObject(value) {
2
4
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
3
5
  }
@@ -64,34 +66,7 @@ export function observeOpenCodeFacts(acc, record) {
64
66
  }
65
67
  if (record.type !== "opencode_usage")
66
68
  return;
67
- acc.opencode_usage_records = (acc.opencode_usage_records ?? 0) + 1;
68
- if (record.status === "unknown") {
69
- acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
70
- return;
71
- }
72
- if (typeof record.identity !== "string" || !/^[a-f0-9]{64}$/.test(record.identity) || typeof record.model !== "string")
73
- return;
74
- const tokens = nativeObject(record.tokens);
75
- const cache = nativeObject(tokens.cache);
69
+ const tokens = nativeObject(record.tokens), cache = nativeObject(tokens.cache);
76
70
  const number = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
77
- const claimedUsage = { input_tokens: number(tokens.input), output_tokens: number(tokens.output) + number(tokens.reasoning), cache_read_input_tokens: number(cache.read), cache_creation_input_tokens: number(cache.write) };
78
- acc.opencode_usage_claims ??= new Map();
79
- if (!acc.opencode_usage_claims.has(record.identity) && acc.opencode_usage_claims.size >= 1000) {
80
- acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
81
- return;
82
- }
83
- acc.opencode_usage_claims.set(record.identity, { identity: record.identity, model: record.model.slice(0, 200), usage: claimedUsage });
84
- if (record.status === "copied") {
85
- acc.copied_usage_records = (acc.copied_usage_records ?? 0) + 1;
86
- return;
87
- }
88
- if (record.status !== "known" || acc.seen_usage_ids.has(record.identity))
89
- return;
90
- acc.seen_usage_ids.add(record.identity);
91
- const usage = acc.usage_by_model[record.model] ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
92
- usage.input_tokens += number(tokens.input);
93
- usage.output_tokens += number(tokens.output) + number(tokens.reasoning);
94
- usage.cache_read_input_tokens += number(cache.read);
95
- usage.cache_creation_input_tokens += number(cache.write);
96
- acc.usage_by_model[record.model] = usage;
71
+ observeNativeUsageFacts(acc, { status: record.status, identity: record.identity, model: record.model, usage: { input_tokens: number(tokens.input), output_tokens: number(tokens.output) + number(tokens.reasoning), cache_read_input_tokens: number(cache.read), cache_creation_input_tokens: number(cache.write) } });
97
72
  }
@@ -0,0 +1,2 @@
1
+ import type { SessionFactsAccumulator } from './session-facts.js';
2
+ export declare function observePiFacts(acc: SessionFactsAccumulator, record: Record<string, unknown>): void;
@@ -0,0 +1,37 @@
1
+ /** Native Pi facts share the existing wire claim contract without pretending Pi is another format. */
2
+ import { createHash } from 'node:crypto';
3
+ import { piObject, piString } from './pi-transcript-usage.js';
4
+ import { piTurnText } from './pi-transcript.js';
5
+ import { observeNativeUsageFacts } from './native-usage-facts.js';
6
+ export function observePiFacts(acc, record) {
7
+ const message = piObject(record.message);
8
+ if (record.type === "pi_raw_fragment" || (record.type === "pi_capture" && Array.isArray(record.pending_reasons) && record.pending_reasons.length))
9
+ acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + 1;
10
+ if (record.type === 'message') {
11
+ if (typeof record.id === 'string') {
12
+ const key = `pi-entry:${record.id}:${createHash('sha256').update(JSON.stringify({ ...record, parentId: null })).digest('hex')}`;
13
+ if (acc.seen_usage_ids.has(key))
14
+ return;
15
+ acc.seen_usage_ids.add(key);
16
+ }
17
+ if (piTurnText(record, 'user')?.trim())
18
+ acc.user_prompt_count++;
19
+ if (piTurnText(record, 'assistant')?.trim())
20
+ acc.assistant_response_count++;
21
+ if (message.role === 'assistant')
22
+ acc.opencode_usage_messages = (acc.opencode_usage_messages ?? 0) + 1;
23
+ if (message.role === 'assistant')
24
+ for (const block of Array.isArray(message.content) ? message.content.map(piObject) : []) {
25
+ if (block.type !== 'toolCall')
26
+ continue;
27
+ const name = (piString(block.name) ?? 'unknown').slice(0, 120);
28
+ acc.tool_calls_by_name[name] = (acc.tool_calls_by_name[name] ?? 0) + 1;
29
+ }
30
+ }
31
+ if (record.type !== 'pi_usage')
32
+ return;
33
+ const usage = piObject(record.usage);
34
+ const number = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
35
+ observeNativeUsageFacts(acc, { status: record.status, identity: record.identity, model: record.model,
36
+ usage: { input_tokens: number(usage.input_tokens), output_tokens: number(usage.output_tokens), cache_read_input_tokens: number(usage.cache_read_input_tokens), cache_creation_input_tokens: number(usage.cache_creation_input_tokens) } });
37
+ }
@@ -5,6 +5,8 @@ export function accountPiUsage(sessionId, entry, ledger) {
5
5
  const api = piString(message.api), responseId = piString(message.responseId), entryId = piString(entry.id);
6
6
  const identity = provider && api && responseId ? JSON.stringify([provider, api, responseId]) : null;
7
7
  const result = { status: 'unknown', identity, ownerSessionId: null, model, provider, usage: null, reason: 'pi_usage_identity_or_fields_missing' };
8
+ if (!['stop', 'toolUse', 'length'].includes(String(message.stopReason)))
9
+ return { ...result, reason: 'pi_response_not_terminal_usage_unverified' };
8
10
  const native = piObject(message.usage);
9
11
  const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'totalTokens'];
10
12
  if (!identity || !model || !entryId || !fields.every(key => nonnegativeNumber(native[key])))
@@ -21,6 +21,7 @@ export declare const SessionFactsSchema: z.ZodObject<{
21
21
  codex: "codex";
22
22
  claude_code: "claude_code";
23
23
  opencode: "opencode";
24
+ pi: "pi";
24
25
  }>;
25
26
  usage_accounting: z.ZodOptional<z.ZodEnum<{
26
27
  complete: "complete";
@@ -24,7 +24,7 @@ export const SessionFactsUsageSchema = z
24
24
  export const SessionFactsSchema = z
25
25
  .object({
26
26
  extractor_version: z.string().trim().min(1).max(40),
27
- source: z.enum(["codex", "claude_code", "opencode"]),
27
+ source: z.enum(["codex", "claude_code", "opencode", "pi"]),
28
28
  usage_accounting: z.enum(["complete", "partial", "unavailable"]).optional(),
29
29
  usage_identity_scope: z.enum(["machine", "operator"]).optional(),
30
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(),
@@ -48,6 +48,8 @@ export function claudeSpawn(current, record) {
48
48
  * reports every distinct unmapped value so a real one (a VS Code or JetBrains entrypoint) is added from evidence.
49
49
  */
50
50
  export function claudeClientApp(entrypoint) {
51
+ if (entrypoint === "t3-code")
52
+ return "t3_code";
51
53
  if (entrypoint === "cli" || entrypoint === "sdk-cli")
52
54
  return "claude_cli";
53
55
  if (entrypoint === "claude-desktop")
@@ -6,7 +6,7 @@ import type { SkillUseCount } from "./session-facts-skills.js";
6
6
  /** Bump when a counting rule changes, never when a field is added. */
7
7
  export declare const SESSION_FACTS_VERSION = "det.v6";
8
8
  /** How many distinct models and tool names one session may report. */
9
- export type SessionFactsSource = "codex" | "claude_code" | "opencode";
9
+ export type SessionFactsSource = "codex" | "claude_code" | "opencode" | "pi";
10
10
  export interface SessionFactsUsage {
11
11
  input_tokens: number;
12
12
  output_tokens: number;
@@ -34,6 +34,7 @@ import { readT3ProjectionMessage } from "./t3-projection-message.js";
34
34
  */
35
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
36
  export { SESSION_FACTS_MAX_MODELS, SESSION_FACTS_MAX_TOOL_NAMES } from "./session-facts-schema.js";
37
+ import { observePiFacts } from "./pi-session-facts.js";
37
38
  import { observeOpenCodeFacts } from "./opencode-transcript.js";
38
39
  import { includeCodexRevisionRecord, observeCodexCumulativeUsage, codexRevisionUsageModel } from "./codex-record-copies.js";
39
40
  import { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText } from "./session-facts-text.js";
@@ -85,7 +86,9 @@ export function observeSessionFactsRecord(acc, record) {
85
86
  acc.last_timestamp_ms =
86
87
  acc.last_timestamp_ms == null ? ms : Math.max(acc.last_timestamp_ms, ms);
87
88
  }
88
- if (acc.source === "opencode")
89
+ if (acc.source === "pi")
90
+ observePiFacts(acc, record);
91
+ else if (acc.source === "opencode")
89
92
  observeOpenCodeFacts(acc, record);
90
93
  else if (acc.source === "claude_code")
91
94
  observeClaudeRecord(acc, record);
@@ -222,7 +225,7 @@ export function codexUsageFromCumulativeTotal(total) {
222
225
  };
223
226
  }
224
227
  export function finalizeSessionFacts(acc) {
225
- if (acc.source === "opencode")
228
+ if (acc.source === "opencode" || acc.source === "pi")
226
229
  acc.unknown_usage_records = (acc.unknown_usage_records ?? 0) + Math.max(0, (acc.opencode_usage_messages ?? 0) - (acc.opencode_usage_records ?? 0));
227
230
  // A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
228
231
  const usageModel = codexRevisionUsageModel(acc);
@@ -242,7 +245,7 @@ export function finalizeSessionFacts(acc) {
242
245
  return {
243
246
  extractor_version: SESSION_FACTS_VERSION,
244
247
  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 } : {}),
248
+ ...((acc.source === "opencode" || acc.source === "pi") ? { 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 } : {}),
246
249
  usage_by_model,
247
250
  models: keptUsage.map(([model]) => model).sort((a, b) => a.localeCompare(b)),
248
251
  input_tokens: totals.input_tokens,
package/dist/shelf.d.ts CHANGED
@@ -68,6 +68,7 @@ export declare const ShelfSessionMetricsSchema: z.ZodObject<{
68
68
  tool: z.ZodOptional<z.ZodEnum<{
69
69
  codex: "codex";
70
70
  opencode: "opencode";
71
+ pi: "pi";
71
72
  claude: "claude";
72
73
  }>>;
73
74
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -106,6 +107,7 @@ export declare const ShelfReportSchema: z.ZodObject<{
106
107
  tool: z.ZodOptional<z.ZodEnum<{
107
108
  codex: "codex";
108
109
  opencode: "opencode";
110
+ pi: "pi";
109
111
  claude: "claude";
110
112
  }>>;
111
113
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -155,6 +157,7 @@ export declare const ShelfReportsEnvelopeSchema: z.ZodObject<{
155
157
  tool: z.ZodOptional<z.ZodEnum<{
156
158
  codex: "codex";
157
159
  opencode: "opencode";
160
+ pi: "pi";
158
161
  claude: "claude";
159
162
  }>>;
160
163
  model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -179,7 +182,7 @@ export declare function shelfRequestHeaders(options: {
179
182
  }): Record<string, string>;
180
183
  /** The fields of a counted session the bare record is projected from (a subset of `SessionFacts`). */
181
184
  export interface ShelfMetricsFacts {
182
- source: "codex" | "claude_code" | "opencode";
185
+ source: "codex" | "claude_code" | "opencode" | "pi";
183
186
  usage_by_model: Record<string, {
184
187
  input_tokens: number;
185
188
  output_tokens: number;
package/dist/shelf.js CHANGED
@@ -63,7 +63,7 @@ export const ShelfSessionMetricsSchema = z
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
65
  usage_accounting: z.enum(["unavailable"]).optional(),
66
- tool: z.enum(["claude", "codex", "opencode"]).optional(),
66
+ tool: z.enum(["claude", "codex", "opencode", "pi"]).optional(),
67
67
  model_tokens: z.record(z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9._:/-]+$/), Count).optional(),
68
68
  spawn_kind: z.enum(["human", "automated", "subagent"]).optional(),
69
69
  })
@@ -161,8 +161,8 @@ export function projectShelfMetrics(facts, allow = []) {
161
161
  metrics.day = day.toISOString().slice(0, 10);
162
162
  }
163
163
  if (allowed.has("tool"))
164
- metrics.tool = facts.source === "opencode" ? "opencode" : facts.source === "codex" ? "codex" : "claude";
165
- if (facts.source === "opencode") {
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
166
  // Drawer privacy excludes native request identities, so global copied usage cannot be settled here.
167
167
  metrics.usage_accounting = "unavailable";
168
168
  metrics.input_tokens = null;
@@ -171,7 +171,7 @@ export function projectShelfMetrics(facts, allow = []) {
171
171
  metrics.cache_creation_tokens = null;
172
172
  metrics.total_tokens = null;
173
173
  }
174
- if (allowed.has("model") && facts.source !== "opencode") {
174
+ if (allowed.has("model") && (facts.source !== "opencode" && facts.source !== "pi")) {
175
175
  const byModel = {};
176
176
  for (const [model, usage] of Object.entries(facts.usage_by_model)) {
177
177
  const key = model.trim().slice(0, 80);
@@ -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.98",
3
+ "version": "0.1.99",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",