@bli-cockpit/telemetry-core 0.1.98 → 0.1.100

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 (43) hide show
  1. package/dist/agent-artifacts.d.ts +3 -0
  2. package/dist/agent-artifacts.js +1 -1
  3. package/dist/collector-heartbeat.d.ts +4 -0
  4. package/dist/collector-heartbeat.js +4 -2
  5. package/dist/evidence-rules-fingerprint.js +1 -0
  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 +11 -3
  12. package/dist/evidence-upload.js +1 -1
  13. package/dist/excluded-folders-contract.d.ts +40 -0
  14. package/dist/excluded-folders-contract.js +128 -0
  15. package/dist/founder-standing-contract.d.ts +3 -1
  16. package/dist/image-byte-scan.js +30 -1
  17. package/dist/image-descriptions.d.ts +1 -0
  18. package/dist/image-descriptions.js +1 -1
  19. package/dist/image-store.d.ts +1 -0
  20. package/dist/image-store.js +1 -1
  21. package/dist/index.d.ts +5 -0
  22. package/dist/index.js +5 -0
  23. package/dist/local-config.d.ts +1 -0
  24. package/dist/local-config.js +5 -0
  25. package/dist/memory-capture-contract.d.ts +7 -1
  26. package/dist/memory-capture-contract.js +3 -1
  27. package/dist/memory-hook-stats.d.ts +1 -1
  28. package/dist/native-usage-facts.d.ts +8 -0
  29. package/dist/native-usage-facts.js +28 -0
  30. package/dist/opencode-transcript.d.ts +0 -1
  31. package/dist/opencode-transcript.js +4 -29
  32. package/dist/pi-session-facts.d.ts +2 -0
  33. package/dist/pi-session-facts.js +37 -0
  34. package/dist/pi-transcript-usage.js +2 -0
  35. package/dist/session-facts-schema.d.ts +1 -0
  36. package/dist/session-facts-schema.js +1 -1
  37. package/dist/session-facts-spawn.js +2 -0
  38. package/dist/session-facts.d.ts +1 -1
  39. package/dist/session-facts.js +6 -3
  40. package/dist/shelf.d.ts +4 -1
  41. package/dist/shelf.js +4 -4
  42. package/dist/transcript-images.js +12 -0
  43. package/package.json +1 -1
@@ -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",
@@ -55,12 +55,14 @@ export declare const CaptureOptOutsSchema: z.ZodObject<{
55
55
  collect_claude_jsonl_false: "collect_claude_jsonl_false";
56
56
  collect_codex_jsonl_false: "collect_codex_jsonl_false";
57
57
  raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
58
+ excluded_folder: "excluded_folder";
58
59
  }>>;
59
60
  ignored: z.ZodArray<z.ZodEnum<{
60
61
  memory_capture_off: "memory_capture_off";
61
62
  collect_claude_jsonl_false: "collect_claude_jsonl_false";
62
63
  collect_codex_jsonl_false: "collect_codex_jsonl_false";
63
64
  raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
65
+ excluded_folder: "excluded_folder";
64
66
  }>>;
65
67
  }, z.core.$strict>;
66
68
  export type CaptureOptOuts = z.infer<typeof CaptureOptOutsSchema>;
@@ -395,12 +397,14 @@ export declare const CollectorHeartbeatSchema: z.ZodObject<{
395
397
  collect_claude_jsonl_false: "collect_claude_jsonl_false";
396
398
  collect_codex_jsonl_false: "collect_codex_jsonl_false";
397
399
  raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
400
+ excluded_folder: "excluded_folder";
398
401
  }>>;
399
402
  ignored: z.ZodArray<z.ZodEnum<{
400
403
  memory_capture_off: "memory_capture_off";
401
404
  collect_claude_jsonl_false: "collect_claude_jsonl_false";
402
405
  collect_codex_jsonl_false: "collect_codex_jsonl_false";
403
406
  raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
407
+ excluded_folder: "excluded_folder";
404
408
  }>>;
405
409
  }, z.core.$strict>>;
406
410
  }, z.core.$strict>;
@@ -58,12 +58,14 @@ const CaptureOptOutLabelSchema = z.enum([
58
58
  "collect_claude_jsonl_false",
59
59
  "collect_codex_jsonl_false",
60
60
  "raw_evidence_upload_disabled",
61
+ // BLI-24635: the machine holds excluded folders.
62
+ "excluded_folder",
61
63
  ]);
