@slack/radar-mcp 1.25.0 → 1.27.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 (63) hide show
  1. package/README.md +47 -3
  2. package/dist/mcp/api-paths.d.ts +25 -1
  3. package/dist/mcp/api-paths.js +85 -9
  4. package/dist/mcp/dispatch.d.ts +1 -0
  5. package/dist/mcp/dispatch.js +4 -2
  6. package/dist/mcp/flags-tools.d.ts +1 -0
  7. package/dist/mcp/flags-tools.js +1 -1
  8. package/dist/mcp/index.js +36 -11
  9. package/dist/mcp/json-rows.d.ts +6 -0
  10. package/dist/mcp/json-rows.js +10 -0
  11. package/dist/mcp/radar-response.d.ts +2 -2
  12. package/dist/mcp/radar-response.js +2 -2
  13. package/dist/mcp/redact.d.ts +14 -0
  14. package/dist/mcp/redact.js +71 -0
  15. package/dist/mcp/session-enable.d.ts +1 -0
  16. package/dist/mcp/session-enable.js +8 -6
  17. package/dist/mcp/snapshot-cli.d.ts +52 -0
  18. package/dist/mcp/snapshot-cli.js +331 -0
  19. package/dist/mcp/snapshot-summary.d.ts +1 -0
  20. package/dist/mcp/snapshot-summary.js +254 -0
  21. package/dist/mcp/snapshot.d.ts +32 -3
  22. package/dist/mcp/snapshot.js +392 -125
  23. package/dist/mcp/test-runs-tools.d.ts +2 -0
  24. package/dist/mcp/test-runs-tools.js +58 -5
  25. package/dist/mcp/tools.js +32 -6
  26. package/dist/shared/android.d.ts +40 -4
  27. package/dist/shared/android.js +199 -12
  28. package/dist/shared/constants.d.ts +6 -5
  29. package/dist/shared/constants.js +6 -5
  30. package/dist/shared/feature-flags.d.ts +14 -5
  31. package/dist/shared/feature-flags.js +23 -6
  32. package/dist/shared/radar-token.d.ts +5 -5
  33. package/dist/shared/radar-token.js +24 -10
  34. package/dist/shared/switchboard-note.js +2 -1
  35. package/dist/shared/switchboard-report.js +4 -1
  36. package/dist/shared/test-case-capture.d.ts +15 -0
  37. package/dist/shared/test-case-capture.js +235 -0
  38. package/dist/shared/test-case-store.d.ts +54 -0
  39. package/dist/shared/test-case-store.js +208 -0
  40. package/dist/shared/transport.d.ts +27 -1
  41. package/dist/web/install-app.js +1 -1
  42. package/dist/web/public/index.html +2 -0
  43. package/dist/web/public/next/app.js +12 -1
  44. package/dist/web/public/next/feature-flags.js +23 -6
  45. package/dist/web/public/next/feed.js +19 -4
  46. package/dist/web/public/next/filters.js +5 -5
  47. package/dist/web/public/next/flags.js +5 -3
  48. package/dist/web/public/next/registry.js +3 -2
  49. package/dist/web/public/next/save-case.js +92 -0
  50. package/dist/web/public/next/store.js +4 -2
  51. package/dist/web/public/next/switchboard-note.js +2 -1
  52. package/dist/web/public/next/test-cases.js +328 -0
  53. package/dist/web/public/next/voice-model.js +13 -1
  54. package/dist/web/public/next/voice.js +9 -4
  55. package/dist/web/server.d.ts +1 -0
  56. package/dist/web/server.js +214 -2
  57. package/dist/web/spec.d.ts +3 -2
  58. package/dist/web/spec.js +10 -9
  59. package/package.json +1 -1
  60. package/dist/mcp/test-cases.d.ts +0 -14
  61. package/dist/mcp/test-cases.js +0 -77
  62. /package/dist/web/public/icons/{radar-1024.png → icon-1024.png} +0 -0
  63. /package/dist/web/public/icons/{radar.svg → icon.svg} +0 -0
