@slack/radar-mcp 1.21.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 (80) hide show
  1. package/README.md +68 -15
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  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 +117 -32
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-response.d.ts +4 -1
  12. package/dist/mcp/radar-response.js +8 -3
  13. package/dist/mcp/session-backfill.js +3 -4
  14. package/dist/mcp/session-enable.d.ts +1 -0
  15. package/dist/mcp/session-enable.js +146 -15
  16. package/dist/mcp/snapshot.js +42 -26
  17. package/dist/mcp/sources-gate.js +1 -0
  18. package/dist/mcp/stale-dashboard.d.ts +23 -0
  19. package/dist/mcp/stale-dashboard.js +122 -0
  20. package/dist/mcp/switchboard-spool.d.ts +12 -0
  21. package/dist/mcp/switchboard-spool.js +107 -0
  22. package/dist/mcp/switchboard-tools.d.ts +9 -0
  23. package/dist/mcp/switchboard-tools.js +144 -6
  24. package/dist/mcp/tools.d.ts +4 -1
  25. package/dist/mcp/tools.js +60 -15
  26. package/dist/mcp/web-child-env.d.ts +4 -1
  27. package/dist/mcp/web-child-env.js +4 -1
  28. package/dist/shared/android.d.ts +43 -0
  29. package/dist/shared/android.js +227 -19
  30. package/dist/shared/constants.d.ts +9 -4
  31. package/dist/shared/constants.js +9 -4
  32. package/dist/shared/feature-flags.d.ts +1 -0
  33. package/dist/shared/feature-flags.js +1 -0
  34. package/dist/shared/ios-logs.d.ts +10 -0
  35. package/dist/shared/ios-logs.js +91 -0
  36. package/dist/shared/ios.d.ts +25 -2
  37. package/dist/shared/ios.js +157 -3
  38. package/dist/{web → shared}/log-session.d.ts +45 -31
  39. package/dist/shared/log-session.js +300 -0
  40. package/dist/shared/radar-request-raw.d.ts +7 -0
  41. package/dist/shared/radar-request-raw.js +89 -0
  42. package/dist/shared/radar-token.d.ts +25 -0
  43. package/dist/shared/radar-token.js +164 -0
  44. package/dist/shared/stream.d.ts +3 -0
  45. package/dist/shared/stream.js +107 -15
  46. package/dist/shared/switchboard-host-store.d.ts +21 -0
  47. package/dist/shared/switchboard-host-store.js +166 -0
  48. package/dist/shared/switchboard-note.d.ts +15 -0
  49. package/dist/shared/switchboard-note.js +92 -0
  50. package/dist/shared/switchboard-report-file.d.ts +5 -0
  51. package/dist/shared/switchboard-report-file.js +26 -0
  52. package/dist/shared/switchboard-report.d.ts +20 -0
  53. package/dist/shared/switchboard-report.js +406 -0
  54. package/dist/shared/switchboard.d.ts +111 -2
  55. package/dist/shared/switchboard.js +436 -3
  56. package/dist/shared/transport.d.ts +43 -3
  57. package/dist/shared/version.d.ts +2 -0
  58. package/dist/shared/version.js +18 -0
  59. package/dist/shared/wire.d.ts +14 -1
  60. package/dist/web/install-app.d.ts +57 -8
  61. package/dist/web/install-app.js +270 -60
  62. package/dist/web/macapp/RadarApp.swift +340 -22
  63. package/dist/web/public/index.html +51 -9
  64. package/dist/web/public/next/app.js +33 -18
  65. package/dist/web/public/next/feed.js +102 -15
  66. package/dist/web/public/next/flags.js +3 -0
  67. package/dist/web/public/next/inspector.js +69 -3
  68. package/dist/web/public/next/prefs.js +5 -2
  69. package/dist/web/public/next/registry.js +18 -5
  70. package/dist/web/public/next/store.js +455 -29
  71. package/dist/web/public/next/switchboard-note.js +93 -0
  72. package/dist/web/public/next/toast.js +9 -5
  73. package/dist/web/public/next/voice-model.js +215 -35
  74. package/dist/web/public/next/voice.js +173 -18
  75. package/dist/web/server.d.ts +15 -11
  76. package/dist/web/server.js +690 -168
  77. package/dist/web/spec.d.ts +2 -1
  78. package/dist/web/spec.js +2 -1
  79. package/package.json +2 -2
  80. package/dist/web/log-session.js +0 -166