62
64
  export const CaptureOptOutsSchema = z
63
65
  .object({
64
66
  standing: z.enum(["founder", "not_founder", "unknown"]),
65
- obeyed: z.array(CaptureOptOutLabelSchema).max(4),
66
- ignored: z.array(CaptureOptOutLabelSchema).max(4),
67
+ obeyed: z.array(CaptureOptOutLabelSchema).max(5),
68
+ ignored: z.array(CaptureOptOutLabelSchema).max(5),
67
69
  })
68
70
  .strict();
69
71
  /**
@@ -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({
@@ -0,0 +1,40 @@
1
+ /**
2
+ * BLI-24635: a founder's excluded folders. A session whose working folder is inside one of these never leaves the
3
+ * machine by any path (scheduled sync, backfill, raw evidence, images, the memory hooks).
4
+ *
5
+ * The list lives in the collector config (`excluded_folders`, absolute paths) and survives every config rewrite like
6
+ * the source opt-outs do. Like them it is obeyed ONLY for a founder, on Tower's LIVE answer
7
+ * (`founder-standing-contract.ts`, `optOutVerdict`): ignored and reported for anyone else, held (treated as obeyed)
8
+ * while Tower cannot answer.
9
+ *
10
+ * This file is the ONE matching rule, shared by the collector and the memory hooks so they cannot disagree. It is
11
+ * pure (no filesystem): a caller that can resolve symlinks passes `realpath`, and both the raw and the resolved form
12
+ * of each side are compared.
13
+ *
14
+ * - The platform is read from each path itself: a drive letter, a UNC share or a backslash is Windows. Windows
15
+ * compares case-insensitively with either slash; macOS and Linux compare exactly.
16
+ * - Trailing slashes, `.` and `..` segments and doubled separators are normalised away.
17
+ * - Containment is whole segments: `Personal Projects 2` is NOT inside `Personal Projects`.
18
+ * - A Windows path never matches a POSIX folder, or the reverse.
19
+ *
20
+ * Logs say `excluded_folder` with counts only. Never a path or a folder name.
21
+ */
22
+ /** The reason label every withhold logs, and the label a heartbeat reports. */
23
+ export declare const EXCLUDED_FOLDER_REASON = "excluded_folder";
24
+ /** A config holds at most this many; more is refused by the schema. */
25
+ export declare const EXCLUDED_FOLDERS_MAX = 100;
26
+ /**
27
+ * The comparison key for one path, or null when it is not absolute (a relative path cannot be placed, so it never
28
+ * matches anything). Windows keys are lower-case with forward slashes (`c:/users/me/personal projects`); POSIX keys
29
+ * keep their case (`/Users/me/Personal Projects`).
30
+ */
31
+ export declare function excludedFolderKey(value: string | null | undefined): string | null;
32
+ /**
33
+ * Is this working folder inside any excluded folder? `realpath` is optional: when given, a symlinked folder and its
34
+ * target both count, on either side. It must not throw (a throw reads as "could not resolve").
35
+ */
36
+ export declare function pathInsideExcludedFolders(cwd: string | null | undefined, folders: readonly string[], realpath?: (value: string) => string | null): boolean;
37
+ /** The list a config holds, deduplicated by key, or [] when it holds none. Never throws. */
38
+ export declare function configExcludedFolders(config: {
39
+ excluded_folders?: unknown;
40
+ } | Record<string, unknown> | null | undefined): string[];
@@ -0,0 +1,128 @@
1
+ /**
2
+ * BLI-24635: a founder's excluded folders. A session whose working folder is inside one of these never leaves the
3
+ * machine by any path (scheduled sync, backfill, raw evidence, images, the memory hooks).
4
+ *
5
+ * The list lives in the collector config (`excluded_folders`, absolute paths) and survives every config rewrite like
6
+ * the source opt-outs do. Like them it is obeyed ONLY for a founder, on Tower's LIVE answer
7
+ * (`founder-standing-contract.ts`, `optOutVerdict`): ignored and reported for anyone else, held (treated as obeyed)
8
+ * while Tower cannot answer.
9
+ *
10
+ * This file is the ONE matching rule, shared by the collector and the memory hooks so they cannot disagree. It is
11
+ * pure (no filesystem): a caller that can resolve symlinks passes `realpath`, and both the raw and the resolved form
12
+ * of each side are compared.
13
+ *
14
+ * - The platform is read from each path itself: a drive letter, a UNC share or a backslash is Windows. Windows
15
+ * compares case-insensitively with either slash; macOS and Linux compare exactly.
16
+ * - Trailing slashes, `.` and `..` segments and doubled separators are normalised away.
17
+ * - Containment is whole segments: `Personal Projects 2` is NOT inside `Personal Projects`.
18
+ * - A Windows path never matches a POSIX folder, or the reverse.
19
+ *
20
+ * Logs say `excluded_folder` with counts only. Never a path or a folder name.
21
+ */
22
+ /** The reason label every withhold logs, and the label a heartbeat reports. */
23
+ export const EXCLUDED_FOLDER_REASON = "excluded_folder";
24
+ /** A config holds at most this many; more is refused by the schema. */
25
+ export const EXCLUDED_FOLDERS_MAX = 100;
26
+ function looksWindows(value) {
27
+ return /^[A-Za-z]:([\\/]|$)/u.test(value) || value.startsWith("\\\\") || value.startsWith("//?/") || value.includes("\\");
28
+ }
29
+ /**
30
+ * The comparison key for one path, or null when it is not absolute (a relative path cannot be placed, so it never
31
+ * matches anything). Windows keys are lower-case with forward slashes (`c:/users/me/personal projects`); POSIX keys
32
+ * keep their case (`/Users/me/Personal Projects`).
33
+ */
34
+ export function excludedFolderKey(value) {
35
+ const raw = (value ?? "").trim();
36
+ if (!raw)
37
+ return null;
38
+ const windows = looksWindows(raw);
39
+ let text = windows ? raw.replace(/\\/gu, "/") : raw;
40
+ if (windows) {
41
+ text = text.replace(/^\/\/\?\/(unc\/)?/iu, (_match, unc) => (unc ? "//" : ""));
42
+ }
43
+ let prefix;
44
+ let rest;
45
+ if (windows && /^[A-Za-z]:(\/|$)/u.test(text)) {
46
+ prefix = `${text.slice(0, 2).toLowerCase()}/`;
47
+ rest = text.slice(2);
48
+ }
49
+ else if (windows && text.startsWith("//")) {
50
+ prefix = "//";
51
+ rest = text.slice(2);
52
+ }
53
+ else if (!windows && text.startsWith("/")) {
54
+ prefix = "/";
55
+ rest = text;
56
+ }
57
+ else {
58
+ return null;
59
+ }
60
+ const parts = [];
61
+ for (const part of rest.split("/")) {
62
+ if (!part || part === ".")
63
+ continue;
64
+ if (part === "..") {
65
+ parts.pop();
66
+ continue;
67
+ }
68
+ parts.push(windows ? part.toLowerCase() : part);
69
+ }
70
+ return prefix + parts.join("/");
71
+ }
72
+ /** True when `candidateKey` is `folderKey` or a path below it, by whole segments. */
73
+ function keyWithin(candidateKey, folderKey) {
74
+ if (candidateKey === folderKey)
75
+ return true;
76
+ const base = folderKey.endsWith("/") ? folderKey : `${folderKey}/`;
77
+ return candidateKey.startsWith(base);
78
+ }
79
+ /** Every key a path is known by: as written, and resolved through symlinks when the caller can. */
80
+ function keysOf(value, realpath) {
81
+ const keys = new Set();
82
+ const direct = excludedFolderKey(value);
83
+ if (direct)
84
+ keys.add(direct);
85
+ if (realpath) {
86
+ let resolved = null;
87
+ try {
88
+ resolved = realpath(value);
89
+ }
90
+ catch {
91
+ resolved = null;
92
+ }
93
+ const resolvedKey = excludedFolderKey(resolved);
94
+ if (resolvedKey)
95
+ keys.add(resolvedKey);
96
+ }
97
+ return [...keys];
98
+ }
99
+ /**
100
+ * Is this working folder inside any excluded folder? `realpath` is optional: when given, a symlinked folder and its
101
+ * target both count, on either side. It must not throw (a throw reads as "could not resolve").
102
+ */
103
+ export function pathInsideExcludedFolders(cwd, folders, realpath) {
104
+ if (!cwd || folders.length === 0)
105
+ return false;
106
+ const cwdKeys = keysOf(cwd, realpath);
107
+ if (cwdKeys.length === 0)
108
+ return false;
109
+ return folders.some((folder) => keysOf(folder, realpath).some((folderKey) => cwdKeys.some((key) => keyWithin(key, folderKey))));
110
+ }
111
+ /** The list a config holds, deduplicated by key, or [] when it holds none. Never throws. */
112
+ export function configExcludedFolders(config) {
113
+ const value = config?.excluded_folders;
114
+ if (!Array.isArray(value))
115
+ return [];
116
+ const seen = new Set();
117
+ const folders = [];
118
+ for (const entry of value) {
119
+ if (typeof entry !== "string")
120
+ continue;
121
+ const key = excludedFolderKey(entry);
122
+ if (!key || seen.has(key))
123
+ continue;
124
+ seen.add(key);
125
+ folders.push(entry);
126
+ }
127
+ return folders;
128
+ }
@@ -120,7 +120,9 @@ export declare function founderAnswerFromReply(reply: {
120
120
  body: unknown;
121
121
  }): LiveFounderAnswer;