package/README.md CHANGED
@@ -54,6 +54,7 @@ Opens `http://localhost:8100` automatically. Set `SLACK_RADAR_WEB_PORT` to use a
54
54
  * **Database** — read-only browser for the on-device SQLite stores (pick a database, then a table, or run a read-only query). See the data-handling note below.
55
55
  * **Preferences** — read-only browser for the on-device SharedPreferences files (pick a file, browse its keys, or search across every file at once).
56
56
  * **Feature Flags** — live view of every feature flag and experiment the Slack app knows about, with its current effective value (ON/OFF for toggles, group name for experiments), its scope, and whether it is locally overridden; updates as they change on the device. Filter by name.
57
+ * **Test cases** — pick a built-in or saved case, set repeat and rate, Run it on the device and Stop it, read the per-type counts with p50, p90, p99 and max times, copy the settled summary as JSON, and delete a saved case. Shown on builds that serve `test_runs`.
57
58
  * **Custom** — a tab Claude builds on request. Ask a Claude Code session in your terminal for a view the pre-built tabs do not cover (e.g. "graph calls per second and flag the slow ones"); it authors the view via the `open_radar_dashboard` tool and it appears here. A Custom view can carry `exclude` terms to hide noisy rows; add more with the **exclude…** control on the feed toolbar or the Filters panel (comma-separated there), or have the agent set them in the spec (one phrase per term, no commas or line breaks). A log view narrowed to one tag is the same kind of ask: "show me only the `<Tag>` logs, DEBUG and up, without the noisy lines" becomes a spec with `source: log`, `match: {package, tag}`, `minLevel` and `exclude`, opened as a Custom tab. Persists until you refresh the page; exclude terms are remembered in the browser only on the pre-built tabs.
58
59
 
