@bli-cockpit/telemetry-core 0.1.75 → 0.1.77

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.
@@ -4,6 +4,37 @@
4
4
  * answers the caller names (`vercel_cli_missing`, ...), not stack traces.
5
5
  */
6
6
  import { spawn } from "node:child_process";
7
+ function spawnChild(command, args) {
8
+ try {
9
+ // Windows installs `vercel` and `railway` as .cmd shims, which spawn only runs through a shell. Every argument
10
+ // is built from fixed words, ISO times we format and a service name that digestSource and readService both
11
+ // matched against ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ BEFORE this runs; nothing caller-supplied is quoted or escaped.
12
+ const child = spawn(command, [...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, shell: process.platform === "win32" });
13
+ return { child };
14
+ }
15
+ catch (error) {
16
+ return { failed: { status: null, stdout: "", stderr: "", failure: error.code ?? "spawn_failed" } };
17
+ }
18
+ }
19
+ /** cmd.exe answers a program it cannot find with exit 1 and this sentence, where POSIX gives ENOENT. */
20
+ function cmdCouldNotFind(status, stderr) {
21
+ return process.platform === "win32" && status !== 0 && /is not recognized as an internal or external command/i.test(stderr);
22
+ }
23
+ function cliRun(status, stdout, stderr, failure, truncated) {
24
+ return {
25
+ status,
26
+ stdout,
27
+ stderr,
28
+ ...(failure ? { failure } : {}),
29
+ ...(truncated ? { truncated } : {}),
30
+ };
31
+ }
32
+ /** A plain-text (non-JSON) line in the chunk matches the caller's abort pattern. */
33
+ function chunkMatchesAbort(chunk, abortOn) {
34
+ if (!abortOn)
35
+ return false;
36
+ return chunk.toString("utf8").split("\n").some((line) => !line.startsWith("{") && abortOn.test(line));
37
+ }
7
38
  export const nodeRunCli = (command, args, options) => new Promise((resolve) => {
8
39
  const out = [];
9
40
  const err = [];
@@ -11,17 +42,12 @@ export const nodeRunCli = (command, args, options) => new Promise((resolve) => {
11
42
  let failure;
12
43
  let truncated = false;
13
44
  let settled = false;
14
- let child;
15
- try {
16
- // Windows installs `vercel` and `railway` as .cmd shims, which spawn only runs through a shell. Every argument
17
- // is built from fixed words, ISO times we format and a service name that digestSource and readService both
18
- // matched against ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ BEFORE this runs; nothing caller-supplied is quoted or escaped.
19
- child = spawn(command, [...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, shell: process.platform === "win32" });
20
- }
21
- catch (error) {
22
- resolve({ status: null, stdout: "", stderr: "", failure: error.code ?? "spawn_failed" });
45
+ const spawned = spawnChild(command, args);
46
+ if ("failed" in spawned) {
47
+ resolve(spawned.failed);
23
48
  return;
24
49
  }
50
+ const child = spawned.child;
25
51
  const finish = (status) => {
26
52
  if (settled)
27
53
  return;
@@ -29,16 +55,9 @@ export const nodeRunCli = (command, args, options) => new Promise((resolve) => {
29
55
  clearTimeout(timer);
30
56
  const stdout = Buffer.concat(out).toString("utf8");
31
57
  const stderr = Buffer.concat(err).toString("utf8").slice(-4000);
32
- // cmd.exe answers a program it cannot find with exit 1 and this sentence, where POSIX gives ENOENT.
33
- if (!failure && process.platform === "win32" && status !== 0 && /is not recognized as an internal or external command/i.test(stderr))
58
+ if (!failure && cmdCouldNotFind(status, stderr))
34
59
  failure = "ENOENT";
35
- resolve({
36
- status,
37
- stdout,
38
- stderr,
39
- ...(failure ? { failure } : {}),
40
- ...(truncated ? { truncated } : {}),
41
- });
60
+ resolve(cliRun(status, stdout, stderr, failure, truncated));
42
61
  };
43
62
  const timer = setTimeout(() => {
44
63
  failure = "timeout";
@@ -47,7 +66,7 @@ export const nodeRunCli = (command, args, options) => new Promise((resolve) => {
47
66
  setTimeout(() => finish(null), 2000).unref();
48
67
  }, options.timeoutMs);
49
68
  const abortIfMatched = (chunk) => {
50
- if (options.abortOn && !failure && chunk.toString("utf8").split("\n").some((line) => !line.startsWith("{") && options.abortOn.test(line))) {
69
+ if (!failure && chunkMatchesAbort(chunk, options.abortOn)) {
51
70
  failure = "aborted";
52
71
  truncated = true;
53
72
  child.kill("SIGTERM");
@@ -77,6 +77,16 @@ function parseRecords(stdout) {
77
77
  }
78
78
  return records;
79
79
  }
80
+ function countStatusClass(classes, status) {
81
+ if (status >= 500)
82
+ classes.server += 1;
83
+ else if (status >= 400 && status < 500)
84
+ classes.client += 1;
85
+ else if (status >= 300 && status < 400)
86
+ classes.redirect += 1;
87
+ else if (status >= 200 && status < 300)
88
+ classes.ok += 1;
89
+ }
80
90
  /**
81
91
  * Turns Vercel request records into digest lines: each nested console line is one line, and a request that ended
82
92
  * 5xx / 429 / 403 adds a synthetic line even when the code logged nothing. Shared by the CLI reader above and the
@@ -97,31 +107,49 @@ export function vercelRecordLines(records, fromEpoch, unitPrefix) {
97
107
  lines.push({ unit, message: entry.message, ts, level: entry.level });
98
108
  }
99
109
  const status = record.responseStatusCode ?? 0;
100
- if (status >= 200 && status < 300)
101
- classes.ok += 1;
102
- else if (status >= 300 && status < 400)
103
- classes.redirect += 1;
104
- else if (status >= 400 && status < 500)
105
- classes.client += 1;
106
- else if (status >= 500)
107
- classes.server += 1;
110
+ countStatusClass(classes, status);
108
111
  if (status >= 500 || status === 429 || status === 403) {
109
112
  lines.push({ unit, message: `HTTP ${status} ${record.requestMethod ?? "?"} ${route || "?"}`, ts, level: "error" });
110
113
  }
111
114
  }
112
115
  return { lines, classes };
113
116
  }
114
- export async function readDashboard(context) {
115
- const { window, run, log } = context;
116
- const allLevels = context.allLevels ?? false;
117
- const queries = allLevels ? ALL_QUERIES : PROBLEM_QUERIES;
118
- const seen = new Map();
117
+ /** The window cut into slices, one per query; a slice that comes back full is split again later. */
118
+ function initialTasks(window, queries, allLevels) {
119
119
  const queue = [];
120
120
  const width = allLevels ? 120 : Math.max(300, Math.ceil((window.toEpoch - window.fromEpoch) / 4));
121
121
  for (const query of queries) {
122
122
  for (let end = window.toEpoch; end > window.fromEpoch; end -= width)
123
123
  queue.push({ from: Math.max(window.fromEpoch, end - width), to: end, query });
124
124
  }
125
+ return queue;
126
+ }
127
+ /** One `vercel logs` call for a time slice; a refusal throws, a timeout is an answer the caller splits on. */
128
+ async function fetchSlice(context, task) {
129
+ const result = await context.run("vercel", ["logs", "--project", VERCEL_PROJECT, "--scope", VERCEL_SCOPE, "--since", isoOf(task.from), "--until", isoOf(task.to), ...task.query, "--json", "--limit", "100", "--no-color", "--non-interactive"], { timeoutMs: context.limits?.timeoutMs ?? CALL_TIMEOUT_MS, maxBytes: 64 * 1024 * 1024, abortOn: VERCEL_ABORT_PATTERN });
130
+ const refusal = vercelRefusal(result);
131
+ if (refusal)
132
+ throw refusal;
133
+ if (result.failure && result.failure !== "timeout")
134
+ throw new SourceRefusal("vercel_failed", `the vercel CLI could not run (${result.failure})`);
135
+ if (result.status !== 0 && result.status !== null && !result.stdout.includes('"id"')) {
136
+ const tail = (result.stderr.trim().split("\n").pop() ?? "").slice(0, 160).replace(/\s+/g, " ");
137
+ throw new SourceRefusal("vercel_failed", `vercel logs exited ${result.status}: ${tail}`);
138
+ }
139
+ return { records: parseRecords(result.stdout), timedOut: result.failure === "timeout" };
140
+ }
141
+ function dashboardCoverageNote(allLevels, classes, recordCount) {
142
+ const requests = classes.ok + classes.redirect + classes.client + classes.server;
143
+ return allLevels
144
+ ? `requests ${requests.toLocaleString("en-US")}: 2xx ${classes.ok.toLocaleString("en-US")}, 3xx ${classes.redirect}, 4xx ${classes.client}, 5xx ${classes.server}`
145
+ : `read only the records Vercel marks error, warning or fatal, and every 5xx (${recordCount} records); info-only requests were not read (--all-levels reads them, slowly)`;
146
+ }
147
+ export async function readDashboard(context) {
148
+ const { window, log } = context;
149
+ const allLevels = context.allLevels ?? false;
150
+ const queries = allLevels ? ALL_QUERIES : PROBLEM_QUERIES;
151
+ const seen = new Map();
152
+ const queue = initialTasks(window, queries, allLevels);
125
153
  let calls = 0;
126
154
  let splits = 0;
127
155
  let incomplete = 0;
@@ -129,21 +157,11 @@ export async function readDashboard(context) {
129
157
  let failure = null;
130
158
  const attempt = async (task) => {
131
159
  calls += 1;
132
- const result = await run("vercel", ["logs", "--project", VERCEL_PROJECT, "--scope", VERCEL_SCOPE, "--since", isoOf(task.from), "--until", isoOf(task.to), ...task.query, "--json", "--limit", "100", "--no-color", "--non-interactive"], { timeoutMs: context.limits?.timeoutMs ?? CALL_TIMEOUT_MS, maxBytes: 64 * 1024 * 1024, abortOn: VERCEL_ABORT_PATTERN });
133
- const refusal = vercelRefusal(result);
134
- if (refusal)
135
- throw refusal;
136
- if (result.failure && result.failure !== "timeout")
137
- throw new SourceRefusal("vercel_failed", `the vercel CLI could not run (${result.failure})`);
138
- if (result.status !== 0 && result.status !== null && !result.stdout.includes('"id"')) {
139
- const tail = (result.stderr.trim().split("\n").pop() ?? "").slice(0, 160).replace(/\s+/g, " ");
140
- throw new SourceRefusal("vercel_failed", `vercel logs exited ${result.status}: ${tail}`);
141
- }
142
- const records = parseRecords(result.stdout);
160
+ const { records, timedOut } = await fetchSlice(context, task);
143
161
  for (const record of records)
144
162
  if (record.id && !seen.has(record.id))
145
163
  seen.set(record.id, record);
146
- const suspect = records.length >= PAGE || result.failure === "timeout";
164
+ const suspect = records.length >= PAGE || timedOut;
147
165
  if (!suspect)
148
166
  return;
149
167
  if (task.to - task.from > MIN_SLICE_SECONDS && calls < MAX_CALLS) {
@@ -155,38 +173,35 @@ export async function readDashboard(context) {
155
173
  incomplete += 1;
156
174
  }
157
175
  };
176
+ const runTask = async (task) => {
177
+ active += 1;
178
+ try {
179
+ await attempt(task);
180
+ }
181
+ catch (error) {
182
+ failure = error instanceof SourceRefusal ? error : new SourceRefusal("vercel_failed", "the vercel read failed unexpectedly");
183
+ }
184
+ finally {
185
+ active -= 1;
186
+ }
187
+ };
158
188
  const worker = async () => {
159
- for (;;) {
160
- if (failure)
161
- return;
189
+ while (!failure) {
162
190
  const task = queue.shift();
163
- if (!task) {
164
- if (active === 0)
165
- return;
166
- await new Promise((resolve) => setTimeout(resolve, 25));
191
+ if (task) {
192
+ await runTask(task);
167
193
  continue;
168
194
  }
169
- active += 1;
170
- try {
171
- await attempt(task);
172
- }
173
- catch (error) {
174
- failure = error instanceof SourceRefusal ? error : new SourceRefusal("vercel_failed", "the vercel read failed unexpectedly");
175
- }
176
- finally {
177
- active -= 1;
178
- }
195
+ if (active === 0)
196
+ return;
197
+ await new Promise((resolve) => setTimeout(resolve, 25));
179
198
  }
180
199
  };
181
200
  await Promise.all(Array.from({ length: CONCURRENCY }, () => worker()));
182
201
  if (failure)
183
202
  throw failure;
184
203
  const { lines, classes } = vercelRecordLines([...seen.values()], window.fromEpoch, "dashboard");
185
- const notes = [];
186
- const requests = classes.ok + classes.redirect + classes.client + classes.server;
187
- notes.push(allLevels
188
- ? `requests ${requests.toLocaleString("en-US")}: 2xx ${classes.ok.toLocaleString("en-US")}, 3xx ${classes.redirect}, 4xx ${classes.client}, 5xx ${classes.server}`
189
- : `read only the records Vercel marks error, warning or fatal, and every 5xx (${seen.size} records); info-only requests were not read (--all-levels reads them, slowly)`);
204
+ const notes = [dashboardCoverageNote(allLevels, classes, seen.size)];
190
205
  if (incomplete > 0)
191
206
  notes.push(`incomplete: ${incomplete} slice${incomplete === 1 ? "" : "s"} still returned a full page at ${MIN_SLICE_SECONDS} s or at the call limit`);
192
207
  log("[logs dashboard] read complete", { calls, splits, incomplete_slices: incomplete, records: seen.size, lines: lines.length, server_errors: classes.server, all_levels: allLevels });
@@ -116,14 +116,12 @@ export function notReadLines(stillRefusing, notWired) {
116
116
  lines.push(` +${ordered.length - MAX_STILL_REFUSING_LINES} more still refusing (--json lists all)`);
117
117
  return lines;
118
118
  }
119
- /** Many windows of stored rows merged by template id into one capped digest (about 2 KB, real bugs first). */
120
- export function mergeStored(storedRows, windows, options) {
121
- // Defence in depth: whatever wrote the rows, what leaves the table is scrubbed again (the scrub is idempotent).
122
- const rows = storedRows.map(scrubRow);
123
- const newestFirst = [...rows].sort((a, b) => (a.window_end < b.window_end ? 1 : a.window_end > b.window_end ? -1 : 0));
124
- // The exact verdict of a template id (newest window wins), and a verdict by printed text for the renderer, which only
125
- // sees unit and template: two ids whose scrubbed text is identical share it, and the WORSE class wins, so a
126
- // collision can only make a line louder, never hide a bug.
119
+ /**
120
+ * The exact verdict of a template id (newest window wins), and a verdict by printed text for the renderer, which only
121
+ * sees unit and template: two ids whose scrubbed text is identical share it, and the WORSE class wins, so a
122
+ * collision can only make a line louder, never hide a bug.
123
+ */
124
+ function indexVerdicts(newestFirst) {
127
125
  const verdictOfTid = new Map();
128
126
  const verdicts = new Map();
129
127
  const sources = new Map();
@@ -138,6 +136,30 @@ export function mergeStored(storedRows, windows, options) {
138
136
  names.add(row.source);
139
137
  sources.set(row.tid, names);
140
138
  }
139
+ return { verdictOfTid, verdicts, sources };
140
+ }
141
+ /** One line saying how much of the span was read, or why nothing was. */
142
+ function windowCoverageNote(okWindows, neverRan, stillRefusing, lastRowAt) {
143
+ const spans = okWindows.map((window) => [Date.parse(window.window_start), Date.parse(window.window_end)]);
144
+ if (spans.length > 0) {
145
+ const from = new Date(Math.min(...spans.map((span) => span[0]))).toISOString().slice(0, 16);
146
+ const to = new Date(Math.max(...spans.map((span) => span[1]))).toISOString().slice(0, 16);
147
+ const names = new Set(okWindows.map((window) => window.source));
148
+ return `stored digests: ${okWindows.length} window${okWindows.length === 1 ? "" : "s"} of ${names.size} source${names.size === 1 ? "" : "s"}, ${from}Z to ${to}Z`;
149
+ }
150
+ // The ONLY case that says "not run yet": the project has no window row at all, a good one or a refusal.
151
+ if (neverRan)
152
+ return "stored digests: the cron has not run for this project yet (it has written no window row for it)";
153
+ // The cron has run. A refusal is named above; with none, say how old the newest row is instead of guessing why.
154
+ const newest = stillRefusing.length === 0 && lastRowAt ? `; the newest row Tower has for this project was written ${minuteOf(lastRowAt)}` : "";
155
+ return `stored digests: no window was read in this span${newest}`;
156
+ }
157
+ /** Many windows of stored rows merged by template id into one capped digest (about 2 KB, real bugs first). */
158
+ export function mergeStored(storedRows, windows, options) {
159
+ // Defence in depth: whatever wrote the rows, what leaves the table is scrubbed again (the scrub is idempotent).
160
+ const rows = storedRows.map(scrubRow);
161
+ const newestFirst = [...rows].sort((a, b) => (a.window_end < b.window_end ? 1 : a.window_end > b.window_end ? -1 : 0));
162
+ const { verdictOfTid, verdicts, sources } = indexVerdicts(newestFirst);
141
163
  const groups = rows.map((row) => ({
142
164
  tid: row.tid,
143
165
  unit: row.unit,
@@ -158,22 +180,7 @@ export function mergeStored(storedRows, windows, options) {
158
180
  const stillBlind = new Set(stillRefusing.map((entry) => entry.source));
159
181
  // The verdict first, right under the header: a source that is blind or unwired means the counts below are not the whole story.
160
182
  const notes = notReadLines(stillRefusing, options.notWired ?? []);
161
- const spans = okWindows.map((window) => [Date.parse(window.window_start), Date.parse(window.window_end)]);
162
- if (spans.length > 0) {
163
- const from = new Date(Math.min(...spans.map((span) => span[0]))).toISOString().slice(0, 16);
164
- const to = new Date(Math.max(...spans.map((span) => span[1]))).toISOString().slice(0, 16);
165
- const names = new Set(okWindows.map((window) => window.source));
166
- notes.push(`stored digests: ${okWindows.length} window${okWindows.length === 1 ? "" : "s"} of ${names.size} source${names.size === 1 ? "" : "s"}, ${from}Z to ${to}Z`);
167
- }
168
- else if (options.neverRan) {
169
- // The ONLY case that says "not run yet": the project has no window row at all, a good one or a refusal.
170
- notes.push("stored digests: the cron has not run for this project yet (it has written no window row for it)");
171
- }
172
- else {
173
- // The cron has run. A refusal is named above; with none, say how old the newest row is instead of guessing why.
174
- const newest = stillRefusing.length === 0 && options.lastRowAt ? `; the newest row Tower has for this project was written ${minuteOf(options.lastRowAt)}` : "";
175
- notes.push(`stored digests: no window was read in this span${newest}`);
176
- }
183
+ notes.push(windowCoverageNote(okWindows, options.neverRan, stillRefusing, options.lastRowAt));
177
184
  // A refusal inside the span from a source that is still refusing is already in the NOT READ block; this lists the gaps that closed.
178
185
  const gaps = [...new Set(windows.filter((window) => window.status !== "ok" && !stillBlind.has(window.source)).map((window) => `${window.source}: ${window.status}`))];
179
186
  if (gaps.length > 0) {
@@ -58,20 +58,15 @@ export function askMemoryDaemonHttp(options) {
58
58
  settled = true;
59
59
  for (const timer of timers)
60
60
  clearTimeout(timer);
61
- try {
62
- socket?.destroy();
63
- }
64
- catch {
65
- // Already gone.
66
- }
61
+ destroyQuietly(socket);
67
62
  resolve({ ...result, elapsedMs: now() - started });
68
63
  };
69
64
  const arm = (ms, reason) => {
70
65
  const timer = setTimeout(() => finish({ ok: false, reason }), Math.max(1, ms));
71
66
  timer.unref?.();
72
67
  timers.push(timer);
68
+ return timer;
73
69
  };
74
- let connectTimer;
75
70
  try {
76
71
  socket = connect(options.address);
77
72
  }
@@ -81,9 +76,7 @@ export function askMemoryDaemonHttp(options) {
81
76
  }
82
77
  socket.setNoDelay?.(true);
83
78
  arm(options.deadlineMs, "daemon_http_deadline");
84
- connectTimer = setTimeout(() => finish({ ok: false, reason: "daemon_connect_timeout" }), Math.max(1, connectTimeoutMs));
85
- connectTimer.unref?.();
86
- timers.push(connectTimer);
79
+ const connectTimer = arm(connectTimeoutMs, "daemon_connect_timeout");
87
80
  socket.on("error", (error) => {
88
81
  finish({ ok: false, reason: connectReason(error) });
89
82
  });
@@ -93,25 +86,32 @@ export function askMemoryDaemonHttp(options) {
93
86
  });
94
87
  socket.on("data", (chunk) => {
95
88
  buffered += chunk.toString("utf8");
96
- if (buffered.length > MEMORY_DAEMON_MAX_LINE_BYTES) {
97
- finish({ ok: false, reason: "daemon_answer_too_large" });
98
- return;
99
- }
100
- const newline = buffered.indexOf("\n");
101
- if (newline === -1)
102
- return;
103
- const parsed = parseHttpProxyAnswerLine(buffered.slice(0, newline));
104
- if (!parsed.ok) {
105
- finish({ ok: false, reason: parsed.reason });
106
- return;
107
- }
108
- finish({ ok: true, answer: parsed.answer });
89
+ const answered = settleBuffered(buffered);
90
+ if (answered)
91
+ finish(answered);
109
92
  });
110
93
  socket.on("close", () => {
111
94
  finish({ ok: false, reason: "daemon_closed_without_answer" });
112
95
  });
113
96
  });
114
97
  }
98
+ function destroyQuietly(socket) {
99
+ try {
100
+ socket?.destroy();
101
+ }
102
+ catch {
103
+ // Already gone.
104
+ }
105
+ }
106
+ /** The settled answer once the buffer holds a whole line (or has grown past the cap); null while more bytes are needed. */
107
+ function settleBuffered(buffered) {
108
+ if (buffered.length > MEMORY_DAEMON_MAX_LINE_BYTES)
109
+ return { ok: false, reason: "daemon_answer_too_large" };
110
+ const newline = buffered.indexOf("\n");
111
+ if (newline === -1)
112
+ return null;
113
+ return parseHttpProxyAnswerLine(buffered.slice(0, newline));
114
+ }
115
115
  /** One JSON line, the same envelope every daemon event uses. */
116
116
  export function encodeHttpProxyLine(request) {
117
117
  return `${JSON.stringify({
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The client app of a session read from the HEAD of its transcript (ticket 19258): no full download, no counting.
3
+ *
4
+ * The backfill stages a session's stored raw evidence and hands the first bytes here. The same two functions the
5
+ * session facts use (`claudeSpawn`, `codexSpawn`) decide, so a label read from a head and one counted at upload cannot
6
+ * disagree. `raw` carries the label strings the transcript used (an originator, a source word, an entrypoint), never any
7
+ * text of the conversation, so an unmapped value can be reported and mapped from evidence.
8
+ */
9
+ import { type ClientApp } from "./session-facts-spawn.js";
10
+ export interface ClientAppRead {
11
+ client_app: ClientApp | null;
12
+ /** The raw marker strings seen, labels only. */
13
+ raw: {
14
+ originator?: string;
15
+ source?: string;
16
+ entrypoint?: string;
17
+ };
18
+ /** `no_marker` when the head named no app (an older Claude Code, a truncated file), else `read`. */
19
+ reason: "read" | "no_marker" | "unreadable";
20
+ }
21
+ export declare function clientAppFromHead(source: "codex" | "claude_code", head: string): ClientAppRead;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The client app of a session read from the HEAD of its transcript (ticket 19258): no full download, no counting.
3
+ *
4
+ * The backfill stages a session's stored raw evidence and hands the first bytes here. The same two functions the
5
+ * session facts use (`claudeSpawn`, `codexSpawn`) decide, so a label read from a head and one counted at upload cannot
6
+ * disagree. `raw` carries the label strings the transcript used (an originator, a source word, an entrypoint), never any
7
+ * text of the conversation, so an unmapped value can be reported and mapped from evidence.
8
+ */
9
+ import { claudeSpawn, codexSpawn } from "./session-facts-spawn.js";
10
+ const MAX_LINES = 200;
11
+ const word = (value) => (typeof value === "string" && value.length > 0 ? value.slice(0, 60) : undefined);
12
+ export function clientAppFromHead(source, head) {
13
+ let spawn = null;
14
+ const raw = {};
15
+ let parsed = 0;
16
+ for (const line of head.split("\n", MAX_LINES)) {
17
+ if (!line.trim())
18
+ continue;
19
+ let record;
20
+ try {
21
+ record = JSON.parse(line);
22
+ }
23
+ catch {
24
+ continue; // the head can end mid-line; a bad line is skipped, never guessed at
25
+ }
26
+ if (!record || typeof record !== "object")
27
+ continue;
28
+ parsed += 1;
29
+ if (source === "codex") {
30
+ if (record["type"] !== "session_meta")
31
+ continue;
32
+ const payload = (record["payload"] && typeof record["payload"] === "object" ? record["payload"] : {});
33
+ raw.originator = word(payload["originator"]);
34
+ const sourceField = payload["source"];
35
+ raw.source = typeof sourceField === "string" ? word(sourceField) : sourceField && typeof sourceField === "object" ? "subagent" : undefined;
36
+ spawn = codexSpawn(null, payload);
37
+ break;
38
+ }
39
+ const next = claudeSpawn(spawn, record);
40
+ if (next && !spawn) {
41
+ raw.entrypoint = word(record["entrypoint"]);
42
+ spawn = next;
43
+ break;
44
+ }
45
+ }
46
+ if (parsed === 0)
47
+ return { client_app: null, raw, reason: "unreadable" };
48
+ if (!spawn?.client_app)
49
+ return { client_app: null, raw, reason: "no_marker" };
50
+ return { client_app: spawn.client_app, raw, reason: "read" };
51
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Active time of a session (ticket 19258): the harvest's own rule (`extract/claude.ts`, `extract/codex.ts` `IDLE_GAP_MS`).
3
+ * Sort every record timestamp; a gap of 10 minutes or less to the previous record is time in use, a longer gap is idle and
4
+ * is dropped. Order-blind by construction, so a sidecar file read after the main transcript cannot change the answer.
5
+ */
6
+ export declare const ACTIVE_IDLE_GAP_MS: number;
7
+ export declare function activeSeconds(timestampsMs: readonly number[]): number;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Active time of a session (ticket 19258): the harvest's own rule (`extract/claude.ts`, `extract/codex.ts` `IDLE_GAP_MS`).
3
+ * Sort every record timestamp; a gap of 10 minutes or less to the previous record is time in use, a longer gap is idle and
4
+ * is dropped. Order-blind by construction, so a sidecar file read after the main transcript cannot change the answer.
5
+ */
6
+ export const ACTIVE_IDLE_GAP_MS = 10 * 60 * 1000;
7
+ export function activeSeconds(timestampsMs) {
8
+ if (timestampsMs.length < 2)
9
+ return 0;
10
+ const sorted = [...timestampsMs].sort((a, b) => a - b);
11
+ let active = 0;
12
+ for (let i = 1; i < sorted.length; i += 1) {
13
+ const gap = sorted[i] - sorted[i - 1];
14
+ if (gap <= ACTIVE_IDLE_GAP_MS)
15
+ active += gap;
16
+ }
17
+ return Math.round(active / 1000);
18
+ }
@@ -10,8 +10,19 @@
10
10
  import { z } from "zod";
11
11
  /** `interactive` is a person's session; `worker` and `subagent` were started by a program. */
12
12
  export type SessionSpawnKind = "interactive" | "worker" | "subagent";
13
+ /**
14
+ * Which app a session ran in (ticket 19258). A label only: it changes nothing about what is collected.
15
+ * The field names are the ones real transcripts carry, probed 2026-10-14 on 2,222 Codex and 4,558 Claude Code
16
+ * sessions: Codex `session_meta.originator` (`codex_exec`, `codex-tui`, `Codex Desktop`, `codex_work_desktop`,
17
+ * `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
18
+ * `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
19
+ */
20
+ export declare const CLIENT_APPS: readonly ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
21
+ export type ClientApp = (typeof CLIENT_APPS)[number];
13
22
  export interface SessionSpawn {
14
23
  kind: SessionSpawnKind;
24
+ /** Which app the session ran in. Absent from a block a CLI published before this field. */
25
+ client_app?: ClientApp;
15
26
  /** The parent session's id when the transcript names one (Codex `parent_thread_id`, `forked_from_id`). */
16
27
  parent_session_id?: string;
17
28
  }
@@ -21,6 +32,16 @@ export declare const SessionSpawnSchema: z.ZodObject<{
21
32
  worker: "worker";
22
33
  subagent: "subagent";
23
34
  }>;
35
+ client_app: z.ZodOptional<z.ZodEnum<{
36
+ unknown: "unknown";
37
+ claude_cli: "claude_cli";
38
+ claude_desktop: "claude_desktop";
39
+ claude_ide: "claude_ide";
40
+ codex_cli: "codex_cli";
41
+ codex_desktop: "codex_desktop";
42
+ codex_ide: "codex_ide";
43
+ codex_exec: "codex_exec";
44
+ }>>;
24
45
  parent_session_id: z.ZodOptional<z.ZodString>;
25
46
  }, z.core.$strict>;
26
47
  /**
@@ -32,6 +53,13 @@ export declare const SessionSpawnSchema: z.ZodObject<{
32
53
  * never decide it, because they ride inside their parent's session.
33
54
  */
34
55
  export declare function claudeSpawn(current: SessionSpawn | null, record: Record<string, unknown>): SessionSpawn | null;
56
+ /**
57
+ * Observed `entrypoint` values only. `sdk-cli` is the CLI binary driven by a program (`claude -p`): the client app
58
+ * is still the CLI, and `spawn.kind` already says a program drove it. `sdk-ts` (the TypeScript SDK, one session seen)
59
+ * and anything unobserved are `unknown`. No IDE value had been observed when this was written; a fleet-wide backfill
60
+ * reports every distinct unmapped value so a real one (a VS Code or JetBrains entrypoint) is added from evidence.
61
+ */
62
+ export declare function claudeClientApp(entrypoint: string): ClientApp;
35
63
  /**
36
64
  * Codex writes who started a session in its first `session_meta`: `source` is
37
65
  * `exec` for `codex exec`, `cli` or `vscode` for a person, or an object
@@ -39,3 +67,11 @@ export declare function claudeSpawn(current: SessionSpawn | null, record: Record
39
67
  * program-driven run; `parent_thread_id` and `forked_from_id` name a parent.
40
68
  */
41
69
  export declare function codexSpawn(current: SessionSpawn | null, meta: Record<string, unknown>): SessionSpawn | null;
70
+ /**
71
+ * The originator names the app; the source names the host the app declared. Observed on real files: `codex_exec`
72
+ * (the exec runner), `Codex Desktop` and `codex_work_desktop` (the desktop apps, whose source is `vscode` because they
73
+ * share the app-server), `codex-tui` (the terminal UI: source `cli`, or `vscode` when started from VS Code, which is
74
+ * the IDE). A subagent keeps its parent app's originator. `Claude Code` as an originator is Claude Code driving a Codex
75
+ * run, not a Codex client a person used, so it is `unknown`.
76
+ */
77
+ export declare function codexClientApp(originator: unknown, source: unknown): ClientApp;
@@ -8,11 +8,20 @@
8
8
  * and a kind word only.
9
9
  */
10
10
  import { z } from "zod";
11
+ /**
12
+ * Which app a session ran in (ticket 19258). A label only: it changes nothing about what is collected.
13
+ * The field names are the ones real transcripts carry, probed 2026-10-14 on 2,222 Codex and 4,558 Claude Code
14
+ * sessions: Codex `session_meta.originator` (`codex_exec`, `codex-tui`, `Codex Desktop`, `codex_work_desktop`,
15
+ * `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
16
+ * `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
17
+ */
18
+ export const CLIENT_APPS = ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
11
19
  const SPAWN_ID = /^[A-Za-z0-9._-]{1,80}$/u;
12
20
  const spawnId = (value) => typeof value === "string" && SPAWN_ID.test(value) ? value : undefined;
13
21
  export const SessionSpawnSchema = z
14
22
  .object({
15
23
  kind: z.enum(["interactive", "worker", "subagent"]),
24
+ client_app: z.enum(CLIENT_APPS).optional(),
16
25
  parent_session_id: z.string().regex(SPAWN_ID).optional(),
17
26
  })
18
27
  .strict();
@@ -30,8 +39,31 @@ export function claudeSpawn(current, record) {
30
39
  const entrypoint = record["entrypoint"];
31
40
  if (typeof entrypoint !== "string" || !entrypoint)
32
41
  return current;
33
- return { kind: entrypoint === "cli" ? "interactive" : "worker" };
42
+ return { kind: PROGRAM_ENTRYPOINT.test(entrypoint) ? "worker" : "interactive", client_app: claudeClientApp(entrypoint) };
43
+ }
44
+ /**
45
+ * Observed `entrypoint` values only. `sdk-cli` is the CLI binary driven by a program (`claude -p`): the client app
46
+ * is still the CLI, and `spawn.kind` already says a program drove it. `sdk-ts` (the TypeScript SDK, one session seen)
47
+ * and anything unobserved are `unknown`. No IDE value had been observed when this was written; a fleet-wide backfill
48
+ * reports every distinct unmapped value so a real one (a VS Code or JetBrains entrypoint) is added from evidence.
49
+ */
50
+ export function claudeClientApp(entrypoint) {
51
+ if (entrypoint === "cli" || entrypoint === "sdk-cli")
52
+ return "claude_cli";
53
+ if (entrypoint === "claude-desktop")
54
+ return "claude_desktop";
55
+ return "unknown";
34
56
  }
57
+ /**
58
+ * The entrypoints a PROGRAM drives: `sdk-cli` (`claude -p`), `sdk-ts`, `sdk-py`
59
+ * and Claude Code run as an MCP server. Everything else is a person at a
60
+ * keyboard: `cli`, and the editor and desktop apps (`claude-vscode`,
61
+ * `claude-desktop`), which an earlier version of this rule filed as workers and
62
+ * so hid from usage as "automated" (BLI-19277). An unfamiliar entrypoint reads
63
+ * as interactive: a program missed counts as a person's session, never a
64
+ * person's session hidden.
65
+ */
66
+ const PROGRAM_ENTRYPOINT = /^(?:sdk(?:[-_].+)?|mcp)$/u;
35
67
  /**
36
68
  * Codex writes who started a session in its first `session_meta`: `source` is
37
69
  * `exec` for `codex exec`, `cli` or `vscode` for a person, or an object
@@ -46,5 +78,21 @@ export function codexSpawn(current, meta) {
46
78
  const exec = meta["originator"] === "codex_exec" || source === "exec";
47
79
  const parent = spawnId(meta["parent_thread_id"]) ?? spawnId(meta["forked_from_id"]);
48
80
  const kind = spawnedSubagent ? "subagent" : exec ? "worker" : "interactive";
49
- return { kind, ...(parent ? { parent_session_id: parent } : {}) };
81
+ return { kind, client_app: codexClientApp(meta["originator"], meta["source"]), ...(parent ? { parent_session_id: parent } : {}) };
82
+ }
83
+ /**
84
+ * The originator names the app; the source names the host the app declared. Observed on real files: `codex_exec`
85
+ * (the exec runner), `Codex Desktop` and `codex_work_desktop` (the desktop apps, whose source is `vscode` because they
86
+ * share the app-server), `codex-tui` (the terminal UI: source `cli`, or `vscode` when started from VS Code, which is
87
+ * the IDE). A subagent keeps its parent app's originator. `Claude Code` as an originator is Claude Code driving a Codex
88
+ * run, not a Codex client a person used, so it is `unknown`.
89
+ */
90
+ export function codexClientApp(originator, source) {
91
+ if (originator === "codex_exec")
92
+ return "codex_exec";
93
+ if (originator === "Codex Desktop" || originator === "codex_work_desktop")
94
+ return "codex_desktop";
95
+ if (originator === "codex-tui")
96
+ return source === "vscode" ? "codex_ide" : "codex_cli";
97
+ return "unknown";
50
98
  }