122
122
  /** The labels a machine's opt-outs are reported under (heartbeat, doctor, logs). */
123
- export type CaptureOptOutLabel = "memory_capture_off" | "collect_claude_jsonl_false" | "collect_codex_jsonl_false" | "raw_evidence_upload_disabled";
123
+ export type CaptureOptOutLabel = "memory_capture_off" | "collect_claude_jsonl_false" | "collect_codex_jsonl_false" | "raw_evidence_upload_disabled"
124
+ /** BLI-24635: the machine holds excluded folders (`excluded-folders-contract.ts`). */
125
+ | "excluded_folder";
124
126
  /** The refusal a non-founder gets from every door that records an "off". */
125
127
  export declare const FOUNDERS_ONLY_REFUSAL = "memory_off_founders_only";
126
128
  /** The refusal when Tower could not be asked; nothing is recorded. */
@@ -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
@@ -1,5 +1,6 @@
1
1
  export * from "./agent-artifacts.js";
2
2
  export * from "./collection-scope.js";
3
+ export * from "./excluded-folders-contract.js";
3
4
  export * from "./collector-heartbeat.js";
4
5
  export * from "./setup-receipt.js";
5
6
  export * from "./agent-setup.js";
@@ -55,3 +56,7 @@ export * from "./trace-sink.js";
55
56
  export * from "./upload-failure-class.js";