59
60
  Each tab has a filter / sort / pause / clear feed and a payload inspector, most a live rate, Network and Traces a graph. **Clear** empties the dashboard's own view only, so the device keeps its buffers and a reconnect or a source switch backfills recent records again (ask a Claude Code session for `clear_buffers` to wipe the device too). The filter box takes space-separated terms that must all match, `-term` to exclude, `/pattern/` for regex, and `"quoted phrases"` for spaces or a literal `-` or `/` (curly quotes count too, and pasting text with spaces quotes it for you, unless you are mid-word or the text starts in filter syntax). `-term` is page-wide and gone on reload; to keep an exclusion, use the **exclude…** control on the feed toolbar (one term, then Enter), the **exclude** row in the Filters panel (comma separated) or an agent's `exclude` on the spec: the terms show above the feed as removable chips, are saved with the tab, and on a pre-built tab are remembered in the browser when you come back; a spec an agent pushes lands as written and does not touch that memory. An exclude term written `field:value` (say `kind:frame`, the Switchboard record's own kind field; no space after the colon) hides rows whose field equals the value, case-insensitive, and a field no row carries hides nothing; plain terms match by substring, and the Switchboard tab's kind chips toggle those `kind:` terms for you. The `?` at the right edge of the box opens a short legend under it. A phrase that itself contains a quote character goes in `/regex/` form instead, where quotes are plain text. Committed terms turn into removable pills; a leading `-` is now the exclude operator (the old box matched it as plain text), and quoting restores the literal. Regex flags are optional and short (i/m/s/g, 1-2 letters only, so an ambiguous tail like `/api/im` reads as flags, noted in the tooltip); typos like `/error/x` become part of the pattern and match literally, and quoting any `/…/` term matches it literally. Invalid regexes and incomplete typing (e.g. `/foo(`) are ignored (the term turns amber) instead of blanking the feed. On the Live tab a row type name (`log`, `clog`, `trace`, `rtm`, `network`, `switchboard`) also matches rows of that type, and the `-log` form excludes by row type only, so it hides logcat lines without touching a `logout` clog (quote it, `-"log"`, to exclude by text instead). Switching tabs replays what you have already seen this session (the browser caches it, bounded by count and age) so the view does not reset to empty. ADB forwarding and device activation are handled for you; a reconnect control re-arms after a device sleep. The device-side session shuts down after its idle timeout, and an open dashboard tab now recovers that on its own: the header says there is no radar session on the device and re-enables it, once right away (or on the minute, if the session just came back and died again) and then at most once a minute, giving up after three failed attempts (a session that dies again within a minute of coming back counts as a failed attempt), or at once if the attached device changed, so the next press is yours. Only a tab you are looking at does this (a background tab never arms a device you let idle out), never a dashboard an agent opened, and **✋ stop auto re-enable** in the header turns it off for dashboards at this address if you would rather do it by hand (`SLACK_RADAR_NO_ARM=1` on the process turns it off for that process, along with the arm at launch). The dashboard follows your system light/dark setting by default; the theme toggle in the header overrides it and is remembered. A form-encoded request body is shown decoded, field by field, JSON fields expanded; Copy cURL still carries the raw bytes. A field whose JSON nests too deep stays as text with a note saying so, and a request body the device cap cut shows a truncation banner.
@@ -145,7 +146,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
145
146
  | `get_recent_traces` | Performance trace/span summaries: trace name, span name, duration. Filterable by name substring. |
146
147
  | `get_trace_detail` | Full trace/span detail for a specific trace, including tags. |
147
148
  | `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. `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
+ | `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 and not taken down since was still up at the session's last record). |
149
150
  | `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
151
  | `wait_for_events` | Block until matching events arrive via SSE stream. Idle-timeout based, not polling. |
151
152
  | `search` | Full-text search across network, RTM, clog, and trace buffers. |
@@ -153,7 +154,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
153
154
  | `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
155
  | `list_profiles` | List the Android users and profiles on the device (personal, work, and so on). |
155
156
  | `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. |
157
+ | `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
158
  | `screenshot` | Capture device screen as PNG. 720px default, `full_res=true` for full resolution. |
158
159
  | `record_screen` | Record short screen video (MP4). Default 5s, max 30s. |
159
160
  | `list_databases` | List the app's on-device SQLite databases. Read-only. |
@@ -162,12 +163,14 @@ Radar starts **disabled** each session. All tools except `ping` return an error
162
163
  | `list_prefs` | List the app's on-device SharedPreferences files. Read-only. |
163
164
  | `get_prefs` | Read a preferences file's keys and values, optionally filtered to specific keys. |
164
165
  | `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 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. Boolean toggles carry `enabled`; multi-variant experiments carry `type: "experiment"` and a `group_name` string (the effective variant, e.g. `"treatment_a"`) instead. |
166
+ | `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
167
  | `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
168
  | `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
169
  | `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`. |
169
170
  | `get_test_run` | Read `run_id`, or list the last ten when omitted. Optional `wait_seconds` (max 45) polls until settled. It bounds when the last read may start; every read then gets 3 seconds. |
170
171
  | `stop_test_run` | Stop `run_id`. Its counts stay readable with `get_test_run`. |
172
+ | `save_test_case` | Save captured RTM events as a replay case. Pass `name` and `ids` from `get_recent_rtm_events`, optional `repeat`, `rate_per_second` and `overwrite`. |
173
+ | `list_test_cases` | List built-in and saved cases with repeat, rate, event count and type counts. A file that cannot load shows its error. |
171
174
  | `clear_buffers` | Clear all captured buffers (network, RTM, clog, trace, settled test runs) on the device and locally, and the switchboard copy `export_switchboard_session` falls back to. The session event spool `query_session` reads is kept. |
172
175
  | `open_radar_dashboard` | Author or refine a custom live dashboard tab from a spec (source, filters, widgets, alerts). Suggested when a request is not covered by the pre-built tabs; not auto-invoked. Returns the dashboard URL; debug builds only, local only. |
173
176
  | `_radar_session_enable` | Enable radar for the session. A repeat on a live session checks the device first. |
@@ -175,12 +178,16 @@ Radar starts **disabled** each session. All tools except `ping` return an error
175
178
 
176
179
  ### Test cases
177
180
 
181
+ The dashboard's Test cases tab runs the built-in and saved cases below.
182
+
178
183
  Replay frames go into the app's own message handler on the device, not over the socket. Use a quiet workspace and a debug build that serves the `test_runs` source. Open a screen in a signed-in team first.
179
184
 
180
185
  `message_changed` and `message_replied` seed a message, then edit it or update its reply count. Each event carries about 4 KB of made-up text. Both default to `repeat: 100`, `rate_per_second: 10`, so they send 200 frames over about 20 seconds. The rate counts every frame, including the seed. Frames per run = repeat × events.
181
186
 
182
187
  Write custom cases to `~/.slack-radar/test-cases/<name>.json`, then pass the name or name.json. A file named like a built-in replaces it. Names use 1 to 64 letters, digits, underscores or hyphens. The file must be regular, at most 256 KB, and contain an object with an `events` array and a required `rate_per_second` key. Null means burst. Repeat defaults to 1. Call arguments override repeat and rate, including a null rate, but cannot rescue a file missing the rate key.
183
188
 
189
+ Save a case from traffic with `save_test_case`. Only server-sent `message`, `message_changed` and `message_replied` frames are kept. The file holds test channel, user, timestamp and file ids and same-length filler text, so it carries none of the real ones. Every iteration replays the updates against one seeded message, so edits to several different messages share that one message. The dashboard's RTM tab does the same for the rows you select (Save as test case), into the same folder, so the case runs with `run_test_case`.
190
+
184
191
  | Placeholder | Device fills it with |
185
192
  |---|---|
186
193
  | `{{test_channel}}` | The test channel |
@@ -259,6 +266,41 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
259
266
  * **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
267
  * **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
268
 
269
+ ## Headless snapshot
270
+
271
+ `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.
272
+
273
+ ```sh
274
+ # when the run starts: remember the device clock
275
+ radar-mcp snapshot --start --serial emulator-5554
276
+
277
+ # ... run the test ...
278
+
279
+ # when it ends: bundle only what happened since the start
280
+ radar-mcp snapshot --serial emulator-5554 --out /tmp/run-1
281
+ ```
282
+
283
+ | Flag | What it does |
284
+ |---|---|
285
+ | `--serial <id>` | Device to use. Needed when more than one is attached. |
286
+ | `--out <dir>` | Where to write the snapshot. Default `~/.slack-radar/snapshots`. A directory you pass is never chmodded. |
287
+ | `--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`. |
288
+ | `--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. |
289
+ | `--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. |
290
+ | `--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. |
291
+ | `--no-redact` | Keep tokens and auth headers as the device sent them. |
292
+
293
+ 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.
294
+
295
+ 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`.
296
+
297
+ 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.
298
+
299
+ On a shared host:
300
+
301
+ * Each run forwards its own free port, so parallel emulators need nothing extra; `SLACK_RADAR_DEVICE_PORT` still forces one. Pass `--serial` when several devices are attached.
302
+ * The Radar token is one per OS user, not per run, and Radar stays on until its idle timeout after the end snapshot.
303
+
262
304
  ## Data Capture
263
305
 
264
306
  What gets captured depends on the in-app server implementation. The MCP server is agnostic to the data source. The Android implementation captures:
@@ -272,6 +314,8 @@ What gets captured depends on the in-app server implementation. The MCP server i
272
314
  * **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
315
  * **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.
274
316
 
317
+ 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.
318
+
275
319
  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
320
 
277
321
  ### What gets captured, in detail
@@ -9,4 +9,28 @@ export declare function switchboardSessionQuery(args: Record<string, unknown>):
9
9
  error: string;
10
10
  };
