@bli-cockpit/telemetry-core 0.1.76 → 0.1.78

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.
@@ -48,15 +48,37 @@ export function applyImageNotes(text, notes, escape = "json") {
48
48
  return description ? describedMarker(whole, description, escape) : whole;
49
49
  });
50
50
  }
51
- export function createImageDescriptionResolver(lookup, options) {
51
+ /** Logs one line per resolved text, with run-wide totals carried across calls. */
52
+ function createSummaryLogger(reader, log) {
53
+ let totalFound = 0;
54
+ let totalResolved = 0;
55
+ let totalLookups = 0;
56
+ return (summary) => {
57
+ totalFound += summary.found;
58
+ totalResolved += summary.resolved;
59
+ totalLookups += summary.lookups;
60
+ log(`${TAG} markers resolved`, {
61
+ reader,
62
+ found: summary.found,
63
+ resolved: summary.resolved,
64
+ missing: summary.found - summary.resolved,
65
+ missing_reasons: summary.reasons,
66
+ distinct: summary.distinct,
67
+ looked_up: summary.askedFor,
68
+ lookups: summary.lookups,
69
+ run_found: totalFound,
70
+ run_resolved: totalResolved,
71
+ run_lookups: totalLookups,
72
+ });
73
+ };
74
+ }
75
+ /** The remembered descriptions, the batched lookups behind them and the run-wide counters that log them. */
76
+ function createMarkerLookups(lookup, options) {
52
77
  const log = options.log ?? ((message, fields) => console.info(message, JSON.stringify(fields)));
53
78
  const batchSize = Math.max(1, options.batchSize ?? DEFAULT_BATCH);
54
79
  const maxRemembered = Math.max(1, options.maxRemembered ?? DEFAULT_MAX_REMEMBERED);
55
80
  /** description, or null for "asked and there is none". A failed lookup is never remembered. */
56
81
  const remembered = new Map();
57
- let totalFound = 0;
58
- let totalResolved = 0;
59
- let totalLookups = 0;
60
82
  function remember(prefix, description) {
61
83
  if (remembered.size >= maxRemembered) {
62
84
  const oldest = remembered.keys().next();
@@ -99,25 +121,12 @@ export function createImageDescriptionResolver(lookup, options) {
99
121
  const { lookups, failed } = toAsk.length ? await fetchMissing(toAsk) : { lookups: 0, failed: new Set() };
100
122
  return { found: markers.length, distinct, failed, lookups, askedFor: toAsk.length };
101
123
  }
102
- function logSummary(summary) {
103
- totalFound += summary.found;
104
- totalResolved += summary.resolved;
105
- totalLookups += summary.lookups;
106
- log(`${TAG} markers resolved`, {
107
- reader: options.reader,
108
- found: summary.found,
109
- resolved: summary.resolved,
110
- missing: summary.found - summary.resolved,
111
- missing_reasons: summary.reasons,
112
- distinct: summary.distinct,
113
- looked_up: summary.askedFor,
114
- lookups: summary.lookups,
115
- run_found: totalFound,
116
- run_resolved: totalResolved,
117
- run_lookups: totalLookups,
118
- });
119
- }
124
+ const logSummary = createSummaryLogger(options.reader, log);
120
125
  const reasonFor = (prefix, failed) => (failed.has(prefix) ? "lookup_failed" : "no_description_row");
126
+ return { remembered, ask, logSummary, reasonFor };
127
+ }
128
+ export function createImageDescriptionResolver(lookup, options) {
129
+ const { remembered, ask, logSummary, reasonFor } = createMarkerLookups(lookup, options);
121
130
  return {
122
131
  async inline(text, callOptions) {
123
132
  const asked = await ask(text);
@@ -56,6 +56,34 @@ export function classifyTemplates(result, table, family) {
56
56
  // What needs a person first, then by count: the same order the text view uses.
57
57
  return rows.sort((a, b) => (CLASS_ORDER[a.class] ?? 0) - (CLASS_ORDER[b.class] ?? 0) || b.count - a.count || (a.tid < b.tid ? -1 : 1));
58
58
  }
59
+ /** The source's lines, or the named refusal the source gave instead. */
60
+ async function readSource(read, context, log, family) {
61
+ try {
62
+ return await read(context);
63
+ }
64
+ catch (error) {
65
+ if (error instanceof SourceRefusal) {
66
+ log("[logs digest] refused", { reason: error.reason, source: family });
67
+ return { ok: false, reason: error.reason, detail: error.detail };
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ /** Adds every line to the digest; when `wanted` names a template, also collects that template's lines as printable text. */
73
+ function feedDigest(digest, lines, wanted) {
74
+ const raw = [];
75
+ let matched = 0;
76
+ for (const line of lines) {
77
+ const before = wanted ? digest.groups.get(wanted)?.count ?? 0 : 0;
78
+ digest.addLine(line.unit, line.message, line.ts, { level: line.level });
79
+ if (wanted && (digest.groups.get(wanted)?.count ?? 0) !== before) {
80
+ matched += 1;
81
+ const stamp = line.ts ? `${new Date(line.ts * 1000).toISOString().slice(11, 19)}Z ` : "";
82
+ raw.push(`${stamp}${line.unit}: ${cut(redact(squash(line.message)), RAW_LINE_CHARS)}`);
83
+ }
84
+ }
85
+ return { raw, matched };
86
+ }
59
87
  /** Reads, digests, classifies and renders one source. Never throws for a refusal: it is returned, named. */
60
88
  export async function digestSource(request, env = {}) {
61
89
  const log = env.log ?? defaultLog;
@@ -86,32 +114,14 @@ export async function digestSource(request, env = {}) {
86
114
  const context = {
87
115
  window, run: env.run ?? nodeRunCli, log, stateDir: env.stateDir, stdinText: env.stdinText, stdinIsTerminal: env.stdinIsTerminal, limits: env.limits, allLevels: request.allLevels,
88
116
  };
89
- let source;
90
- try {
91
- source = await read(context);
92
- }
93
- catch (error) {
94
- if (error instanceof SourceRefusal) {
95
- log("[logs digest] refused", { reason: error.reason, source: family });
96
- return { ok: false, reason: error.reason, detail: error.detail };
97
- }
98
- throw error;
99
- }
117
+ const source = await readSource(read, context, log, family);
118
+ if ("ok" in source)
119
+ return source;
100
120
  const digest = new Digest({ noise: table.noiseUnits, taggedLines: true });
101
- const raw = [];
102
- const wanted = request.raw;
103
- let matched = 0;
104
- for (const line of source.lines) {
105
- const before = wanted ? digest.groups.get(wanted)?.count ?? 0 : 0;
106
- digest.addLine(line.unit, line.message, line.ts, { level: line.level });
107
- if (wanted && (digest.groups.get(wanted)?.count ?? 0) !== before) {
108
- matched += 1;
109
- const stamp = line.ts ? `${new Date(line.ts * 1000).toISOString().slice(11, 19)}Z ` : "";
110
- raw.push(`${stamp}${line.unit}: ${cut(redact(squash(line.message)), RAW_LINE_CHARS)}`);
111
- }
112
- }
121
+ const { raw, matched } = feedDigest(digest, source.lines, request.raw);
113
122
  const result = digest.result();
114
123
  const facts = windowFacts(window);
124
+ const wanted = request.raw;
115
125
  if (wanted) {
116
126
  const limit = request.rawLimit ?? RAW_DEFAULT_LIMIT;
117
127
  const lines = raw.slice(-limit);
@@ -78,6 +78,10 @@ export declare class Digest {
78
78
  addEntry(entry: JournalEntry): void;
79
79
  /** One log line from any source. `ts` is epoch seconds (0 when the source has none). */
80
80
  addLine(unit: string, message: string, ts: number, facts?: LineFacts): void;
81
+ private addJsonLine;
82
+ /** True when the line carried a `[tag]` and was filed; false leaves it for the plain-line rules. */
83
+ private addTaggedLine;
84
+ private addPlainLine;
81
85
  /** A line the class table asked to see even without a trouble word (a `watch` pattern matches its masked text). */
82
86
  private watched;
83
87
  private routineCount;
@@ -113,49 +113,58 @@ export class Digest {
113
113
  return;
114
114
  const stripped = message.trim();
115
115
  if (stripped.startsWith("{") || Array.from(stripped).length > LONG_LINE_CHARS) {
116
- const records = jsonRecords(stripped);
117
- if (records === null) {
118
- // journald splits a huge JSON line into pieces; a piece is not a sentence, and words like
119
- // "archiveFailed" or "errors" inside it are key names, not failures.
120
- this.routineCount(group, "json_fragment", null);
121
- return;
122
- }
123
- for (const data of records) {
124
- if (this.routineUnits.has(bare)) {
125
- this.routineCount(group, "relay", null); // watchdog and breaker records: ingested from their own files
126
- continue;
127
- }
128
- const judged = judgeJson(data);
129
- if (judged.important && judged.template !== null) {
130
- this.addGroup(group, instance, judged.event, judged.template, ts, cut(pythonJson(data), EXAMPLE_CHARS * 2));
131
- }
132
- else {
133
- this.routineCount(group, judged.event, judged.subject);
134
- }
135
- }
116
+ this.addJsonLine(stripped, group, instance, bare, ts);
136
117
  return;
137
118
  }
138
119
  if (FRAME_LINE.test(message) || message.startsWith(" ")) {
139
120
  this.routineCount(group, "traceback_frame", null); // a frame or code line whose traceback header was interleaved away
140
121
  return;
141
122
  }
142
- if (this.taggedLines && !manager) {
143
- const parsed = parseTagged(message);
144
- if (parsed) {
145
- const judged = judgeTagged(parsed, facts.level);
146
- if (!judged.important && this.watched(group, message)) {
147
- this.addGroup(group, instance, "tagged", mask(message), ts, message);
148
- }
149
- else if (!judged.important) {
150
- this.routineCount(group, judged.template, null);
151
- }
152
- else {
153
- const template = judged.declaredWarning ? cut(judged.template, TEMPLATE_CHARS - DECLARED_WARNING.length) + DECLARED_WARNING : judged.template;
154
- this.addGroup(group, instance, "tagged", template, ts, message);
155
- }
156
- return;
123
+ if (this.taggedLines && !manager && this.addTaggedLine(message, group, instance, ts, facts.level))
124
+ return;
125
+ this.addPlainLine(unit, message, group, instance, ts, manager);
126
+ }
127
+ addJsonLine(stripped, group, instance, bare, ts) {
128
+ const records = jsonRecords(stripped);
129
+ if (records === null) {
130
+ // journald splits a huge JSON line into pieces; a piece is not a sentence, and words like
131
+ // "archiveFailed" or "errors" inside it are key names, not failures.
132
+ this.routineCount(group, "json_fragment", null);
133
+ return;
134
+ }
135
+ for (const data of records) {
136
+ if (this.routineUnits.has(bare)) {
137
+ this.routineCount(group, "relay", null); // watchdog and breaker records: ingested from their own files
138
+ continue;
139
+ }
140
+ const judged = judgeJson(data);
141
+ if (judged.important && judged.template !== null) {
142
+ this.addGroup(group, instance, judged.event, judged.template, ts, cut(pythonJson(data), EXAMPLE_CHARS * 2));
157
143
  }
144
+ else {
145
+ this.routineCount(group, judged.event, judged.subject);
146
+ }
147
+ }
148
+ }
149
+ /** True when the line carried a `[tag]` and was filed; false leaves it for the plain-line rules. */
150
+ addTaggedLine(message, group, instance, ts, level) {
151
+ const parsed = parseTagged(message);
152
+ if (!parsed)
153
+ return false;
154
+ const judged = judgeTagged(parsed, level);
155
+ if (!judged.important && this.watched(group, message)) {
156
+ this.addGroup(group, instance, "tagged", mask(message), ts, message);
158
157
  }
158
+ else if (!judged.important) {
159
+ this.routineCount(group, judged.template, null);
160
+ }
161
+ else {
162
+ const template = judged.declaredWarning ? cut(judged.template, TEMPLATE_CHARS - DECLARED_WARNING.length) + DECLARED_WARNING : judged.template;
163
+ this.addGroup(group, instance, "tagged", template, ts, message);
164
+ }
165
+ return true;
166
+ }
167
+ addPlainLine(unit, message, group, instance, ts, manager) {
159
168
  const event = manager ? "systemd" : unit === "kernel" ? "kernel" : "log";
160
169
  // The source's own level is NOT a verdict on a plain line: Tower writes ordinary output to stderr, which Vercel
161
170
  // and Railway both mark "error" (measured 2026-10-07). Words and fields decide; see tagged.ts.
@@ -50,22 +50,27 @@ function objectEnd(text, start) {
50
50
  let inString = false;
51
51
  for (let index = start; index < text.length; index += 1) {
52
52
  const char = text[index];
53
+ if (inString && char === "\\") {
54
+ index += 1;
55
+ continue;
56
+ }
53
57
  if (inString) {
54
- if (char === "\\")
55
- index += 1;
56
- else if (char === '"')
57
- inString = false;
58
+ inString = char !== '"';
58
59
  continue;
59
60
  }
60
- if (char === '"')
61
+ if (char === '"') {
61
62
  inString = true;
62
- else if (char === "{")
63
+ continue;
64
+ }
65
+ if (char === "{") {
63
66
  depth += 1;
64
- else if (char === "}") {
65
- depth -= 1;
66
- if (depth === 0)
67
- return index + 1;
67
+ continue;
68
68
  }
69
+ if (char !== "}")
70
+ continue;
71
+ depth -= 1;
72
+ if (depth === 0)
73
+ return index + 1;
69
74
  }
70
75
  return -1;
71
76
  }
@@ -12,6 +12,50 @@ function latest(a, b) {
12
12
  const value = Math.max(a ?? 0, b ?? 0);
13
13
  return value || null;
14
14
  }
15
+ function widenSpan(merged, span) {
16
+ const [start, end] = span ?? [null, null];
17
+ if (start && (merged.span[0] === null || start < merged.span[0]))
18
+ merged.span[0] = start;
19
+ if (end && (merged.span[1] === null || end > merged.span[1]))
20
+ merged.span[1] = end;
21
+ }
22
+ function carryCursors(merged, cursors) {
23
+ const [first, last] = cursors ?? [null, null];
24
+ merged.cursors[0] = merged.cursors[0] ?? first;
25
+ merged.cursors[1] = last ?? merged.cursors[1];
26
+ }
27
+ function mergeGroup(merged, record, registry) {
28
+ const known = merged.groups.get(record.tid);
29
+ if (!known) {
30
+ merged.groups.set(record.tid, { ...registry[record.tid], ...record, instances: [...(record.instances ?? [])], tid: record.tid });
31
+ return;
32
+ }
33
+ known.count += record.count;
34
+ known.first = earliest(known.first, record.first);
35
+ known.last = latest(known.last, record.last);
36
+ for (const instance of record.instances ?? []) {
37
+ if (!known.instances.includes(instance) && known.instances.length < 64)
38
+ known.instances.push(instance);
39
+ }
40
+ }
41
+ function addSubjects(into, subjects) {
42
+ for (const [subject, amount] of Object.entries(subjects)) {
43
+ if (subject in into || Object.keys(into).length < SUBJECTS_TRACKED)
44
+ into[subject] = (into[subject] ?? 0) + amount;
45
+ else
46
+ into["…"] = (into["…"] ?? 0) + amount;
47
+ }
48
+ }
49
+ function mergeRoutine(merged, routine) {
50
+ for (const [group, events] of Object.entries(routine ?? {})) {
51
+ const into = (merged.routine[group] ??= Object.create(null));
52
+ for (const [event, [count, subjects]] of Object.entries(events)) {
53
+ const record = (into[event] ??= [0, Object.create(null)]);
54
+ record[0] += count;
55
+ addSubjects(record[1], subjects);
56
+ }
57
+ }
58
+ }
15
59
  export function mergeResults(results, registry = {}) {
16
60
  const merged = {
17
61
  lines: 0, noise: 0,
@@ -23,42 +67,12 @@ export function mergeResults(results, registry = {}) {
23
67
  for (const result of results) {
24
68
  merged.lines += result.lines ?? 0;
25
69
  merged.noise += result.noise ?? 0;
26
- const [start, end] = result.span ?? [null, null];
27
- if (start && (merged.span[0] === null || start < merged.span[0]))
28
- merged.span[0] = start;
29
- if (end && (merged.span[1] === null || end > merged.span[1]))
30
- merged.span[1] = end;
31
- const [first, last] = result.cursors ?? [null, null];
32
- merged.cursors[0] = merged.cursors[0] ?? first;
33
- merged.cursors[1] = last ?? merged.cursors[1];
70
+ widenSpan(merged, result.span);
71
+ carryCursors(merged, result.cursors);
34
72
  const groups = result.groups ?? [];
35
- for (const record of Array.isArray(groups) ? groups : Object.values(groups)) {
36
- const known = merged.groups.get(record.tid);
37
- if (!known) {
38
- merged.groups.set(record.tid, { ...registry[record.tid], ...record, instances: [...(record.instances ?? [])], tid: record.tid });
39
- continue;
40
- }
41
- known.count += record.count;
42
- known.first = earliest(known.first, record.first);
43
- known.last = latest(known.last, record.last);
44
- for (const instance of record.instances ?? []) {
45
- if (!known.instances.includes(instance) && known.instances.length < 64)
46
- known.instances.push(instance);
47
- }
48
- }
49
- for (const [group, events] of Object.entries(result.routine ?? {})) {
50
- const into = (merged.routine[group] ??= Object.create(null));
51
- for (const [event, [count, subjects]] of Object.entries(events)) {
52
- const record = (into[event] ??= [0, Object.create(null)]);
53
- record[0] += count;
54
- for (const [subject, amount] of Object.entries(subjects)) {
55
- if (subject in record[1] || Object.keys(record[1]).length < SUBJECTS_TRACKED)
56
- record[1][subject] = (record[1][subject] ?? 0) + amount;
57
- else
58
- record[1]["…"] = (record[1]["…"] ?? 0) + amount;
59
- }
60
- }
61
- }
73
+ for (const record of Array.isArray(groups) ? groups : Object.values(groups))
74
+ mergeGroup(merged, record, registry);
75
+ mergeRoutine(merged, result.routine);
62
76
  }
63
77
  const groups = [...merged.groups.values()].sort((a, b) => b.count - a.count || (a.tid < b.tid ? -1 : a.tid > b.tid ? 1 : 0));
64
78
  return { lines: merged.lines, noise: merged.noise, span: merged.span, cursors: merged.cursors, groups, routine: merged.routine, breaker: {} };
@@ -73,12 +73,8 @@ export function fleetView(resultsByServer, classify, window) {
73
73
  return { window: window ?? [Math.min(...(spans.length ? spans : [0])), Math.max(...(spans.length ? spans : [0]))], servers: resultsByServer, classify };
74
74
  }
75
75
  const compareTid = (a, b) => (a.tid < b.tid ? -1 : a.tid > b.tid ? 1 : 0);
76
- /** The fleet digest: every server's templates merged by tid, ERROR first, hiccups counted, WARNINGs one line. */
77
- export function renderFleet(view) {
78
- const [start, end] = view.window;
79
- const names = Object.keys(view.servers).sort();
80
- const kept = names.reduce((sum, name) => sum + view.servers[name].lines, 0);
81
- const noise = names.reduce((sum, name) => sum + view.servers[name].noise, 0);
76
+ /** Every server's templates merged by tid: counts summed, times widened, the servers that saw it listed. */
77
+ function mergeFleetTemplates(view, names) {
82
78
  const byTid = new Map();
83
79
  for (const name of names) {
84
80
  for (const record of view.servers[name].groups) {
@@ -93,6 +89,15 @@ export function renderFleet(view) {
93
89
  entry.instances = [...new Set([...entry.instances, ...record.instances])].sort();
94
90
  }
95
91
  }
92
+ return byTid;
93
+ }
94
+ /** The fleet digest: every server's templates merged by tid, ERROR first, hiccups counted, WARNINGs one line. */
95
+ export function renderFleet(view) {
96
+ const [start, end] = view.window;
97
+ const names = Object.keys(view.servers).sort();
98
+ const kept = names.reduce((sum, name) => sum + view.servers[name].lines, 0);
99
+ const noise = names.reduce((sum, name) => sum + view.servers[name].noise, 0);
100
+ const byTid = mergeFleetTemplates(view, names);
96
101
  const sections = { ERROR: [], hiccup: [], WARNING: [] };
97
102
  for (const entry of byTid.values()) {
98
103
  const verdict = view.classify(entry.unit, entry.template, entry.servers[0]);
@@ -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) {
@@ -289,6 +289,22 @@ export const TOWER_PATTERNS = [
289
289
  basis: "railway docs-import-notion 1 d: 10 lines, Notion's own message names the fix",
290
290
  },
291
291
  // ------------------------------------------------------------------ any source
292
+ {
293
+ id: "any-node-deprecation-warning",
294
+ class: "benign",
295
+ match: raw `^\(node:(#|\d+)\) \[DEP\d+\] DeprecationWarning: `,
296
+ note: "Node announces that an API we (or a dependency) call is deprecated, once per process; nothing failed and the run goes on. Finding and replacing the call is the cleanup, not an incident (BLI-21949).",
297
+ basis: "stored tower digest, 2 d to 2026-10-19: the paired hint line on 16 Railway cron units (mail-sync x224, linear-sync x610, cal-sync x223, …), every one classified unknown ERROR",
298
+ },
299
+ {
300
+ // Node prints this second line ONLY after a DeprecationWarning; other
301
+ // warnings say `--trace-warnings`, which stays unmatched and still alerts.
302
+ id: "any-node-trace-deprecation-hint",
303
+ class: "benign",
304
+ match: raw `^\(Use \`node --trace-deprecation \.\.\.\` to show where the warning was created\)$`,
305
+ note: "the second line Node prints under every DeprecationWarning: a hint, not a failure",
306
+ basis: "stored tower digest, 2 d to 2026-10-19: about 3,000 lines across 16 Railway cron units, the largest source of unknown ERROR templates",
307
+ },
292
308
  {
293
309
  id: "any-ai-sdk-warning",
294
310
  class: "benign",
@@ -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({
@@ -216,12 +216,7 @@ export function finalizeSessionFacts(acc) {
216
216
  const keptTools = toolEntries.slice(0, SESSION_FACTS_MAX_TOOL_NAMES);
217
217
  const usage_by_model = Object.fromEntries(keptUsage);
218
218
  const tool_calls_by_name = Object.fromEntries(keptTools);
219
- const totals = keptUsage.reduce((sum, [, usage]) => ({
220
- input_tokens: sum.input_tokens + usage.input_tokens,
221
- output_tokens: sum.output_tokens + usage.output_tokens,
222
- cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
223
- cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
224
- }), emptyUsage());
219
+ const totals = sumUsage(keptUsage.map(([, usage]) => usage));
225
220
  const first = acc.first_timestamp_ms;
226
221
  const last = acc.last_timestamp_ms;
227
222
  return {
@@ -300,6 +295,14 @@ function usageTotal(usage) {
300
295
  usage.cache_read_input_tokens +
301
296
  usage.cache_creation_input_tokens);
302
297
  }
298
+ function sumUsage(usages) {
299
+ return usages.reduce((sum, usage) => ({
300
+ input_tokens: sum.input_tokens + usage.input_tokens,
301
+ output_tokens: sum.output_tokens + usage.output_tokens,
302
+ cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
303
+ cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
304
+ }), emptyUsage());
305
+ }
303
306
  function emptyUsage() {
304
307
  return {
305
308
  input_tokens: 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.76",
3
+ "version": "0.1.78",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",