@@ -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";
@@ -1,9 +1,118 @@
1
+ import { type RadarTokenSender, type TokenSurface } from "./radar-token.js";
1
2
  export declare const SWITCHBOARD_KIND = "switchboard";
2
3
  export declare const SWITCHBOARD_BACKFILL_SESSIONS = 3;
3
4
  export declare const SWITCHBOARD_BACKFILL_DEADLINE_MS: number;
4
5
  export declare function switchboardListPath(): string;
5
- export declare const SWITCHBOARD_KINDS: readonly ["session", "state", "frame", "phase", "player"];
6
+ export declare const SWITCHBOARD_KINDS: readonly ["session", "state", "frame", "phase", "player", "levels", "turn", "saved_turn"];
6
7
  export type SwitchboardKind = (typeof SWITCHBOARD_KINDS)[number];
7
- export declare function switchboardSessionPath(sessionId: number, limit: number, kind?: SwitchboardKind): string;
8
+ export declare function switchboardSessionPath(sessionId: number, limit: number, kind?: SwitchboardKind, beforeId?: number): string;
8
9
  export declare function newestSwitchboardSessionIds(list: unknown): number[];
9
10
  export declare function switchboardPageEvents(session: unknown): Record<string, unknown>[];
11
+ export declare function nonNegativeIntArg(v: unknown): number | null;
12
+ export declare const SWITCHBOARD_EXPORT_MAX_LIMIT = 2000;
13
+ export declare const SWITCHBOARD_DEVICE_RING_CAP = 10000;
14
+ export declare const SWITCHBOARD_EXPORT_MAX_PAGES = 25;
15
+ export declare const SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES: number;
16
+ export declare const SWITCHBOARD_EXPORT_IDLE_MS = 10000;
17
+ export declare const SWITCHBOARD_EXPORT_OVERALL_MS = 60000;
18
+ export declare const SWITCHBOARD_EXPORT_WALK_DEADLINE_MS: number;
19
+ export interface SwitchboardExportGet {
20
+ (path: string, capBytes?: number, deadline?: number): Promise<{
21
+ status: number;
22
+ body: Record<string, unknown> | null;
23
+ bytes?: number;
24
+ capped?: boolean;
25
+ }>;
26
+ }
27
+ export type SwitchboardWalkStopReason = "done" | "byte-cap" | "max-pages" | "old-device" | "not-found-mid-walk" | "request-failed" | "unauthorized-mid-walk" | "walk-deadline";
28
+ export declare function switchboardWalkStopNote(reason: SwitchboardWalkStopReason, refused: string, again: string): string | null;
29
+ export type SwitchboardExportOutcome = {
30
+ ok: true;
31
+ sessionId: number;
32
+ detail: Record<string, unknown>;
33
+ devicePages: number;
34
+ deviceBytes: number;
35
+ stopReason: SwitchboardWalkStopReason;
36
+ } | {
37
+ ok: false;
38
+ reason: "unreachable";
39
+ sessionId?: number;
40
+ } | {
41
+ ok: false;
42
+ reason: "unauthorized";
43
+ sessionId?: number;
44
+ } | {
45
+ ok: false;
46
+ reason: "no-sessions";
47
+ } | {
48
+ ok: false;
49
+ reason: "not-found";
50
+ sessionId: number;
51
+ } | {
52
+ ok: false;
53
+ reason: "bad-response";
54
+ sessionId?: number;
55
+ };
56
+ /**
57
+ * Page backwards from an already-fetched first page with before_id. Uses the device's
58
+ * next_before_id when it names one; otherwise falls back to the page's oldest id, stopping on a
59
+ * short page or no progress (an old device re-answering the same page).
60
+ */
61
+ export declare function walkSwitchboardExportPages(sessionId: number, get: SwitchboardExportGet, firstPageBody: Record<string, unknown>, firstPageBytes: number, limit?: number, byteCap?: number, maxPages?: number, walkDeadlineMs?: number): Promise<{
62
+ events: Record<string, unknown>[];
63
+ pages: number;
64
+ bytes: number;
65
+ stopReason: SwitchboardWalkStopReason;
66
+ }>;
67
+ /**
68
+ * Resolve the session (the given id, or the newest listed) and walk its device pages. The
69
+ * returned events are the device's contribution only; host records merge in separately. deadline
70
+ * covers the whole export, list request included.
71
+ */
72
+ export declare function resolveSwitchboardExport(requestedId: number | null, get: SwitchboardExportGet, deadline?: number): Promise<SwitchboardExportOutcome>;
73
+ export interface SwitchboardMergeResult {
74
+ events: Record<string, unknown>[];
75
+ hostOnlyCount: number;
76
+ gapCount: number;
77
+ }
78
+ /**
79
+ * Merge device records with the host's streamed copy. The device wins on a shared id; the host
80
+ * copy is only a backstop for evicted records. hostOnlyCount counts only host records below the
81
+ * device's lowest id, since one above it may have streamed in during the walk.
82
+ */
83
+ export declare function mergeSwitchboardRecords(deviceEvents: Record<string, unknown>[], hostEvents: Record<string, unknown>[], beganAt?: number | null): SwitchboardMergeResult;
84
+ export declare function hostOnlyGapCount(records: Record<string, unknown>[]): number;
85
+ /**
86
+ * A session detail built only from host records. Anything no record evidences stays unknown
87
+ * rather than guessed. Keeps only records from the last session begin onward as a backstop, so
88
+ * two calls never mix even if the host store missed a reset.
89
+ */
90
+ export declare function hostOnlySwitchboardDetail(sessionId: number, hostRecords: Record<string, unknown>[]): Record<string, unknown>;
91
+ export declare function oldestSwitchboardTimestamp(events: Record<string, unknown>[]): number | null;
92
+ export type SwitchboardExportAssembly = {
93
+ ok: true;
94
+ sendsToken?: boolean;
95
+ surface?: TokenSurface;
96
+ sessionId: number;
97
+ detail: Record<string, unknown>;
98
+ hostStreamCount: number;
99
+ deviceEventCount: number | null;
100
+ deviceOldestTimestamp: number | null;
101
+ hostOnlyCause: "not-found" | "unreachable" | "too-large" | "disabled" | "unauthorized" | null;
102
+ walkStopReason: SwitchboardWalkStopReason | null;
103
+ gapCount: number;
104
+ } | {
105
+ ok: false;
106
+ reason: "no-sessions" | "not-found" | "unreachable" | "bad-response" | "unauthorized";
107
+ sessionId?: number;
108
+ message: string;
109
+ };
110
+ export type SwitchboardReportAssembly = Extract<SwitchboardExportAssembly, {
111
+ ok: true;
112
+ }>;
113
+ /**
114
+ * The whole export flow, shared by the MCP tool and the web route so fallbacks and error wording
115
+ * cannot drift. getHostRecords is injected to avoid a circular import with
116
+ * switchboard-host-store.ts.
117
+ */
118
+ export declare function assembleSwitchboardExport(requestedId: number | null, get: SwitchboardExportGet, getHostRecords: (sessionId: number) => Record<string, unknown>[], getNewestHostSessionId: (() => number | null) | undefined, sender: RadarTokenSender, surface?: TokenSurface): Promise<SwitchboardExportAssembly>;