@slack/radar-mcp 1.24.0 → 1.26.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 (51) hide show
  1. package/README.md +41 -4
  2. package/dist/mcp/dispatch.d.ts +1 -0
  3. package/dist/mcp/dispatch.js +4 -2
  4. package/dist/mcp/flags-tools.d.ts +1 -0
  5. package/dist/mcp/flags-tools.js +3 -9
  6. package/dist/mcp/index.js +16 -40
  7. package/dist/mcp/json-rows.d.ts +6 -0
  8. package/dist/mcp/json-rows.js +10 -0
  9. package/dist/mcp/radar-response.d.ts +2 -2
  10. package/dist/mcp/radar-response.js +2 -2
  11. package/dist/mcp/redact.d.ts +14 -0
  12. package/dist/mcp/redact.js +71 -0
  13. package/dist/mcp/session-enable.d.ts +1 -0
  14. package/dist/mcp/session-enable.js +8 -6
  15. package/dist/mcp/snapshot-cli.d.ts +52 -0
  16. package/dist/mcp/snapshot-cli.js +316 -0
  17. package/dist/mcp/snapshot-summary.d.ts +1 -0
  18. package/dist/mcp/snapshot-summary.js +254 -0
  19. package/dist/mcp/snapshot.d.ts +32 -3
  20. package/dist/mcp/snapshot.js +347 -102
  21. package/dist/mcp/tools.js +11 -7
  22. package/dist/shared/android.d.ts +25 -0
  23. package/dist/shared/android.js +97 -0
  24. package/dist/shared/feature-flags.d.ts +20 -0
  25. package/dist/shared/feature-flags.js +35 -4
  26. package/dist/shared/radar-token.d.ts +5 -5
  27. package/dist/shared/radar-token.js +24 -10
  28. package/dist/shared/switchboard-note.d.ts +19 -0
  29. package/dist/shared/switchboard-note.js +76 -0
  30. package/dist/shared/switchboard-report.js +43 -4
  31. package/dist/shared/switchboard.d.ts +1 -1
  32. package/dist/shared/switchboard.js +14 -2
  33. package/dist/shared/transport.d.ts +18 -0
  34. package/dist/shared/wire.d.ts +2 -0
  35. package/dist/web/install-app-cli.d.ts +2 -0
  36. package/dist/web/install-app-cli.js +60 -0
  37. package/dist/web/install-app.d.ts +16 -7
  38. package/dist/web/install-app.js +92 -39
  39. package/dist/web/macapp/RadarApp.swift +12 -11
  40. package/dist/web/public/index.html +5 -2
  41. package/dist/web/public/next/feature-flags.js +50 -0
  42. package/dist/web/public/next/feed.js +15 -4
  43. package/dist/web/public/next/flags.js +17 -3
  44. package/dist/web/public/next/registry.js +4 -4
  45. package/dist/web/public/next/store.js +90 -4
  46. package/dist/web/public/next/switchboard-note.js +76 -0
  47. package/dist/web/public/next/voice-model.js +209 -15
  48. package/dist/web/public/next/voice.js +73 -10
  49. package/dist/web/spec.d.ts +1 -1
  50. package/dist/web/spec.js +1 -1
  51. package/package.json +1 -1
package/README.md CHANGED
@@ -145,7 +145,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
145
145
  | `get_recent_traces` | Performance trace/span summaries: trace name, span name, duration. Filterable by name substring. |
146
146
  | `get_trace_detail` | Full trace/span detail for a specific trace, including tags. |
