@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
@@ -1,26 +1,27 @@
1
1
  /**
2
- * Session-long host-side logcat capture for the web dashboard.
2
+ * Session-long host-side log capture for the web dashboard.
3
3
  *
4
- * The device does not buffer logcat for us (the on-device radar server captures
5
- * network/RTM/clog into ring buffers, but logcat is a host-side `adb logcat`
6
- * stream with no replayable device buffer). So when a browser switches dashboard
7
- * tabs, the SSE `/stream` connection is torn down and reopened, and anything that
8
- * used to drive logcat off the per-connection lifecycle would lose every line
9
- * emitted while no stream was attached — the user sees their log count shrink on
10
- * a tab switch.
4
+ * The device does not buffer host logs for us (the on-device radar server captures
5
+ * network/RTM/clog into ring buffers, but device logs come from a host-side child,
6
+ * `adb logcat` on Android or `simctl spawn … log stream` on the iOS Simulator, with no
7
+ * replayable device buffer). So when a browser switches dashboard tabs, the SSE
8
+ * `/stream` connection is torn down and reopened, and anything that used to drive
9
+ * the capture off the per-connection lifecycle would lose every line emitted while
10
+ * no stream was attached — the user sees their log count shrink on a tab switch.
11
11
  *
12
- * This module fixes that the way Android Studio does: ONE logcat process per
12
+ * This module fixes that the way Android Studio does: ONE capture process per
13
13
  * device for the whole server session, feeding a bounded session ring buffer.
14
14
  * Each `/stream` connection subscribes as a listener and is first replayed the
15
15
  * entire retained buffer, then receives live lines. Switching tabs only
16
16
  * adds/removes a listener; the underlying capture and its history are untouched.
17
17
  *
18
18
  * The class takes its spawn and parse functions by injection so it is unit
19
- * testable without spawning a real `adb logcat` (the integration path is covered
20
- * by the smoke test on a real device).
19
+ * testable without spawning a real capture child, and so each platform supplies
20
+ * its own command and line format (the integration path is covered by the smoke
21
+ * test on a real device).
21
22
  */
22
23
  import type { ChildProcess } from "child_process";