56
57
  export * from "./work-context.js";
57
58
  export { openCodeTurnText, openCodeProviderIdentity, nativeObject } from "./opencode-transcript.js";
59
+ export * from "./pi-transcript.js";
60
+ export * from "./pi-transcript-usage.js";
61
+ export * from "./pi-transcript-extract.js";
62
+ export * from "./pi-transcript-lineage.js";
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./agent-artifacts.js";
2
2
  export * from "./collection-scope.js";
3
+ export * from "./excluded-folders-contract.js";
3
4
  export * from "./collector-heartbeat.js";
4
5
  export * from "./setup-receipt.js";
5
6
  export * from "./agent-setup.js";
@@ -55,3 +56,7 @@ export * from "./trace-sink.js";
55
56
  export * from "./upload-failure-class.js";
56
57
  export * from "./work-context.js";
57
58
  export { openCodeTurnText, openCodeProviderIdentity, nativeObject } from "./opencode-transcript.js";
59
+ export * from "./pi-transcript.js";
60
+ export * from "./pi-transcript-usage.js";
61
+ export * from "./pi-transcript-extract.js";
62
+ export * from "./pi-transcript-lineage.js";
@@ -30,6 +30,7 @@ export declare const LocalCollectorConfigSchema: z.ZodObject<{
30
30
  tool: "tool";
31
31
  day: "day";
32
32
  }>>>;
33
+ excluded_folders: z.ZodOptional<z.ZodArray<z.ZodString>>;
33
34
  session_file_path: z.ZodOptional<z.ZodString>;
34
35
  state_dir_path: z.ZodOptional<z.ZodString>;
