@slack/radar-mcp 1.25.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 (37) hide show
  1. package/README.md +39 -2
  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 +1 -1
  6. package/dist/mcp/index.js +14 -8
  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 +8 -4
  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 +14 -5
  25. package/dist/shared/feature-flags.js +23 -6
  26. package/dist/shared/radar-token.d.ts +5 -5
  27. package/dist/shared/radar-token.js +24 -10
  28. package/dist/shared/switchboard-report.js +3 -0
  29. package/dist/shared/transport.d.ts +18 -0
  30. package/dist/web/public/index.html +1 -0
  31. package/dist/web/public/next/feature-flags.js +23 -6
  32. package/dist/web/public/next/feed.js +2 -2
  33. package/dist/web/public/next/flags.js +5 -3
  34. package/dist/web/public/next/store.js +1 -1
  35. package/dist/web/public/next/voice-model.js +13 -1
  36. package/dist/web/public/next/voice.js +8 -3
  37. package/package.json +1 -1
@@ -0,0 +1,316 @@
1
+ /**
2
+ * `radar-mcp snapshot`: a headless front door for a test run. It arms Radar, then calls the
3
+ * same composer `capture_snapshot` uses and prints one JSON line. Runs before the MCP server
4
+ * starts, so there is no stdio session and no mcp-seen marker.
5
+ *
6
+ * Two uses:
7
+ * radar-mcp snapshot --start at the start of a run: remember the device clock
8
+ * radar-mcp snapshot [--out <dir>] at the end: bundle only what happened since
9
+ */
10
+ import fs from "fs";
11
+ import os from "os";
12
+ import path from "path";
13
+ import { AndroidTransport } from "../shared/android.js";
14
+ import { RADAR_HOST, RADAR_PORT } from "../shared/constants.js";
15
+ import { radarHttpRequest } from "./radar-http.js";
16
+ import { unauthorizedResponse } from "./radar-response.js";
17
+ import { runSessionEnable } from "./session-enable.js";
18
+ import { createSnapshot } from "./snapshot.js";
19
+ const DEFAULT_TIMEOUT_MINUTES = 60;
20
+ const SNAPSHOT_LOG_LINES = 5000;
21
+ const RESTART_SLACK_MS = 2000;
22
+ const STALE_MARKER_MS = 24 * 60 * 60 * 1000;
23
+ export const SNAPSHOT_USAGE = `Usage: radar-mcp snapshot [options]
24
+
25
+ Save a Radar snapshot without an MCP client. Run it with --start when a test run
26
+ begins and without --start when it ends.
27
+
28
+ Android only: it needs adb and a debug build on a device or emulator. Other platforms are
29
+ not supported.
30
+
31
+ Options:
32
+ --serial <id> Device to use (default: the only attached device)
33
+ --out <dir> Directory to write the snapshot under (default: ~/.slack-radar/snapshots)
34
+ --start Only record the start of a run; no snapshot is written
35
+ --since <epoch-ms> Keep events from this time on. Device clock, the same clock as the
36
+ since_ms that --start prints. Beats the start marker
37
+ --detail-url <text> Also keep the details of calls whose URL contains this text
38
+ (repeatable); failed calls are always kept
39
+ --timeout-minutes <n> How long Radar stays on with no calls, 1-1440 (default ${DEFAULT_TIMEOUT_MINUTES})
40
+ --no-redact Keep tokens and auth headers as the device sent them
41
+ --help Show this text
42
+
43
+ Prints one JSON line on stdout. Exit codes: 0 done, 1 failed, 2 bad usage.
44
+ `;
45
+ export function parseSnapshotArgs(argv) {
46
+ const args = {
47
+ serial: null,
48
+ out: null,
49
+ start: false,
50
+ since: null,
51
+ detailUrls: [],
52
+ timeoutMinutes: DEFAULT_TIMEOUT_MINUTES,
53
+ redact: true,
54
+ };
55
+ const usage = (message) => ({ kind: "usage", message });
56
+ for (let i = 0; i < argv.length; i++) {
57
+ const flag = argv[i];
58
+ const value = () => {
59
+ const v = argv[i + 1];
60
+ if (v === undefined || v.startsWith("--"))
61
+ return null;
62
+ i++;
63
+ return v;
64
+ };
65
+ // The value of a flag that must have one, or the usage error to return.
66
+ const need = () => value() || usage(`${flag} needs a value`);
67
+ switch (flag) {
68
+ case "--help":
69
+ case "-h":
70
+ return { kind: "help" };
71
+ case "--start":
72
+ args.start = true;
73
+ break;
74
+ case "--no-redact":
75
+ args.redact = false;
76
+ break;
77
+ case "--serial": {
78
+ const v = need();
79
+ if (typeof v !== "string")
80
+ return v;
81
+ args.serial = v;
82
+ break;
83
+ }
84
+ case "--out": {
85
+ const v = need();
86
+ if (typeof v !== "string")
87
+ return v;
88
+ args.out = v;
89
+ break;
90
+ }
91
+ case "--detail-url": {
92
+ const v = need();
93
+ if (typeof v !== "string")
94
+ return v;
95
+ args.detailUrls.push(v);
96
+ break;
97
+ }
98
+ case "--since": {
99
+ const v = value();
100
+ if (v === null || !/^\d+$/.test(v))
101
+ return usage("--since needs a device epoch in milliseconds");
102
+ args.since = Number(v);
103
+ break;
104
+ }
105
+ case "--timeout-minutes": {
106
+ const v = value();
107
+ const n = v !== null && /^\d+$/.test(v) ? Number(v) : NaN;
108
+ if (!(n >= 1 && n <= 1440))
109
+ return usage("--timeout-minutes needs a whole number from 1 to 1440");
110
+ args.timeoutMinutes = n;
111
+ break;
112
+ }
113
+ default:
114
+ return usage(`unknown option ${flag}`);
115
+ }
116
+ }
117
+ if (args.start && (args.since !== null || args.out !== null || args.detailUrls.length > 0)) {
118
+ return usage("--start cannot be combined with --since, --out or --detail-url");
119
+ }
120
+ return { kind: "run", args };
121
+ }
122
+ // --- start marker ---
123
+ /** Serial reduced to characters that are safe in a file name. */
124
+ export function markerFileName(serial) {
125
+ const safe = (serial ?? "").replace(/[^A-Za-z0-9._:-]/g, "_");
126
+ return `${safe === "" ? "default" : safe}.json`;
127
+ }
128
+ export function markerPath(homeDir, serial) {
129
+ return path.join(homeDir, ".slack-radar", "snapshot-starts", markerFileName(serial));
130
+ }
131
+ export function writeStartMarker(homeDir, serial, sinceMs) {
132
+ const file = markerPath(homeDir, serial);
133
+ const dir = path.dirname(file);
134
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
135
+ // mkdir only sets the mode on directories it creates.
136
+ fs.chmodSync(dir, 0o700);
137
+ fs.writeFileSync(file, JSON.stringify({ since_ms: sinceMs, serial }), { mode: 0o600 });
138
+ fs.chmodSync(file, 0o600);
139
+ return file;
140
+ }
141
+ export function readStartMarker(homeDir, serial) {
142
+ const file = markerPath(homeDir, serial);
143
+ try {
144
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
145
+ if (typeof parsed.since_ms !== "number" || !Number.isFinite(parsed.since_ms))
146
+ return null;
147
+ return { since_ms: parsed.since_ms, ageMs: Date.now() - fs.statSync(file).mtimeMs, file };
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ /**
154
+ * GET helper for the snapshot reads. The forwarded port is host-wide and a dashboard or another
155
+ * run can repoint it, so it is pointed at this device again before every read.
156
+ */
157
+ export function cliFetchJson(device, send) {
158
+ return async (apiPath) => {
159
+ const forwarded = device.reassertForward?.() ?? device.ensureForward();
160
+ if (!forwarded) {
161
+ throw new Error(`port forward to ${device.getSelectedDevice?.()?.serial ?? "the device"} failed`);
162
+ }
163
+ const checked = unauthorizedResponse(await send(apiPath), device, "cli");
164
+ if (checked.error)
165
+ throw new Error(checked.error);
166
+ return checked;
167
+ };
168
+ }
169
+ function defaultDeps() {
170
+ const device = new AndroidTransport();
171
+ const ping = () => radarHttpRequest({
172
+ host: RADAR_HOST,
173
+ port: RADAR_PORT,
174
+ path: "/api/ping",
175
+ timeoutMs: 2000,
176
+ deadlineMs: Date.now() + 2000,
177
+ transport: device,
178
+ });
179
+ const enableDeps = {
180
+ device,
181
+ // No MCP session here, so nothing streams, spools or backfills.
182
+ destroyStream: () => { },
183
+ connectStream: () => { },
184
+ isStreamConnected: () => false,
185
+ wasStreamRejected: () => false,
186
+ resetDbState: () => { },
187
+ startSpool: () => { },
188
+ runBackfill: async () => { },
189
+ onDeviceSwitch: () => { },
190
+ ping,
191
+ surface: "cli",
192
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
193
+ };
194
+ return {
195
+ device,
196
+ enable: (timeout, serial) => runSessionEnable(timeout, serial, enableDeps),
197
+ fetchJson: cliFetchJson(device, (apiPath) => radarHttpRequest({ host: RADAR_HOST, port: RADAR_PORT, path: apiPath, transport: device })),
198
+ snapshot: createSnapshot,
199
+ now: () => Date.now(),
200
+ homeDir: os.homedir(),
201
+ stdout: (t) => process.stdout.write(t),
202
+ stderr: (t) => process.stderr.write(t),
203
+ };
204
+ }
205
+ function iso(ms) {
206
+ return new Date(ms).toISOString();
207
+ }
208
+ /** Runs the command and returns the exit code. Prints exactly one JSON line for exit 0 and 1. */
209
+ export async function runSnapshotCli(argv, deps = defaultDeps()) {
210
+ const parsed = parseSnapshotArgs(argv);
211
+ if (parsed.kind === "help") {
212
+ deps.stdout(SNAPSHOT_USAGE);
213
+ return 0;
214
+ }
215
+ if (parsed.kind === "usage") {
216
+ deps.stderr(`${parsed.message}\n\n${SNAPSHOT_USAGE}`);
217
+ return 2;
218
+ }
219
+ const { args } = parsed;
220
+ const { device } = deps;
221
+ const warnings = [];
222
+ const fail = (message) => {
223
+ deps.stderr(`${message}\n`);
224
+ deps.stdout(`${JSON.stringify({ error: message, warnings })}\n`);
225
+ return 1;
226
+ };
227
+ try {
228
+ const outcome = await deps.enable(args.timeoutMinutes, args.serial);
229
+ if (!outcome.enabled) {
230
+ return fail(typeof outcome.body.error === "string" ? outcome.body.error : "Radar did not start on the device");
231
+ }
232
+ // The enable picked the device; key the start marker by it so --start and the end agree.
233
+ const serial = device.getSelectedDevice?.()?.serial ?? args.serial;
234
+ const warning = outcome.body.warning;
235
+ if (typeof warning === "string")
236
+ warnings.push(warning);
237
+ const viaArgv = outcome.body.token_via_argv;
238
+ if (typeof viaArgv === "string") {
239
+ warnings.push(`the Radar token was sent on the adb command line because ${viaArgv}`);
240
+ }
241
+ for (const w of warnings)
242
+ deps.stderr(`warning: ${w}\n`);
243
+ // The enable starts a log capture that has seconds of lines at most. Stop it so the
244
+ // composer reads the device log instead.
245
+ device.stopLogCapture?.();
246
+ device.reassertForward?.();
247
+ if (args.start) {
248
+ const sinceMs = device.deviceClockMs?.() ?? null;
249
+ if (sinceMs === null)
250
+ return fail("could not read the device clock over adb");
251
+ const file = writeStartMarker(deps.homeDir, serial, sinceMs);
252
+ deps.stdout(`${JSON.stringify({ started: true, since_ms: sinceMs, serial, marker_path: file, warnings })}\n`);
253
+ return 0;
254
+ }
255
+ const marker = args.since === null ? readStartMarker(deps.homeDir, serial) : null;
256
+ const since = args.since ?? marker?.since_ms ?? null;
257
+ const untilMs = device.deviceClockMs?.() ?? null;
258
+ const notes = [];
259
+ const uptime = outcome.body.uptime_ms;
260
+ if (since !== null && untilMs !== null && typeof uptime === "number") {
261
+ const radarStart = untilMs - uptime;
262
+ // since comes from whole device seconds, so allow a little rounding before calling it a restart.
263
+ if (radarStart > since + RESTART_SLACK_MS) {
264
+ notes.push(`Radar restarted during the run: network, RTM and voice sessions before ${iso(radarStart)} are gone`);
265
+ }
266
+ }
267
+ if (marker && marker.ageMs > STALE_MARKER_MS) {
268
+ notes.push("The start marker is more than 24 hours old; it may be left from an earlier run");
269
+ }
270
+ const result = await deps.snapshot(device, deps.fetchJson, {
271
+ since,
272
+ windowSource: args.since !== null ? "since_flag" : "start_marker",
273
+ untilMs,
274
+ redact: args.redact,
275
+ logSource: "device",
276
+ // A crash can be older than the default 500 lines; this stays under the 10000 maximum.
277
+ logTailLines: SNAPSHOT_LOG_LINES,
278
+ notes,
279
+ detailUrls: args.detailUrls,
280
+ }, deps.now(), args.out ?? undefined);
281
+ // The marker goes only once the summary is written. A failed delete is a warning, not a failure.
282
+ if (marker && result.summary_path) {
283
+ try {
284
+ fs.rmSync(marker.file, { force: true });
285
+ }
286
+ catch (e) {
287
+ const w = `could not delete the start marker ${marker.file}: ${e.message}`;
288
+ warnings.push(w);
289
+ deps.stderr(`warning: ${w}\n`);
290
+ }
291
+ }
292
+ deps.stdout(`${JSON.stringify({
293
+ path: result.path,
294
+ zip_path: result.zip_path,
295
+ summary_path: result.summary_path,
296
+ counts: result.counts,
297
+ run_window: result.run_window,
298
+ redacted: result.redacted,
299
+ warnings,
300
+ errors: result.errors,
301
+ privacy_notice: result.privacy_notice,
302
+ })}\n`);
303
+ return result.summary_path ? 0 : 1;
304
+ }
305
+ catch (e) {
306
+ return fail(`snapshot failed: ${e.message}`);
307
+ }
308
+ finally {
309
+ device.stopLogCapture?.();
310
+ }
311
+ }
312
+ /** Entry for index.ts: run, then exit so no adb child keeps the process alive. */
313
+ export async function snapshotCliMain(argv) {
314
+ const code = await runSnapshotCli(argv);
315
+ process.exit(code);
316
+ }
@@ -0,0 +1 @@
1
+ export declare function buildSnapshotSummary(bundle: unknown, logText: string): string;
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The short markdown a model reads first in a snapshot (summary.md). Pure: it takes the
3
+ * bundle object (already redacted) plus the log text and returns the file body.
4
+ *
5
+ * The bundle is read defensively, field by field, since any source can be missing when its
6
+ * fetch failed. A missing source says "not captured" with the reason from `errors`, never a
7
+ * silent "none". Every section is capped so the file stays well under 16 KB.
8
+ */
9
+ import { flagRestartNote } from "../shared/feature-flags.js";
10
+ import { asObj, rowsOf } from "./json-rows.js";
11
+ import { isFailedCall } from "./snapshot.js";
12
+ const MAX_FAILED = 20;
13
+ const MAX_LOG_LINES = 30;
14
+ const MAX_CLOG_NAMES = 30;
15
+ const MAX_FLAGS = 30;
16
+ const MAX_VOICE = 10;
17
+ const MAX_LINE = 300;
18
+ const MAX_ERRORS = 20;
19
+ const MAX_TOTAL = 15000;
20
+ function str(v) {
21
+ return typeof v === "string" && v !== "" ? v : null;
22
+ }
23
+ function num(v) {
24
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
25
+ }
26
+ function clip(s, n = MAX_LINE) {
27
+ return s.length > n ? `${s.slice(0, n)}...` : s;
28
+ }
29
+ function iso(ms) {
30
+ const n = num(ms);
31
+ if (n === null)
32
+ return "?";
33
+ const d = new Date(n);
34
+ return Number.isNaN(d.getTime()) ? "?" : d.toISOString();
35
+ }
36
+ /** Rows of a list buffer, or null when the buffer was not captured. */
37
+ function rows(buffer, key) {
38
+ return asObj(buffer) ? rowsOf(buffer, key) : null;
39
+ }
40
+ /** URL without its query or fragment, so no token in a query string reaches the summary. */
41
+ function urlPath(url) {
42
+ const s = str(url);
43
+ if (!s)
44
+ return "?";
45
+ return clip(s.replace(/[?#].*$/, ""), 200);
46
+ }
47
+ function notCaptured(errors, word) {
48
+ const hit = errors.find((e) => e.toLowerCase().includes(word));
49
+ return hit ? `not captured: ${clip(hit)}` : "not captured";
50
+ }
51
+ /** Newest-first call lines, capped at MAX_FAILED, with the "more" notes under them. */
52
+ function pushCallList(out, calls, truncated, opts) {
53
+ const sorted = calls.slice().sort((x, y) => (num(y.timestamp) ?? 0) - (num(x.timestamp) ?? 0));
54
+ for (const c of sorted.slice(0, MAX_FAILED)) {
55
+ const err = opts.withError ? str(c.error) : null;
56
+ out.push(`- ${iso(c.timestamp)} ${str(c.method) ?? "?"} ${urlPath(c.url)} -> ${num(c.status_code) ?? "?"}${err ? ` (${clip(err, 120)})` : ""}`);
57
+ }
58
+ if (calls.length > MAX_FAILED)
59
+ out.push(`${calls.length - MAX_FAILED} more in bundle.json`);
60
+ if (truncated)
61
+ out.push("more not kept");
62
+ }
63
+ const ERROR_LOG = /^\S+\s+\S+\s+\d+\s+\d+\s+[EF]\s|FATAL EXCEPTION|ANR in|AndroidRuntime/;
64
+ export function buildSnapshotSummary(bundle, logText) {
65
+ const b = asObj(bundle) ?? {};
66
+ const buffers = asObj(b.buffers) ?? {};
67
+ const errors = (Array.isArray(b.errors) ? b.errors : []).filter((e) => typeof e === "string");
68
+ const out = ["# Radar snapshot summary", ""];
69
+ // 1. Header
70
+ const win = asObj(b.run_window);
71
+ const src = str(win?.source);
72
+ const since = num(win?.since_ms);
73
+ const until = num(win?.until_ms);
74
+ let windowLine;
75
+ if (since === null || src === "none") {
76
+ windowLine = "none (whole buffers)";
77
+ }
78
+ else {
79
+ const how = src === "start_marker" ? "start marker" : src === "since_flag" ? "--since" : (src ?? "unknown source");
80
+ windowLine = `${iso(since)} to ${until === null ? "now" : iso(until)} (set by ${how})`;
81
+ }
82
+ const device = asObj(b.device) ?? {};
83
+ const app = asObj(b.app) ?? {};
84
+ const deviceBits = [
85
+ str(device.model),
86
+ str(device.android_release) ? `Android ${device.android_release}` : null,
87
+ str(device.sdk) ? `SDK ${device.sdk}` : null,
88
+ typeof device.emulator === "boolean" ? (device.emulator ? "emulator" : "physical device") : null,
89
+ ].filter(Boolean);
90
+ const appBits = [
91
+ str(app.package),
92
+ str(app.version_name) ? `version ${app.version_name}` : null,
93
+ str(app.version_code) ? `code ${app.version_code}` : null,
94
+ str(app.resumed_activity) ? `screen ${app.resumed_activity}` : null,
95
+ ].filter(Boolean);
96
+ out.push("## Run");
97
+ out.push(`- Window: ${windowLine}`);
98
+ out.push(`- Device: ${deviceBits.length ? deviceBits.join(", ") : "not captured"}`);
99
+ out.push(`- App: ${appBits.length ? appBits.join(", ") : "not captured"}`);
100
+ out.push(`- Radar ${str(b.mcp_version) ?? "?"}, bundle format ${num(b.bundle_format_version) ?? "?"}`);
101
+ out.push("");
102
+ const calls = rows(buffers.network, "calls");
103
+ const rtm = rows(buffers.rtm, "events");
104
+ const clogs = rows(buffers.clogs, "clogs");
105
+ const traces = rows(buffers.traces, "traces");
106
+ const flags = rows(buffers.feature_flags, "feature_flags");
107
+ const voice = rows(buffers.switchboard, "sessions");
108
+ // Failed calls come from the composer's detail pass; fall back to the status filter.
109
+ const nf = asObj(b.network_failures);
110
+ const nfCalls = Array.isArray(nf?.calls) ? rowsOf(nf, "calls") : null;
111
+ const failed = (nfCalls ?? (calls ? calls.filter(isFailedCall) : []))
112
+ .slice()
113
+ .sort((x, y) => (num(y.timestamp) ?? 0) - (num(x.timestamp) ?? 0));
114
+ // 2. Counts. Failed calls kept without details (`unread`) count as checked, so F never exceeds C.
115
+ const checkedCount = (num(nf?.checked) ?? calls?.length ?? 0) + (num(nf?.unread) ?? 0);
116
+ const counts = asObj(b.counts) ?? {};
117
+ const logs = asObj(b.logs);
118
+ const n = (rowsOrNull, word) => (rowsOrNull ? String(rowsOrNull.length) : notCaptured(errors, word));
119
+ const logSource = str(logs?.source);
120
+ // No source means no log was read at all; counts.log_lines is always a number, so it cannot say.
121
+ const logPart = logSource === null
122
+ ? `log lines: ${notCaptured(errors, "logcat")}`
123
+ : `log lines: ${num(counts.log_lines) ?? 0} (${logSource})`;
124
+ out.push("## Counts");
125
+ out.push(`- network: ${calls ? `${calls.length} (failed ${failed.length} of ${checkedCount} checked)` : notCaptured(errors, "network")}; rtm: ${n(rtm, "rtm")}; clogs: ${n(clogs, "clog")}; traces: ${n(traces, "trace")}`);
126
+ out.push(`- voice sessions: ${n(voice, "switchboard")}; ${logPart}; flag rows: ${n(flags, "feature_flags")}`);
127
+ out.push("");
128
+ // Problems come right after the counts: the total cut drops the tail first, and the restart
129
+ // and stale-marker notes live here.
130
+ out.push("## Snapshot problems");
131
+ if (errors.length === 0)
132
+ out.push("none");
133
+ else {
134
+ for (const e of errors.slice(0, MAX_ERRORS))
135
+ out.push(`- ${clip(e)}`);
136
+ if (errors.length > MAX_ERRORS)
137
+ out.push(`${errors.length - MAX_ERRORS} more in bundle.json`);
138
+ }
139
+ out.push("");
140
+ // 3. Failed network calls
141
+ out.push("## Failed network calls");
142
+ if (!calls && !nfCalls) {
143
+ out.push(notCaptured(errors, "network"));
144
+ }
145
+ else if (failed.length === 0) {
146
+ out.push("none");
147
+ }
148
+ else {
149
+ pushCallList(out, failed, nf?.truncated === true, { withError: true });
150
+ }
151
+ out.push("");
152
+ // Kept responses: calls the caller asked to keep by URL, failed or not.
153
+ const nm = asObj(b.network_matches);
154
+ const matches = Array.isArray(nm?.calls) ? rowsOf(nm, "calls") : null;
155
+ if (matches) {
156
+ out.push("## Kept responses");
157
+ if (matches.length === 0)
158
+ out.push("none");
159
+ pushCallList(out, matches, nm?.truncated === true, { withError: false });
160
+ out.push("");
161
+ }
162
+ // 4. Log errors
163
+ out.push("## Log errors and crashes");
164
+ out.push("The log tail is not cut to the run window.");
165
+ // Say how wide the search was, so "none" is never read as wider than what was fetched.
166
+ if (logSource !== null) {
167
+ const searched = logText ? logText.split("\n").filter(Boolean).length : 0;
168
+ out.push(`Searched the last ${searched} log lines.`);
169
+ }
170
+ const appBuffer = str(asObj(b.logs)?.source) === "app_buffer";
171
+ // The app's own buffer has no level column, so only crash markers can be found in it.
172
+ if (appBuffer)
173
+ out.push("This log has no level column, so only crash markers (FATAL EXCEPTION, ANR in, AndroidRuntime) are listed.");
174
+ if (!logText) {
175
+ out.push(logSource === null ? notCaptured(errors, "logcat") : "none");
176
+ }
177
+ else {
178
+ const hits = logText.split("\n").filter((l) => ERROR_LOG.test(l));
179
+ if (hits.length === 0)
180
+ out.push(appBuffer ? "no crash markers" : "none");
181
+ else {
182
+ for (const l of hits.slice(0, MAX_LOG_LINES))
183
+ out.push(`- ${clip(l.trim())}`);
184
+ if (hits.length > MAX_LOG_LINES)
185
+ out.push(`${hits.length - MAX_LOG_LINES} more in logcat.tail.log`);
186
+ }
187
+ }
188
+ out.push("");
189
+ // 5. Clogs
190
+ out.push("## Clogs fired");
191
+ if (!clogs)
192
+ out.push(notCaptured(errors, "clog"));
193
+ else if (clogs.length === 0)
194
+ out.push("none");
195
+ else {
196
+ const by = new Map();
197
+ for (const c of clogs) {
198
+ const name = str(c.event_name) ?? "?";
199
+ by.set(name, (by.get(name) ?? 0) + 1);
200
+ }
201
+ const sorted = [...by.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]));
202
+ for (const [name, count] of sorted.slice(0, MAX_CLOG_NAMES))
203
+ out.push(`- ${clip(name, 120)}: ${count}`);
204
+ if (sorted.length > MAX_CLOG_NAMES)
205
+ out.push(`${sorted.length - MAX_CLOG_NAMES} more names in bundle.json`);
206
+ }
207
+ out.push("");
208
+ // 6. Flags
209
+ out.push("## Flags worth a look");
210
+ if (!flags)
211
+ out.push(notCaptured(errors, "feature_flags"));
212
+ else {
213
+ const picked = flags
214
+ .map((f) => ({ f, note: flagRestartNote(f)?.note }))
215
+ .filter((x) => x.f.is_overridden === true || x.note !== undefined);
216
+ if (picked.length === 0)
217
+ out.push("none");
218
+ for (const { f, note } of picked.slice(0, MAX_FLAGS)) {
219
+ const bits = [
220
+ f.is_overridden === true ? "overridden" : null,
221
+ note ?? null,
222
+ ].filter(Boolean);
223
+ out.push(`- ${clip(str(f.key) ?? "?", 120)} (${str(f.scope) ?? "?"}) = ${String(f.enabled ?? "?")}${bits.length ? `; ${bits.join("; ")}` : ""}`);
224
+ }
225
+ if (picked.length > MAX_FLAGS)
226
+ out.push(`${picked.length - MAX_FLAGS} more in bundle.json`);
227
+ out.push(`${flags.length} flag rows in total`);
228
+ }
229
+ out.push("");
230
+ // 7. Voice sessions
231
+ out.push("## Voice sessions");
232
+ if (!voice)
233
+ out.push(notCaptured(errors, "switchboard"));
234
+ else if (voice.length === 0)
235
+ out.push("none");
236
+ else {
237
+ const sorted = voice.slice().sort((x, y) => (num(y.began_at) ?? 0) - (num(x.began_at) ?? 0));
238
+ for (const s of sorted.slice(0, MAX_VOICE)) {
239
+ const turns = num(asObj(s.turns)?.count);
240
+ const saved = asObj(s.saved_turn_counts);
241
+ const savedText = saved
242
+ ? `; saved turns ${Object.entries(saved).map(([k, v]) => `${k} ${String(v)}`).join(", ")}`
243
+ : "";
244
+ const ls = asObj(s.last_state);
245
+ const last = ls ? `${str(ls.state_kind) ?? "?"} -> ${str(ls.to) ?? "?"}` : null;
246
+ out.push(`- #${String(s.session_id ?? "?")} ${iso(s.began_at)} to ${s.ended_at == null ? "still open" : iso(s.ended_at)}; last state ${last ?? "?"}; turns ${turns ?? "?"}${savedText}`);
247
+ }
248
+ if (sorted.length > MAX_VOICE)
249
+ out.push(`${sorted.length - MAX_VOICE} more in bundle.json`);
250
+ }
251
+ out.push("");
252
+ const text = out.join("\n");
253
+ return text.length > MAX_TOTAL ? `${text.slice(0, MAX_TOTAL)}\n...cut\n` : text;
254
+ }
@@ -1,19 +1,38 @@
1
1
  import type { DeviceTransport } from "../shared/transport.js";
2
+ import { type Obj } from "./json-rows.js";
2
3
  export interface SnapshotOptions {
3
4
  includeLogs?: boolean;
4
5
  includeScreenshot?: boolean;
5
6
  logTailLines?: number;
7
+ /** Device-clock ms; list rows older than this are left out. */
8
+ since?: number | null;
9
+ windowSource?: "start_marker" | "since_flag" | "none";
10
+ /** Device-clock ms the run ended at, recorded in run_window. */
11
+ untilMs?: number | null;
12
+ /** Blank tokens and auth headers by pattern. Default true. */
13
+ redact?: boolean;
14
+ /** "device" skips a running capture file and reads the device log. */
15
+ logSource?: "capture_then_device" | "device";
16
+ /** Extra lines for errors[] (the CLI's restart and stale-marker notes). */
17
+ notes?: string[];
18
+ /** URL substrings whose calls keep their details even when they succeeded. */
19
+ detailUrls?: string[];
20
+ /** Time budget for reading call details; tests shrink it. */
21
+ detailBudgetMs?: number;
6
22
  }
7
23
  export interface SnapshotResult {
8
24
  path: string;
9
25
  files: string[];
10
26
  zip_path: string | null;
27
+ summary_path: string | null;
11
28
  timestamp: number;
12
29
  counts: {
13
30
  network: number;
14
31
  rtm: number;
15
32
  clogs: number;
16
33
  traces: number;
34
+ feature_flags: number;
35
+ switchboard: number;
17
36
  log_lines: number;
18
37
  log_lines_truncated: boolean;
19
38
  screenshot: boolean;
@@ -23,9 +42,17 @@ export interface SnapshotResult {
23
42
  rtm: boolean;
24
43
  clogs: boolean;
25
44
  traces: boolean;
45
+ feature_flags: boolean;
46
+ switchboard: boolean;
26
47
  };
27
48
  errors: string[];
28
49
  privacy_notice: string;
50
+ redacted: boolean;
51
+ run_window: {
52
+ since_ms: number | null;
53
+ until_ms: number | null;
54
+ source: string;
55
+ };
29
56
  }
30
57
  /**
31
58
  * Resolve the output directory for a snapshot. Exported for tests.
@@ -52,9 +79,11 @@ export interface LogTailResult {
52
79
  * the user they got fewer lines than requested.
53
80
  */
54
81
  export declare function readRecentLogTail(requestedLimit?: number): LogTailResult;
82
+ /** A call whose recorded status says it failed: 400 and up, or 0 and below. */
83
+ export declare function isFailedCall(row: Obj): boolean;
55
84
  /**
56
- * Write a snapshot bundle to disk. The caller supplies `fetchBuffer` (a
57
- * callback that hits the device's HTTP endpoint for a given buffer name)
85
+ * Write a snapshot bundle to disk. The caller supplies `fetchJson` (a
86
+ * callback that GETs a device-side Radar path and throws on a device error)
58
87
  * so this module does not need to know how `radarRequest` works — easier
59
88
  * to test and keeps the device-HTTP plumbing in `index.ts`.
60
89
  *
@@ -62,4 +91,4 @@ export declare function readRecentLogTail(requestedLimit?: number): LogTailResul
62
91
  * snapshot still lands on disk with whatever succeeded; failures are
63
92
  * collected in `result.errors` so the model can tell the user.
64
93
  */
65
- export declare function createSnapshot(device: DeviceTransport, fetchBuffer: (kind: "network" | "rtm" | "clogs" | "traces") => Promise<unknown>, opts?: SnapshotOptions, now?: number, snapshotRoot?: string): Promise<SnapshotResult>;
94
+ export declare function createSnapshot(device: DeviceTransport, fetchJson: (path: string) => Promise<unknown>, opts?: SnapshotOptions, now?: number, snapshotRoot?: string): Promise<SnapshotResult>;