23
- /** A parsed logcat frame, as delivered to the dashboard over SSE. */
24
+ /** A parsed host log frame (logcat or unified log), as delivered to the dashboard over SSE. */
24
25
  export interface LogFrame {
25
26
  id: number;
26
27
  timestamp: number;
@@ -31,37 +32,47 @@ export interface LogFrame {
31
32
  tag: string;
32
33
  message: string;
33
34
  package?: string;
35
+ subsystem?: string;
36
+ process?: string;
34
37
  }
35
- /** Spawn a process producing logcat lines on stdout. Injectable for tests. */
36
- export type SpawnLogcat = () => ChildProcess;
37
- /** Parse one raw logcat line into a frame, or null if it is not a log line. */
38
- export type ParseLine = (line: string) => LogFrame | null;
39
- /** Receives one frame. `replay` is true for buffered history, false for live. */
40
- export type LogListener = (frame: LogFrame, replay: boolean) => void;
38
+ type SpawnStream = () => ChildProcess;
39
+ type ParseLine = (line: string) => LogFrame | null;
40
+ type LogListener = (frame: LogFrame, replay: boolean) => void;
41
+ type LogStatusListener = (running: boolean, failure?: string) => void;
41
42
  /**
42
- * A single session-long logcat capture with a bounded ring buffer and listener
43
- * fan-out. One instance is shared across every dashboard stream connection.
43
+ * A session-long capture with listener fan-out. New subscribers receive retained
44
+ * history first, then live frames.
44
45
  */
45
46
  export declare class LogSession {
46
- private readonly spawnLogcat;
47
+ private readonly spawnStream;
47
48
  private readonly parseLine;
48
49
  private readonly cap;
49
50
  private child;
50
51
  private lineBuf;
52
+ private decoder;
51
53
  private readonly ring;
54
+ private readonly frameBytes;
55
+ private retainedBytes;
52
56
  private readonly listeners;
57
+ private readonly statusListeners;
53
58
  private cleanupRegistered;
54
- constructor(spawnLogcat: SpawnLogcat, parseLine: ParseLine, cap?: number);
55
- /** True while a logcat child is running. */
59
+ private lastFailure;
60
+ private restartTimer;
61
+ private restartDelayMs;
62
+ constructor(spawnStream: SpawnStream, parseLine: ParseLine, cap?: number);
63
+ /** True while the capture child is running. */
56
64
  isRunning(): boolean;
57
65
  /** Number of frames currently retained (for tests / diagnostics). */
58
66
  bufferSize(): number;
59
67
  /** Number of attached stream listeners (for tests / diagnostics). */
60
68
  listenerCount(): number;
69
+ /** Return and clear the most recent unexpected spawn/error/exit failure. */
70
+ takeLastFailure(): string | null;
71
+ recent(tag: string, limit: number, grep?: string): LogFrame[];
61
72
  /**
62
73
  * Start the capture if it is not already running. Idempotent: a second call
63
74
  * while a child is alive is a no-op, so concurrent tab opens cannot fan out
64
- * duplicate logcat processes. Returns true if a capture is running after the
75
+ * duplicate capture processes. Returns true if a capture is running after the
65
76
  * call (already-running counts as success), false if the spawn failed.
66
77
  */
67
78
  start(): boolean;
@@ -75,18 +86,16 @@ export declare class LogSession {
75
86
  * valid and should survive) -- but a switch to DIFFERENT hardware means every
76
87
  * retained frame belongs to the wrong device, and replaying them into a freshly
77
88
  * opened /stream on the new device would show device A's logs mislabeled as
78
- * device B's. The caller (handleEnable's switched branch) is responsible for
79
- * calling armLogcat() / start() again afterward if a log tab is active; this
80
- * method only tears down, matching stop()'s existing division of labor.
89
+ * device B's. The caller is responsible for calling start() again afterward if
90
+ * a log tab is active; this method only tears down.
81
91
  */
82
92
  restart(): void;
83
93
  /**
84
- * Install process-exit handlers (once) so the persistent `adb logcat` child is
94
+ * Install process-exit handlers (once) so the persistent capture child is
85
95
  * killed when the server process exits. Without this, the capture orphans when
86
96
  * the server is terminated by signal — notably when `open_radar_dashboard`
87
- * spawns the dashboard as a child and later kills it by PID — and orphaned adb
88
- * logcat readers accumulate across dashboard open/close cycles, holding the
89
- * device's logcat stream. Mirrors logcat-capture.ts's registerCleanup().
97
+ * spawns the dashboard as a child and later kills it by PID — and orphaned
98
+ * capture readers accumulate across dashboard open/close cycles.
90
99
  */
91
100
  registerCleanup(): void;
92
101
  /**
@@ -96,7 +105,12 @@ export declare class LogSession {
96
105
  * function; call it when the stream closes (this does NOT stop the capture).
97
106
  */
98
107
  subscribe(listener: LogListener): () => void;
108
+ /** Observe capture availability without consuming takeLastFailure(). */
109
+ subscribeStatus(listener: LogStatusListener): () => void;
99
110
  private onChildGone;
111
+ private scheduleRestart;
112
+ private notifyStatus;
100
113
  private onData;
101
114
  private push;
102
115
  }
