@slack/radar-mcp 1.20.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
@@ -0,0 +1,92 @@
1
+ // Kept free of imports: scripts/mirror-shared.mjs mirrors it into the browser bundle, which could
2
+ // not resolve switchboard-report.ts's Node-side import chain.
3
+ // NOTE lines are lowercase inline in the report; a caller opening a sentence with one needs this.
4
+ export function capitalizeSwitchboardNote(note) {
5
+ return note ? note.charAt(0).toUpperCase() + note.slice(1) : note;
6
+ }
7
+ // A peak at or above this is clipping. Shared here so the report and the dashboard sparkline use
8
+ // the same threshold.
9
+ export const CLIP_PEAK = 0.99;
10
+ // A turn record's `clock` in words. Shared here so the feed row and the report read the same.
11
+ // An unknown value is the device's to add, so it shows as sent rather than throwing.
12
+ const TURN_CLOCK_LABELS = {
13
+ no_card: "no card",
14
+ resumed_from_tap: "after tap",
15
+ resumed_from_server_answer: "after server answer",
16
+ };
17
+ export function switchboardClockLabel(clock) {
18
+ return Object.hasOwn(TURN_CLOCK_LABELS, clock) ? TURN_CLOCK_LABELS[clock] : clock;
19
+ }
20
+ // The saved_turn outcomes, the one list the feed row, the panel and the report read. `applied`
21
+ // (a subtitle line still held the frame's item) and `no_line` (no line held it any more, a normal
22
+ // late save, still kept) keep the turn; the drop reasons lose it. The words are the row's and the
23
+ // panel's. A server resend counts again under `applied` while its line still holds the slot, then
24
+ // under `no_line` once the line has moved on; no counting code needs the resend as its own name.
25
+ const SAVED_TURN_KEPT = { applied: "saved", no_line: "saved (line moved on)" };
26
+ const SAVED_TURN_DROPS = { missing_field: "missing field", other_session: "other session" };
27
+ const DROP_PREFIX = "dropped";
28
+ const THREAD_FLAG = "thread";
29
+ const NO_THREAD_FLAG = "no thread";
30
+ export const SAVED_TURN_DROP_OUTCOMES = Object.keys(SAVED_TURN_DROPS);
31
+ // Only these keep the turn. The panel warns on anything else, so a drop reason the device adds
32
+ // later fails closed instead of reading as a clean session.
33
+ export const SAVED_TURN_KEPT_OUTCOMES = Object.keys(SAVED_TURN_KEPT);
34
+ // The four a revision 3 build always counts, in the order the panel and the report list them.
35
+ export const SAVED_TURN_OUTCOMES = [...Object.keys(SAVED_TURN_KEPT), ...SAVED_TURN_DROP_OUTCOMES];
36
+ // Code points a free-form device string could use to fake a line break, a report boundary, or a
37
+ // hidden direction override: controls, bidi marks, zero-width characters, U+2028/2029 (a newline
38
+ // to a browser), and the BOM. Here rather than in the report so the panel strips the same set.
39
+ export const SWITCHBOARD_CONTROL_CHARS = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200b-\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069\\ufeff]", "g");
40
+ export function stripSwitchboardControlChars(s) {
41
+ return s.replace(SWITCHBOARD_CONTROL_CHARS, "");
42
+ }
43
+ // The words a device name could be misread by: the kept marker "saved", the retired "replaced",
44
+ // the drop prefix, the thread flag, and the known outcome names. A name is matched on its letters
45
+ // alone, lowercased, so Saved, saved_again, savedAgain, saved2 and noLine all hit, while a name
46
+ // that only shares a filler word with a label (session_closed, line_busy) stays bare.
47
+ const letters = (s) => s.toLowerCase().replace(/[^a-z]/g, "");
48
+ const SAVED_TURN_MARKERS = [...SAVED_TURN_OUTCOMES, "saved", "replaced", DROP_PREFIX, THREAD_FLAG].map(letters);
49
+ // A device-added name (an outcome, a counts key) as the panel, the feed row and the report print
50
+ // it: bare only when it is a plain token with none of the marker words in it, quoted otherwise, so
51
+ // it cannot pass for a built-in word or a count of its own. The quoted form escapes the raw name,
52
+ // anything outside printable ASCII as \uXXXX, rather than stripping it first: the escape already
53
+ // makes a control or invisible character harmless, and stripping would print two names that differ
54
+ // only by one the same.
55
+ export function switchboardDeviceToken(name) {
56
+ if (/^[A-Za-z0-9_.-]+$/.test(name) && !SAVED_TURN_MARKERS.some((m) => letters(name).includes(m)))
57
+ return name;
58
+ return JSON.stringify(name).replace(/[^\x20-\x7e]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
59
+ }
60
+ // An outcome in words: "saved", "saved (line moved on)", "dropped: missing field", decided on the
61
+ // raw outcome. An unknown outcome is the device's to add and prints as a device token (above).
62
+ export function savedTurnCountWord(outcome) {
63
+ if (Object.hasOwn(SAVED_TURN_KEPT, outcome))
64
+ return SAVED_TURN_KEPT[outcome];
65
+ return Object.hasOwn(SAVED_TURN_DROPS, outcome) ? `${DROP_PREFIX}: ${SAVED_TURN_DROPS[outcome]}` : switchboardDeviceToken(outcome);
66
+ }
67
+ // A saved_turn record in words, shared by the feed row and the report like the clock above. A kept
68
+ // turn reads with its thread flag; a drop reads its reason alone; an unknown outcome reads as its
69
+ // token and never gets a thread flag, so it cannot read as a kept turn. A non-string outcome reads "".
70
+ export function savedTurnLabel(outcome, hasThread) {
71
+ if (typeof outcome !== "string")
72
+ return "";
73
+ const word = savedTurnCountWord(outcome);
74
+ return Object.hasOwn(SAVED_TURN_KEPT, outcome) ? `${word}, ${hasThread === true ? THREAD_FLAG : NO_THREAD_FLAG}` : word;
75
+ }
76
+ // A summary's `saved_turn_counts` as ordered entries: the four known outcomes first, then any key
77
+ // the device added, as sent. A count reads null when nothing counted it: absent (a revision 2 build
78
+ // counts nothing, which is not zero), a known key missing from a present object (revision 3 always
79
+ // sends all four), or a value that is not a non-negative safe integer. The caller prints "?" rather
80
+ // than a count nobody sent.
81
+ export function savedTurnCountEntries(counts) {
82
+ const obj = counts !== null && typeof counts === "object" && !Array.isArray(counts) ? counts : {};
83
+ const read = (k) => {
84
+ const v = obj[k];
85
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : null;
86
+ };
87
+ const out = SAVED_TURN_OUTCOMES.map((k) => ({ outcome: k, count: read(k) }));
88
+ for (const k of Object.keys(obj))
89
+ if (!SAVED_TURN_OUTCOMES.includes(k))
90
+ out.push({ outcome: k, count: read(k) });
91
+ return out;
92
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Write `content` under `dir` and return the path. The random suffix keeps two same-millisecond
3
+ * writes apart, since writeFileSync follows symlinks and overwrites. Throws on I/O failure.
4
+ */
5
+ export declare function writeSwitchboardReportFile(dir: string, prefix: string, content: string, now?: number): string;
@@ -0,0 +1,26 @@
1
+ // Shared by the MCP export tool and the web export route.
2
+ import crypto from "crypto";
3
+ import fs from "fs";
4
+ import path from "path";
5
+ const DIR_MODE = 0o700;
6
+ const FILE_MODE = 0o600;
7
+ /**
8
+ * Write `content` under `dir` and return the path. The random suffix keeps two same-millisecond
9
+ * writes apart, since writeFileSync follows symlinks and overwrites. Throws on I/O failure.
10
+ */
11
+ export function writeSwitchboardReportFile(dir, prefix, content, now = Date.now()) {
12
+ fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
13
+ // mkdirSync's mode only applies to directories it creates, so tighten existing ones too.
14
+ for (const p of [dir, path.dirname(dir)]) {
15
+ try {
16
+ if (fs.existsSync(p))
17
+ fs.chmodSync(p, DIR_MODE);
18
+ }
19
+ catch {
20
+ // Best effort; not fatal.
21
+ }
22
+ }
23
+ const file = path.join(dir, `${prefix}-${now}-${crypto.randomBytes(8).toString("hex")}.txt`);
24
+ fs.writeFileSync(file, content, { mode: FILE_MODE });
25
+ return file;
26
+ }
@@ -0,0 +1,20 @@
1
+ import { type SwitchboardReportAssembly } from "./switchboard.js";
2
+ export { SWITCHBOARD_CONTROL_CHARS, stripSwitchboardControlChars } from "./switchboard-note.js";
3
+ export declare const DBFS_FLOOR = -60;
4
+ export declare function toDbfs(linear: number): number;
5
+ export declare function fmtDbfs(v: unknown): string;
6
+ export declare function fmtDbfsRange(s: {
7
+ min: number;
8
+ max: number;
9
+ } | null): string;
10
+ /**
11
+ * Build the report for one assembled export. Records sort by their own timestamp then id, never
12
+ * the device's arrival order, since a late-landing batch can carry a higher id than an earlier
13
+ * neighbor. now is a parameter so the report stays pure and testable.
14
+ *
15
+ * A hostOnlyCause overrides every other NOTE: the eviction and ring-cap reasoning needs device
16
+ * detail that a host-only report does not have.
17
+ */
18
+ export declare function buildSwitchboardReport(assembly: SwitchboardReportAssembly, now?: number): string;
19
+ export declare function switchboardReportNotes(report: string): string[];
20
+ export { capitalizeSwitchboardNote } from "./switchboard-note.js";
@@ -0,0 +1,406 @@
1
+ // Pure text builder for one switchboard (Slackbot voice) session report. Input is read
2
+ // defensively: it crossed the device wire, and one odd or older-build field must never throw.
3
+ import { SWITCHBOARD_DEVICE_RING_CAP, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_WALK_DEADLINE_MS, switchboardWalkStopNote, } from "./switchboard.js";
4
+ import { CLIP_PEAK, SAVED_TURN_OUTCOMES, savedTurnCountEntries, savedTurnLabel, stripSwitchboardControlChars, switchboardClockLabel, switchboardDeviceToken, } from "./switchboard-note.js";
5
+ const refusedPhrase = (sendsToken) => sendsToken ? "the device refused this Radar session's token" : "the device refused the request (HTTP 401)";
6
+ const againPhrase = (surface) => surface === "dashboard" ? "press Reconnect and export again for the device copy" : "run /radar-enable and export again for the device copy";
7
+ // Re-exported so the existing callers keep their import; the set itself lives in the note.
8
+ export { SWITCHBOARD_CONTROL_CHARS, stripSwitchboardControlChars } from "./switchboard-note.js";
9
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
10
+ const str = (v) => (typeof v === "string" ? stripSwitchboardControlChars(v) : null);
11
+ const rec = (v) => (v !== null && typeof v === "object" ? v : {});
12
+ function isoOrRaw(ts) {
13
+ const n = num(ts);
14
+ if (n === null)
15
+ return "unknown time";
16
+ try {
17
+ return new Date(n).toISOString();
18
+ }
19
+ catch {
20
+ return String(n);
21
+ }
22
+ }
23
+ // The report's own clock wording. A resumed_from_server_answer time can be the gap between two
24
+ // reply chunks, and an export is read without the docs, so it says so here. The shared label
25
+ // stays bare because the dashboard feed row uses it too.
26
+ function reportClockLabel(clock) {
27
+ const label = switchboardClockLabel(clock);
28
+ return clock === "resumed_from_server_answer" ? `${label}, may be a chunk gap` : label;
29
+ }
30
+ function fmtMs(v) {
31
+ const n = num(v);
32
+ return n === null ? "?" : `${n} ms`;
33
+ }
34
+ // A range rather than an average, which would wash out the one spike a debugger is looking for.
35
+ function minMax(arr) {
36
+ if (!Array.isArray(arr) || arr.length === 0)
37
+ return null;
38
+ // A loop, not Math.min(...nums): a large levels batch would blow the argument limit.
39
+ let min = Infinity;
40
+ let max = -Infinity;
41
+ let found = false;
42
+ for (const v of arr) {
43
+ if (typeof v === "number" && Number.isFinite(v)) {
44
+ found = true;
45
+ if (v < min)
46
+ min = v;
47
+ if (v > max)
48
+ max = v;
49
+ }
50
+ }
51
+ if (!found)
52
+ return null;
53
+ const round3 = (n) => Math.round(n * 1000) / 1000;
54
+ return { min: round3(min), max: round3(max) };
55
+ }
56
+ // Same dBFS scale and floor as the dashboard sparkline, so the report reads in the tab's units.
57
+ export const DBFS_FLOOR = -60;
58
+ export function toDbfs(linear) {
59
+ const v = Math.max(0, Math.min(1, linear));
60
+ if (v <= 0)
61
+ return DBFS_FLOOR;
62
+ const db = 20 * Math.log10(v);
63
+ return Math.max(DBFS_FLOOR, Math.min(0, db));
64
+ }
65
+ const round1 = (n) => Math.round(n * 10) / 10;
66
+ // Zero prints "silent", not "-60 dBFS": the floor is a clamp, and would read as a real measurement.
67
+ export function fmtDbfs(v) {
68
+ const n = num(v);
69
+ if (n === null)
70
+ return "?";
71
+ if (n <= 0)
72
+ return `silent (${n})`;
73
+ return `${round1(toDbfs(n))} dBFS (${n})`;
74
+ }
75
+ export function fmtDbfsRange(s) {
76
+ if (!s)
77
+ return "?";
78
+ // Only a silent max means the whole range was silent; {0, 0.5} still has a real peak.
79
+ if (s.max <= 0)
80
+ return `silent (${s.min}..${s.max})`;
81
+ return `${round1(toDbfs(s.min))}..${round1(toDbfs(s.max))} dBFS (${s.min}..${s.max})`;
82
+ }
83
+ // Unknown or missing fields print as "?": a newer device build can add kinds or fields.
84
+ function recordLine(r) {
85
+ const ts = isoOrRaw(r.timestamp);
86
+ const kind = str(r.kind) ?? "?";
87
+ const id = num(r.id);
88
+ const head = `[${ts}]${id !== null ? ` #${id}` : ""} ${kind}`;
89
+ switch (kind) {
90
+ case "session": {
91
+ const event = str(r.event) ?? "?";
92
+ const serverId = str(r.server_session_id);
93
+ return `${head} ${event}${serverId ? ` server_session_id=${serverId}` : ""}`;
94
+ }
95
+ case "state": {
96
+ const stateKind = str(r.state_kind) ?? "?";
97
+ const from = str(r.from) ?? "?";
98
+ const to = str(r.to) ?? "?";
99
+ const cause = str(r.cause);
100
+ return `${head} ${stateKind} ${from} -> ${to}${cause ? ` (${cause})` : ""}`;
101
+ }
102
+ case "frame": {
103
+ const direction = str(r.direction) ?? "?";
104
+ const frameType = str(r.frame_type) ?? "?";
105
+ const bytes = num(r.bytes);
106
+ return `${head} ${direction} ${frameType}${bytes !== null ? ` ${bytes} B` : ""}`;
107
+ }
108
+ case "phase": {
109
+ const phase = str(r.phase) ?? "?";
110
+ return `${head} ${phase} ${fmtMs(r.duration_ms)}`;
111
+ }
112
+ case "player": {
113
+ const event = str(r.event) ?? "?";
114
+ const gap = num(r.gap_ms);
115
+ const queued = num(r.bytes_queued);
116
+ const parts = [event];
117
+ if (gap !== null)
118
+ parts.push(`gap ${gap} ms`);
119
+ if (queued !== null)
120
+ parts.push(`${queued} B queued`);
121
+ return `${head} ${parts.join(", ")}`;
122
+ }
123
+ case "levels": {
124
+ // Span from started_at, not timestamp: a levels record's timestamp is its last tick.
125
+ const sampleCount = num(r.sample_count);
126
+ const startedAt = num(r.started_at);
127
+ const offsets = Array.isArray(r.offsets_ms) ? r.offsets_ms : [];
128
+ const lastOffset = offsets.length ? num(offsets[offsets.length - 1]) : null;
129
+ const span = startedAt !== null && lastOffset !== null ? `${isoOrRaw(startedAt)}..${isoOrRaw(startedAt + lastOffset)}` : "unknown span";
130
+ const micRms = minMax(r.mic_rms);
131
+ const micPeak = minMax(r.mic_peak);
132
+ const playbackRms = minMax(r.playback_rms);
133
+ const playbackPeak = minMax(r.playback_peak);
134
+ const clipping = (micPeak !== null && micPeak.max >= CLIP_PEAK) || (playbackPeak !== null && playbackPeak.max >= CLIP_PEAK);
135
+ // No "max" label on a silent peak: "max silent (0)" reads as a contradiction.
136
+ const peakDbfs = (s) => {
137
+ if (s === null)
138
+ return "?";
139
+ return s.max <= 0 ? fmtDbfs(s.max) : `max ${fmtDbfs(s.max)}`;
140
+ };
141
+ return `${head} ${sampleCount ?? "?"} samples, span ${span}, mic_rms ${fmtDbfsRange(micRms)} mic_peak ${peakDbfs(micPeak)} playback_rms ${fmtDbfsRange(playbackRms)} playback_peak ${peakDbfs(playbackPeak)}${clipping ? " CLIPPING" : ""}`;
142
+ }
143
+ case "turn": {
144
+ const clock = str(r.clock);
145
+ return `${head} ${fmtMs(r.response_ms)}, ${clock ? reportClockLabel(clock) : "?"}`;
146
+ }
147
+ case "saved_turn": {
148
+ // Raw, not stripped: known or unknown is decided on what the device sent, so "applied" plus a
149
+ // hidden character is an unknown outcome, quoted, and never "saved, thread".
150
+ return `${head} ${typeof r.outcome === "string" && r.outcome ? savedTurnLabel(r.outcome, r.has_thread) : "?"}`;
151
+ }
152
+ default:
153
+ // The raw dump bypasses str(), so it needs its own strip.
154
+ return `${head} ${stripSwitchboardControlChars(JSON.stringify(r))}`;
155
+ }
156
+ }
157
+ // The walk-stop NOTE for when the live stream copy closed the gap, where the default wording
158
+ // ("older records are not in this file") would be false.
159
+ function hostFilledWalkNoteText(reason, hostFilledStart, refused, again) {
160
+ if (!hostFilledStart)
161
+ return null;
162
+ switch (reason) {
163
+ case "old-device":
164
+ return "this device build is too old to send older records; the live stream copy supplied the older records.";
165
+ case "byte-cap":
166
+ return `the export stopped at the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap; the live stream copy supplied the older records.`;
167
+ case "max-pages":
168
+ return "the export stopped at the page limit; the live stream copy supplied the older records.";
169
+ case "not-found-mid-walk":
170
+ return "the device dropped this session partway through the export; the live stream copy supplied the older records.";
171
+ case "request-failed":
172
+ return "the device stopped answering partway through the export; the live stream copy supplied the older records.";
173
+ case "unauthorized-mid-walk":
174
+ return `${refused} partway through the export; the live stream copy supplied the older records, ${again}.`;
175
+ case "walk-deadline":
176
+ return `the export stopped at its ${SWITCHBOARD_EXPORT_WALK_DEADLINE_MS / (60 * 1000)} minute time limit; the live stream copy supplied the older records.`;
177
+ default:
178
+ return null;
179
+ }
180
+ }
181
+ /**
182
+ * Build the report for one assembled export. Records sort by their own timestamp then id, never
183
+ * the device's arrival order, since a late-landing batch can carry a higher id than an earlier
184
+ * neighbor. now is a parameter so the report stays pure and testable.
185
+ *
186
+ * A hostOnlyCause overrides every other NOTE: the eviction and ring-cap reasoning needs device
187
+ * detail that a host-only report does not have.
188
+ */
189
+ export function buildSwitchboardReport(assembly, now = Date.now()) {
190
+ const { sendsToken = true, surface = "mcp" } = assembly;
191
+ const refused = refusedPhrase(sendsToken);
192
+ const again = againPhrase(surface);
193
+ const { detail, hostStreamCount = 0, deviceOldestTimestamp = null, hostOnlyCause = null, walkStopReason = null, deviceEventCount = null, gapCount = 0 } = assembly;
194
+ const deviceGone = hostOnlyCause !== null;
195
+ const d = rec(detail);
196
+ const sessionId = num(d.session_id);
197
+ // An older build omits the key rather than sending null; only a present key means "pending".
198
+ const hasServerSessionIdKey = Object.hasOwn(d, "server_session_id");
199
+ const serverSessionId = str(d.server_session_id);
200
+ const teamId = str(d.team_id);
201
+ const beganAt = d.began_at;
202
+ const beganAtNum = num(beganAt);
203
+ const endedAt = d.ended_at;
204
+ const live = endedAt == null;
205
+ // What the device holds now, not a lifetime count: the ring may already have shed records.
206
+ const totalCaptured = num(d.total_captured);
207
+ const frames = rec(d.frames);
208
+ const lastState = d.last_state ? rec(d.last_state) : null;
209
+ const levels = d.levels ? rec(d.levels) : null;
210
+ // Null before the first turn, absent on an older build; both print no line rather than a 0.
211
+ const turns = d.turns ? rec(d.turns) : null;
212
+ const rawEvents = Array.isArray(d.events) ? d.events : [];
213
+ const events = rawEvents
214
+ .map(rec)
215
+ .sort((a, b) => (num(a.timestamp) ?? 0) - (num(b.timestamp) ?? 0) || (num(a.id) ?? 0) - (num(b.id) ?? 0));
216
+ const hasBeginRow = events.some((e) => e.kind === "session" && e.event === "begin");
217
+ const startMissing = events.length > 0 && !hasBeginRow;
218
+ // Not events.length: host-recovered records could make the count reach total_captured even
219
+ // though the device walk came back short.
220
+ const deviceOnlyCount = deviceEventCount !== null ? deviceEventCount : events.length - hostStreamCount;
221
+ const streamedDuringExport = deviceEventCount !== null ? Math.max(0, events.length - hostStreamCount - deviceEventCount) : 0;
222
+ const fetchIncomplete = deviceOnlyCount > 0 && totalCaptured !== null && deviceOnlyCount < totalCaptured;
223
+ // Suggestive, not proof, that the ring lost the start, so it only earns the soft phrasing. The
224
+ // oldest-timestamp signal counts only when the walk reached the end of the device's range.
225
+ const oldestTimestampIsRingEvidence = walkStopReason === null || walkStopReason === "done";
226
+ const ringEvidence = (totalCaptured !== null && totalCaptured >= SWITCHBOARD_DEVICE_RING_CAP) ||
227
+ (oldestTimestampIsRingEvidence && deviceOldestTimestamp !== null && beganAtNum !== null && deviceOldestTimestamp > beganAtNum);
228
+ const lines = [];
229
+ lines.push(`Switchboard voice session ${sessionId ?? "?"}`);
230
+ // Same "pending" rule as the dashboard pill, but never for a host-only report, which has no
231
+ // live device connection to promise one.
232
+ const serverSessionIdText = serverSessionId ?? (!deviceGone && live && hasServerSessionIdKey ? "pending" : "(not reported)");
233
+ lines.push(`server_session_id: ${serverSessionIdText}`);
234
+ lines.push(`team_id: ${teamId ?? "(none)"}`);
235
+ lines.push(`began_at: ${isoOrRaw(beganAt)}`);
236
+ // A host-only report with no end record is not evidence the call is still live.
237
+ const endedAtText = hostOnlyCause === "unauthorized" && live
238
+ ? `unknown, ${refused}`
239
+ : hostOnlyCause === "unreachable" && live
240
+ ? "unknown, the device could not be reached"
241
+ : hostOnlyCause === "too-large" && live
242
+ ? "unknown, the device reply was too large to read"
243
+ : hostOnlyCause === "disabled" && live
244
+ ? "unknown, the Radar session is off"
245
+ : deviceGone && live
246
+ ? "unknown, not in the live stream copy"
247
+ : live
248
+ ? "(still live)"
249
+ : isoOrRaw(endedAt);
250
+ lines.push(`ended_at: ${endedAtText}`);
251
+ const heldParts = [];
252
+ if (hostStreamCount > 0 || streamedDuringExport > 0) {
253
+ if (deviceOnlyCount > 0)
254
+ heldParts.push(`${deviceOnlyCount} from the device`);
255
+ if (hostStreamCount > 0)
256
+ heldParts.push(`${hostStreamCount} recovered from the live stream copy`);
257
+ if (streamedDuringExport > 0)
258
+ heldParts.push(`${streamedDuringExport} streamed in during the export`);
259
+ }
260
+ const heldNote = heldParts.length > 0 ? ` (this report holds ${events.length}: ${heldParts.join(", ")})` : ` (this report holds ${events.length})`;
261
+ lines.push(`total_captured: ${totalCaptured ?? "?"}${heldNote}`);
262
+ lines.push(`frames: incoming=${num(frames.incoming) ?? "?"} outgoing=${num(frames.outgoing) ?? "?"}`);
263
+ if (lastState) {
264
+ lines.push(`last_state: ${str(lastState.state_kind) ?? "?"} -> ${str(lastState.to) ?? "?"}`);
265
+ }
266
+ if (levels) {
267
+ lines.push(`latest levels (${isoOrRaw(levels.timestamp)}): mic_rms=${fmtDbfs(levels.mic_rms)} mic_peak=${fmtDbfs(levels.mic_peak)} playback_rms=${fmtDbfs(levels.playback_rms)} playback_peak=${fmtDbfs(levels.playback_peak)}`);
268
+ }
269
+ // A revision 2 build sends no saved_turn_counts: nothing counted, which is not zero, so every
270
+ // count prints "?" and the line says why. A host-only report has no device summary at all, and a
271
+ // present non-object is not a count either; both print "?" too. A key the device added prints
272
+ // as a device token (switchboardDeviceToken, the panel's rule too), so neither "x saved=99" nor
273
+ // "applied" plus a hidden character can print as a count of its own.
274
+ const rawCounts = d.saved_turn_counts;
275
+ const countsAbsent = !deviceGone && !Object.hasOwn(d, "saved_turn_counts");
276
+ const countsUnreadable = deviceGone || (!countsAbsent && (rawCounts === null || typeof rawCounts !== "object" || Array.isArray(rawCounts)));
277
+ const countParts = savedTurnCountEntries(rawCounts).map(({ outcome, count }, i) => `${i < SAVED_TURN_OUTCOMES.length ? outcome : switchboardDeviceToken(outcome)}=${countsUnreadable ? "?" : (count ?? "?")}`);
278
+ lines.push(`saved_turn_counts: ${countParts.join(" ")}${countsAbsent ? " (not reported by this device build)" : ""}`);
279
+ if (turns) {
280
+ // turns and last_clock shipped together, so a missing or unusable clock is a device bug and
281
+ // prints "?", like the turn record's clock.
282
+ const lastClock = str(turns.last_clock);
283
+ const clockText = lastClock ? `, ${reportClockLabel(lastClock)}` : ", ?";
284
+ lines.push(`turns: ${num(turns.count) ?? "?"}, last response ${fmtMs(turns.last_response_ms)}${clockText}`);
285
+ }
286
+ lines.push(`exported_at: ${isoOrRaw(now)}`);
287
+ // A host copy with a mid-call gap did not really supply the older records.
288
+ const hostFilledStart = !startMissing && hostStreamCount > 0 && gapCount === 0;
289
+ const hostWalkNote = hostFilledWalkNoteText(walkStopReason, hostFilledStart, refused, again);
290
+ // "up to": ids come from one counter shared across sessions, so gapCount is an upper bound.
291
+ const gapNote = (cause) => `the report reaches the call's start, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing: ${cause}`;
292
+ // Only a walk that reached the end ("done") can blame eviction; any other stop is named instead.
293
+ const gapCauseText = (reason) => {
294
+ if (reason === "done" || reason === null)
295
+ return "the live stream dropped out and the device no longer holds them.";
296
+ if (reason === "old-device")
297
+ return "this device build is too old to send older records; the live stream copy missed them.";
298
+ if (reason === "byte-cap")
299
+ return `the export stopped at the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap; the live stream copy missed them.`;
300
+ if (reason === "request-failed")
301
+ return "the device stopped answering; the live stream copy missed them.";
302
+ if (reason === "not-found-mid-walk")
303
+ return "the device dropped this session partway through the export; the live stream copy missed them.";
304
+ if (reason === "unauthorized-mid-walk")
305
+ return `${refused} partway through the export; the live stream copy missed them, ${again}.`;
306
+ if (reason === "walk-deadline")
307
+ return `the export stopped at its ${SWITCHBOARD_EXPORT_WALK_DEADLINE_MS / (60 * 1000)} minute time limit; the live stream copy missed them.`;
308
+ return "the export stopped at the page limit; the live stream copy missed them.";
309
+ };
310
+ // Consulted only when ringEvidence is false, so the two causes never compete in one sentence.
311
+ const startMissingCauseText = (reason) => {
312
+ if (reason === "old-device")
313
+ return "this device build is too old to send older records.";
314
+ if (reason === "byte-cap")
315
+ return `the export stopped at the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap.`;
316
+ return null;
317
+ };
318
+ const notes = [];
319
+ if (hostOnlyCause === "unauthorized") {
320
+ const gapSuffix = !startMissing && gapCount > 0 ? `, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing (the stream dropped mid-call)` : "";
321
+ notes.push(startMissing
322
+ ? `${refused}; every record came from the live stream copy, and it does not reach the start of the call, ${again}.`
323
+ : `${refused}; every record came from the live stream copy${gapSuffix}, ${again}.`);
324
+ }
325
+ else if (hostOnlyCause === "unreachable") {
326
+ // Everything folds into notes[0], the only note the toast and MCP summary show.
327
+ const gapSuffix = !startMissing && gapCount > 0 ? `, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing (the stream dropped mid-call)` : "";
328
+ notes.push(startMissing
329
+ ? "the device could not be reached; every record came from the live stream copy, and it does not reach the start of the call."
330
+ : `the device could not be reached; every record came from the live stream copy${gapSuffix}.`);
331
+ }
332
+ else if (hostOnlyCause === "not-found") {
333
+ const gapSuffix = !startMissing && gapCount > 0 ? `, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing (the stream dropped mid-call)` : "";
334
+ notes.push(startMissing
335
+ ? "the device no longer holds this session; every record came from the live stream copy, and it does not reach the start of the call."
336
+ : `the device no longer holds this session; every record came from the live stream copy${gapSuffix}.`);
337
+ }
338
+ else if (hostOnlyCause === "too-large") {
339
+ const gapSuffix = !startMissing && gapCount > 0 ? `, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing (the stream dropped mid-call)` : "";
340
+ notes.push(startMissing
341
+ ? "the device reply was too large to read; every record came from the live stream copy, and it does not reach the start of the call."
342
+ : `the device reply was too large to read; every record came from the live stream copy${gapSuffix}.`);
343
+ }
344
+ else if (hostOnlyCause === "disabled") {
345
+ // Not "unreachable": the device was never asked, so this must not claim a failed contact.
346
+ const gapSuffix = !startMissing && gapCount > 0 ? `, but up to ${gapCount} record${gapCount === 1 ? "" : "s"} in the middle may be missing (the stream dropped mid-call)` : "";
347
+ notes.push(startMissing
348
+ ? "the Radar session is off; every record came from the live stream copy, and it does not reach the start of the call."
349
+ : `the Radar session is off; every record came from the live stream copy${gapSuffix}.`);
350
+ }
351
+ else {
352
+ // notes[0], the one the toast and MCP summary show, always answers whether the report reaches
353
+ // the call's start. gapCount can be positive with no gap note, since startMissing wins that slot.
354
+ let gapNotePushed = false;
355
+ let startCauseFolded = false;
356
+ if (startMissing) {
357
+ const startCause = ringEvidence ? null : startMissingCauseText(walkStopReason);
358
+ startCauseFolded = startCause !== null;
359
+ notes.push(ringEvidence
360
+ ? "this report does not reach the start of the call; the device no longer holds it."
361
+ : startCause
362
+ ? `this report does not reach the start of the call; ${startCause}`
363
+ : "this report does not reach the start of the call.");
364
+ }
365
+ else if (gapCount > 0) {
366
+ notes.push(gapNote(gapCauseText(walkStopReason)));
367
+ gapNotePushed = true;
368
+ }
369
+ else if (hostWalkNote) {
370
+ notes.push(hostWalkNote);
371
+ }
372
+ else if (fetchIncomplete && hostStreamCount > 0) {
373
+ notes.push("the live stream copy filled in the older records this export did not fetch from the device.");
374
+ }
375
+ if (fetchIncomplete) {
376
+ const hostCoversSuffix = hostWalkNote ? "; the live stream copy covers them" : "";
377
+ notes.push(`the export did not fetch every record the device holds (${deviceOnlyCount} of ${totalCaptured})${hostCoversSuffix}.`);
378
+ }
379
+ // Skipped when an earlier note already explained the shortfall.
380
+ if (walkStopReason && !hostWalkNote && !gapNotePushed && !startCauseFolded) {
381
+ const plain = switchboardWalkStopNote(walkStopReason, refused, again);
382
+ if (plain)
383
+ notes.push(plain);
384
+ }
385
+ }
386
+ if (notes.length > 0) {
387
+ lines.push("");
388
+ for (const n of notes)
389
+ lines.push(`NOTE: ${n}`);
390
+ }
391
+ lines.push("");
392
+ lines.push(`Records (${events.length}, oldest first):`);
393
+ for (const e of events) {
394
+ lines.push(recordLine(e));
395
+ }
396
+ return lines.join("\n") + "\n";
397
+ }
398
+ const NOTE_PREFIX = "NOTE: ";
399
+ // Parses the rendered report rather than recomputing the notes, so it can never disagree with it.
400
+ export function switchboardReportNotes(report) {
401
+ return report
402
+ .split("\n")
403
+ .filter((line) => line.startsWith(NOTE_PREFIX))
404
+ .map((line) => line.slice(NOTE_PREFIX.length));
405
+ }
406
+ export { capitalizeSwitchboardNote } from "./switchboard-note.js";