@bli-cockpit/telemetry-core 0.1.82 → 0.1.84

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()
@@ -0,0 +1,47 @@
1
+ /** Log the remaining quota once it drops below this. */
2
+ export declare const LOW_QUOTA = 500;
3
+ export type Via = "app" | "user";
4
+ export interface ResolvedToken {
5
+ token: string;
6
+ via: Via;
7
+ }
8
+ export type TokenProvider = () => Promise<ResolvedToken>;
9
+ /** A fixed token (tests, the personal-token path) or a provider that mints and caches. */
10
+ export type GithubToken = string | TokenProvider;
11
+ export declare function resolveToken(source: GithubToken): Promise<ResolvedToken>;
12
+ /** An RS256 JWT for the App: issued a minute in the past (clock skew), valid for nine minutes. */
13
+ export declare function signAppJwt(appId: string, privateKey: string, nowSeconds?: number): string;
14
+ /** Where the installation token reaches: one repository, or every repository of the org's installation. */
15
+ export type TokenScope = {
16
+ repo: string;
17
+ owner?: never;
18
+ } | {
19
+ owner: string;
20
+ repo?: never;
21
+ };
22
+ export type TokenSourceOptions = TokenScope & {
23
+ appId?: string;
24
+ privateKey?: string;
25
+ /** The personal token, used only when the App token cannot be minted. */
26
+ userToken?: string;
27
+ /** Log tag; the runner keeps `[runner github token]`. */
28
+ tag?: string;
29
+ fetchImpl?: typeof fetch;
30
+ now?: () => number;
31
+ };
32
+ /** Returns a provider: the cached App token, a fresh mint when near expiry, else the personal token (reason logged). Never throws unless no token exists at all. */
33
+ export declare function createTokenSource(opts: TokenSourceOptions): TokenProvider;
34
+ /** The provider for this env: App first, `GITHUB_TOKEN` (else `GH_TOKEN`) as the fallback. */
35
+ export declare function tokenSourceFromEnv(scope: TokenScope, env?: Record<string, string | undefined>, opts?: {
36
+ fetchImpl?: typeof fetch;
37
+ tag?: string;
38
+ }): TokenProvider;
39
+ /** True when this env can produce any GitHub token at all (the App pair, or a personal token). */
40
+ export declare function hasGithubCredentials(env?: Record<string, string | undefined>): boolean;
41
+ /** One log line per GitHub call: which token carried it, plus the remaining quota once it is low. Metadata only: the host and the query string are dropped. */
42
+ export declare function logGithubCall(tag: string, fields: {
43
+ path: string;
44
+ status: number;
45
+ via: Via;
46
+ headers?: Pick<Headers, "get"> | null;
47
+ }): void;
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The one GitHub App READ token source for Tower's server code (ticket 22427 for the runner, BLI-23182 for the dashboard).
3
+ *
4
+ * `GITHUB_TOKEN` is a fine-grained personal token, and a fine-grained token cannot read check runs, commit status or
5
+ * Actions runs at all (403). So server readers mint an installation token from the `BLI Cloud Agents` App instead (its own
6
+ * rate-limit bucket, Checks / Commit statuses / Actions read), the same App the Agent Batch uses (`scripts/agent-token.mjs`):
7
+ * an RS256 JWT from the App key, the installation (one repo's, or the whole org's), an installation token, cached until five
8
+ * minutes before it expires. Only when minting fails does a call use the personal token, with the reason logged once, and
9
+ * every call logs `via: app|user`. The key and the tokens are never logged.
10
+ *
11
+ * Two scopes: `repo` mints a token limited to that one repository (the runner); `owner` mints one for every repository the
12
+ * org's installation covers (the dashboard's readers, which read many BLI-INC repos).
13
+ *
14
+ * Env: AGENT_APP_ID, AGENT_APP_PRIVATE_KEY (the same names as the repo secrets), GITHUB_TOKEN, else GH_TOKEN (fallback).
15
+ * Docs: docs/runbooks/cloud-agent-lanes.md, "The runner's GitHub token".
16
+ */
17
+ import { createSign } from "node:crypto";
18
+ const API = "https://api.github.com";
19
+ /** Mint again this long before the hour is up. */
20
+ const REFRESH_BEFORE_MS = 5 * 60_000;
21
+ /** Log the remaining quota once it drops below this. */
22
+ export const LOW_QUOTA = 500;
23
+ const DEFAULT_TAG = "[github token]";
24
+ export async function resolveToken(source) {
25
+ return typeof source === "string" ? { token: source, via: "user" } : source();
26
+ }
27
+ const b64url = (input) => Buffer.from(input).toString("base64url");
28
+ /** An RS256 JWT for the App: issued a minute in the past (clock skew), valid for nine minutes. */
29
+ export function signAppJwt(appId, privateKey, nowSeconds = Math.floor(Date.now() / 1000)) {
30
+ const unsigned = `${b64url(JSON.stringify({ alg: "RS256", typ: "JWT" }))}.${b64url(JSON.stringify({ iat: nowSeconds - 60, exp: nowSeconds + 540, iss: String(appId) }))}`;
31
+ const signature = createSign("RSA-SHA256").update(unsigned).sign(privateKey.replaceAll("\\n", "\n"));
32
+ return `${unsigned}.${signature.toString("base64url")}`;
33
+ }
34
+ class MintError extends Error {
35
+ }
36
+ async function appCall(doFetch, method, path, jwt, expected, body) {
37
+ let response;
38
+ try {
39
+ response = await doFetch(`${API}${path}`, {
40
+ method,
41
+ headers: {
42
+ Authorization: `Bearer ${jwt}`,
43
+ Accept: "application/vnd.github+json",
44
+ "X-GitHub-Api-Version": "2022-11-28",
45
+ "User-Agent": "bli-cockpit-github-app",
46
+ },
47
+ body: body ? JSON.stringify(body) : undefined,
48
+ signal: AbortSignal.timeout(30_000),
49
+ });
50
+ }
51
+ catch {
52
+ throw new MintError("network");
53
+ }
54
+ if (response.status !== expected)
55
+ throw new MintError(String(response.status));
56
+ return (await response.json().catch(() => ({})));
57
+ }
58
+ /** Returns a provider: the cached App token, a fresh mint when near expiry, else the personal token (reason logged). Never throws unless no token exists at all. */
59
+ export function createTokenSource(opts) {
60
+ const now = opts.now ?? Date.now;
61
+ const doFetch = opts.fetchImpl ?? fetch;
62
+ const tag = opts.tag ?? DEFAULT_TAG;
63
+ let cached = null;
64
+ let loggedFallback = false;
65
+ const [owner, name] = opts.repo ? opts.repo.split("/") : [opts.owner, undefined];
66
+ const scope = name ? "repo" : "org";
67
+ const mint = async () => {
68
+ let jwt;
69
+ try {
70
+ jwt = signAppJwt(opts.appId, opts.privateKey, Math.floor(now() / 1000));
71
+ }
72
+ catch {
73
+ throw new MintError("key_invalid");
74
+ }
75
+ const installation = await appCall(doFetch, "GET", name ? `/repos/${owner}/${name}/installation` : `/orgs/${owner}/installation`, jwt, 200);
76
+ const minted = await appCall(doFetch, "POST", `/app/installations/${String(installation["id"])}/access_tokens`, jwt, 201, name ? { repositories: [name] } : undefined);
77
+ const token = typeof minted["token"] === "string" ? minted["token"] : "";
78
+ if (!token)
79
+ throw new MintError("no_token");
80
+ const expires = Date.parse(String(minted["expires_at"] ?? ""));
81
+ return { token, expiresMs: Number.isFinite(expires) ? expires : now() + 55 * 60_000 };
82
+ };
83
+ const fallback = (reason) => {
84
+ if (!opts.userToken) {
85
+ console.error(`${tag} no token`, JSON.stringify({ reason: `${reason}_and_user_token_missing`, scope }));
86
+ throw new Error("github_token_missing");
87
+ }
88
+ if (!loggedFallback) {
89
+ console.warn(`${tag} using the personal token`, JSON.stringify({ reason, scope }));
90
+ loggedFallback = true;
91
+ }
92
+ return { token: opts.userToken, via: "user" };
93
+ };
94
+ const refresh = async () => {
95
+ try {
96
+ cached = await mint();
97
+ loggedFallback = false;
98
+ console.info(`${tag} minted`, JSON.stringify({ via: "app", scope, valid_min: Math.round((cached.expiresMs - now()) / 60_000) }));
99
+ return { token: cached.token, via: "app" };
100
+ }
101
+ catch (error) {
102
+ cached = null;
103
+ return fallback(`app_mint_failed:${error instanceof MintError ? error.message : "unexpected"}`);
104
+ }
105
+ };
106
+ // Concurrent callers (a reader's pool) share one mint instead of each minting their own.
107
+ let inflight = null;
108
+ return async () => {
109
+ if (!opts.appId || !opts.privateKey)
110
+ return fallback("app_secrets_absent");
111
+ if (cached && cached.expiresMs - REFRESH_BEFORE_MS > now())
112
+ return { token: cached.token, via: "app" };
113
+ inflight ??= refresh().finally(() => { inflight = null; });
114
+ return inflight;
115
+ };
116
+ }
117
+ /** The provider for this env: App first, `GITHUB_TOKEN` (else `GH_TOKEN`) as the fallback. */
118
+ export function tokenSourceFromEnv(scope, env = process.env, opts = {}) {
119
+ return createTokenSource({
120
+ ...scope,
121
+ appId: env["AGENT_APP_ID"]?.trim() || undefined,
122
+ privateKey: env["AGENT_APP_PRIVATE_KEY"]?.trim() || undefined,
123
+ userToken: env["GITHUB_TOKEN"]?.trim() || env["GH_TOKEN"]?.trim() || undefined,
124
+ ...opts,
125
+ });
126
+ }
127
+ /** True when this env can produce any GitHub token at all (the App pair, or a personal token). */
128
+ export function hasGithubCredentials(env = process.env) {
129
+ return Boolean((env["AGENT_APP_ID"]?.trim() && env["AGENT_APP_PRIVATE_KEY"]?.trim()) || env["GITHUB_TOKEN"]?.trim() || env["GH_TOKEN"]?.trim());
130
+ }
131
+ /** One log line per GitHub call: which token carried it, plus the remaining quota once it is low. Metadata only: the host and the query string are dropped. */
132
+ export function logGithubCall(tag, fields) {
133
+ // A response without headers (a test double, an odd proxy) still gets its line; logging never breaks a read.
134
+ const remaining = typeof fields.headers?.get === "function" ? fields.headers.get("x-ratelimit-remaining") : null;
135
+ const base = { path: fields.path.replace(API, "").split("?")[0], status: fields.status, via: fields.via };
136
+ console.info(`${tag} github call`, JSON.stringify(base));
137
+ const left = remaining === null ? NaN : Number(remaining);
138
+ if (Number.isFinite(left) && left < LOW_QUOTA) {
139
+ console.warn(`${tag} github quota low`, JSON.stringify({ ...base, ratelimit_remaining: left, ratelimit_reset: fields.headers?.get("x-ratelimit-reset") ?? null }));
140
+ }
141
+ }
package/dist/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
32
  export * from "./session-facts-delta.js";
33
+ export * from "./shelf.js";
33
34
  export * from "./session-facts-skills.js";
34
35
  export * from "./session-facts-spawn.js";
35
36
  export * from "./session-facts-active.js";
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ export * from "./run-verdict.js";
30
30
  export * from "./secret-guards.js";
31
31
  export * from "./session-facts.js";
32
32
  export * from "./session-facts-delta.js";
33
+ export * from "./shelf.js";
33
34
  export * from "./session-facts-skills.js";
34
35
  export * from "./session-facts-spawn.js";
35
36
  export * from "./session-facts-active.js";
@@ -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.82",
3
+ "version": "0.1.84",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -44,6 +44,11 @@
44
44
  "types": "./dist/node-read-cache.d.ts",
45
45
  "import": "./dist/node-read-cache.js",
46
46
  "default": "./dist/node-read-cache.js"
47
+ },
48
+ "./github-app-token": {
49
+ "types": "./dist/github-app-token.d.ts",
50
+ "import": "./dist/github-app-token.js",
51
+ "default": "./dist/github-app-token.js"
47
52
  }
48
53
  },
49
54
  "publishConfig": {