116
+ export {};
@@ -0,0 +1,300 @@
1
+ import { StringDecoder } from "node:string_decoder";
2
+ import { MAX_LOG_FRAME_BYTES, MAX_LOG_SESSION_BUFFER, MAX_LOG_SESSION_BYTES, } from "./constants.js";
3
+ const RESTART_DELAY_MIN_MS = 250;
4
+ const RESTART_DELAY_MAX_MS = 10_000;
5
+ // Approximate the JSON payload size without allocating and serializing a second copy
6
+ // of every high-volume log frame. The fixed allowance covers keys, punctuation, and
7
+ // numeric fields; string payloads dominate and are measured exactly in UTF-8 bytes.
8
+ function estimateFrameBytes(frame) {
9
+ let bytes = 96;
10
+ for (const value of [
11
+ frame.log_ts,
12
+ frame.level,
13
+ frame.tag,
14
+ frame.message,
15
+ frame.package,
16
+ frame.subsystem,
17
+ frame.process,
18
+ ]) {
19
+ if (value)
20
+ bytes += Buffer.byteLength(value);
21
+ }
22
+ return bytes;
23
+ }
24
+ /**
25
+ * A session-long capture with listener fan-out. New subscribers receive retained
26
+ * history first, then live frames.
27
+ */
28
+ export class LogSession {
29
+ spawnStream;
30
+ parseLine;
31
+ cap;
32
+ child = null;
33
+ lineBuf = "";
34
+ decoder = new StringDecoder("utf8");
35
+ ring = [];
36
+ frameBytes = [];
37
+ retainedBytes = 0;
38
+ listeners = new Set();
39
+ statusListeners = new Set();
40
+ cleanupRegistered = false;
41
+ lastFailure = null;
42
+ restartTimer = null;
43
+ restartDelayMs = RESTART_DELAY_MIN_MS;
44
+ constructor(spawnStream, parseLine, cap = MAX_LOG_SESSION_BUFFER) {
45
+ this.spawnStream = spawnStream;
46
+ this.parseLine = parseLine;
47
+ this.cap = cap > 0 ? cap : MAX_LOG_SESSION_BUFFER;
48
+ }
49
+ /** True while the capture child is running. */
50
+ isRunning() {
51
+ return this.child !== null;
52
+ }
53
+ /** Number of frames currently retained (for tests / diagnostics). */
54
+ bufferSize() {
55
+ return this.ring.length;
56
+ }
57
+ /** Number of attached stream listeners (for tests / diagnostics). */
58
+ listenerCount() {
59
+ return this.listeners.size;
60
+ }
61
+ /** Return and clear the most recent unexpected spawn/error/exit failure. */
62
+ takeLastFailure() {
63
+ const failure = this.lastFailure;
64
+ this.lastFailure = null;
65
+ return failure;
66
+ }
67
+ recent(tag, limit, grep) {
68
+ const found = [];
69
+ const count = Number.isFinite(limit) ? Math.min(1000, Math.max(1, Math.floor(limit))) : 50;
70
+ const needle = grep?.toLowerCase();
71
+ for (let i = this.ring.length - 1; i >= 0 && found.length < count; i--) {
72
+ const frame = this.ring[i];
73
+ if (tag && !frame.tag.includes(tag))
74
+ continue;
75
+ if (needle && ![
76
+ frame.message, frame.tag, frame.subsystem, frame.process, frame.level,
77
+ frame.log_ts, frame.pid, frame.tid, frame.package,
78
+ ].join(" ").toLowerCase().includes(needle))
79
+ continue;
80
+ found.push(frame);
81
+ }
82
+ return found.reverse();
83
+ }
84
+ /**
85
+ * Start the capture if it is not already running. Idempotent: a second call
86
+ * while a child is alive is a no-op, so concurrent tab opens cannot fan out
87
+ * duplicate capture processes. Returns true if a capture is running after the
88
+ * call (already-running counts as success), false if the spawn failed.
89
+ */
90
+ start() {
91
+ if (this.child)
92
+ return true;
93
+ let child;
94
+ try {
95
+ child = this.spawnStream();
96
+ }
97
+ catch (error) {
98
+ this.lastFailure = `could not start (${error instanceof Error ? error.message : String(error)})`;
99
+ this.notifyStatus(false, this.lastFailure);
100
+ this.scheduleRestart();
101
+ return false;
102
+ }
103
+ this.lastFailure = null;
104
+ this.child = child;
105
+ this.lineBuf = "";
106
+ this.decoder = new StringDecoder("utf8");
107
+ // A background diagnostic child must not keep the host process alive on its
108
+ // own. The listening dashboard socket is what holds the event loop open in
109
+ // production; when that closes (a test, or a clean shutdown) node should be
110
+ // free to exit even if a log capture is still running. registerCleanup
111
+ // still kills the child on exit, so unref only removes the loop-blocking ref.
112
+ child.unref?.();
113
+ child.stdout?.on("data", (c) => {
114
+ if (this.child === child)
115
+ this.onData(c);
116
+ });
117
+ // A crashed/killed capture (device unplugged, adb server restart, Simulator shutdown) clears the
118
+ // child so the next connect() can restart it. The retained ring survives so
119
+ // history is not lost across a transient device drop.
120
+ child.on("error", (error) => {
121
+ this.onChildGone(child, `process error: ${error.message}`);
122
+ });
123
+ child.on("exit", (code, signal) => {
124
+ const reason = signal
125
+ ? `process exited from signal ${signal}`
126
+ : `process exited with code ${code ?? "unknown"}`;
127
+ this.onChildGone(child, reason);
128
+ });
129
+ this.notifyStatus(true);
130
+ return true;
131
+ }
132
+ /** Stop the capture and drop the child. The ring buffer is preserved. */
133
+ stop() {
134
+ if (this.restartTimer) {
135
+ clearTimeout(this.restartTimer);
136
+ this.restartTimer = null;
137
+ }
138
+ const child = this.child;
139
+ this.child = null;
140
+ this.lineBuf = "";
141
+ if (child) {
142
+ try {
143
+ child.kill();
144
+ }
145
+ catch {
146
+ // already dead
147
+ }
148
+ }
149
+ }
150
+ /**
151
+ * Stop the capture AND drop the retained ring, for when the underlying device
152
+ * actually changed (PR #94 multi-device switch), not just dropped transiently.
153
+ * stop() alone preserves the ring by design (a transient adb-server hiccup or
154
+ * device unplug/replug is the SAME device coming back, so its history is still
155
+ * valid and should survive) -- but a switch to DIFFERENT hardware means every
156
+ * retained frame belongs to the wrong device, and replaying them into a freshly
157
+ * opened /stream on the new device would show device A's logs mislabeled as
158
+ * device B's. The caller is responsible for calling start() again afterward if
159
+ * a log tab is active; this method only tears down.
160
+ */
161
+ restart() {
162
+ this.stop();
163
+ this.ring.length = 0;
164
+ this.frameBytes.length = 0;
165
+ this.retainedBytes = 0;
166
+ }
167
+ /**
168
+ * Install process-exit handlers (once) so the persistent capture child is
169
+ * killed when the server process exits. Without this, the capture orphans when
170
+ * the server is terminated by signal — notably when `open_radar_dashboard`
171
+ * spawns the dashboard as a child and later kills it by PID — and orphaned
172
+ * capture readers accumulate across dashboard open/close cycles.
173
+ */
174
+ registerCleanup() {
175
+ if (this.cleanupRegistered)
176
+ return;
177
+ this.cleanupRegistered = true;
178
+ process.on("exit", () => this.stop());
179
+ process.on("SIGINT", () => {
180
+ this.stop();
181
+ process.exit(130);
182
+ });
183
+ process.on("SIGTERM", () => {
184
+ this.stop();
185
+ process.exit(143);
186
+ });
187
+ }
188
+ /**
189
+ * Subscribe a stream to the session. The listener is FIRST replayed the entire
190
+ * retained ring (replay=true) so a freshly opened tab shows full history, then
191
+ * receives every subsequent live frame (replay=false). Returns an unsubscribe
192
+ * function; call it when the stream closes (this does NOT stop the capture).
193
+ */
194
+ subscribe(listener) {
195
+ // Replay a snapshot of the current ring. Snapshot first so a frame arriving
196
+ // mid-replay is not delivered twice (once via replay, once live).
197
+ const snapshot = this.ring.slice();
198
+ for (const frame of snapshot)
199
+ listener(frame, true);
200
+ this.listeners.add(listener);
201
+ if (!this.child)
202
+ this.scheduleRestart(0);
203
+ return () => {
204
+ this.listeners.delete(listener);
205
+ if (this.listeners.size === 0 && this.restartTimer) {
206
+ clearTimeout(this.restartTimer);
207
+ this.restartTimer = null;
208
+ }
209
+ };
210
+ }
211
+ /** Observe capture availability without consuming takeLastFailure(). */
212
+ subscribeStatus(listener) {
213
+ this.statusListeners.add(listener);
214
+ if (this.child)
215
+ listener(true);
216
+ else if (this.lastFailure)
217
+ listener(false, this.lastFailure);
218
+ return () => {
219
+ this.statusListeners.delete(listener);
220
+ };
221
+ }
222
+ onChildGone(child, failure) {
223
+ // Guard against a late event from an already-replaced child.
224
+ if (this.child === child) {
225
+ this.child = null;
226
+ this.lineBuf = "";
227
+ this.lastFailure = failure;
228
+ this.notifyStatus(false, failure);
229
+ this.scheduleRestart();
230
+ }
231
+ }
232
+ scheduleRestart(delayMs = this.restartDelayMs) {
233
+ if (this.restartTimer || this.child || this.listeners.size === 0)
234
+ return;
235
+ const delay = Math.max(0, delayMs);
236
+ if (delay > 0) {
237
+ this.restartDelayMs = Math.min(RESTART_DELAY_MAX_MS, Math.max(RESTART_DELAY_MIN_MS, this.restartDelayMs * 2));
238
+ }
239
+ this.restartTimer = setTimeout(() => {
240
+ this.restartTimer = null;
241
+ if (this.listeners.size > 0 && !this.child)
242
+ this.start();
243
+ }, delay);
244
+ this.restartTimer.unref?.();
245
+ }
246
+ notifyStatus(running, failure) {
247
+ for (const listener of this.statusListeners) {
248
+ try {
249
+ listener(running, failure);
250
+ }
251
+ catch {
252
+ // Status reporting must never interfere with capture recovery.
253
+ }
254
+ }
255
+ }
256
+ onData(chunk) {
257
+ this.lineBuf += this.decoder.write(chunk);
258
+ if (this.lineBuf.length > MAX_LOG_FRAME_BYTES && !this.lineBuf.includes("\n")) {
259
+ this.lineBuf = "";
260
+ return;
261
+ }
262
+ let nl;
263
+ while ((nl = this.lineBuf.indexOf("\n")) >= 0) {
264
+ const line = this.lineBuf.slice(0, nl);
265
+ this.lineBuf = this.lineBuf.slice(nl + 1);
266
+ const frame = this.parseLine(line);
267
+ if (!frame)
268
+ continue;
269
+ // Only a line that parses proves the replacement capture is healthy, so only
270
+ // that resets the retry backoff. Raw output is not enough: logcat's
271
+ // "--------- beginning of main" separator and the unified log's preamble
272
+ // both arrive before a child that is about to die, and resetting on those
273
+ // would respawn a failing capture every 250 ms forever.
274
+ this.restartDelayMs = RESTART_DELAY_MIN_MS;
275
+ this.push(frame);
276
+ }
277
+ }
278
+ push(frame) {
279
+ const bytes = estimateFrameBytes(frame);
280
+ if (bytes > MAX_LOG_FRAME_BYTES)
281
+ return;
282
+ this.ring.push(frame);
283
+ this.frameBytes.push(bytes);
284
+ this.retainedBytes += bytes;
285
+ while (this.ring.length > this.cap || this.retainedBytes > MAX_LOG_SESSION_BYTES) {
286
+ this.ring.shift();
287
+ this.retainedBytes -= this.frameBytes.shift();
288
+ }
289
+ for (const listener of this.listeners) {
290
+ // A throwing listener (e.g. a closed response) must not kill the capture
291
+ // or starve the other listeners.
292
+ try {
293
+ listener(frame, false);
294
+ }
295
+ catch {
296
+ // best-effort fan-out
297
+ }
298
+ }
299
+ }
300
+ }
@@ -0,0 +1,7 @@
1
+ import { type RadarTokenSender, type TokenSurface } from "./radar-token.js";
2
+ export declare function radarRequestRaw(host: string, port: number, requestPath: string, idleMs: number, overallMs: number, capBytes: number, deadline: number | undefined, transport: RadarTokenSender, surface?: TokenSurface): Promise<{
3
+ status: number;
4
+ body: Record<string, unknown> | null;
5
+ bytes: number;
6
+ capped?: boolean;
7
+ }>;
@@ -0,0 +1,89 @@
1
+ // The export path's raw device GET, in its own module so a test can import it and point it at a
2
+ // fake server via host/port.
3
+ //
4
+ // The export report goes to a file, never the model context, so it skips radarRequest's byte
5
+ // budget and uses the generous SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES instead. Never rejects: a
6
+ // network error, timeout, non-JSON, or over-cap body resolves with status 0.
7
+ //
8
+ // deadline is the whole export's absolute wall-clock cutoff (epoch ms); overallMs shrinks to fit
9
+ // it, so callers need not recompute the budget themselves.
10
+ import http from "http";
11
+ import { radarTokenHeaderFor } from "./radar-token.js";
12
+ export function radarRequestRaw(host, port, requestPath, idleMs, overallMs, capBytes, deadline,
13
+ // Required so every caller decides whether the token goes out.
14
+ transport, surface = "mcp") {
15
+ // A past deadline still fires asynchronously; a caller that wants to skip the request entirely
16
+ // checks the deadline itself.
17
+ const effectiveOverallMs = deadline === undefined ? overallMs : Math.max(0, Math.min(overallMs, deadline - Date.now()));
18
+ return new Promise((resolve) => {
19
+ let settled = false;
20
+ let idleTimer;
21
+ let overallTimer;
22
+ const done = (r) => {
23
+ if (settled)
24
+ return;
25
+ settled = true;
26
+ clearTimeout(idleTimer);
27
+ clearTimeout(overallTimer);
28
+ resolve(r);
29
+ };
30
+ // http.get can throw synchronously (a bad port, an unescaped path), caught below so the
31
+ // promise never rejects and no timer arms against an unassigned req.
32
+ let req;
33
+ const armIdle = () => {
34
+ clearTimeout(idleTimer);
35
+ idleTimer = setTimeout(() => {
36
+ req.destroy();
37
+ done({ status: 0, body: null, bytes: 0 });
38
+ }, idleMs);
39
+ };
40
+ try {
41
+ req = http.get({ host, port, path: requestPath, headers: radarTokenHeaderFor(transport, surface) }, (res) => {
42
+ // Decode once at the end: a multi-byte UTF-8 character can split across chunks.
43
+ const chunks = [];
44
+ let bytes = 0;
45
+ armIdle();
46
+ res.on("data", (chunk) => {
47
+ if (settled)
48
+ return;
49
+ armIdle();
50
+ bytes += chunk.length;
51
+ if (bytes > capBytes) {
52
+ // capped tells a deliberate cap abort apart from a network failure of the same shape.
53
+ done({ status: 0, body: null, bytes: 0, capped: true });
54
+ req.destroy();
55
+ return;
56
+ }
57
+ chunks.push(chunk);
58
+ });
59
+ // A socket closing mid-body raises this and never "end"; without it the request hangs.
60
+ res.on("error", () => done({ status: 0, body: null, bytes: 0 }));
61
+ res.on("end", () => {
62
+ try {
63
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
64
+ done({
65
+ status: res.statusCode ?? 0,
66
+ body: parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null,
67
+ bytes,
68
+ });
69
+ }
70
+ catch {
71
+ done({ status: res.statusCode ?? 0, body: null, bytes });
72
+ }
73
+ });
74
+ });
75
+ }
76
+ catch {
77
+ done({ status: 0, body: null, bytes: 0 });
78
+ return;
79
+ }
80
+ // Armed before headers too, so a device that accepts and never answers trips the idle limit.
81
+ armIdle();
82
+ // The idle timer resets on every byte, so only this fixed limit catches a steady trickle.
83
+ overallTimer = setTimeout(() => {
84
+ req.destroy();
85
+ done({ status: 0, body: null, bytes: 0 });
86
+ }, effectiveOverallMs);
87
+ req.on("error", () => done({ status: 0, body: null, bytes: 0 }));
88
+ });
89
+ }
@@ -0,0 +1,25 @@
1
+ import type { DeviceTransport } from "./transport.js";
2
+ export declare const RADAR_TOKEN_HEADER = "X-Radar-Token";
3
+ export type TokenSurface = "mcp" | "dashboard";
4
+ export type TokenFileSurface = TokenSurface | "profile";
5
+ export declare class TokenFileError extends Error {
6
+ readonly problem: string;
7
+ readonly fix: string;
8
+ constructor(problem: string, fix: string);
9
+ }
10
+ export declare function tokenFileMessage(error: Pick<TokenFileError, "problem" | "fix">, surface?: TokenFileSurface): string;
11
+ export declare function getOrCreateRadarToken(): string;
12
+ export declare function clearRadarTokenCache(): void;
13
+ export declare function radarTokenHeader(): Record<string, string>;
14
+ export type RadarTokenSender = Pick<DeviceTransport, "sendsRadarToken"> | null | undefined;
15
+ export declare const TOKEN_MISMATCH_MESSAGE = "The device holds a different token than this session's. Check these, then run /radar-enable here. Another machine or OS user enabled Radar on this device: stop that session. Radar was enabled in a different profile: make sure the Slack debug build runs in the profile you want (list_profiles shows which profiles have it). Another Radar session on this machine still uses a token file you deleted: run /radar-enable there too.";
16
+ export declare const TOKEN_MISMATCH_DASHBOARD_MESSAGE = "This device answered to a different Radar token. Stop any other Radar session using it, or run /radar-enable there if you deleted the token file, then press Reconnect.";
17
+ export declare const DEVICE_401_MESSAGE = "The device refused the request (HTTP 401). Run /radar-enable to try again.";
18
+ export declare const DEVICE_401_DASHBOARD_MESSAGE = "The device refused the request (HTTP 401). Press Reconnect to try again.";
19
+ export declare function lastHeaderBuildFailure(): TokenFileError | null;
20
+ export declare function unauthorizedMessageFor(sender: RadarTokenSender, surface?: TokenSurface): string;
21
+ export declare function radarTokenHeaderFor(transport: RadarTokenSender, surface?: TokenSurface): Record<string, string>;
22
+ export declare const OPEN_MODE_WARNING = "The device is in open mode, so anything that reaches the forwarded port can read and change its Radar data. An older Radar MCP or dashboard, or a manual enable broadcast, turned the token check off. If an older Radar MCP or dashboard is still running, stop it, then run /radar-enable.";
23
+ export declare const OPEN_MODE_PROFILE_WARNING = "The device is in open mode even though this enable sent the token, so the broadcast did not reach the server that answered: it likely runs in a different profile and was enabled without a token. Anything that reaches the forwarded port can read and change its Radar data. Run list_profiles, then activate_for_user for the profile you want, or stop the older Radar MCP or dashboard that enabled it.";
24
+ export declare function openModeWarning(tokenRequired: unknown): string | undefined;
25
+ export declare function openModeWarningAfterEnable(tokenRequired: unknown, activateError: string | null): string | undefined;