147
147
  | `get_switchboard_sessions` | Slackbot voice (switchboard) sessions the device still holds, newest first: `session_id`, `team_id`, `began_at`, `ended_at`, record and frame counts, the newest state and audio levels, `server_session_id` (the server's own name for the session, null until it names one; absent on an older build), `turns` (turn count, the newest response time and its clock, null before the first turn; absent on an older build), and `saved_turn_counts` (saved turns per outcome; absent on an older build means not counted, not zero). Ids restart with the app process. |
148
- | `get_switchboard_session` | One voice session's summary plus its records, oldest first: `state` transitions, control frames (`frame`) in and out, `player` stutter events, `phase` startup timings, `session` begin/end/ready (`ready` carries `server_session_id`), `levels` (batched mic/playback meter ticks), `turn` (one timed voice turn: `response_ms` and `clock`), and `saved_turn` (whether a spoken turn got saved to the DM: `outcome` (`applied`, `no_line`, `missing_field`, `other_session`) and `has_thread`; the summary's `saved_turn_counts` counts each outcome, and absent on an older device build means not counted, not zero). Narrow with `kind`; `limit` is how many of the newest records come back (default 50, max 2000 per request; the device may hold more, paged with before_id), filtered by kind first, so a kind page is the newest `limit` records of that kind. |
148
+ | `get_switchboard_session` | One voice session's summary plus its records, oldest first: `state` transitions, control frames (`frame`) in and out, `player` stutter events, `phase` startup timings, `session` begin/end/ready (`ready` carries `server_session_id`), `levels` (batched mic/playback meter ticks), `turn` (one timed voice turn: `response_ms` and `clock`), and `saved_turn` (whether a spoken turn got saved to the DM: `outcome` (`applied`, `no_line`, `missing_field`, `other_session`) and `has_thread`; the summary's `saved_turn_counts` counts each outcome, and absent on an older device build means not counted, not zero). Narrow with `kind`; `limit` is how many of the newest records come back (default 50, max 2000 per request; the device may hold more, paged with before_id), filtered by kind first, so a kind page is the newest `limit` records of that kind. `reconnect_try` (one voice reconnect try: `trigger` (`restart`, `drop`, `settings`), `try` and `outcome` (`ready`, `retry`, `refused`, `gave_up`)); a Reconnecting state's cause is its trigger, and the summary's `server_session_ids` lists every ready id. `card` (one move of a voice card the server is waiting on: `card_kind`, `event`, `by`, `card_id`; a card shown or carried with no later record was still up at the session's last record). |
149
149
  | `export_switchboard_session` | Write one voice session's summary and its records to a plain-text report under `~/.slack-radar/exports/`, permissions 0700/0600 like `capture_snapshot`. Pages the device, then merges in the live stream copy; the export can stop early (for example an old build, the 32 MB size cap, the page limit, or the device stopping answering), and the report notes say why anything is missing. An unknown id (404, unreachable, or too large to read) errors unless this process streamed the call live, then the report comes from the live stream copy alone, whichever process ran the export, since this MCP server and the web dashboard each keep their own. Defaults to newest when `id` is omitted; returns the file path and a summary. |
150
150
  | `wait_for_events` | Block until matching events arrive via SSE stream. Idle-timeout based, not polling. |
151
151
  | `search` | Full-text search across network, RTM, clog, and trace buffers. |
@@ -153,7 +153,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
153
153
  | `get_recent_logs` | Recent device logs, optionally filtered by tag (omit `tag` for all lines). Android reads the app's own debug buffer first, falling back to logcat (`app_buffer` / `logcat_capture` / `logcat_ring`); iOS Simulator reads a bounded live unified-log capture. The result's `source` identifies which one served it. |
154
154
  | `list_profiles` | List the Android users and profiles on the device (personal, work, and so on). |
155
155
  | `activate_for_user` | Activate radar for a specific Android user or profile. |
156
- | `capture_snapshot` | Bundle the current network, RTM, clog, and trace buffers, plus an optional screenshot, into one saved snapshot for a bug report or repro. Switchboard voice records are not included. |
156
+ | `capture_snapshot` | Bundle the current network, RTM, clog, and trace buffers, feature flags, voice-session summaries, details of failed network calls, and device and app facts, plus an optional screenshot, into one saved snapshot for a bug report or repro. `summary.md` is the short digest to read first. Auth headers, cookies and token-shaped strings are blanked by default (best effort); `redact=false` keeps them raw. |
157
157
  | `screenshot` | Capture device screen as PNG. 720px default, `full_res=true` for full resolution. |
158
158
  | `record_screen` | Record short screen video (MP4). Default 5s, max 30s. |
159
159
  | `list_databases` | List the app's on-device SQLite databases. Read-only. |
@@ -162,7 +162,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
162
162
  | `list_prefs` | List the app's on-device SharedPreferences files. Read-only. |
163
163
  | `get_prefs` | Read a preferences file's keys and values, optionally filtered to specific keys. |
164
164
  | `search_prefs` | Search preference keys and values across every file by a substring. |
165
- | `list_feature_flags` | List every feature flag with its latest effective value and override status; toggle rows also carry `session_enabled`, the flag's own value fixed for this session. Optionally filtered to just the overridden ones. Boolean toggles carry `enabled`; multi-variant experiments carry `type: "experiment"` and a `group_name` string (the effective variant, e.g. `"treatment_a"`) instead. |
165
+ | `list_feature_flags` | List every feature flag with its latest effective value and override status; toggle rows also carry `session_enabled`, the flag's own value the app runs now: the first-read value for a flag already read this session, or the value a read returns now for one not yet read. Optionally filtered to just the overridden ones. Experiment rows also carry `session_group_name` (`""` is no group, absent is not known). Boolean toggles carry `enabled`; multi-variant experiments carry `type: "experiment"` and a `group_name` string (the effective variant, e.g. `"treatment_a"`) instead. |
166
166
  | `search_feature_flags` | Case-insensitive substring search on feature flag names, against the same live list as `list_feature_flags`. Rows carry the same `type`/`group_name` fields for experiments. |
167
167
  | `get_feature_flag` | Look up one feature flag by its exact key. Returns one row per scope (authenticated/unauthenticated) and per signed-in org, since each workspace resolves its own value; pass `org_id` to narrow to one workspace. An experiment row carries `type: "experiment"` and its `group_name` variant rather than a boolean `enabled`. |
168
168
  | `run_test_case` | Replay a built-in or hand-written case. Pass `case`, optional `repeat` and `rate_per_second` (null for burst). Requires a debug build serving `test_runs`. |
@@ -259,6 +259,41 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
259
259
  * **Keep-alive is not forgeable from a web page.** Only the dashboard's own client and the MCP can postpone auto-close. A write to `/setspec` or `/enable` has to carry `X-Radar-Dashboard: 1`, or a content-type whose type is exactly `application/json`; the `/health` presence ping requires the header specifically, since a content-type says nothing about a request with no body. A cross-origin request cannot set either one without a CORS preflight it will fail. A request without either still works and still writes, it just does not extend the process lifetime, so `curl -X POST .../setspec -H 'Content-Type: text/plain'` sets the spec but will not stop the dashboard closing on schedule; use `-H 'Content-Type: application/json'` if you want it to count. This is a CSRF guard, not authentication: any local process can send either header, and the port is loopback-only by design.
260
260
  * **Loopback `Host` only.** The dashboard answers a request only when its `Host` header names this machine (`localhost`, `127.0.0.1`, `[::1]`, `0.0.0.0`, with or without a port). Anything else gets a 403 whose body names the host it refused and how to allow it. Binding to 127.0.0.1 alone is not enough: a page that resolves its own domain to 127.0.0.1 connects locally, counts as same-origin in the browser, and could otherwise set the header above and stop your dashboard. If you reach the dashboard by some other name — a `/etc/hosts` alias, a container or Codespaces forwarded URL, your machine's LAN hostname — list it in `SLACK_RADAR_ALLOWED_HOSTS` (comma-separated, host or `host:port`). A plain SSH or VS Code port forward needs nothing, because the `Host` stays `localhost`.
261
261
 
262
+ ## Headless snapshot
263
+
264
+ `radar-mcp snapshot` saves the same snapshot as `capture_snapshot` without an MCP client, for a test run or CI job. It is Android only (it needs adb and a debug build on a device or emulator); iOS and the webapp are not supported. It arms Radar on the device, writes the bundle and prints one JSON line (path, `zip_path`, `summary_path`, counts, `run_window`, `redacted`, `warnings`, `errors`, `privacy_notice`). Everything else goes to stderr.
265
+
266
+ ```sh
267
+ # when the run starts: remember the device clock
268
+ radar-mcp snapshot --start --serial emulator-5554
269
+
270
+ # ... run the test ...
271
+
272
+ # when it ends: bundle only what happened since the start
273
+ radar-mcp snapshot --serial emulator-5554 --out /tmp/run-1
274
+ ```
275
+
276
+ | Flag | What it does |
277
+ |---|---|
278
+ | `--serial <id>` | Device to use. Needed when more than one is attached. |
279
+ | `--out <dir>` | Where to write the snapshot. Default `~/.slack-radar/snapshots`. A directory you pass is never chmodded. |
280
+ | `--start` | Only records the start of the run (`~/.slack-radar/snapshot-starts/<serial>.json`, mode 0600) and prints `since_ms`. Cannot be combined with `--since`, `--out` or `--detail-url`. |
281
+ | `--since <epoch-ms>` | Keep events from this time on. This is the **device clock**, the same clock as the `since_ms` that `--start` prints, not the host clock. Beats the start marker. |
282
+ | `--detail-url <text>` | Also keep the headers and bodies of calls whose URL contains this text, even when they succeeded (repeatable). Failed calls are always kept. |
283
+ | `--timeout-minutes <n>` | 1 to 1440, default 60. Radar turns itself off after this long with no call, and turning Radar off, or on again, empties the network, RTM and voice-session buffers, so set it longer than your run. |
284
+ | `--no-redact` | Keep tokens and auth headers as the device sent them. |
285
+
286
+ Without a start marker (or `--since`) the snapshot holds the whole buffers. A marker is deleted once its snapshot is written. If Radar restarted during the run, or the marker is more than 24 hours old, the `errors` list says so.
287
+
288
+ Exit codes: `0` when `bundle.json` and `summary.md` were written (a missing zip tool is an `errors` line and a null `zip_path`), `1` when the device could not be picked, Radar would not start or the bundle was not written, `2` for bad usage. `--help` prints the usage on stdout and exits `0`.
289
+
290
+ Redaction blanks the value of `Authorization`, `Cookie` and `Set-Cookie` headers and of any header whose name contains token, secret, password, cookie, auth, session or signature. Inside text, bodies and the log it blanks `Bearer` values, `xox?-` tokens, and `name=value` or JSON string pairs whose name matches that list; other fields are not blanked by name. This covers the bundle, the log and `summary.md`, not `screenshot.png`. It is pattern matching and best effort; `auth` also hits `author`, a blank too many being the safe side.
291
+
292
+ On a shared host:
293
+
294
+ * Parallel emulators each need their own `SLACK_RADAR_DEVICE_PORT`, since the forwarded port is per host.
295
+ * The Radar token is one per OS user, not per run, and Radar stays on until its idle timeout after the end snapshot.
296
+
262
297
  ## Data Capture
263
298
 
264
299
  What gets captured depends on the in-app server implementation. The MCP server is agnostic to the data source. The Android implementation captures:
@@ -270,7 +305,9 @@ What gets captured depends on the in-app server implementation. The MCP server i
270
305
  * **Test runs**: Made-up RTM replay frames sent to the app's handler. The device keeps the last ten run summaries, with settled counts and per-type timings.
271
306
  * **SQLite database** (Database tab, web dashboard only): when you open a database, a read-only **plaintext** copy of that on-device store (message text, request/response bodies, user/channel/team IDs) is pulled to a temp directory **on your own machine** (`os.tmpdir()/slack-radar-db-<port>`, files mode 0600). Auto-deleted when the dashboard process stops.
272
307
  * **SharedPreferences** (`list_prefs`/`get_prefs`/`search_prefs`, and the Preferences tab): read directly off the device over `adb`, no local copy written. Files can contain feature flag overrides, cached team/org/channel IDs, and other app state.
273
- * **Feature flags** (`list_feature_flags`/`search_feature_flags`/`get_feature_flag`): read directly off the device over `adb`, no local copy written. Shows every flag's latest effective value, the flag's own value fixed for this session where the build reports it, and whether it is locally overridden.
308
+ * **Feature flags** (`list_feature_flags`/`search_feature_flags`/`get_feature_flag`): read directly off the device over `adb`, no local copy written. Shows every flag's latest effective value, the flag's own value the app runs now (the first-read value once a flag has been read this session) where the build reports it, and whether it is locally overridden.
309
+
310
+ A snapshot (`capture_snapshot`) writes `summary.md` (a short digest), `bundle.json`, the device log tail (the app's own log buffer, or logcat from every app on the device) and an optional screenshot to `~/.slack-radar/snapshots/`, mode 0700/0600. `bundle.json` holds the list buffers, feature flags, voice-session summaries, the headers and bodies (cut to 4 KB and 8 KB) of failed network calls, and device and app facts. By default it blanks the values of `Authorization`, `Cookie` and `Set-Cookie` headers and of headers whose name contains token, secret, password, cookie, auth, session or signature, plus `Bearer` values, `xox?-` tokens and `name=value` or JSON string pairs with such a name inside text and bodies, then says so in the bundle's privacy notice. `screenshot.png` is never redacted. This is pattern matching and best effort: a secret in an odd shape can slip through, and `auth` also blanks `author`, a blank too many being the safe side. Pass `redact=false` for raw values, only for a bundle that stays on your machine.
274
311
 
275
312
  The network, RTM, clog, and trace captures are in-memory ring buffers. The Database tab is the exception: it writes a plaintext copy of the selected on-device database to a temp file on your host for the duration of the session. Review before sharing anything from it.
276
313
 
@@ -1,4 +1,5 @@
1
1
  export declare function computeDispatch(argv1: string | undefined, sub: string | undefined): {
2
2
  wantsInstallApp: boolean;
3
+ wantsSnapshot: boolean;
3
4
  wantsWeb: boolean;
4
5
  };
@@ -4,6 +4,7 @@
4
4
  // slack-radar -> web dashboard (the human launcher: bare = open the UI)
5
5
  // slack-radar web -> web dashboard
6
6
  // slack-radar install-app -> build the macOS dock launcher, then exit
7
+ // <any bin> snapshot -> headless snapshot, then exit (radar-mcp snapshot, slack-radar snapshot)
7
8
  // slack-radar mcp -> stdio MCP server (explicit, if a human ever needs it)
8
9
  // radar-mcp -> stdio MCP server (the name MCP hosts configure; no arg)
9
10
  // slack-radar-mcp -> stdio MCP server
@@ -21,6 +22,7 @@
21
22
  export function computeDispatch(argv1, sub) {
22
23
  const binName = (argv1 ?? "").split("/").pop() ?? "";
23
24
  const wantsInstallApp = sub === "install-app";
24
- const wantsWeb = !wantsInstallApp && (sub === "web" || (binName === "slack-radar" && sub !== "mcp"));
25
- return { wantsInstallApp, wantsWeb };
25
+ const wantsSnapshot = sub === "snapshot";
26
+ const wantsWeb = !wantsInstallApp && !wantsSnapshot && (sub === "web" || (binName === "slack-radar" && sub !== "mcp"));
27
+ return { wantsInstallApp, wantsSnapshot, wantsWeb };
26
28
  }
@@ -18,6 +18,7 @@ export interface FeatureFlagRow {
18
18
  group_name?: string;
19
19
  is_overridden?: boolean;
20
20
  session_enabled?: boolean | string;
21
+ session_group_name?: string;
21
22
  restart_note?: string;
22
23
  org_id?: string;
23
24
  timestamp?: number;
@@ -8,7 +8,7 @@
8
8
  // Flags dashboard tab filters client-side after one full fetch. A device-side fix is the real
9
9
  // fix (tracked separately); this stays the correct behavior either way once that ships, since
10
10
  // filtering an already-correct list is a no-op.
11
- import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
11
+ import { flagRestartNote, friendlyFeatureFlagError } from "../shared/feature-flags.js";
12
12
  /**
13
13
  * Shares one in-flight fetch of the flag list across the three tools (a model doing "list,
14
14
  * then search, then get" in one turn would otherwise pay a device round-trip per call).
@@ -57,18 +57,12 @@ function wellFormedRows(response) {
57
57
  .map(dropEmptyOrg)
58
58
  .map(withRestartNote);
59
59
  }
60
- // A flag the app read once keeps that value until restart, so `enabled` (latest or override) can
61
- // differ from what the app runs. Only two real booleans that differ earn a note: an absent or
62
- // non-boolean session_enabled is "not known", and saying nothing there is the honest answer.
63
60
  function withRestartNote(f) {
64
61
  // Dropped first so a device that sent its own note cannot pass it through: only this function
65
62
  // writes it, and only for a real mismatch.
66
63
  const { restart_note: _dropped, ...row } = f;
67
- const { enabled, session_enabled: session } = row;
68
- if (typeof enabled !== "boolean" || typeof session !== "boolean" || enabled === session)
69
- return row;
70
- const source = isOverridden(f) ? "override" : "fetched";
71
- return { ...row, restart_note: `app uses ${session} until restart, ${source} ${enabled}` };
64
+ const note = flagRestartNote(f);
65
+ return note === undefined ? row : { ...row, restart_note: note.note };
72
66
  }
73
67
  // An empty org id means the same thing as no org id, so it is dropped rather than treated as a
74
68
  // distinct org a caller could match or that an error message would render as a blank name. Same
package/dist/mcp/index.js CHANGED
@@ -21,7 +21,7 @@ import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStrea
21
21
  import { makeCallRadarForExport } from "./radar-export-get.js";
22
22
  import { radarRequestRaw } from "../shared/radar-request-raw.js";
23
23
  import { TokenFileError, clearRadarTokenCache, openModeWarning, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
24
- import { buildBufferPath, createSnapshot } from "./snapshot.js";
24
+ import { createSnapshot } from "./snapshot.js";
25
25
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
26
26
  import { querySession, clampByteCap, toNum } from "./session-query.js";
27
27
  import { resolveDetailById } from "./session-detail.js";
@@ -49,19 +49,7 @@ import { buildOpenDashboardResult, readDashboardFingerprint } from "./stale-dash
49
49
  // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
50
50
  // pulled out to a pure function so the bin-name/subcommand rules are unit-testable.
51
51
  const sub = process.argv[2];
52
- const { wantsInstallApp, wantsWeb } = computeDispatch(process.argv[1], sub);
53
- // The background check RadarApp.swift spawns on every dock launch (see install-app.ts's
54
- // runSelfHealCheck). A sibling of install-app, not a third dispatch branch: same subcommand,
55
- // different entry point once inside.
56
- const wantsSelfHealCheck = wantsInstallApp && process.argv.includes("--self-heal-check");
57
- // What RadarApp.swift ACTUALLY spawns now (see install-app.ts's runSelfHealPrecheck): a safe
58
- // registry-version precheck that only falls through to --self-heal-check once a real upgrade is
59
- // confirmed. Checked before wantsSelfHealCheck below so the two flags stay mutually exclusive.
60
- const wantsSelfHealPrecheck = wantsInstallApp && process.argv.includes("--self-heal-precheck");
61
- // The two interactive halves of the app's Check for Updates... item: ask whether a newer build is
62
- // published, then install it. Each prints a single JSON line for the app to read.
63
- const wantsCheckUpdate = wantsInstallApp && process.argv.includes("--check-update");
64
- const wantsUpdateNow = wantsInstallApp && process.argv.includes("--update-now");
52
+ const { wantsInstallApp, wantsSnapshot, wantsWeb } = computeDispatch(process.argv[1], sub);
65
53
  // --- Web dashboard bridge (open_radar_dashboard) ---
66
54
  //
67
55
  // The MCP server and the web dashboard are separate processes. open_radar_dashboard
@@ -217,26 +205,13 @@ async function openDashboardSpec(device, spec, armed) {
217
205
  return { ...r.json, fingerprint };
218
206
  }
219
207
  if (wantsInstallApp) {
220
- if (wantsCheckUpdate) {
221
- const { checkForUpdate } = await import("../web/install-app.js");
222
- console.log(JSON.stringify(await checkForUpdate(process.env.RADAR_APP_VERSION)));
223
- }
224
- else if (wantsUpdateNow) {
225
- const { runUpdateNow } = await import("../web/install-app.js");
226
- await runUpdateNow();
227
- }
228
- else if (wantsSelfHealPrecheck) {
229
- const { runSelfHealPrecheck } = await import("../web/install-app.js");
230
- runSelfHealPrecheck();
231
- }
232
- else if (wantsSelfHealCheck) {
233
- const { runSelfHealCheck } = await import("../web/install-app.js");
234
- runSelfHealCheck();
235
- }
236
- else {
237
- const { runInstallApp } = await import("../web/install-app.js");
238
- runInstallApp();
239
- }
208
+ const { runInstallAppCli } = await import("../web/install-app-cli.js");
209
+ await runInstallAppCli(process.argv);
210
+ }
211
+ else if (wantsSnapshot) {
212
+ // Headless: arms Radar, writes one snapshot, exits. Never reaches the MCP stdio server.
213
+ const { snapshotCliMain } = await import("./snapshot-cli.js");
214
+ await snapshotCliMain(process.argv.slice(3));
240
215
  }
241
216
  else if (wantsWeb) {
242
217
  const { startWebServer } = await import("../web/bin.js");
@@ -738,20 +713,21 @@ async function runMcpServer() {
738
713
  async function handleCaptureSnapshot(args) {
739
714
  try {
740
715
  // Adapt `callRadar` (device HTTP + retry + session gate) into the
741
- // simple `fetchBuffer(kind)` contract `createSnapshot` expects. Any
742
- // `res.error` from callRadar is rethrown so the composer's per-buffer
716
+ // simple `fetchJson(path)` contract `createSnapshot` expects. Any
717
+ // `res.error` from callRadar is rethrown so the composer's per-source
743
718
  // try/catch can record it in `errors[]` without bringing down the
744
719
  // whole snapshot.
745
- const fetchBuffer = async (kind) => {
746
- const res = await callRadar(buildBufferPath(kind));
720
+ const fetchJson = async (apiPath) => {
721
+ const res = await callRadar(apiPath);
747
722
  if (res.error)
748
723
  throw new Error(res.error);
749
724
  return res;
750
725
  };
751
- const result = await createSnapshot(device, fetchBuffer, {
726
+ const result = await createSnapshot(device, fetchJson, {
752
727
  includeLogs: args?.include_logs !== false,
753
728
  includeScreenshot: args?.include_screenshot !== false,
754
729
  logTailLines: args?.log_tail_lines,
730
+ redact: args?.redact !== false,
755
731
  });
756
732
  return textResult(result, result.errors.length > 0 && result.files.length === 0);
757
733
  }
@@ -911,7 +887,7 @@ async function runMcpServer() {
911
887
  }
912
888
  }
913
889
  // --- MCP Server ---
914
- const server = new Server({ name: "slack-radar", version: "1.24.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
890
+ const server = new Server({ name: "slack-radar", version: "1.26.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
915
891
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
916
892
  tools: TOOL_DEFINITIONS,
917
893
  }));
@@ -0,0 +1,6 @@
1
+ /** Small readers for untrusted JSON bodies from the device. */
2
+ export type Obj = Record<string, unknown>;
3
+ /** The value as a plain object, or null for anything else (arrays included). */
4
+ export declare function asObj(v: unknown): Obj | null;
5
+ /** Rows under `key` of a list envelope; [] when the body or the list is missing. */
6
+ export declare function rowsOf(body: unknown, key: string): Obj[];
@@ -0,0 +1,10 @@
1
+ /** Small readers for untrusted JSON bodies from the device. */
2
+ /** The value as a plain object, or null for anything else (arrays included). */
3
+ export function asObj(v) {
4
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
5
+ }
6
+ /** Rows under `key` of a list envelope; [] when the body or the list is missing. */
7
+ export function rowsOf(body, key) {
8
+ const b = asObj(body);
9
+ return b && Array.isArray(b[key]) ? b[key].map((r) => asObj(r) ?? {}) : [];
10
+ }
@@ -1,4 +1,4 @@
1
- import { type RadarTokenSender } from "../shared/radar-token.js";
1
+ import { type RadarTokenSender, type TokenSurface } from "../shared/radar-token.js";
2
2
  export interface RadarResponse {
3
3
  error?: string;
4
4
  status?: unknown;
@@ -22,7 +22,7 @@ export interface RadarResponse {
22
22
  * body keeps the existing {raw} behavior, a real if unusual success payload.
23
23
  */
24
24
  export declare function interpretRadarResponse(status: number, body: string): RadarResponse;
25
- export declare function unauthorizedResponse(response: RadarResponse, sender: RadarTokenSender): RadarResponse;
25
+ export declare function unauthorizedResponse(response: RadarResponse, sender: RadarTokenSender, surface?: TokenSurface): RadarResponse;
26
26
  /**
27
27
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
28
28
  * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
@@ -39,8 +39,8 @@ export function interpretRadarResponse(status, body) {
39
39
  }
40
40
  return status >= 400 ? { ...parsed, http_status: status } : parsed;
41
41
  }
42
- export function unauthorizedResponse(response, sender) {
43
- return response.http_status === 401 ? { error: unauthorizedMessageFor(sender), http_status: 401 } : response;
42
+ export function unauthorizedResponse(response, sender, surface = "mcp") {
43
+ return response.http_status === 401 ? { error: unauthorizedMessageFor(sender, surface), http_status: 401 } : response;
44
44
  }
45
45
  /**
46
46
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Best-effort blanking of secrets in snapshot bundles. Pattern based, so it can
3
+ * miss a secret in an odd shape and can blank a harmless value; a blank too many
4
+ * is the safe side.
5
+ */
6
+ /**
7
+ * Names whose value is blanked. `auth` also hits `author`; kept on purpose, since
8
+ * a wrongly blanked author is cheaper than a leaked auth value.
9
+ */
10
+ export declare const SENSITIVE_NAME: RegExp;
11
+ export declare function redactText(s: string): string;
12
+ export declare function redactHeaders(h: Record<string, unknown>): Record<string, unknown>;
13
+ /** Returns a redacted copy of a JSON value; the input is never mutated. */
14
+ export declare function redactDeep(v: unknown): unknown;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Best-effort blanking of secrets in snapshot bundles. Pattern based, so it can
3
+ * miss a secret in an odd shape and can blank a harmless value; a blank too many
4
+ * is the safe side.
5
+ */
6
+ import { asObj } from "./json-rows.js";
7
+ const REDACTED = "[redacted]";
8
+ /**
9
+ * Names whose value is blanked. `auth` also hits `author`; kept on purpose, since
10
+ * a wrongly blanked author is cheaper than a leaked auth value.
11
+ */
12
+ export const SENSITIVE_NAME = /token|secret|password|cookie|auth|session|signature/i;
13
+ const NAME_SRC = SENSITIVE_NAME.source;
14
+ // %, + / = so a URL-encoded or base64-ish token is blanked whole, not up to its first escape.
15
+ const TOKEN_RE = /xoxe\.xox[a-z]-[A-Za-z0-9%+/=-]+|xox[a-z]-[A-Za-z0-9%+/=-]+/gi;
16
+ const BEARER_RE = /\bBearer\s+[^\s"',;]+/gi;
17
+ // Capital B and a base64-looking value, so the plain word "basic" in a sentence is left alone.
18
+ // Eight fixed then `*`, not `{8,}`: a counted repeat overflows the stack past about 5 MB.
19
+ const BASIC_RE = /\bBasic\s+[A-Za-z0-9+/]{8}[A-Za-z0-9+/]*={0,2}/g;
20
+ // "name": "value" where name is sensitive; the value stays a JSON string.
21
+ const JSON_FIELD_RE = new RegExp(`("[^"\\\\]{0,128}(?:${NAME_SRC})[^"\\\\]{0,128}"\\s*:\\s*)"(?:[^"\\\\]|\\\\.)*"`, "gi");
22
+ // name=value in a query or form body; value runs to & or whitespace or quote. The match starts
23
+ // at the sensitive word itself (what comes before it stays untouched) and the part after it is
24
+ // bounded, so a long unbroken run is never rescanned from every position, and a long dotted key
25
+ // ending in token= still gets its value blanked.
26
+ const PAIR_RE = new RegExp(`((?:${NAME_SRC})[A-Za-z0-9_.\\-\\[\\]]{0,64}=)[^&\\s"'<>]*`, "gi");
27
+ const SENSITIVE_HEADERS = new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
28
+ export function redactText(s) {
29
+ // Bearer first: in `Authorization=Bearer abc` the pair rule would stop at the space and leave
30
+ // the real value behind.
31
+ return s
32
+ .replace(JSON_FIELD_RE, `$1"${REDACTED}"`)
33
+ .replace(BEARER_RE, `Bearer ${REDACTED}`)
34
+ .replace(BASIC_RE, `Basic ${REDACTED}`)
35
+ .replace(PAIR_RE, `$1${REDACTED}`)
36
+ .replace(TOKEN_RE, REDACTED);
37
+ }
38
+ export function redactHeaders(h) {
39
+ const out = {};
40
+ for (const [name, value] of Object.entries(h)) {
41
+ if (SENSITIVE_HEADERS.has(name.toLowerCase()) || SENSITIVE_NAME.test(name)) {
42
+ out[name] = REDACTED;
43
+ }
44
+ else {
45
+ out[name] = redactDeep(value);
46
+ }
47
+ }
48
+ return out;
49
+ }
50
+ /** Returns a redacted copy of a JSON value; the input is never mutated. */
51
+ export function redactDeep(v) {
52
+ if (typeof v === "string")
53
+ return redactText(v);
54
+ if (Array.isArray(v))
55
+ return v.map(redactDeep);
56
+ const o = asObj(v);
57
+ if (o) {
58
+ const out = {};
59
+ for (const [k, val] of Object.entries(o)) {
60
+ const headers = asObj(val);
61
+ if ((k === "request_headers" || k === "response_headers") && headers) {
62
+ out[k] = redactHeaders(headers);
63
+ }
64
+ else {
65
+ out[k] = redactDeep(val);
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+ return v;
71
+ }
@@ -11,6 +11,7 @@ export interface EnableDeps {
11
11
  runBackfill: () => Promise<unknown>;
12
12
  ping: () => Promise<Record<string, unknown>>;
13
13
  sleep: (ms: number) => Promise<void>;
14
+ surface?: "mcp" | "cli";
14
15
  onDeviceSwitch: () => void;
15
16
  onForeignOwnerAfterBackfill?: () => void;
16
17
  }
@@ -176,7 +176,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
176
176
  return outcome;
177
177
  }
178
178
  async function enableSession(timeoutMinutes, deviceSerial, deps) {
179
- const { device, destroyStream, connectStream, isStreamConnected, wasStreamRejected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
179
+ const { device, destroyStream, connectStream, isStreamConnected, wasStreamRejected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, surface = "mcp", } = deps;
180
180
  // Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
181
181
  // transport state so this enable starts clean. Without the reset, a stale adb
182
182
  // forward (device end dead after an idle timeout or a replug) makes ensureForward()
@@ -200,7 +200,9 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
200
200
  enabled: false,
201
201
  body: {
202
202
  // The transport error is a neutral core; the MCP body appends agent-facing retry guidance.
203
- error: `${selection.error} Retry _radar_session_enable with device_serial set to one of them. If you cannot tell which device the user wants, ask them before retrying.`,
203
+ error: surface === "cli"
204
+ ? selection.error
205
+ : `${selection.error} Retry _radar_session_enable with device_serial set to one of them. If you cannot tell which device the user wants, ask them before retrying.`,
204
206
  devices: selection.devices,
205
207
  enabled: false,
206
208
  platform: device.platform,
@@ -267,7 +269,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
267
269
  if (tokenFileError) {
268
270
  return {
269
271
  enabled: false,
270
- body: { error: tokenFileMessage(tokenFileError, "mcp"), enabled: false, platform: device.platform },
272
+ body: { error: tokenFileMessage(tokenFileError, surface), enabled: false, platform: device.platform },
271
273
  };
272
274
  }
273
275
  const activateError = device.getLastActivateError?.() ?? null;
@@ -309,7 +311,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
309
311
  enabled: false,
310
312
  body: {
311
313
  error: device.getLastActivateBareError?.() ? activateError : error instanceof PingRefused
312
- ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
314
+ ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device, surface)}`
313
315
  : device.radarListenerHint
314
316
  ? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
315
317
  : `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
@@ -383,7 +385,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
383
385
  return {
384
386
  enabled: false,
385
387
  body: {
386
- error: unauthorizedMessageFor(device),
388
+ error: unauthorizedMessageFor(device, surface),
387
389
  enabled: false,
388
390
  platform: device.platform,
389
391
  ...tokenViaArgvField(device),
@@ -417,7 +419,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
417
419
  else if (!isStreamConnected())
418
420
  connectStream();
419
421
  // A tokened enable that stays open did not take, so name its broadcast failure.
420
- const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
422
+ const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError, surface);
421
423
  return {
422
424
  enabled: true,
423
425
  body: {
@@ -0,0 +1,52 @@
1
+ import type { DeviceTransport } from "../shared/transport.js";
2
+ import { type RadarResponse } from "./radar-response.js";
3
+ import { type EnableOutcome } from "./session-enable.js";
4
+ import { type SnapshotOptions, type SnapshotResult } from "./snapshot.js";
5
+ export declare const SNAPSHOT_USAGE = "Usage: radar-mcp snapshot [options]\n\nSave a Radar snapshot without an MCP client. Run it with --start when a test run\nbegins and without --start when it ends.\n\nAndroid only: it needs adb and a debug build on a device or emulator. Other platforms are\nnot supported.\n\nOptions:\n --serial <id> Device to use (default: the only attached device)\n --out <dir> Directory to write the snapshot under (default: ~/.slack-radar/snapshots)\n --start Only record the start of a run; no snapshot is written\n --since <epoch-ms> Keep events from this time on. Device clock, the same clock as the\n since_ms that --start prints. Beats the start marker\n --detail-url <text> Also keep the details of calls whose URL contains this text\n (repeatable); failed calls are always kept\n --timeout-minutes <n> How long Radar stays on with no calls, 1-1440 (default 60)\n --no-redact Keep tokens and auth headers as the device sent them\n --help Show this text\n\nPrints one JSON line on stdout. Exit codes: 0 done, 1 failed, 2 bad usage.\n";
6
+ export interface SnapshotCliArgs {
7
+ serial: string | null;
8
+ out: string | null;
9
+ start: boolean;
10
+ since: number | null;
11
+ detailUrls: string[];
12
+ timeoutMinutes: number;
13
+ redact: boolean;
14
+ }
15
+ export type ParsedSnapshotArgs = {
16
+ kind: "run";
17
+ args: SnapshotCliArgs;
18
+ } | {
19
+ kind: "help";
20
+ } | {
21
+ kind: "usage";
22
+ message: string;
23
+ };
24
+ export declare function parseSnapshotArgs(argv: string[]): ParsedSnapshotArgs;
25
+ /** Serial reduced to characters that are safe in a file name. */
26
+ export declare function markerFileName(serial: string | null): string;
27
+ export declare function markerPath(homeDir: string, serial: string | null): string;
28
+ export declare function writeStartMarker(homeDir: string, serial: string | null, sinceMs: number): string;
29
+ export declare function readStartMarker(homeDir: string, serial: string | null): {
30
+ since_ms: number;
31
+ ageMs: number;
32
+ file: string;
33
+ } | null;
34
+ export interface SnapshotCliDeps {
35
+ device: DeviceTransport;
36
+ enable: (timeoutMinutes: number, serial: string | null) => Promise<EnableOutcome>;
37
+ fetchJson: (path: string) => Promise<unknown>;
38
+ snapshot: (device: DeviceTransport, fetchJson: (path: string) => Promise<unknown>, opts: SnapshotOptions, now: number, root?: string) => Promise<SnapshotResult>;
39
+ now: () => number;
40
+ homeDir: string;
41
+ stdout: (text: string) => void;
42
+ stderr: (text: string) => void;
43
+ }
44
+ /**
45
+ * GET helper for the snapshot reads. The forwarded port is host-wide and a dashboard or another
46
+ * run can repoint it, so it is pointed at this device again before every read.
47
+ */
48
+ export declare function cliFetchJson(device: DeviceTransport, send: (apiPath: string) => Promise<RadarResponse>): (apiPath: string) => Promise<unknown>;
49
+ /** Runs the command and returns the exit code. Prints exactly one JSON line for exit 0 and 1. */
50
+ export declare function runSnapshotCli(argv: string[], deps?: SnapshotCliDeps): Promise<number>;
51
+ /** Entry for index.ts: run, then exit so no adb child keeps the process alive. */
52
+ export declare function snapshotCliMain(argv: string[]): Promise<never>;