@bli-cockpit/telemetry-core 0.1.81 → 0.1.83

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.
@@ -53,6 +53,12 @@ export declare const CollectorHeartbeatSchema: z.ZodObject<{
53
53
  basename: z.ZodString;
54
54
  path_sha256: z.ZodString;
55
55
  }, z.core.$strict>>;
56
+ shelved_roots: z.ZodOptional<z.ZodArray<z.ZodObject<{
57
+ shelf: z.ZodEnum<{
58
+ drawer: "drawer";
59
+ safe: "safe";
60
+ }>;
61
+ }, z.core.$strict>>>;
56
62
  last_sync_status: z.ZodDefault<z.ZodEnum<{
57
63
  skipped: "skipped";
58
64
  ok: "ok";
@@ -66,6 +66,15 @@ export const CollectorHeartbeatSchema = z
66
66
  .regex(/^[a-z0-9_-]+$/iu)
67
67
  .optional(),
68
68
  roots: z.array(CollectorRootLabelSchema).max(COLLECTOR_HEARTBEAT_MAX_ROOTS),
69
+ /**
70
+ * BLI-22734 (three shelves): how many approved roots are labelled drawer or safe on this machine. Those roots
71
+ * never appear in `roots` (no basename, no path hash): only their shelf, counted. Absent on CLIs before the
72
+ * routing release.
73
+ */
74
+ shelved_roots: z
75
+ .array(z.object({ shelf: z.enum(["drawer", "safe"]) }).strict())
76
+ .max(COLLECTOR_HEARTBEAT_MAX_ROOTS)
77
+ .optional(),
69
78
  /**
70
79
  * How the tick that produced this heartbeat went, so a machine that is
71
80
  * alive AND failing is distinguishable from one that is alive and idle
@@ -638,6 +638,7 @@ export declare const CodexSessionAttributionSchema: z.ZodObject<{
638
638
  inside: "inside";
639
639
  outside: "outside";
640
640
  }>>;
641
+ shelf: z.ZodOptional<z.ZodLiteral<"team">>;
641
642
  cwd_basename: z.ZodOptional<z.ZodString>;
642
643
  cwd_hash: z.ZodOptional<z.ZodString>;
643
644
  raw_evidence_pointer_id: z.ZodOptional<z.ZodString>;
@@ -772,6 +773,7 @@ export declare const CodexSessionAttributionReportRequestSchema: z.ZodObject<{
772
773
  inside: "inside";
773
774
  outside: "outside";
774
775
  }>>;
776
+ shelf: z.ZodOptional<z.ZodLiteral<"team">>;
775
777
  cwd_basename: z.ZodOptional<z.ZodString>;
776
778
  cwd_hash: z.ZodOptional<z.ZodString>;
777
779
  raw_evidence_pointer_id: z.ZodOptional<z.ZodString>;
@@ -333,6 +333,12 @@ export const CodexSessionAttributionSchema = z
333
333
  .max(100)
334
334
  .optional(),
335
335
  root_scope: RootScopeSchema.optional(),
336
+ /**
337
+ * BLI-22734 (three shelves): which shelf this session row belongs to. Only `team` rows are ever sent; a
338
+ * drawer or safe session sends a bare record instead (`shelf.ts`). Optional because CLIs before the routing
339
+ * release send none; the server refuses a founder's row without it once founder routing is on.
340
+ */
341
+ shelf: z.literal("team").optional(),
336
342
  cwd_basename: BasenameSchema.optional(),
337
343
  cwd_hash: z
338
344
  .string()
package/dist/index.d.ts CHANGED
@@ -29,6 +29,8 @@ export * from "./risk-flags.js";
29
29
  export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
+ export * from "./session-facts-delta.js";
33
+ export * from "./shelf.js";
32
34
  export * from "./session-facts-skills.js";
33
35
  export * from "./session-facts-spawn.js";
34
36
  export * from "./session-facts-active.js";
package/dist/index.js CHANGED
@@ -29,6 +29,8 @@ export * from "./risk-flags.js";
29
29
  export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
+ export * from "./session-facts-delta.js";
33
+ export * from "./shelf.js";
32
34
  export * from "./session-facts-skills.js";
33
35
  export * from "./session-facts-spawn.js";
34
36
  export * from "./session-facts-active.js";
@@ -0,0 +1,45 @@
1
+ /**
2
+ * One file's contribution to a session's facts, remembered so the file need not be read again (BLI-22797).
3
+ *
4
+ * The collector counts a session by feeding its main transcript and each accepted sidecar into ONE accumulator
5
+ * (`session-facts.ts`). That accumulator is not a plain sum: usage is deduped by request id ACROSS files, the
6
+ * Codex totals and the spawn marker are first/last-wins folds, the skill tally keeps first-seen order, and the
7
+ * active-time rule needs every timestamp. So a remembered contribution cannot be a bag of totals. It is what
8
+ * the file would have done to a fresh accumulator, stored in a form that replays onto a live one identically:
9
+ *
10
+ * - `usage`: each request id the file contributed (first occurrence in the file), in file order, so the id
11
+ * dedupe against files already merged is the same decision a fresh read makes;
12
+ * - plain counters add; `timestamps` are sorted and delta-encoded (the active-time rule is order-blind);
13
+ * - `codex_total_usage` / `codex_model_hint` overwrite when set (last file wins); `spawn` fills only an
14
+ * empty slot (first file wins); `skills` merge in first-seen order.
15
+ *
16
+ * Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
17
+ */
18
+ import { type SessionFactsAccumulator, type SessionFactsSource } from "./session-facts.js";
19
+ import type { SessionSpawn } from "./session-facts-spawn.js";
20
+ import type { SkillUseCount } from "./session-facts-skills.js";
21
+ /** `[request id, model, input, output, cache read, cache creation]`. */
22
+ export type SessionFactsDeltaUsage = [string, string, number, number, number, number];
23
+ export interface SessionFactsDelta {
24
+ source: SessionFactsSource;
25
+ usage: SessionFactsDeltaUsage[];
26
+ record_count: number;
27
+ user_prompt_count: number;
28
+ assistant_response_count: number;
29
+ tool_calls_by_name: Record<string, number>;
30
+ /** Sorted ascending: the first value, then the gap to each next one, in ms. */
31
+ timestamps: number[];
32
+ transcript_bytes: number;
33
+ transcript_lines: number;
34
+ transcript_files: number;
35
+ codex_total_usage: Record<string, unknown> | null;
36
+ codex_model_hint: string | null;
37
+ skills: SkillUseCount[];
38
+ spawn: SessionSpawn | null;
39
+ }
40
+ /** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
41
+ export declare function captureSessionFactsDelta(source: SessionFactsSource, feed: (acc: SessionFactsAccumulator) => void): SessionFactsDelta;
42
+ /** Leave `acc` as a fresh read of the same file would have left it. */
43
+ export declare function mergeSessionFactsDelta(acc: SessionFactsAccumulator, delta: SessionFactsDelta): void;
44
+ /** A stored delta read back from disk, or null when it is not one (the caller then reads the file fresh). */
45
+ export declare function parseSessionFactsDelta(value: unknown): SessionFactsDelta | null;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * One file's contribution to a session's facts, remembered so the file need not be read again (BLI-22797).
3
+ *
4
+ * The collector counts a session by feeding its main transcript and each accepted sidecar into ONE accumulator
5
+ * (`session-facts.ts`). That accumulator is not a plain sum: usage is deduped by request id ACROSS files, the
6
+ * Codex totals and the spawn marker are first/last-wins folds, the skill tally keeps first-seen order, and the
7
+ * active-time rule needs every timestamp. So a remembered contribution cannot be a bag of totals. It is what
8
+ * the file would have done to a fresh accumulator, stored in a form that replays onto a live one identically:
9
+ *
10
+ * - `usage`: each request id the file contributed (first occurrence in the file), in file order, so the id
11
+ * dedupe against files already merged is the same decision a fresh read makes;
12
+ * - plain counters add; `timestamps` are sorted and delta-encoded (the active-time rule is order-blind);
13
+ * - `codex_total_usage` / `codex_model_hint` overwrite when set (last file wins); `spawn` fills only an
14
+ * empty slot (first file wins); `skills` merge in first-seen order.
15
+ *
16
+ * Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
17
+ */
18
+ import { addClaudeUsage, newSessionFactsAccumulator, } from "./session-facts.js";
19
+ const finite = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
20
+ /** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
21
+ export function captureSessionFactsDelta(source, feed) {
22
+ const acc = newSessionFactsAccumulator(source);
23
+ acc.usage_log = [];
24
+ feed(acc);
25
+ const sorted = [...acc.timestamps_ms].sort((a, b) => a - b);
26
+ return {
27
+ source,
28
+ usage: acc.usage_log.map(({ id, model, usage }) => [
29
+ id,
30
+ model,
31
+ finite(usage["input_tokens"]),
32
+ finite(usage["output_tokens"]),
33
+ finite(usage["cache_read_input_tokens"]),
34
+ finite(usage["cache_creation_input_tokens"]),
35
+ ]),
36
+ record_count: acc.record_count,
37
+ user_prompt_count: acc.user_prompt_count,
38
+ assistant_response_count: acc.assistant_response_count,
39
+ tool_calls_by_name: { ...acc.tool_calls_by_name },
40
+ timestamps: sorted.map((value, i) => (i === 0 ? value : value - sorted[i - 1])),
41
+ transcript_bytes: acc.transcript_bytes,
42
+ transcript_lines: acc.transcript_lines,
43
+ transcript_files: acc.transcript_files,
44
+ codex_total_usage: acc.codex_total_usage ? { ...acc.codex_total_usage } : null,
45
+ codex_model_hint: acc.codex_model_hint,
46
+ skills: acc.skill_tally.entries(),
47
+ spawn: acc.spawn ? { ...acc.spawn } : null,
48
+ };
49
+ }
50
+ /** Leave `acc` as a fresh read of the same file would have left it. */
51
+ export function mergeSessionFactsDelta(acc, delta) {
52
+ for (const [id, model, input, output, cacheRead, cacheCreation] of delta.usage) {
53
+ if (acc.seen_usage_ids.has(id))
54
+ continue;
55
+ acc.seen_usage_ids.add(id);
56
+ addClaudeUsage(acc, model, {
57
+ input_tokens: input,
58
+ output_tokens: output,
59
+ cache_read_input_tokens: cacheRead,
60
+ cache_creation_input_tokens: cacheCreation,
61
+ });
62
+ }
63
+ acc.record_count += delta.record_count;
64
+ acc.user_prompt_count += delta.user_prompt_count;
65
+ acc.assistant_response_count += delta.assistant_response_count;
66
+ for (const [name, count] of Object.entries(delta.tool_calls_by_name)) {
67
+ acc.tool_calls_by_name[name] = (acc.tool_calls_by_name[name] ?? 0) + count;
68
+ }
69
+ let at = 0;
70
+ delta.timestamps.forEach((value, i) => {
71
+ at = i === 0 ? value : at + value;
72
+ acc.timestamps_ms.push(at);
73
+ acc.first_timestamp_ms = acc.first_timestamp_ms == null ? at : Math.min(acc.first_timestamp_ms, at);
74
+ acc.last_timestamp_ms = acc.last_timestamp_ms == null ? at : Math.max(acc.last_timestamp_ms, at);
75
+ });
76
+ acc.transcript_bytes += delta.transcript_bytes;
77
+ acc.transcript_lines += delta.transcript_lines;
78
+ acc.transcript_files += delta.transcript_files;
79
+ if (delta.codex_total_usage)
80
+ acc.codex_total_usage = { ...delta.codex_total_usage };
81
+ if (delta.codex_model_hint !== null)
82
+ acc.codex_model_hint = delta.codex_model_hint;
83
+ acc.skill_tally.mergeEntries(delta.skills);
84
+ if (!acc.spawn && delta.spawn)
85
+ acc.spawn = { ...delta.spawn };
86
+ }
87
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
88
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
89
+ /** A stored delta read back from disk, or null when it is not one (the caller then reads the file fresh). */
90
+ export function parseSessionFactsDelta(value) {
91
+ if (!isObj(value))
92
+ return null;
93
+ const v = value;
94
+ if (v["source"] !== "claude_code" && v["source"] !== "codex")
95
+ return null;
96
+ const usage = v["usage"];
97
+ if (!Array.isArray(usage) || !usage.every((u) => Array.isArray(u) && u.length === 6 && typeof u[0] === "string" && typeof u[1] === "string" && u.slice(2).every(isNum)))
98
+ return null;
99
+ for (const key of ["record_count", "user_prompt_count", "assistant_response_count", "transcript_bytes", "transcript_lines", "transcript_files"]) {
100
+ if (!isNum(v[key]))
101
+ return null;
102
+ }
103
+ const tools = v["tool_calls_by_name"];
104
+ if (!isObj(tools) || !Object.values(tools).every(isNum))
105
+ return null;
106
+ const stamps = v["timestamps"];
107
+ if (!Array.isArray(stamps) || !stamps.every(isNum))
108
+ return null;
109
+ const skills = v["skills"];
110
+ if (!Array.isArray(skills) || !skills.every((s) => isObj(s) && typeof s["skill"] === "string" && (s["plugin"] === null || typeof s["plugin"] === "string") && isNum(s["by_person"]) && isNum(s["by_agent"])))
111
+ return null;
112
+ const total = v["codex_total_usage"];
113
+ if (total !== null && !isObj(total))
114
+ return null;
115
+ const hint = v["codex_model_hint"];
116
+ if (hint !== null && typeof hint !== "string")
117
+ return null;
118
+ const spawn = v["spawn"];
119
+ if (spawn !== null && !(isObj(spawn) && typeof spawn["kind"] === "string"))
120
+ return null;
121
+ return value;
122
+ }
@@ -45,6 +45,10 @@ export declare class SkillUseTally {
45
45
  private readonly counts;
46
46
  addByPerson(raw: string): void;
47
47
  addByAgent(raw: string): void;
48
+ /** Every tallied skill in first-seen order (unsorted), so a memoized delta merges back identically (BLI-22797). */
49
+ entries(): SkillUseCount[];
50
+ /** Add another tally's counts, creating keys in the given order, exactly as counting those uses here would have. */
51
+ mergeEntries(entries: readonly SkillUseCount[]): void;
48
52
  /** Most used first, ties by name, so the stored list is stable. */
49
53
  toList(): SkillUseCount[];
50
54
  private entry;
@@ -64,6 +64,24 @@ export class SkillUseTally {
64
64
  if (entry)
65
65
  entry.by_agent += 1;
66
66
  }
67
+ /** Every tallied skill in first-seen order (unsorted), so a memoized delta merges back identically (BLI-22797). */
68
+ entries() {
69
+ return [...this.counts.values()].map((c) => ({ ...c }));
70
+ }
71
+ /** Add another tally's counts, creating keys in the given order, exactly as counting those uses here would have. */
72
+ mergeEntries(entries) {
73
+ for (const e of entries) {
74
+ const key = `${e.plugin ?? ""}:${e.skill}`;
75
+ const existing = this.counts.get(key);
76
+ if (existing) {
77
+ existing.by_person += e.by_person;
78
+ existing.by_agent += e.by_agent;
79
+ }
80
+ else {
81
+ this.counts.set(key, { skill: e.skill, plugin: e.plugin, by_person: e.by_person, by_agent: e.by_agent });
82
+ }
83
+ }
84
+ }
67
85
  /** Most used first, ties by name, so the stored list is stable. */
68
86
  toList() {
69
87
  return [...this.counts.values()]
@@ -103,6 +103,12 @@ export interface SessionFactsAccumulator {
103
103
  codex_model_hint: string | null;
104
104
  skill_tally: SkillUseTally;
105
105
  spawn: SessionSpawn | null;
106
+ /** Set only by `session-facts-delta.ts` while it captures one file's contribution (BLI-22797). */
107
+ usage_log?: Array<{
108
+ id: string;
109
+ model: string;
110
+ usage: Record<string, unknown>;
111
+ }>;
106
112
  }
107
113
  export declare function newSessionFactsAccumulator(source: SessionFactsSource): SessionFactsAccumulator;
108
114
  /** One transcript file's size, for callers that never hold its whole text. */
@@ -112,6 +118,7 @@ export declare function observeSessionFactsFile(acc: SessionFactsAccumulator, fi
112
118
  }): void;
113
119
  /** One parsed JSONL record. The caller owns parsing; this owns the rules. */
114
120
  export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): void;
121
+ export declare function addClaudeUsage(acc: SessionFactsAccumulator, model: string, usage: Record<string, unknown>): void;
115
122
  /**
116
123
  * OpenAI semantics differ from the Anthropic-shaped usage the price table
117
124
  * assumes: `input_tokens` INCLUDES `cached_input_tokens` and `output_tokens`
@@ -106,13 +106,13 @@ function observeClaudeRecord(acc, record) {
106
106
  const msg = message;
107
107
  const model = typeof msg["model"] === "string" ? msg["model"] : null;
108
108
  const usage = msg["usage"];
109
- // One API request emits several records repeating the same usage; the id is
110
- // what makes summing them safe.
109
+ // One API request emits several records repeating the same usage; the id makes summing safe.
111
110
  const usageId = (typeof msg["id"] === "string" && msg["id"]) ||
112
111
  (typeof record["requestId"] === "string" && record["requestId"]) ||
113
112
  null;
114
113
  if (model && usage && typeof usage === "object" && usageId && !acc.seen_usage_ids.has(usageId)) {
115
114
  acc.seen_usage_ids.add(usageId);
115
+ acc.usage_log?.push({ id: usageId, model, usage: usage });
116
116
  addClaudeUsage(acc, model, usage);
117
117
  }
118
118
  if (claudeAssistantText(record)?.trim())
@@ -177,7 +177,7 @@ function countTool(acc, name) {
177
177
  const key = name.slice(0, MAX_TOOL_NAME_CHARS) || "unknown";
178
178
  acc.tool_calls_by_name[key] = (acc.tool_calls_by_name[key] ?? 0) + 1;
179
179
  }
180
- function addClaudeUsage(acc, model, usage) {
180
+ export function addClaudeUsage(acc, model, usage) {
181
181
  const key = model.slice(0, MAX_MODEL_NAME_CHARS);
182
182
  const current = acc.usage_by_model[key] ?? emptyUsage();
183
183
  current.input_tokens += num(usage["input_tokens"]);
@@ -203,9 +203,7 @@ export function codexUsageFromCumulativeTotal(total) {
203
203
  };
204
204
  }
205
205
  export function finalizeSessionFacts(acc) {
206
- // A Codex session whose usage never named a model is left uncounted rather
207
- // than filed under a guess: det.v5 did the same, and a token total on the
208
- // wrong model is money attributed to the wrong place.
206
+ // A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
209
207
  if (acc.codex_total_usage && acc.codex_model_hint) {
210
208
  acc.usage_by_model[acc.codex_model_hint.slice(0, MAX_MODEL_NAME_CHARS)] =
211
209
  codexUsageFromCumulativeTotal(acc.codex_total_usage);
@@ -264,9 +262,7 @@ export function observeSessionFactsContent(acc, content) {
264
262
  record = JSON.parse(line);
265
263
  }
266
264
  catch {
267
- // Silent by design: the parser's message quotes the offending line,
268
- // which is transcript content. The line still counts toward the file's
269
- // line total, so the loss is visible as a number.
265
+ // Silent by design: the parser's message quotes the line (transcript content); the line still counts in the total.
270
266
  continue;
271
267
  }
272
268
  if (!record || typeof record !== "object" || Array.isArray(record))
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Three shelves for founders' information (BLI-22734, slice 1 of the three-shelves design).
3
+ *
4
+ * A founder's session or memory goes to one of three places, decided on the laptop by folder:
5
+ * - `team` — Tower, as today;
6
+ * - `drawer` — stays on the laptop, never uploaded;
7
+ * - `safe` — encrypted on the laptop before it leaves (a later slice; not a legal value on the wire yet
8
+ * for session content).
9
+ *
10
+ * This module is the shared contract between the laptop (collector, hooks) and the server lock
11
+ * (`apps/dashboard/src/lib/api/owner-shelf-guard.ts`): the three request headers, the CLI release that first
12
+ * sends them, and the one strict shape of the numbers-only "bare record" a drawer or safe session sends instead
13
+ * of its words.
14
+ */
15
+ import { z } from "zod";
16
+ export declare const SHELVES: readonly ["team", "drawer", "safe"];
17
+ export type Shelf = (typeof SHELVES)[number];
18
+ /** The shelves a session can be kept OFF Tower on. A bare record is only ever one of these. */
19
+ export declare const OFF_TEAM_SHELVES: readonly ["drawer", "safe"];
20
+ export type OffTeamShelf = (typeof OFF_TEAM_SHELVES)[number];
21
+ /**
22
+ * Request headers, lower case (HTTP header names are case-insensitive; `Headers.get` folds them).
23
+ *
24
+ * - `x-tower-shelf`: the shelf the text in this request belongs to. Only `team` text may reach Tower.
25
+ * - `x-tower-caller`: which program on the laptop made the call. A memory door accepts a founder's text only
26
+ * from `hook` (the host hands a hook its folder; the MCP server cannot prove one).
27
+ * - `x-tower-cli-version`: the `@bli-cockpit/cli` release making the call.
28
+ */
29
+ export declare const SHELF_HEADER = "x-tower-shelf";
30
+ export declare const SHELF_CALLER_HEADER = "x-tower-caller";
31
+ export declare const SHELF_CLI_VERSION_HEADER = "x-tower-cli-version";
32
+ export declare const SHELF_CALLERS: readonly ["hook", "collector", "mcp"];
33
+ export type ShelfCaller = (typeof SHELF_CALLERS)[number];
34
+ /**
35
+ * The first `@bli-cockpit/cli` release whose collector and hooks route by shelf and send the three headers.
36
+ * A founder's device below it is refused at every content door once founder routing is switched on. Slice 1b
37
+ * (the collector half) raises this to the exact version it publishes if that differs.
38
+ */
39
+ export declare const SHELF_ROUTING_MIN_CLI_VERSION = "0.2.250";
40
+ /** The categories a founder may opt in to beyond the always-sent numbers (all off by default). */
41
+ export declare const SHELF_METRIC_CATEGORIES: readonly ["day", "tool", "model", "spawn"];
42
+ export type ShelfMetricCategory = (typeof SHELF_METRIC_CATEGORIES)[number];
43
+ export declare const SHELF_METRICS_SCHEMA_VERSION = "shelf.v1";
44
+ /**
45
+ * The bare record (design 3.2). STRICT on purpose: any extra key — a folder, a branch, a commit, a session id —
46
+ * fails validation, and the server refuses the whole report (`shelf_metrics_schema_violation`) rather than
47
+ * dropping the key and storing the rest.
48
+ */
49
+ export declare const ShelfSessionMetricsSchema: z.ZodObject<{
50
+ wall_duration_seconds: z.ZodNumber;
51
+ active_seconds: z.ZodNumber;
52
+ turn_count: z.ZodNumber;
53
+ user_prompt_count: z.ZodNumber;
54
+ assistant_response_count: z.ZodNumber;
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;
61
+ transcript_bytes: z.ZodNumber;
62
+ transcript_lines: z.ZodNumber;
63
+ transcript_files: z.ZodNumber;
64
+ day: z.ZodOptional<z.ZodString>;
65
+ tool: z.ZodOptional<z.ZodEnum<{
66
+ codex: "codex";
67
+ claude: "claude";
68
+ }>>;
69
+ model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
70
+ spawn_kind: z.ZodOptional<z.ZodEnum<{
71
+ human: "human";
72
+ subagent: "subagent";
73
+ automated: "automated";
74
+ }>>;
75
+ }, z.core.$strict>;
76
+ export type ShelfSessionMetrics = z.infer<typeof ShelfSessionMetricsSchema>;
77
+ export declare const ShelfReportSchema: z.ZodObject<{
78
+ report_id: z.ZodString;
79
+ shelf: z.ZodEnum<{
80
+ drawer: "drawer";
81
+ safe: "safe";
82
+ }>;
83
+ metrics: z.ZodObject<{
84
+ wall_duration_seconds: z.ZodNumber;
85
+ active_seconds: z.ZodNumber;
86
+ turn_count: z.ZodNumber;
87
+ user_prompt_count: z.ZodNumber;
88
+ assistant_response_count: z.ZodNumber;
89
+ 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
+ transcript_bytes: z.ZodNumber;
96
+ transcript_lines: z.ZodNumber;
97
+ transcript_files: z.ZodNumber;
98
+ day: z.ZodOptional<z.ZodString>;
99
+ tool: z.ZodOptional<z.ZodEnum<{
100
+ codex: "codex";
101
+ claude: "claude";
102
+ }>>;
103
+ model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
104
+ spawn_kind: z.ZodOptional<z.ZodEnum<{
105
+ human: "human";
106
+ subagent: "subagent";
107
+ automated: "automated";
108
+ }>>;
109
+ }, z.core.$strict>;
110
+ }, z.core.$strict>;
111
+ export type ShelfReport = z.infer<typeof ShelfReportSchema>;
112
+ export declare const SHELF_REPORTS_ENVELOPE_VERSION = "shelf-reports.v1";
113
+ export declare const SHELF_REPORTS_MAX_PER_REQUEST = 200;
114
+ /**
115
+ * The body a laptop posts to `/api/ambient/ingest` for bare records. Its own envelope, deliberately: the
116
+ * telemetry envelope carries a work context and a session reference, and a bare record sent beside those would
117
+ * be correlated by them.
118
+ */
119
+ export declare const ShelfReportsEnvelopeSchema: z.ZodObject<{
120
+ envelope_version: z.ZodLiteral<"shelf-reports.v1">;
121
+ generated_at: z.ZodString;
122
+ shelf_reports: z.ZodArray<z.ZodObject<{
123
+ report_id: z.ZodString;
124
+ shelf: z.ZodEnum<{
125
+ drawer: "drawer";
126
+ safe: "safe";
127
+ }>;
128
+ metrics: z.ZodObject<{
129
+ wall_duration_seconds: z.ZodNumber;
130
+ active_seconds: z.ZodNumber;
131
+ turn_count: z.ZodNumber;
132
+ user_prompt_count: z.ZodNumber;
133
+ assistant_response_count: z.ZodNumber;
134
+ 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;
140
+ transcript_bytes: z.ZodNumber;
141
+ transcript_lines: z.ZodNumber;
142
+ transcript_files: z.ZodNumber;
143
+ day: z.ZodOptional<z.ZodString>;
144
+ tool: z.ZodOptional<z.ZodEnum<{
145
+ codex: "codex";
146
+ claude: "claude";
147
+ }>>;
148
+ model_tokens: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
149
+ spawn_kind: z.ZodOptional<z.ZodEnum<{
150
+ human: "human";
151
+ subagent: "subagent";
152
+ automated: "automated";
153
+ }>>;
154
+ }, z.core.$strict>;
155
+ }, z.core.$strict>>;
156
+ }, z.core.$strict>;
157
+ export type ShelfReportsEnvelope = z.infer<typeof ShelfReportsEnvelopeSchema>;
158
+ /** `a >= b` for dotted numeric versions (`0.2.250`). Anything unparseable is treated as too old. */
159
+ export declare function cliVersionAtLeast(version: string | null | undefined, minimum: string): boolean;
package/dist/shelf.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Three shelves for founders' information (BLI-22734, slice 1 of the three-shelves design).
3
+ *
4
+ * A founder's session or memory goes to one of three places, decided on the laptop by folder:
5
+ * - `team` — Tower, as today;
6
+ * - `drawer` — stays on the laptop, never uploaded;
7
+ * - `safe` — encrypted on the laptop before it leaves (a later slice; not a legal value on the wire yet
8
+ * for session content).
9
+ *
10
+ * This module is the shared contract between the laptop (collector, hooks) and the server lock
11
+ * (`apps/dashboard/src/lib/api/owner-shelf-guard.ts`): the three request headers, the CLI release that first
12
+ * sends them, and the one strict shape of the numbers-only "bare record" a drawer or safe session sends instead
13
+ * of its words.
14
+ */
15
+ import { z } from "zod";
16
+ import { IsoDateTimeSchema } from "./common.js";
17
+ export const SHELVES = ["team", "drawer", "safe"];
18
+ /** The shelves a session can be kept OFF Tower on. A bare record is only ever one of these. */
19
+ export const OFF_TEAM_SHELVES = ["drawer", "safe"];
20
+ /**
21
+ * Request headers, lower case (HTTP header names are case-insensitive; `Headers.get` folds them).
22
+ *
23
+ * - `x-tower-shelf`: the shelf the text in this request belongs to. Only `team` text may reach Tower.
24
+ * - `x-tower-caller`: which program on the laptop made the call. A memory door accepts a founder's text only
25
+ * from `hook` (the host hands a hook its folder; the MCP server cannot prove one).
26
+ * - `x-tower-cli-version`: the `@bli-cockpit/cli` release making the call.
27
+ */
28
+ export const SHELF_HEADER = "x-tower-shelf";
29
+ export const SHELF_CALLER_HEADER = "x-tower-caller";
30
+ export const SHELF_CLI_VERSION_HEADER = "x-tower-cli-version";
31
+ export const SHELF_CALLERS = ["hook", "collector", "mcp"];
32
+ /**
33
+ * The first `@bli-cockpit/cli` release whose collector and hooks route by shelf and send the three headers.
34
+ * A founder's device below it is refused at every content door once founder routing is switched on. Slice 1b
35
+ * (the collector half) raises this to the exact version it publishes if that differs.
36
+ */
37
+ export const SHELF_ROUTING_MIN_CLI_VERSION = "0.2.250";
38
+ /** The categories a founder may opt in to beyond the always-sent numbers (all off by default). */
39
+ export const SHELF_METRIC_CATEGORIES = ["day", "tool", "model", "spawn"];
40
+ export const SHELF_METRICS_SCHEMA_VERSION = "shelf.v1";
41
+ const Count = z.number().int().nonnegative().max(1_000_000_000_000);
42
+ /**
43
+ * The bare record (design 3.2). STRICT on purpose: any extra key — a folder, a branch, a commit, a session id —
44
+ * fails validation, and the server refuses the whole report (`shelf_metrics_schema_violation`) rather than
45
+ * dropping the key and storing the rest.
46
+ */
47
+ export const ShelfSessionMetricsSchema = z
48
+ .object({
49
+ wall_duration_seconds: Count,
50
+ active_seconds: Count,
51
+ turn_count: Count,
52
+ user_prompt_count: Count,
53
+ assistant_response_count: Count,
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,
60
+ transcript_bytes: Count,
61
+ transcript_lines: Count,
62
+ transcript_files: Count,
63
+ // Opt-in categories (A-D), off unless the founder allowed them on that laptop.
64
+ day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
65
+ tool: z.enum(["claude", "codex"]).optional(),
66
+ model_tokens: z.record(z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9._:/-]+$/), Count).optional(),
67
+ spawn_kind: z.enum(["human", "automated", "subagent"]).optional(),
68
+ })
69
+ .strict();
70
+ export const ShelfReportSchema = z
71
+ .object({
72
+ /** Random, generated on the laptop and kept in its cursor so a retry is idempotent. Never a session id. */
73
+ report_id: z.string().uuid(),
74
+ shelf: z.enum(OFF_TEAM_SHELVES),
75
+ metrics: ShelfSessionMetricsSchema,
76
+ })
77
+ .strict();
78
+ export const SHELF_REPORTS_ENVELOPE_VERSION = "shelf-reports.v1";
79
+ export const SHELF_REPORTS_MAX_PER_REQUEST = 200;
80
+ /**
81
+ * The body a laptop posts to `/api/ambient/ingest` for bare records. Its own envelope, deliberately: the
82
+ * telemetry envelope carries a work context and a session reference, and a bare record sent beside those would
83
+ * be correlated by them.
84
+ */
85
+ export const ShelfReportsEnvelopeSchema = z
86
+ .object({
87
+ envelope_version: z.literal(SHELF_REPORTS_ENVELOPE_VERSION),
88
+ generated_at: IsoDateTimeSchema,
89
+ shelf_reports: z.array(ShelfReportSchema).min(1).max(SHELF_REPORTS_MAX_PER_REQUEST),
90
+ })
91
+ .strict();
92
+ /** `a >= b` for dotted numeric versions (`0.2.250`). Anything unparseable is treated as too old. */
93
+ export function cliVersionAtLeast(version, minimum) {
94
+ const parse = (value) => {
95
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value.trim());
96
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
97
+ };
98
+ if (!version)
99
+ return false;
100
+ const have = parse(version);
101
+ const need = parse(minimum);
102
+ if (!have || !need)
103
+ return false;
104
+ for (let i = 0; i < 3; i += 1) {
105
+ if (have[i] > need[i])
106
+ return true;
107
+ if (have[i] < need[i])
108
+ return false;
109
+ }
110
+ return true;
111
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.81",
3
+ "version": "0.1.83",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",