11
11
  export declare function clampSwitchboardLimit(limit: unknown): number;
12
- export declare function buildApiPath(name: string, args: Record<string, unknown>): string | null;
12
+ export declare const FILTERED_LIST_LIMIT = 2000;
13
+ export declare const LIST_TOOLS: Record<string, {
14
+ key: string;
15
+ filters: string[];
16
+ }>;
17
+ /**
18
+ * Keep only the newest `limit` rows of a filtered list reply. When every row has a numeric id,
19
+ * the newest rows are picked by id but returned in the order the device sent them, so a
20
+ * newest-first device stays newest first. Otherwise the device order is kept and the tail wins.
21
+ * Anything else (unfiltered call, other tool, error, odd envelope) is returned as is.
22
+ */
23
+ export declare function trimListResult<T extends {
24
+ error?: string;
25
+ }>(name: string, args: Record<string, unknown>, result: T): T;
26
+ /**
27
+ * The note for a reply retried at the caller's own limit, or null when the retry is complete.
28
+ * Only iOS is known to filter its whole ring, so every other platform keeps the note.
29
+ */
30
+ export declare function retryShortNote(platform: string): string | null;
31
+ export declare function buildApiPath(name: string, args: Record<string, unknown>, wholeRing?: boolean): string | null;
32
+ /**
33
+ * The path a filtered list call would have used without the whole-ring bump, for a retry when the
34
+ * 2000-row reply is over the response size cap. Null for unfiltered calls and other tools.
35
+ */
36
+ export declare function callerLimitPath(name: string, args: Record<string, unknown>): string | null;
@@ -2,7 +2,8 @@
2
2
  // Extracted from index.ts (where it was nested inside runMcpServer, so unreachable by a unit