35
36
  }, z.core.$strict>;
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { CollectionScopeSchema } from "./collection-scope.js";
3
+ import { EXCLUDED_FOLDERS_MAX } from "./excluded-folders-contract.js";
3
4
  import { IsoDateTimeSchema, NonEmptyStringSchema, VersionStringSchema, } from "./common.js";
4
5
  export const LocalCollectorConfigSchema = z
5
6
  .object({
@@ -39,6 +40,10 @@ export const LocalCollectorConfigSchema = z
39
40
  shelf_default: z.enum(["team", "drawer"]).optional(),
40
41
  // BLI-23478: the opt-in categories a founder allows on a bare record (all off when absent).
41
42
  shelf_metrics_allow: z.array(z.enum(["day", "tool", "model", "spawn"])).max(4).optional(),
43
+ // BLI-24635: a founder's excluded folders (absolute paths). A session whose working folder is inside one never
44
+ // leaves the machine. Obeyed only for a founder on Tower's live answer (`excluded-folders-contract.ts`). Optional
45
+ // with no default and written only when non-empty, so a machine that never set it keeps a config every CLI reads.
46
+ excluded_folders: z.array(NonEmptyStringSchema).max(EXCLUDED_FOLDERS_MAX).optional(),
42
47
  session_file_path: NonEmptyStringSchema.optional(),
43
48
  state_dir_path: NonEmptyStringSchema.optional(),
44
49
  })
@@ -81,7 +81,8 @@ export type MemoryHookHost = "claude_code" | "codex";
81
81
  * unreadable (no source opt-out can be read from it, so none applies).
82
82
  */
83
83
  export interface MemoryCaptureGate {
84
- refusal: "memory_opt_out" | "session_upload_opt_out" | null;
84
+ /** `excluded_folder` (BLI-24635): the hook's working folder is inside one of the machine's excluded folders. */
85
+ refusal: "memory_opt_out" | "session_upload_opt_out" | "excluded_folder" | null;
85
86
  /** Opt-outs found and NOT obeyed because Tower says this person is not a founder. */
86
87
  ignored: CaptureOptOutLabel[];
87
88
  /** Why the refusal was obeyed; null when nothing was. */
@@ -95,6 +96,11 @@ export declare function memoryCaptureGate(input: {
95
96
  host: MemoryHookHost;
96
97
  standing: FounderStanding;
97
98
  saveHook: boolean;
99
+ /**
100
+ * BLI-24635: the hook's working folder is inside an excluded folder. EVERY hook skips (recall would send the
101
+ * prompt as a search). Founders only, like the rest.
102
+ */
103
+ excludedFolder?: boolean;
98
104
  }): MemoryCaptureGate;
99
105
  /** The config's opt-out for one host's sessions, or null when they upload. */
100
106
  export declare function sessionOptOutLabel(config: Record<string, unknown> | null, host: MemoryHookHost): CaptureOptOutLabel | null;
@@ -67,9 +67,11 @@ export function renderMemoryCaptureChoice(choice) {
67
67
  export function memoryCaptureGate(input) {
68
68
  const memoryOff = input.choice.state === "off";
69
69
  const sessionLabel = input.saveHook ? sessionOptOutLabel(input.config, input.host) : null;
70
+ const excluded = input.excludedFolder === true;
70
71
  const found = [
71
72
  ...(memoryOff ? ["memory_capture_off"] : []),
72
73
  ...(sessionLabel ? [sessionLabel] : []),
74
+ ...(excluded ? ["excluded_folder"] : []),
73
75
  ];
74
76
  if (found.length === 0)
75
77
  return { refusal: null, ignored: [], obeyedReason: null, held: false };
@@ -77,7 +79,7 @@ export function memoryCaptureGate(input) {
77
79
  if (!verdict.obeyed)
78
80
  return { refusal: null, ignored: found, obeyedReason: null, held: false };
79
81
  return {
80
- refusal: memoryOff ? "memory_opt_out" : "session_upload_opt_out",
82
+ refusal: memoryOff ? "memory_opt_out" : excluded ? "excluded_folder" : "session_upload_opt_out",
81
83
  ignored: [],
82
84
  obeyedReason: verdict.reason,
83
85
  held: verdict.held,
@@ -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.100",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",