@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,118 @@
1
+ import { type RadarTokenSender, type TokenSurface } from "./radar-token.js";
2
+ export declare const SWITCHBOARD_KIND = "switchboard";
3
+ export declare const SWITCHBOARD_BACKFILL_SESSIONS = 3;
4
+ export declare const SWITCHBOARD_BACKFILL_DEADLINE_MS: number;
5
+ export declare function switchboardListPath(): string;
6
+ export declare const SWITCHBOARD_KINDS: readonly ["session", "state", "frame", "phase", "player", "levels", "turn", "saved_turn"];
7
+ export type SwitchboardKind = (typeof SWITCHBOARD_KINDS)[number];
8
+ export declare function switchboardSessionPath(sessionId: number, limit: number, kind?: SwitchboardKind, beforeId?: number): string;
9
+ export declare function newestSwitchboardSessionIds(list: unknown): number[];
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>;
@@ -0,0 +1,487 @@
1
+ // The switchboard replay's device-side shape, shared by the dashboard's /backfill route and the
2
+ // MCP's spool backfill so the two pick the same sessions and build the same paths. Pure: no I/O.
3
+ //
4
+ // The device keeps switchboard two levels deep: `GET /api/switchboard` lists session summaries
5
+ // (`{sessions: [...]}`, newest first), `GET /api/switchboard/<session_id>?limit=N` is one session's
6
+ // summary plus `events`, the newest N records oldest first (the device pages at 50 when the query
7
+ // is absent, so the limit is forwarded per session or a talkative session replays as its last few
8
+ // seconds).
9
+ import { lastHeaderBuildFailure, unauthorizedMessageFor, } from "./radar-token.js";
10
+ export const SWITCHBOARD_KIND = "switchboard";
11
+ // Sessions replayed per backfill. Bounds the round trips (one list plus one fetch per session).
12
+ export const SWITCHBOARD_BACKFILL_SESSIONS = 3;
13
+ // The replay is two waves (list, then the sessions), so on its own it could hold a caller for two
14
+ // device timeouts. Both the dashboard's /backfill and the MCP's spool backfill race it against this
15
+ // deadline and answer with the sessions that had landed. The default matches the ring kinds' device
16
+ // timeout; the env var is there so a suite holding a fake device socket does not wait it out.
17
+ export const SWITCHBOARD_BACKFILL_DEADLINE_MS = Number(process.env.SLACK_RADAR_SWITCHBOARD_BACKFILL_DEADLINE_MS) || 4000;
18
+ export function switchboardListPath() {
19
+ return `/api/${SWITCHBOARD_KIND}`;
20
+ }
21
+ // The record kinds the plugin emits, the closed set a `kind` query may name. Shared so the path
22
+ // builder below takes the type and never sees raw input.
23
+ export const SWITCHBOARD_KINDS = ["session", "state", "frame", "phase", "player", "levels", "turn", "saved_turn"];
24
+ // beforeId asks for records with id < beforeId. An older device ignores it and repeats the newest
25
+ // page; walkSwitchboardExportPages detects that.
26
+ export function switchboardSessionPath(sessionId, limit, kind, beforeId) {
27
+ return `/api/${SWITCHBOARD_KIND}/${sessionId}?limit=${limit}${kind ? `&kind=${kind}` : ""}${beforeId !== undefined ? `&before_id=${beforeId}` : ""}`;
28
+ }
29
+ // The session ids to replay from a list response: newest first by the session's own start time,
30
+ // the id breaking a tie (minted in order), then the first SWITCHBOARD_BACKFILL_SESSIONS. The
31
+ // list's order is the device's to choose, so the pick does not lean on it, and the id alone is
32
+ // not the key: the counter restarts with the app process, so a restarted id 1 can be the newest
33
+ // session. A session id goes into a path, so only a non-negative safe integer counts as one (7.5,
34
+ // -1 and 1e21 are not ids the device minted). Anything else yields [].
35
+ export function newestSwitchboardSessionIds(list) {
36
+ const sessions = Array.isArray(list?.sessions)
37
+ ? list.sessions
38
+ : [];
39
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
40
+ const id = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : null);
41
+ return sessions
42
+ .map((s) => {
43
+ const row = (s !== null && typeof s === "object" ? s : {});
44
+ return { id: id(row.session_id), began: num(row.began_at) ?? 0 };
45
+ })
46
+ .filter((s) => s.id !== null)
47
+ .sort((a, b) => b.began - a.began || b.id - a.id)
48
+ .map((s) => s.id)
49
+ .slice(0, SWITCHBOARD_BACKFILL_SESSIONS);
50
+ }
51
+ // The `events` page of a session response, only its object rows. Anything else yields [].
52
+ export function switchboardPageEvents(session) {
53
+ const events = session?.events;
54
+ if (!Array.isArray(events))
55
+ return [];
56
+ return events.filter((e) => e !== null && typeof e === "object");
57
+ }
58
+ // A number or a digit string, since some callers pass args uncoerced. Shared so the MCP tool and
59
+ // the web export route accept exactly the same ids.
60
+ export function nonNegativeIntArg(v) {
61
+ let n;
62
+ if (typeof v === "number") {
63
+ n = v;
64
+ }
65
+ else if (typeof v === "string" && /^\d+$/.test(v.trim())) {
66
+ n = Number(v.trim());
67
+ }
68
+ else {
69
+ return null;
70
+ }
71
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
72
+ }
73
+ // The device's per-request cap on a session detail limit.
74
+ export const SWITCHBOARD_EXPORT_MAX_LIMIT = 2000;
75
+ // The device's per-session ring cap (docs/wire-contract.md). Eviction checks compare against
76
+ // this, not the much smaller page cap.
77
+ export const SWITCHBOARD_DEVICE_RING_CAP = 10000;
78
+ // 25 pages at the per-page limit is 50000 records, matching the host copy's per-session bound.
79
+ export const SWITCHBOARD_EXPORT_MAX_PAGES = 25;
80
+ // Larger than the model-context budget other tools enforce, since an export goes to a file, never
81
+ // the model. Bounds the walk's total across all pages, not one page.
82
+ export const SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES = 32 * 1024 * 1024;
83
+ // Idle catches a device that goes quiet mid-reply; overall catches one that trickles bytes forever.
84
+ export const SWITCHBOARD_EXPORT_IDLE_MS = 10000;
85
+ export const SWITCHBOARD_EXPORT_OVERALL_MS = 60000;
86
+ // Caps the whole walk: a device trickling each page just under OVERALL_MS could otherwise hold an
87
+ // export open for about MAX_PAGES x OVERALL_MS.
88
+ export const SWITCHBOARD_EXPORT_WALK_DEADLINE_MS = 3 * 60 * 1000;
89
+ export function switchboardWalkStopNote(reason, refused, again) {
90
+ switch (reason) {
91
+ case "done":
92
+ return null;
93
+ case "byte-cap":
94
+ return `the export stopped at the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap; the oldest records are not in this file.`;
95
+ case "max-pages":
96
+ return "the export stopped at the page limit; the oldest records are not in this file.";
97
+ case "old-device":
98
+ return "this device build is too old to send older records, so only the newest records are here.";
99
+ case "not-found-mid-walk":
100
+ return "the device dropped this session partway through the export; older records are not in this file.";
101
+ case "request-failed":
102
+ return "the device stopped answering partway through the export; older records are not in this file.";
103
+ case "unauthorized-mid-walk":
104
+ return `${refused} partway through the export; older records are not in this file, ${again}.`;
105
+ case "walk-deadline":
106
+ // Not request-failed wording: the device answered, just too slowly.
107
+ return `the export stopped at its ${SWITCHBOARD_EXPORT_WALK_DEADLINE_MS / (60 * 1000)} minute time limit; older records are not in this file.`;
108
+ }
109
+ }
110
+ // Ids restart with the app process but climb strictly within one session, which the walk relies on.
111
+ function eventId(e) {
112
+ const v = e.id;
113
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
114
+ }
115
+ // Safe integers only, like nextBeforeIdOf, so the fallback never builds a before_id from a non-id.
116
+ function minEventId(events) {
117
+ let min = null;
118
+ for (const e of events) {
119
+ const v = e.id;
120
+ if (typeof v === "number" && Number.isSafeInteger(v) && (min === null || v < min))
121
+ min = v;
122
+ }
123
+ return min;
124
+ }
125
+ // Without res.bytes the wire size is unknown, so re-serializing the body is the best estimate.
126
+ function responseBytes(res) {
127
+ if (typeof res.bytes === "number" && Number.isFinite(res.bytes))
128
+ return res.bytes;
129
+ return Buffer.byteLength(JSON.stringify(res.body), "utf8");
130
+ }
131
+ // null: nothing older. undefined: absent (older device) or invalid, so the walk uses heuristics
132
+ // rather than trusting a cursor it cannot verify.
133
+ function nextBeforeIdOf(body) {
134
+ if (!Object.hasOwn(body, "next_before_id"))
135
+ return undefined;
136
+ const v = body.next_before_id;
137
+ if (v === null)
138
+ return null;
139
+ return typeof v === "number" && Number.isSafeInteger(v) ? v : undefined;
140
+ }
141
+ /**
142
+ * Page backwards from an already-fetched first page with before_id. Uses the device's
143
+ * next_before_id when it names one; otherwise falls back to the page's oldest id, stopping on a
144
+ * short page or no progress (an old device re-answering the same page).
145
+ */
146
+ export async function walkSwitchboardExportPages(sessionId, get, firstPageBody, firstPageBytes, limit = SWITCHBOARD_EXPORT_MAX_LIMIT, byteCap = SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, maxPages = SWITCHBOARD_EXPORT_MAX_PAGES, walkDeadlineMs = SWITCHBOARD_EXPORT_WALK_DEADLINE_MS) {
147
+ const walkStartedAt = Date.now();
148
+ // Passed into every get, so one slow page cannot overrun it between the per-page checks.
149
+ const deadline = walkStartedAt + walkDeadlineMs;
150
+ const byId = new Map();
151
+ const noId = [];
152
+ const addPage = (events) => {
153
+ for (const e of events) {
154
+ const id = eventId(e);
155
+ if (id === null)
156
+ noId.push(e);
157
+ else
158
+ byId.set(id, e);
159
+ }
160
+ };
161
+ const firstEvents = switchboardPageEvents(firstPageBody);
162
+ addPage(firstEvents);
163
+ let bytes = firstPageBytes;
164
+ let pages = 1;
165
+ let nextBeforeId = nextBeforeIdOf(firstPageBody);
166
+ // Read only while nextBeforeId stays undefined.
167
+ let fallbackCursor = minEventId(firstEvents);
168
+ let lastPageLength = firstEvents.length;
169
+ let stopReason = "done";
170
+ while (true) {
171
+ // End-of-ring checks come before the caps, so a finished walk never reports a cap it never hit.
172
+ if (nextBeforeId === null)
173
+ break;
174
+ let cursor;
175
+ if (typeof nextBeforeId === "number") {
176
+ cursor = nextBeforeId;
177
+ }
178
+ else {
179
+ if (fallbackCursor === null || lastPageLength < limit)
180
+ break;
181
+ cursor = fallbackCursor;
182
+ }
183
+ if (bytes >= byteCap) {
184
+ stopReason = "byte-cap";
185
+ break;
186
+ }
187
+ if (pages >= maxPages) {
188
+ stopReason = "max-pages";
189
+ break;
190
+ }
191
+ if (Date.now() >= deadline) {
192
+ stopReason = "walk-deadline";
193
+ break;
194
+ }
195
+ // Only the room left under the cap, so one late page cannot read a full cap's worth.
196
+ const res = await get(switchboardSessionPath(sessionId, limit, undefined, cursor), byteCap - bytes, deadline);
197
+ // Stop but keep what already landed.
198
+ if (res.status === 401) {
199
+ stopReason = "unauthorized-mid-walk";
200
+ break;
201
+ }
202
+ if (res.status === 404) {
203
+ stopReason = "not-found-mid-walk";
204
+ break;
205
+ }
206
+ // A status 0 after the deadline is our own cutoff, not the device going quiet.
207
+ if (res.status === 0) {
208
+ stopReason = res.capped ? "byte-cap" : Date.now() >= deadline ? "walk-deadline" : "request-failed";
209
+ break;
210
+ }
211
+ if (res.status !== 200 || res.body === null || !Array.isArray(res.body.events)) {
212
+ stopReason = "request-failed";
213
+ break;
214
+ }
215
+ const events = switchboardPageEvents(res.body);
216
+ bytes += responseBytes(res);
217
+ if (typeof nextBeforeId === "number") {
218
+ if (events.length === 0)
219
+ break;
220
+ addPage(events);
221
+ pages++;
222
+ lastPageLength = events.length;
223
+ // Dropping the field after naming it once breaks the device's contract, not a clean finish.
224
+ const nb = nextBeforeIdOf(res.body);
225
+ if (nb === undefined) {
226
+ stopReason = "request-failed";
227
+ break;
228
+ }
229
+ // A cursor that fails to move backward means the device names it but does not honor it.
230
+ if (nb !== null && nb >= cursor) {
231
+ stopReason = "request-failed";
232
+ break;
233
+ }
234
+ nextBeforeId = nb;
235
+ }
236
+ else {
237
+ const pageMin = minEventId(events);
238
+ if (events.length === 0 || pageMin === null)
239
+ break;
240
+ // No progress: the device ignored before_id and repeated the page.
241
+ if (pageMin >= cursor) {
242
+ stopReason = "old-device";
243
+ break;
244
+ }
245
+ addPage(events);
246
+ pages++;
247
+ lastPageLength = events.length;
248
+ fallbackCursor = pageMin;
249
+ }
250
+ }
251
+ const events = [...byId.values()].sort((a, b) => (eventId(a) ?? 0) - (eventId(b) ?? 0));
252
+ return { events: [...events, ...noId], pages, bytes, stopReason };
253
+ }
254
+ /**
255
+ * Resolve the session (the given id, or the newest listed) and walk its device pages. The
256
+ * returned events are the device's contribution only; host records merge in separately. deadline
257
+ * covers the whole export, list request included.
258
+ */
259
+ export async function resolveSwitchboardExport(requestedId, get, deadline = Date.now() + SWITCHBOARD_EXPORT_WALK_DEADLINE_MS) {
260
+ let sessionId = requestedId;
261
+ if (sessionId === null) {
262
+ const list = await get(switchboardListPath(), undefined, deadline);
263
+ // A capped read means the device answered and we stopped reading, so not "unreachable".
264
+ if (list.status === 0)
265
+ return { ok: false, reason: list.capped ? "bad-response" : "unreachable" };
266
+ if (list.status === 401)
267
+ return { ok: false, reason: "unauthorized" };
268
+ // An unreadable list must not claim "zero sessions".
269
+ if (list.status !== 200 || list.body === null || !Array.isArray(list.body.sessions))
270
+ return { ok: false, reason: "bad-response" };
271
+ const newest = newestSwitchboardSessionIds(list.body)[0];
272
+ if (newest === undefined)
273
+ return { ok: false, reason: "no-sessions" };
274
+ sessionId = newest;
275
+ }
276
+ const first = await get(switchboardSessionPath(sessionId, SWITCHBOARD_EXPORT_MAX_LIMIT), undefined, deadline);
277
+ if (first.status === 401)
278
+ return { ok: false, reason: "unauthorized", sessionId };
279
+ if (first.status === 404)
280
+ return { ok: false, reason: "not-found", sessionId };
281
+ // Keeping the id lets a caller still try a host-only fallback.
282
+ if (first.status === 0)
283
+ return first.capped ? { ok: false, reason: "bad-response", sessionId } : { ok: false, reason: "unreachable", sessionId };
284
+ if (first.status !== 200 || first.body === null || !Array.isArray(first.body.events)) {
285
+ return { ok: false, reason: "bad-response" };
286
+ }
287
+ const firstBytes = responseBytes(first);
288
+ // What is left of the same deadline, not a fresh budget.
289
+ const walked = await walkSwitchboardExportPages(sessionId, get, first.body, firstBytes, SWITCHBOARD_EXPORT_MAX_LIMIT, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_MAX_PAGES, Math.max(0, deadline - Date.now()));
290
+ return {
291
+ ok: true,
292
+ sessionId,
293
+ detail: { ...first.body, events: walked.events },
294
+ devicePages: walked.pages,
295
+ deviceBytes: walked.bytes,
296
+ stopReason: walked.stopReason,
297
+ };
298
+ }
299
+ /**
300
+ * Merge device records with the host's streamed copy. The device wins on a shared id; the host
301
+ * copy is only a backstop for evicted records. hostOnlyCount counts only host records below the
302
+ * device's lowest id, since one above it may have streamed in during the walk.
303
+ */
304
+ export function mergeSwitchboardRecords(deviceEvents, hostEvents, beganAt = null) {
305
+ const byId = new Map();
306
+ const noId = [];
307
+ let deviceMinId = null;
308
+ for (const e of deviceEvents) {
309
+ const id = eventId(e);
310
+ if (id === null)
311
+ noId.push(e);
312
+ else {
313
+ byId.set(id, e);
314
+ if (deviceMinId === null || id < deviceMinId)
315
+ deviceMinId = id;
316
+ }
317
+ }
318
+ const hasBeganAt = typeof beganAt === "number" && Number.isFinite(beganAt);
319
+ let hostOnlyCount = 0;
320
+ // All of them, not just the edge: a hole can sit inside the recovered stretch.
321
+ const hostIdsBelowDeviceMin = [];
322
+ // Used for gapCount when the device returned zero events and so has no range to bound against.
323
+ const hostIdsKept = [];
324
+ for (const e of hostEvents) {
325
+ const id = eventId(e);
326
+ if (id === null)
327
+ continue;
328
+ if (hasBeganAt) {
329
+ // Drops an earlier process's records that reuse this session id. This can also drop real
330
+ // records when began_at is late, a rarer misfire than the cross-call leak it prevents.
331
+ const ts = e.timestamp;
332
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts < beganAt)
333
+ continue;
334
+ }
335
+ hostIdsKept.push(id);
336
+ if (deviceMinId !== null && id < deviceMinId)
337
+ hostIdsBelowDeviceMin.push(id);
338
+ if (byId.has(id))
339
+ continue;
340
+ byId.set(id, e);
341
+ if (deviceMinId === null || id < deviceMinId)
342
+ hostOnlyCount++;
343
+ }
344
+ const events = [...byId.values()].sort((a, b) => (eventId(a) ?? 0) - (eventId(b) ?? 0));
345
+ // Appending deviceMinId counts the gap up to the device's range in the same pass.
346
+ const gapCount = deviceMinId !== null ? (hostIdsBelowDeviceMin.length > 0 ? idGapSum([...hostIdsBelowDeviceMin, deviceMinId]) : 0) : idGapSum(hostIdsKept);
347
+ return { events: [...events, ...noId], hostOnlyCount, gapCount };
348
+ }
349
+ function idGapSum(ids) {
350
+ const sorted = [...ids].sort((a, b) => a - b);
351
+ let gap = 0;
352
+ for (let i = 1; i < sorted.length; i++) {
353
+ const diff = sorted[i] - sorted[i - 1] - 1;
354
+ if (diff > 0)
355
+ gap += diff;
356
+ }
357
+ return gap;
358
+ }
359
+ // Like mergeSwitchboardRecords's gapCount (also an upper bound), with no device range to anchor to.
360
+ export function hostOnlyGapCount(records) {
361
+ const ids = records.map((e) => eventId(e)).filter((id) => id !== null);
362
+ return idGapSum(ids);
363
+ }
364
+ /**
365
+ * A session detail built only from host records. Anything no record evidences stays unknown
366
+ * rather than guessed. Keeps only records from the last session begin onward as a backstop, so
367
+ * two calls never mix even if the host store missed a reset.
368
+ */
369
+ export function hostOnlySwitchboardDetail(sessionId, hostRecords) {
370
+ let lastBeginIndex = -1;
371
+ for (let i = 0; i < hostRecords.length; i++) {
372
+ const e = hostRecords[i];
373
+ if (e && typeof e === "object" && e.kind === "session" && e.event === "begin")
374
+ lastBeginIndex = i;
375
+ }
376
+ const records = lastBeginIndex >= 0 ? hostRecords.slice(lastBeginIndex) : hostRecords;
377
+ const first = records[0];
378
+ const beganAt = first && typeof first === "object" && first.kind === "session" && first.event === "begin" && typeof first.timestamp === "number" && Number.isFinite(first.timestamp)
379
+ ? first.timestamp
380
+ : null;
381
+ let teamId = null;
382
+ let serverSessionId = null;
383
+ let endedAt = null;
384
+ for (const e of records) {
385
+ if (teamId === null && typeof e.team_id === "string")
386
+ teamId = e.team_id;
387
+ if (serverSessionId === null && e.kind === "session" && e.event === "ready" && typeof e.server_session_id === "string")
388
+ serverSessionId = e.server_session_id;
389
+ if (endedAt === null && e.kind === "session" && e.event === "end" && typeof e.timestamp === "number" && Number.isFinite(e.timestamp))
390
+ endedAt = e.timestamp;
391
+ }
392
+ const detail = {
393
+ session_id: sessionId,
394
+ team_id: teamId,
395
+ began_at: beganAt,
396
+ ended_at: endedAt,
397
+ total_captured: null,
398
+ frames: {},
399
+ events: records,
400
+ };
401
+ if (serverSessionId !== null)
402
+ detail.server_session_id = serverSessionId;
403
+ return detail;
404
+ }
405
+ export function oldestSwitchboardTimestamp(events) {
406
+ let min = null;
407
+ for (const e of events) {
408
+ const ts = e.timestamp;
409
+ if (typeof ts === "number" && Number.isFinite(ts) && (min === null || ts < min))
410
+ min = ts;
411
+ }
412
+ return min;
413
+ }
414
+ /**
415
+ * The whole export flow, shared by the MCP tool and the web route so fallbacks and error wording
416
+ * cannot drift. getHostRecords is injected to avoid a circular import with
417
+ * switchboard-host-store.ts.
418
+ */
419
+ export async function assembleSwitchboardExport(requestedId, get, getHostRecords,
420
+ // Consulted only when no id was given and the device never resolved one.
421
+ getNewestHostSessionId, sender, surface = "mcp") {
422
+ const outcome = await resolveSwitchboardExport(requestedId, get);
423
+ // Read after the walk: the header is built per request, and a token file that failed to read
424
+ // sent no token at all, so the report must not blame a token the device never saw.
425
+ const sentToken = sender?.sendsRadarToken === true && lastHeaderBuildFailure() === null;
426
+ if (!outcome.ok) {
427
+ // The host may still hold streamed records for a session the device could not serve.
428
+ const resolvedSessionId = outcome.reason === "not-found" || outcome.reason === "unreachable" || outcome.reason === "bad-response" || outcome.reason === "unauthorized" ? outcome.sessionId : undefined;
429
+ // Guess the newest host session only when there was never an id. Not for "bad-response": it
430
+ // may be a capped list, and guessing a stale session would be worse than erroring.
431
+ const fallbackSessionId = (outcome.reason === "unreachable" || outcome.reason === "no-sessions" || outcome.reason === "unauthorized") && resolvedSessionId === undefined
432
+ ? getNewestHostSessionId?.() ?? undefined
433
+ : undefined;
434
+ const sessionIdToTry = resolvedSessionId ?? fallbackSessionId;
435
+ if ((outcome.reason === "not-found" || outcome.reason === "unreachable" || outcome.reason === "bad-response" || outcome.reason === "no-sessions" || outcome.reason === "unauthorized") && sessionIdToTry !== undefined) {
436
+ const hostRecords = getHostRecords(sessionIdToTry);
437
+ if (hostRecords.length > 0) {
438
+ const detail = hostOnlySwitchboardDetail(sessionIdToTry, hostRecords);
439
+ // Count the trimmed detail.events, not hostRecords, so the report never overclaims.
440
+ const heldEvents = Array.isArray(detail.events) ? detail.events : [];
441
+ return {
442
+ ok: true,
443
+ sendsToken: sentToken,
444
+ surface,
445
+ sessionId: sessionIdToTry,
446
+ detail,
447
+ hostStreamCount: heldEvents.length,
448
+ deviceEventCount: null,
449
+ deviceOldestTimestamp: null,
450
+ // Here bad-response can only be a capped detail GET; no-sessions makes the same claim as not-found.
451
+ hostOnlyCause: outcome.reason === "bad-response" ? "too-large" : outcome.reason === "no-sessions" ? "not-found" : outcome.reason,
452
+ walkStopReason: null,
453
+ gapCount: hostOnlyGapCount(heldEvents),
454
+ };
455
+ }
456
+ }
457
+ // A bad-response with a sessionId can only be the capped DETAIL GET.
458
+ const message = outcome.reason === "unauthorized"
459
+ ? unauthorizedMessageFor(sender, surface)
460
+ : outcome.reason === "no-sessions"
461
+ ? "No switchboard sessions held on the device."
462
+ : outcome.reason === "not-found"
463
+ ? `No switchboard session ${outcome.sessionId} on the device (unknown id, or the device already dropped it).`
464
+ : outcome.reason === "unreachable"
465
+ ? "Device unreachable. Is Radar armed?"
466
+ : outcome.reason === "bad-response" && outcome.sessionId !== undefined
467
+ ? `The device reply was too large to read (over the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap), and this process holds no live stream copy of the call.`
468
+ : "The device answered, but not with anything this export could use.";
469
+ return { ok: false, reason: outcome.reason, sessionId: outcome.reason === "not-found" || outcome.reason === "unreachable" || outcome.reason === "unauthorized" ? outcome.sessionId : undefined, message };
470
+ }
471
+ const deviceEvents = Array.isArray(outcome.detail.events) ? outcome.detail.events : [];
472
+ const beganAt = typeof outcome.detail.began_at === "number" ? outcome.detail.began_at : null;
473
+ const merge = mergeSwitchboardRecords(deviceEvents, getHostRecords(outcome.sessionId), beganAt);
474
+ return {
475
+ ok: true,
476
+ sendsToken: sentToken,
477
+ surface,
478
+ sessionId: outcome.sessionId,
479
+ detail: { ...outcome.detail, events: merge.events },
480
+ hostStreamCount: merge.hostOnlyCount,
481
+ deviceEventCount: deviceEvents.length,
482
+ deviceOldestTimestamp: oldestSwitchboardTimestamp(deviceEvents),
483
+ hostOnlyCause: null,
484
+ walkStopReason: outcome.stopReason,
485
+ gapCount: merge.gapCount,
486
+ };
487
+ }