3
3
  // test) into its own module so the device-route contract for EVERY proxied tool -- network,
4
4
  // rtm, clog, trace, search, and the detail-by-id variants -- is pinned by a table test
5
- // (tests/api-paths.test.mjs). Pure: no I/O, no device, just string building.
5
+ // (tests/api-paths.test.mjs). It also trims filtered list replies back to the caller's limit.
6
+ // Pure: no I/O, no device, just string building.
6
7
  //
7
8
  // The arg shapes here are the query-param subset each tool sends; they intentionally duplicate
8
9
  // the (wider) handler arg interfaces in index.ts rather than couple this pure module to them.
@@ -61,13 +62,76 @@ function detailPath(resource, id) {
61
62
  const n = nonNegativeIntArg(id);
62
63
  return n === null ? null : `/api/${resource}/${n}`;
63
64
  }
64
- export function buildApiPath(name, args) {
65
+ // 2000 is the biggest device ring, so asking for that many covers any ring. The Android device scans
66
+ // only 3x the limit of newest rows before it filters, which is why a small limit missed matches under
67
+ // a flood of other rows; the iOS device already filters its whole ring. The host trims back to the
68
+ // caller's limit (trimListResult).
69
+ export const FILTERED_LIST_LIMIT = 2000;
70
+ const DEFAULT_LIST_LIMIT = 50;
71
+ // Per list tool: the envelope array on the device reply and which args count as a filter.
72
+ export const LIST_TOOLS = {
73
+ get_recent_network_calls: { key: "calls", filters: ["url_filter", "status_code"] },
74
+ get_recent_rtm_events: { key: "events", filters: ["event_type", "direction", "channel"] },
75
+ get_recent_clogs: { key: "clogs", filters: ["name"] },
76
+ get_recent_traces: { key: "traces", filters: ["name"] },
77
+ };
78
+ function isFilteredListCall(name, args) {
79
+ const tool = LIST_TOOLS[name];
80
+ return !!tool && tool.filters.some((f) => !!args?.[f]);
81
+ }
82
+ function requestedLimit(args) {
83
+ const n = Number(args?.limit);
84
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : DEFAULT_LIST_LIMIT;
85
+ }
86
+ // The limit to send: the whole-ring limit when a filter is set, else what the caller asked for.
87
+ function sentLimit(name, args, fallback, wholeRing) {
88
+ return wholeRing && isFilteredListCall(name, args) ? FILTERED_LIST_LIMIT : fallback;
89
+ }
90
+ /**
91
+ * Keep only the newest `limit` rows of a filtered list reply. When every row has a numeric id,
92
+ * the newest rows are picked by id but returned in the order the device sent them, so a
93
+ * newest-first device stays newest first. Otherwise the device order is kept and the tail wins.
94
+ * Anything else (unfiltered call, other tool, error, odd envelope) is returned as is.
95
+ */
96
+ export function trimListResult(name, args, result) {
97
+ if (!isFilteredListCall(name, args) || result.error)
98
+ return result;
99
+ const key = LIST_TOOLS[name].key;
100
+ const rows = result[key];
101
+ if (!Array.isArray(rows))
102
+ return result;
103
+ const limit = requestedLimit(args);
104
+ const ids = rows.map((row) => {
105
+ const id = typeof row === "object" && row !== null ? row.id : undefined;
106
+ return typeof id === "number" ? id : undefined;
107
+ });
108
+ if (!ids.every((id) => id !== undefined))
109
+ return { ...result, [key]: rows.slice(-limit) };
110
+ const keep = rows
111
+ .map((_, i) => i)
112
+ .sort((a, b) => ids[b] - ids[a])
113
+ .slice(0, limit)
114
+ .sort((a, b) => a - b);
115
+ return { ...result, [key]: keep.map((i) => rows[i]) };
116
+ }
117
+ /**
118
+ * The note for a reply retried at the caller's own limit, or null when the retry is complete.
119
+ * Only iOS is known to filter its whole ring, so every other platform keeps the note.
120
+ */
121
+ export function retryShortNote(platform) {
122
+ if (platform === "ios")
123
+ return null;
124
+ return "The whole-ring reply was over the response size cap, so only the newest rows were searched and older matches may be missing. Narrow the filter or use capture_snapshot.";
125
+ }
126
+ // wholeRing=false skips the 2000-row bump, giving the caller's own limit (see callerLimitPath).
127
+ export function buildApiPath(name, args, wholeRing = true) {
65
128
  switch (name) {
66
129
  case "get_recent_network_calls": {
67
130
  const a = args;
68
131
  const params = new URLSearchParams();
69
- if (a?.limit)
70
- params.set("limit", String(a.limit));
132
+ const netLimit = sentLimit(name, args, a?.limit, wholeRing);
133
+ if (netLimit)
134
+ params.set("limit", String(netLimit));
71
135
  if (a?.url_filter)
72
136
  params.set("url_filter", a.url_filter);
73
137
  if (a?.status_code)
@@ -82,8 +146,9 @@ export function buildApiPath(name, args) {
82
146
  case "get_recent_rtm_events": {
83
147
  const a = args;
84
148
  const params = new URLSearchParams();
85
- if (a?.limit)
86
- params.set("limit", String(a.limit));
149
+ const rtmLimit = sentLimit(name, args, a?.limit, wholeRing);
150
+ if (rtmLimit)
151
+ params.set("limit", String(rtmLimit));
87
152
  if (a?.event_type)
88
153
  params.set("event_type", a.event_type);
89
154
  if (a?.direction)
@@ -100,8 +165,9 @@ export function buildApiPath(name, args) {
100
165
  case "get_recent_clogs": {
101
166
  const a = args;
102
167
  const params = new URLSearchParams();
103
- if (a?.limit)
104
- params.set("limit", String(a.limit));
168
+ const clogLimit = sentLimit(name, args, a?.limit, wholeRing);
169
+ if (clogLimit)
170
+ params.set("limit", String(clogLimit));
105
171
  if (a?.name)
106
172
  params.set("name", a.name);
107
173
  const qs = params.toString();
@@ -117,7 +183,7 @@ export function buildApiPath(name, args) {
117
183
  // Default the limit when absent: traces can be large and an omitted limit would otherwise
118
184
  // rely on an unverified device-side default and stream an unbounded result into the model
119
185
  // context. 50 matches the other recent-* tools' practical page size.
120
- params.set("limit", String(a?.limit && a.limit > 0 ? a.limit : 50));
186
+ params.set("limit", String(sentLimit(name, args, a?.limit && a.limit > 0 ? a.limit : 50, wholeRing)));
121
187
  if (a?.name)
122
188
  params.set("name", a.name);
123
189
  return `/api/traces?${params.toString()}`;
@@ -144,3 +210,13 @@ export function buildApiPath(name, args) {
144
210
  return null;
145
211
  }
146
212
  }
213
+ /**
214
+ * The path a filtered list call would have used without the whole-ring bump, for a retry when the
215
+ * 2000-row reply is over the response size cap. Null for unfiltered calls and other tools.
216
+ */
217
+ export function callerLimitPath(name, args) {
218
+ // At or above the ring size the retry would ask for as many rows and hit the cap again.
219
+ if (!isFilteredListCall(name, args) || requestedLimit(args) >= FILTERED_LIST_LIMIT)
220
+ return null;
221
+ return buildApiPath(name, args, false);
222
+ }
@@ -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;
@@ -62,7 +62,7 @@ function withRestartNote(f) {
62
62
  // writes it, and only for a real mismatch.
63
63
  const { restart_note: _dropped, ...row } = f;
64
64
  const note = flagRestartNote(f);
65
- return note === undefined ? row : { ...row, restart_note: note };
65
+ return note === undefined ? row : { ...row, restart_note: note.note };
66
66
  }
67
67
  // An empty org id means the same thing as no org id, so it is dropped rather than treated as a
68
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";
@@ -37,19 +37,19 @@ import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverridd
37
37
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
38
38
  import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
39
39
  import { dashboardDebugPackageError, dashboardMatchesDevice } from "./dashboard-identity.js";
40
- import { buildApiPath } from "./api-paths.js";
40
+ import { buildApiPath, callerLimitPath, retryShortNote, trimListResult } from "./api-paths.js";
41
41
  import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, sessionDisabledLine, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
42
42
  import { getSpoolSwitchboardRecords, markSwitchboardSpoolCleared, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
43
43
  import { nonNegativeIntArg, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS } from "../shared/switchboard.js";
44
44
  import { unauthorizedResponse } from "./radar-response.js";
45
45
  import { DEFAULT_TIMEOUT_MS, radarHttpRequest, REQUEST_LOST_PREFIX, REQUEST_TIMED_OUT } from "./radar-http.js";
46
- import { handleRunTestCase, handleGetTestRun, handleStopTestRun } from "./test-runs-tools.js";
46
+ import { handleRunTestCase, handleGetTestRun, handleStopTestRun, handleSaveTestCase, handleListTestCases } from "./test-runs-tools.js";
47
47
  import { buildOpenDashboardResult, readDashboardFingerprint } from "./stale-dashboard.js";
48
48
  // --- Subcommand + bin-name dispatch ---
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);
52
+ const { wantsInstallApp, wantsSnapshot, wantsWeb } = computeDispatch(process.argv[1], sub);
53
53
  // --- Web dashboard bridge (open_radar_dashboard) ---
54
54
  //
55
55
  // The MCP server and the web dashboard are separate processes. open_radar_dashboard
@@ -208,6 +208,11 @@ if (wantsInstallApp) {
208
208
  const { runInstallAppCli } = await import("../web/install-app-cli.js");
209
209
  await runInstallAppCli(process.argv);
210
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));
215
+ }
211
216
  else if (wantsWeb) {
212
217
  const { startWebServer } = await import("../web/bin.js");
213
218
  startWebServer();
@@ -708,20 +713,21 @@ async function runMcpServer() {
708
713
  async function handleCaptureSnapshot(args) {
709
714
  try {
710
715
  // Adapt `callRadar` (device HTTP + retry + session gate) into the
711
- // simple `fetchBuffer(kind)` contract `createSnapshot` expects. Any
712
- // `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
713
718
  // try/catch can record it in `errors[]` without bringing down the
714
719
  // whole snapshot.
715
- const fetchBuffer = async (kind) => {
716
- const res = await callRadar(buildBufferPath(kind));
720
+ const fetchJson = async (apiPath) => {
721
+ const res = await callRadar(apiPath);
717
722
  if (res.error)
718
723
  throw new Error(res.error);
719
724
  return res;
720
725
  };
721
- const result = await createSnapshot(device, fetchBuffer, {
726
+ const result = await createSnapshot(device, fetchJson, {
722
727
  includeLogs: args?.include_logs !== false,
723
728
  includeScreenshot: args?.include_screenshot !== false,
724
729
  logTailLines: args?.log_tail_lines,
730
+ redact: args?.redact !== false,
725
731
  });
726
732
  return textResult(result, result.errors.length > 0 && result.files.length === 0);
727
733
  }
@@ -881,7 +887,7 @@ async function runMcpServer() {
881
887
  }
882
888
  }
883
889
  // --- MCP Server ---
884
- const server = new Server({ name: "slack-radar", version: "1.25.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
890
+ const server = new Server({ name: "slack-radar", version: "1.27.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
885
891
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
886
892
  tools: TOOL_DEFINITIONS,
887
893
  }));
@@ -1009,6 +1015,14 @@ async function runMcpServer() {
1009
1015
  const { data, isError } = await handleRunTestCase(toolArgs, callRadar);
1010
1016
  return textResult(data, isError);
1011
1017
  }
1018
+ if (name === "save_test_case") {
1019
+ const { data, isError } = await handleSaveTestCase(toolArgs, callRadar);
1020
+ return textResult(data, isError);
1021
+ }
1022
+ if (name === "list_test_cases") {
1023
+ const { data, isError } = handleListTestCases();
1024
+ return textResult(data, isError);
1025
+ }
1012
1026
  if (name === "get_test_run") {
1013
1027
  const { data, isError } = await handleGetTestRun(toolArgs, callRadar);
1014
1028
  return textResult(data, isError);
@@ -1035,7 +1049,18 @@ async function runMcpServer() {
1035
1049
  if (apiPath === null) {
1036
1050
  return textResult(`Unknown tool: ${name}`, true);
1037
1051
  }
1038
- const result = await callRadar(apiPath);
1052
+ let raw = await callRadar(apiPath);
1053
+ // The whole-ring ask can top the response size cap where the caller's own limit would not.
1054
+ // A disable during the first read means no more device work, so the retry is skipped then.
1055
+ const fallbackPath = raw._truncated === true && sessionEnabled ? callerLimitPath(name, toolArgs) : null;
1056
+ if (fallbackPath !== null) {
1057
+ raw = await callRadar(fallbackPath);
1058
+ // Outside iOS the retry may only scan the newest rows, so the model is told the answer may be short.
1059
+ const note = retryShortNote(device.platform);
1060
+ if (!raw.error && note)
1061
+ raw = { ...raw, note };
1062
+ }
1063
+ const result = trimListResult(name, toolArgs, raw);
1039
1064
  return textResult(decorateToolResult(name, result), !!result.error);
1040
1065
  });
1041
1066
  const transport = new StdioServerTransport();
@@ -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
  }