@slack/radar-mcp 1.21.0 → 1.23.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.
- package/README.md +114 -18
- package/dist/mcp/api-paths.d.ts +2 -2
- package/dist/mcp/api-paths.js +4 -19
- package/dist/mcp/dashboard-identity.d.ts +6 -0
- package/dist/mcp/dashboard-identity.js +11 -0
- package/dist/mcp/index.js +210 -145
- package/dist/mcp/logs-result.d.ts +1 -0
- package/dist/mcp/logs-result.js +1 -0
- package/dist/mcp/radar-export-get.d.ts +30 -0
- package/dist/mcp/radar-export-get.js +49 -0
- package/dist/mcp/radar-http.d.ts +22 -0
- package/dist/mcp/radar-http.js +61 -0
- package/dist/mcp/radar-response.d.ts +5 -1
- package/dist/mcp/radar-response.js +8 -3
- package/dist/mcp/session-backfill.js +3 -4
- package/dist/mcp/session-enable.d.ts +15 -0
- package/dist/mcp/session-enable.js +268 -19
- package/dist/mcp/snapshot.js +42 -26
- package/dist/mcp/sources-gate.js +6 -0
- package/dist/mcp/stale-dashboard.d.ts +23 -0
- package/dist/mcp/stale-dashboard.js +122 -0
- package/dist/mcp/switchboard-spool.d.ts +12 -0
- package/dist/mcp/switchboard-spool.js +107 -0
- package/dist/mcp/switchboard-tools.d.ts +9 -0
- package/dist/mcp/switchboard-tools.js +144 -6
- package/dist/mcp/test-cases.d.ts +14 -0
- package/dist/mcp/test-cases.js +77 -0
- package/dist/mcp/test-runs-tools.d.ts +8 -0
- package/dist/mcp/test-runs-tools.js +95 -0
- package/dist/mcp/tools.d.ts +4 -1
- package/dist/mcp/tools.js +101 -21
- package/dist/mcp/web-child-env.d.ts +4 -1
- package/dist/mcp/web-child-env.js +4 -1
- package/dist/shared/android.d.ts +44 -0
- package/dist/shared/android.js +234 -24
- package/dist/shared/constants.d.ts +9 -4
- package/dist/shared/constants.js +9 -4
- package/dist/shared/feature-flags.d.ts +1 -0
- package/dist/shared/feature-flags.js +1 -0
- package/dist/shared/ios-logs.d.ts +10 -0
- package/dist/shared/ios-logs.js +91 -0
- package/dist/shared/ios.d.ts +25 -2
- package/dist/shared/ios.js +157 -3
- package/dist/{web → shared}/log-session.d.ts +45 -31
- package/dist/shared/log-session.js +300 -0
- package/dist/shared/logcat-capture.js +17 -1
- package/dist/shared/radar-request-raw.d.ts +7 -0
- package/dist/shared/radar-request-raw.js +89 -0
- package/dist/shared/radar-token.d.ts +25 -0
- package/dist/shared/radar-token.js +164 -0
- package/dist/shared/stream.d.ts +3 -0
- package/dist/shared/stream.js +107 -15
- package/dist/shared/switchboard-host-store.d.ts +21 -0
- package/dist/shared/switchboard-host-store.js +166 -0
- package/dist/shared/switchboard-note.d.ts +15 -0
- package/dist/shared/switchboard-note.js +92 -0
- package/dist/shared/switchboard-report-file.d.ts +5 -0
- package/dist/shared/switchboard-report-file.js +26 -0
- package/dist/shared/switchboard-report.d.ts +20 -0
- package/dist/shared/switchboard-report.js +406 -0
- package/dist/shared/switchboard.d.ts +111 -2
- package/dist/shared/switchboard.js +436 -3
- package/dist/shared/transport.d.ts +49 -3
- package/dist/shared/version.d.ts +2 -0
- package/dist/shared/version.js +18 -0
- package/dist/shared/wire.d.ts +14 -1
- package/dist/web/install-app.d.ts +75 -8
- package/dist/web/install-app.js +330 -67
- package/dist/web/macapp/RadarApp.swift +487 -23
- package/dist/web/public/index.html +51 -9
- package/dist/web/public/next/app.js +33 -18
- package/dist/web/public/next/feed.js +102 -15
- package/dist/web/public/next/flags.js +3 -0
- package/dist/web/public/next/inspector.js +69 -3
- package/dist/web/public/next/prefs.js +5 -2
- package/dist/web/public/next/registry.js +18 -5
- package/dist/web/public/next/store.js +455 -29
- package/dist/web/public/next/switchboard-note.js +93 -0
- package/dist/web/public/next/toast.js +9 -5
- package/dist/web/public/next/voice-model.js +215 -35
- package/dist/web/public/next/voice.js +173 -18
- package/dist/web/server.d.ts +15 -11
- package/dist/web/server.js +690 -168
- package/dist/web/spec.d.ts +2 -1
- package/dist/web/spec.js +2 -1
- package/package.json +2 -2
- package/dist/web/log-session.js +0 -166
|
@@ -11,7 +11,23 @@ import path from "path";
|
|
|
11
11
|
* later. Capturing to a local file from session-enable onward preserves
|
|
12
12
|
* everything from the enable moment forward.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
14
|
+
* Starts through ensureLogCapture, a no-op while a child is live:
|
|
15
|
+
* - A landed activate (recordActivateSuccess).
|
|
16
|
+
* - A landed activate_for_user, same profile or not (activateForUser).
|
|
17
|
+
* - An accepted repeat enable (createEnabler).
|
|
18
|
+
* Restarts on a fresh file:
|
|
19
|
+
* - A different or unknown prior profile (activateForUser).
|
|
20
|
+
* - Size rotation (rotateCaptureIfNeeded below).
|
|
21
|
+
* Stops:
|
|
22
|
+
* - Disable (handleSessionDisable) or device switch (onDeviceSwitch).
|
|
23
|
+
* - A full enable that ends disabled (runSessionEnable).
|
|
24
|
+
* - Its idle timer (rescheduleIdleTimer).
|
|
25
|
+
* - The child's own exit (startCapture).
|
|
26
|
+
* - MCP exit (registerCleanup).
|
|
27
|
+
* Survives resetState, the device-side idle timeout, a failed broadcast,
|
|
28
|
+
* any same-device enable that ends enabled, a thrown enable (the catch in
|
|
29
|
+
* createEnabler) and the self-heal auto-disables, which flip
|
|
30
|
+
* sessionEnabled false without stopping the capture.
|
|
15
31
|
*/
|
|
16
32
|
const LOG_DIR = path.join(os.homedir(), ".slack-radar", "logs");
|
|
17
33
|
const ROTATION_BYTES = 100 * 1024 * 1024;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type RadarTokenSender, type TokenSurface } from "./radar-token.js";
|
|
2
|
+
export declare function radarRequestRaw(host: string, port: number, requestPath: string, idleMs: number, overallMs: number, capBytes: number, deadline: number | undefined, transport: RadarTokenSender, surface?: TokenSurface): Promise<{
|
|
3
|
+
status: number;
|
|
4
|
+
body: Record<string, unknown> | null;
|
|
5
|
+
bytes: number;
|
|
6
|
+
capped?: boolean;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// The export path's raw device GET, in its own module so a test can import it and point it at a
|
|
2
|
+
// fake server via host/port.
|
|
3
|
+
//
|
|
4
|
+
// The export report goes to a file, never the model context, so it skips radarRequest's byte
|
|
5
|
+
// budget and uses the generous SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES instead. Never rejects: a
|
|
6
|
+
// network error, timeout, non-JSON, or over-cap body resolves with status 0.
|
|
7
|
+
//
|
|
8
|
+
// deadline is the whole export's absolute wall-clock cutoff (epoch ms); overallMs shrinks to fit
|
|
9
|
+
// it, so callers need not recompute the budget themselves.
|
|
10
|
+
import http from "http";
|
|
11
|
+
import { radarTokenHeaderFor } from "./radar-token.js";
|
|
12
|
+
export function radarRequestRaw(host, port, requestPath, idleMs, overallMs, capBytes, deadline,
|
|
13
|
+
// Required so every caller decides whether the token goes out.
|
|
14
|
+
transport, surface = "mcp") {
|
|
15
|
+
// A past deadline still fires asynchronously; a caller that wants to skip the request entirely
|
|
16
|
+
// checks the deadline itself.
|
|
17
|
+
const effectiveOverallMs = deadline === undefined ? overallMs : Math.max(0, Math.min(overallMs, deadline - Date.now()));
|
|
18
|
+
return new Promise((resolve) => {
|
|
19
|
+
let settled = false;
|
|
20
|
+
let idleTimer;
|
|
21
|
+
let overallTimer;
|
|
22
|
+
const done = (r) => {
|
|
23
|
+
if (settled)
|
|
24
|
+
return;
|
|
25
|
+
settled = true;
|
|
26
|
+
clearTimeout(idleTimer);
|
|
27
|
+
clearTimeout(overallTimer);
|
|
28
|
+
resolve(r);
|
|
29
|
+
};
|
|
30
|
+
// http.get can throw synchronously (a bad port, an unescaped path), caught below so the
|
|
31
|
+
// promise never rejects and no timer arms against an unassigned req.
|
|
32
|
+
let req;
|
|
33
|
+
const armIdle = () => {
|
|
34
|
+
clearTimeout(idleTimer);
|
|
35
|
+
idleTimer = setTimeout(() => {
|
|
36
|
+
req.destroy();
|
|
37
|
+
done({ status: 0, body: null, bytes: 0 });
|
|
38
|
+
}, idleMs);
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
req = http.get({ host, port, path: requestPath, headers: radarTokenHeaderFor(transport, surface) }, (res) => {
|
|
42
|
+
// Decode once at the end: a multi-byte UTF-8 character can split across chunks.
|
|
43
|
+
const chunks = [];
|
|
44
|
+
let bytes = 0;
|
|
45
|
+
armIdle();
|
|
46
|
+
res.on("data", (chunk) => {
|
|
47
|
+
if (settled)
|
|
48
|
+
return;
|
|
49
|
+
armIdle();
|
|
50
|
+
bytes += chunk.length;
|
|
51
|
+
if (bytes > capBytes) {
|
|
52
|
+
// capped tells a deliberate cap abort apart from a network failure of the same shape.
|
|
53
|
+
done({ status: 0, body: null, bytes: 0, capped: true });
|
|
54
|
+
req.destroy();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
chunks.push(chunk);
|
|
58
|
+
});
|
|
59
|
+
// A socket closing mid-body raises this and never "end"; without it the request hangs.
|
|
60
|
+
res.on("error", () => done({ status: 0, body: null, bytes: 0 }));
|
|
61
|
+
res.on("end", () => {
|
|
62
|
+
try {
|
|
63
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
64
|
+
done({
|
|
65
|
+
status: res.statusCode ?? 0,
|
|
66
|
+
body: parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null,
|
|
67
|
+
bytes,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
done({ status: res.statusCode ?? 0, body: null, bytes });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
done({ status: 0, body: null, bytes: 0 });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
// Armed before headers too, so a device that accepts and never answers trips the idle limit.
|
|
81
|
+
armIdle();
|
|
82
|
+
// The idle timer resets on every byte, so only this fixed limit catches a steady trickle.
|
|
83
|
+
overallTimer = setTimeout(() => {
|
|
84
|
+
req.destroy();
|
|
85
|
+
done({ status: 0, body: null, bytes: 0 });
|
|
86
|
+
}, effectiveOverallMs);
|
|
87
|
+
req.on("error", () => done({ status: 0, body: null, bytes: 0 }));
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DeviceTransport } from "./transport.js";
|
|
2
|
+
export declare const RADAR_TOKEN_HEADER = "X-Radar-Token";
|
|
3
|
+
export type TokenSurface = "mcp" | "dashboard";
|
|
4
|
+
export type TokenFileSurface = TokenSurface | "profile";
|
|
5
|
+
export declare class TokenFileError extends Error {
|
|
6
|
+
readonly problem: string;
|
|
7
|
+
readonly fix: string;
|
|
8
|
+
constructor(problem: string, fix: string);
|
|
9
|
+
}
|
|
10
|
+
export declare function tokenFileMessage(error: Pick<TokenFileError, "problem" | "fix">, surface?: TokenFileSurface): string;
|
|
11
|
+
export declare function getOrCreateRadarToken(): string;
|
|
12
|
+
export declare function clearRadarTokenCache(): void;
|
|
13
|
+
export declare function radarTokenHeader(): Record<string, string>;
|
|
14
|
+
export type RadarTokenSender = Pick<DeviceTransport, "sendsRadarToken"> | null | undefined;
|
|
15
|
+
export declare const TOKEN_MISMATCH_MESSAGE = "The device holds a different token than this session's. Check these, then run /radar-enable here. Another machine or OS user enabled Radar on this device: stop that session. Radar was enabled in a different profile: make sure the Slack debug build runs in the profile you want (list_profiles shows which profiles have it). Another Radar session on this machine still uses a token file you deleted: run /radar-enable there too.";
|
|
16
|
+
export declare const TOKEN_MISMATCH_DASHBOARD_MESSAGE = "This device answered to a different Radar token. Stop any other Radar session using it, or run /radar-enable there if you deleted the token file, then press Reconnect.";
|
|
17
|
+
export declare const DEVICE_401_MESSAGE = "The device refused the request (HTTP 401). Run /radar-enable to try again.";
|
|
18
|
+
export declare const DEVICE_401_DASHBOARD_MESSAGE = "The device refused the request (HTTP 401). Press Reconnect to try again.";
|
|
19
|
+
export declare function lastHeaderBuildFailure(): TokenFileError | null;
|
|
20
|
+
export declare function unauthorizedMessageFor(sender: RadarTokenSender, surface?: TokenSurface): string;
|
|
21
|
+
export declare function radarTokenHeaderFor(transport: RadarTokenSender, surface?: TokenSurface): Record<string, string>;
|
|
22
|
+
export declare const OPEN_MODE_WARNING = "The device is in open mode, so anything that reaches the forwarded port can read and change its Radar data. An older Radar MCP or dashboard, or a manual enable broadcast, turned the token check off. If an older Radar MCP or dashboard is still running, stop it, then run /radar-enable.";
|
|
23
|
+
export declare const OPEN_MODE_PROFILE_WARNING = "The device is in open mode even though this enable sent the token, so the broadcast did not reach the server that answered: it likely runs in a different profile and was enabled without a token. Anything that reaches the forwarded port can read and change its Radar data. Run list_profiles, then activate_for_user for the profile you want, or stop the older Radar MCP or dashboard that enabled it.";
|
|
24
|
+
export declare function openModeWarning(tokenRequired: unknown): string | undefined;
|
|
25
|
+
export declare function openModeWarningAfterEnable(tokenRequired: unknown, activateError: string | null): string | undefined;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// One token per OS user, shared by every local Radar process. The file is created once by linking
|
|
2
|
+
// a fully written tmp file, so a reader never sees a partial token and a losing creator adopts the
|
|
3
|
+
// winner's. Anything unusable is the user's to delete: replacing it would change the shared secret.
|
|
4
|
+
// The token stops a process that reaches the forwarded port but not adb or ~/.slack-radar; a
|
|
5
|
+
// writer inside ~/.slack-radar is out of scope, so there are no symlink, owner or mode checks here.
|
|
6
|
+
import crypto from "crypto";
|
|
7
|
+
import fs from "fs";
|
|
8
|
+
import os from "os";
|
|
9
|
+
import path from "path";
|
|
10
|
+
const TOKEN_DIR = path.join(os.homedir(), ".slack-radar");
|
|
11
|
+
const TOKEN_PATH = path.join(TOKEN_DIR, "radar-token");
|
|
12
|
+
const TOKEN_PATH_SHOWN = "~/.slack-radar/radar-token";
|
|
13
|
+
const FIX_DIR = "Make ~/.slack-radar writable by your user";
|
|
14
|
+
const TOKEN_RE = /^[0-9a-f]{64}$/;
|
|
15
|
+
export const RADAR_TOKEN_HEADER = "X-Radar-Token";
|
|
16
|
+
export class TokenFileError extends Error {
|
|
17
|
+
problem;
|
|
18
|
+
fix;
|
|
19
|
+
constructor(problem, fix) {
|
|
20
|
+
super(tokenFileMessage({ problem, fix }));
|
|
21
|
+
this.problem = problem;
|
|
22
|
+
this.fix = fix;
|
|
23
|
+
this.name = "TokenFileError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function tokenFileMessage(error, surface = "mcp") {
|
|
27
|
+
const act = surface === "dashboard" ? "press Reconnect" : surface === "profile" ? "run activate_for_user again" : "run /radar-enable";
|
|
28
|
+
return `${error.problem}. ${error.fix}, then ${act}.`;
|
|
29
|
+
}
|
|
30
|
+
let cachedToken = null;
|
|
31
|
+
function code(error) {
|
|
32
|
+
return error?.code;
|
|
33
|
+
}
|
|
34
|
+
function words(error) {
|
|
35
|
+
return code(error) ? error.message.split(",")[0].replace(/^[A-Z]+: /, "") : "unknown error";
|
|
36
|
+
}
|
|
37
|
+
function readTokenFile() {
|
|
38
|
+
let raw;
|
|
39
|
+
try {
|
|
40
|
+
raw = fs.readFileSync(TOKEN_PATH, "utf8");
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
const errorCode = code(error);
|
|
44
|
+
if (errorCode === "ENOENT")
|
|
45
|
+
return null;
|
|
46
|
+
const fix = errorCode === "EACCES" || errorCode === "EPERM" ? "Fix the permissions on ~/.slack-radar or delete the file" : "Delete it";
|
|
47
|
+
throw new TokenFileError(`Radar cannot read ${TOKEN_PATH_SHOWN} (${words(error)})`, fix);
|
|
48
|
+
}
|
|
49
|
+
const token = raw.trim();
|
|
50
|
+
if (TOKEN_RE.test(token))
|
|
51
|
+
return token;
|
|
52
|
+
throw new TokenFileError(`Radar cannot use its token file (${TOKEN_PATH_SHOWN} does not hold a valid token)`, "Delete it");
|
|
53
|
+
}
|
|
54
|
+
function createTokenFile() {
|
|
55
|
+
const token = crypto.randomBytes(32).toString("hex");
|
|
56
|
+
const tmp = path.join(TOKEN_DIR, `.radar-token.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`);
|
|
57
|
+
fs.mkdirSync(TOKEN_DIR, { recursive: true, mode: 0o700 });
|
|
58
|
+
fs.writeFileSync(tmp, token, { mode: 0o600, flag: "wx" });
|
|
59
|
+
let lostRace = false;
|
|
60
|
+
try {
|
|
61
|
+
fs.linkSync(tmp, TOKEN_PATH);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (code(error) !== "EEXIST")
|
|
65
|
+
throw error;
|
|
66
|
+
lostRace = true;
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
try {
|
|
70
|
+
fs.rmSync(tmp, { force: true });
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// A leftover 0600 tmp is harmless.
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (!lostRace)
|
|
77
|
+
return token;
|
|
78
|
+
const winner = readTokenFile();
|
|
79
|
+
if (winner === null) {
|
|
80
|
+
throw new TokenFileError(`Radar cannot create ${TOKEN_PATH_SHOWN} (it vanished right after another process created it)`, FIX_DIR);
|
|
81
|
+
}
|
|
82
|
+
return winner;
|
|
83
|
+
}
|
|
84
|
+
function asTokenFileError(error) {
|
|
85
|
+
return error instanceof TokenFileError ? error : new TokenFileError(`Radar cannot create ${TOKEN_PATH_SHOWN} (${words(error)})`, FIX_DIR);
|
|
86
|
+
}
|
|
87
|
+
export function getOrCreateRadarToken() {
|
|
88
|
+
if (cachedToken)
|
|
89
|
+
return cachedToken;
|
|
90
|
+
try {
|
|
91
|
+
cachedToken = readTokenFile() ?? createTokenFile();
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw asTokenFileError(error);
|
|
95
|
+
}
|
|
96
|
+
return cachedToken;
|
|
97
|
+
}
|
|
98
|
+
export function clearRadarTokenCache() {
|
|
99
|
+
cachedToken = null;
|
|
100
|
+
lastHeaderFailure = null;
|
|
101
|
+
loggedTokenFailures.clear();
|
|
102
|
+
}
|
|
103
|
+
// Each rendered failure logs once until the cache is cleared.
|
|
104
|
+
const loggedTokenFailures = new Set();
|
|
105
|
+
// One token file per process; good headers clear this, and 401 messages read it to name the token file.
|
|
106
|
+
let lastHeaderFailure = null;
|
|
107
|
+
export function radarTokenHeader() {
|
|
108
|
+
return { [RADAR_TOKEN_HEADER]: getOrCreateRadarToken() };
|
|
109
|
+
}
|
|
110
|
+
const PROFILE_FIX = "make sure the Slack debug build runs in the profile you want (list_profiles shows which profiles have it)";
|
|
111
|
+
const MISMATCH_TAIL = `Check these, then run /radar-enable here. Another machine or OS user enabled Radar on this device: stop that session. Radar was enabled in a different profile: ${PROFILE_FIX}. Another Radar session on this machine still uses a token file you deleted: run /radar-enable there too.`;
|
|
112
|
+
const DASHBOARD_TAIL = "Stop any other Radar session using it, or run /radar-enable there if you deleted the token file, then press Reconnect.";
|
|
113
|
+
export const TOKEN_MISMATCH_MESSAGE = `The device holds a different token than this session's. ${MISMATCH_TAIL}`;
|
|
114
|
+
export const TOKEN_MISMATCH_DASHBOARD_MESSAGE = `This device answered to a different Radar token. ${DASHBOARD_TAIL}`;
|
|
115
|
+
export const DEVICE_401_MESSAGE = "The device refused the request (HTTP 401). Run /radar-enable to try again.";
|
|
116
|
+
export const DEVICE_401_DASHBOARD_MESSAGE = "The device refused the request (HTTP 401). Press Reconnect to try again.";
|
|
117
|
+
export function lastHeaderBuildFailure() {
|
|
118
|
+
return lastHeaderFailure;
|
|
119
|
+
}
|
|
120
|
+
export function unauthorizedMessageFor(sender, surface = "mcp") {
|
|
121
|
+
if (sender?.sendsRadarToken) {
|
|
122
|
+
if (lastHeaderFailure)
|
|
123
|
+
return tokenFileMessage(lastHeaderFailure, surface);
|
|
124
|
+
return surface === "dashboard" ? TOKEN_MISMATCH_DASHBOARD_MESSAGE : TOKEN_MISMATCH_MESSAGE;
|
|
125
|
+
}
|
|
126
|
+
return surface === "dashboard" ? DEVICE_401_DASHBOARD_MESSAGE : DEVICE_401_MESSAGE;
|
|
127
|
+
}
|
|
128
|
+
// Never throws: an empty header lets the request go out so an open-mode device can answer.
|
|
129
|
+
export function radarTokenHeaderFor(transport, surface = "mcp") {
|
|
130
|
+
if (!transport?.sendsRadarToken)
|
|
131
|
+
return {};
|
|
132
|
+
try {
|
|
133
|
+
const header = radarTokenHeader();
|
|
134
|
+
lastHeaderFailure = null;
|
|
135
|
+
return header;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
const failure = asTokenFileError(error);
|
|
139
|
+
lastHeaderFailure = failure;
|
|
140
|
+
const message = tokenFileMessage(failure, surface);
|
|
141
|
+
if (!loggedTokenFailures.has(message)) {
|
|
142
|
+
loggedTokenFailures.add(message);
|
|
143
|
+
try {
|
|
144
|
+
console.error(message);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// stderr can throw EPIPE after the parent exits; the request still goes out.
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return {};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export const OPEN_MODE_WARNING = "The device is in open mode, so anything that reaches the forwarded port can read and change its Radar data. An older Radar MCP or dashboard, or a manual enable broadcast, turned the token check off. If an older Radar MCP or dashboard is still running, stop it, then run /radar-enable.";
|
|
154
|
+
export const OPEN_MODE_PROFILE_WARNING = "The device is in open mode even though this enable sent the token, so the broadcast did not reach the server that answered: it likely runs in a different profile and was enabled without a token. Anything that reaches the forwarded port can read and change its Radar data. Run list_profiles, then activate_for_user for the profile you want, or stop the older Radar MCP or dashboard that enabled it.";
|
|
155
|
+
export function openModeWarning(tokenRequired) {
|
|
156
|
+
return tokenRequired === false ? OPEN_MODE_WARNING : undefined;
|
|
157
|
+
}
|
|
158
|
+
export function openModeWarningAfterEnable(tokenRequired, activateError) {
|
|
159
|
+
if (tokenRequired !== false)
|
|
160
|
+
return undefined;
|
|
161
|
+
return activateError
|
|
162
|
+
? `The device is in open mode: this enable's broadcast failed (${activateError}) and a server enabled without a token answered instead. Anything that reaches the forwarded port can read and change its Radar data. Check the device connection, then run /radar-enable.`
|
|
163
|
+
: OPEN_MODE_PROFILE_WARNING;
|
|
164
|
+
}
|
package/dist/shared/stream.d.ts
CHANGED
|
@@ -29,7 +29,10 @@ export declare function planReconnect(t: DeviceTransport, attempt: number): numb
|
|
|
29
29
|
export declare function setOnReconnect(fn: (() => void) | null): void;
|
|
30
30
|
export declare function noteStreamConnected(): void;
|
|
31
31
|
export declare function _resetReconnectStateForTest(): void;
|
|
32
|
+
export declare function _reconnectAttemptsForTest(): number;
|
|
32
33
|
export declare function isStreamConnected(): boolean;
|
|
34
|
+
export declare function wasStreamRejected(): boolean;
|
|
35
|
+
export declare function clearStreamRejected(): void;
|
|
33
36
|
export declare function clearLocalBuffers(): void;
|
|
34
37
|
export declare function getStreamConnection(): http.ClientRequest | null;
|
|
35
38
|
/**
|
package/dist/shared/stream.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import http from "http";
|
|
2
2
|
import { RADAR_HOST, RADAR_PORT, MAX_LOCAL_BUFFER } from "./constants.js";
|
|
3
3
|
import { writeFrame } from "./event-spool.js";
|
|
4
|
+
import { radarTokenHeaderFor } from "./radar-token.js";
|
|
4
5
|
let transport = null;
|
|
5
6
|
/** Set the transport used to check forwarding state. Call once at startup. */
|
|
6
7
|
export function setTransport(t) {
|
|
@@ -10,11 +11,12 @@ export const localNetworkBuffer = [];
|
|
|
10
11
|
export const localRtmBuffer = [];
|
|
11
12
|
let streamConnection = null;
|
|
12
13
|
let streamConnected = false;
|
|
14
|
+
// Only a 401 sets this; the next stream open or explicit session transition clears it.
|
|
15
|
+
let streamRejected = false;
|
|
13
16
|
const eventWaiters = [];
|
|
14
|
-
//
|
|
15
|
-
// attempt rebuilds it, because
|
|
16
|
-
//
|
|
17
|
-
// stream proxy's cadence (src/web/server.ts).
|
|
17
|
+
// Transport failure cadence. A plain retry reuses the existing adb forward;
|
|
18
|
+
// every other attempt rebuilds it, because waiting cannot revive a dead device
|
|
19
|
+
// end. HTTP refusals use a flat delay without entering this cadence.
|
|
18
20
|
const RETRY_DELAY_MS = 2000;
|
|
19
21
|
const REBUILD_RETRY_DELAY_MS = 1500;
|
|
20
22
|
// Failures since the last successful connect; drives the every-other-attempt
|
|
@@ -52,11 +54,11 @@ export function planReconnect(t, attempt) {
|
|
|
52
54
|
// Schedule the next reconnect attempt. Stale-callback dedup happens at the
|
|
53
55
|
// call sites (the failure handlers no-op unless their request still owns
|
|
54
56
|
// streamConnection), so by the time this runs the disconnect is real. The
|
|
55
|
-
// timer callback
|
|
56
|
-
//
|
|
57
|
-
// on !isForwarded()
|
|
57
|
+
// timer callback re-checks the forward before every connect and keeps the
|
|
58
|
+
// loop alive when that fails. Otherwise connectStream would early-return
|
|
59
|
+
// on !isForwarded(), leaving
|
|
58
60
|
// the stream down even after the device comes back.
|
|
59
|
-
function scheduleReconnect() {
|
|
61
|
+
function scheduleReconnect(opts = {}) {
|
|
60
62
|
// Never leave a previous timer untracked: if a second chain schedules while
|
|
61
63
|
// one is pending, overwriting the ref would orphan the first timer beyond
|
|
62
64
|
// destroyStream()'s reach, and it would resurrect the stream after a
|
|
@@ -66,13 +68,16 @@ function scheduleReconnect() {
|
|
|
66
68
|
clearTimeout(reconnectTimer);
|
|
67
69
|
streamConnection = null;
|
|
68
70
|
streamConnected = false;
|
|
69
|
-
|
|
70
|
-
|
|
71
|
+
const rebuildForward = opts.rebuildForward !== false;
|
|
72
|
+
if (rebuildForward)
|
|
73
|
+
reconnectAttempts++;
|
|
74
|
+
const delay = transport && rebuildForward
|
|
71
75
|
? planReconnect(transport, reconnectAttempts)
|
|
72
76
|
: RETRY_DELAY_MS;
|
|
73
77
|
reconnectTimer = setTimeout(() => {
|
|
74
78
|
reconnectTimer = null;
|
|
75
|
-
|
|
79
|
+
// Odd retries skip rebuilds, so the token needs a fresh forward check.
|
|
80
|
+
if (transport && !(transport.reassertForward?.() ?? transport.ensureForward())) {
|
|
76
81
|
scheduleReconnect();
|
|
77
82
|
return;
|
|
78
83
|
}
|
|
@@ -109,10 +114,20 @@ export function noteStreamConnected() {
|
|
|
109
114
|
export function _resetReconnectStateForTest() {
|
|
110
115
|
onReconnect = null;
|
|
111
116
|
hasConnectedOnce = false;
|
|
117
|
+
streamRejected = false;
|
|
118
|
+
}
|
|
119
|
+
export function _reconnectAttemptsForTest() {
|
|
120
|
+
return reconnectAttempts;
|
|
112
121
|
}
|
|
113
122
|
export function isStreamConnected() {
|
|
114
123
|
return streamConnected;
|
|
115
124
|
}
|
|
125
|
+
export function wasStreamRejected() {
|
|
126
|
+
return streamRejected;
|
|
127
|
+
}
|
|
128
|
+
export function clearStreamRejected() {
|
|
129
|
+
streamRejected = false;
|
|
130
|
+
}
|
|
116
131
|
export function clearLocalBuffers() {
|
|
117
132
|
localNetworkBuffer.length = 0;
|
|
118
133
|
localRtmBuffer.length = 0;
|
|
@@ -156,9 +171,9 @@ export function bufferEvent(parsed) {
|
|
|
156
171
|
if (localRtmBuffer.length > MAX_LOCAL_BUFFER)
|
|
157
172
|
localRtmBuffer.shift();
|
|
158
173
|
}
|
|
159
|
-
// Spool every frame to the session file
|
|
160
|
-
//
|
|
161
|
-
// waiter-notify path below.
|
|
174
|
+
// Spool every frame to the session file, switchboard included, since the MCP export fallback
|
|
175
|
+
// reads it back (switchboard-spool.ts). writeFrame swallows its own errors and no-ops when no
|
|
176
|
+
// spool is open, so this cannot break the buffer or the waiter-notify path below.
|
|
162
177
|
writeFrame(parsed);
|
|
163
178
|
notifyWaiters(parsed);
|
|
164
179
|
}
|
|
@@ -185,6 +200,11 @@ function notifyWaiters(parsed) {
|
|
|
185
200
|
}
|
|
186
201
|
export function waitForEvents({ event_type, channel, source, timeout_ms = 30000, idle_timeout_ms = 3000, }) {
|
|
187
202
|
return new Promise((resolve) => {
|
|
203
|
+
// stopOnRejected only wakes existing waiters; a later one would wait out its timeout.
|
|
204
|
+
if (streamRejected) {
|
|
205
|
+
resolve([]);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
188
208
|
const waiter = {
|
|
189
209
|
eventType: event_type,
|
|
190
210
|
channel,
|
|
@@ -222,6 +242,68 @@ export function connectStream() {
|
|
|
222
242
|
// nulls reconnectTimer before calling here.
|
|
223
243
|
if (streamConnection || reconnectTimer || !transport?.isForwarded())
|
|
224
244
|
return;
|
|
245
|
+
if (transport.acceptsRadarPeer) {
|
|
246
|
+
connectAfterPeerCheck(transport.acceptsRadarPeer.bind(transport));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
openStream();
|
|
250
|
+
}
|
|
251
|
+
function stopOnRejected(request) {
|
|
252
|
+
if (streamConnection !== request)
|
|
253
|
+
return;
|
|
254
|
+
streamConnection = null;
|
|
255
|
+
streamConnected = false;
|
|
256
|
+
streamRejected = true;
|
|
257
|
+
for (const waiter of [...eventWaiters])
|
|
258
|
+
waiter.resolve(waiter.matches);
|
|
259
|
+
}
|
|
260
|
+
// A transport whose listener shares a host-global port with another platform must prove who
|
|
261
|
+
// answers before every connect, reconnects included: the app on the far side of the port can
|
|
262
|
+
// change between attempts. The probe holds streamConnection while it runs, so destroyStream()
|
|
263
|
+
// cancels it and the ownership guard dedups its failure callbacks exactly like the stream's.
|
|
264
|
+
function connectAfterPeerCheck(accepts) {
|
|
265
|
+
streamRejected = false;
|
|
266
|
+
const MAX_PING_BODY = 64 * 1024;
|
|
267
|
+
const fail = () => {
|
|
268
|
+
if (streamConnection !== probe)
|
|
269
|
+
return;
|
|
270
|
+
scheduleReconnect();
|
|
271
|
+
};
|
|
272
|
+
// Radar does not know who owns this port yet, so the identity probe must not carry the secret.
|
|
273
|
+
const probe = http.get({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/ping", timeout: 2000 }, (res) => {
|
|
274
|
+
let body = "";
|
|
275
|
+
res.on("data", (chunk) => {
|
|
276
|
+
if (body.length < MAX_PING_BODY)
|
|
277
|
+
body += chunk.toString();
|
|
278
|
+
});
|
|
279
|
+
res.on("end", () => {
|
|
280
|
+
if (streamConnection !== probe)
|
|
281
|
+
return;
|
|
282
|
+
let peer = null;
|
|
283
|
+
try {
|
|
284
|
+
peer = JSON.parse(body);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
// Unidentified: rejected below.
|
|
288
|
+
}
|
|
289
|
+
if (peer && typeof peer === "object" && !Array.isArray(peer) &&
|
|
290
|
+
accepts(peer)) {
|
|
291
|
+
streamConnection = null;
|
|
292
|
+
openStream();
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
// Any HTTP answer proves the forward still works.
|
|
296
|
+
scheduleReconnect({ rebuildForward: false });
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
res.on("error", fail);
|
|
300
|
+
});
|
|
301
|
+
probe.on("error", fail);
|
|
302
|
+
probe.on("timeout", () => probe.destroy());
|
|
303
|
+
streamConnection = probe;
|
|
304
|
+
}
|
|
305
|
+
function openStream() {
|
|
306
|
+
streamRejected = false;
|
|
225
307
|
// Ownership guard shared by all three failure callbacks of this request. A
|
|
226
308
|
// destroyed request emits its failure events asynchronously (verified: res
|
|
227
309
|
// "error"/"aborted" fire a tick after destroy()), so by the time a stale
|
|
@@ -236,7 +318,17 @@ export function connectStream() {
|
|
|
236
318
|
return;
|
|
237
319
|
scheduleReconnect();
|
|
238
320
|
};
|
|
239
|
-
const req = http.get({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/stream", timeout: 0 }, (res) => {
|
|
321
|
+
const req = http.get({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/stream", timeout: 0, headers: radarTokenHeaderFor(transport) }, (res) => {
|
|
322
|
+
if (res.statusCode !== 200) {
|
|
323
|
+
// destroy() below still emits on res a tick later, after ownership has moved on.
|
|
324
|
+
res.on("error", () => { });
|
|
325
|
+
if (res.statusCode === 401)
|
|
326
|
+
stopOnRejected(req);
|
|
327
|
+
else if (streamConnection === req)
|
|
328
|
+
scheduleReconnect({ rebuildForward: false });
|
|
329
|
+
req.destroy();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
240
332
|
streamConnected = true;
|
|
241
333
|
// Connected cleanly, so the next disconnect starts its rebuild cadence
|
|
242
334
|
// from attempt 1 rather than inheriting a counter grown across the session.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export declare const SWITCHBOARD_HOST_STORE_MAX_RECORDS = 50000;
|
|
2
|
+
export declare const SWITCHBOARD_HOST_STORE_MAX_SESSIONS = 8;
|
|
3
|
+
export declare const SWITCHBOARD_HOST_STORE_MAX_TOTAL_BYTES: number;
|
|
4
|
+
/**
|
|
5
|
+
* Record one live switchboard event. A session_id restarts with the app process, so the same id
|
|
6
|
+
* can name two calls; the entry resets on a second session/begin, or on an id at or below the
|
|
7
|
+
* newest held one with a later timestamp (ids climb within a call). Otherwise the previous call's
|
|
8
|
+
* tail would export as bogus host-recovered records on the new call. A lower id without a later
|
|
9
|
+
* timestamp is a late arrival and is inserted in id order.
|
|
10
|
+
*
|
|
11
|
+
* Duplicates are checked first, so a redelivered begin (even with no timestamp on either copy)
|
|
12
|
+
* does not wipe the entry.
|
|
13
|
+
*/
|
|
14
|
+
export declare function recordSwitchboardStreamed(event: Record<string, unknown>): void;
|
|
15
|
+
/** One session's held records in id order; [] for a session never seen live or already cleared. */
|
|
16
|
+
export declare function getHostSwitchboardRecords(sessionId: number): Record<string, unknown>[];
|
|
17
|
+
/** Ranked by newest record timestamp, not id: ids restart with the app process, timestamps do not. */
|
|
18
|
+
export declare function newestHostSwitchboardSessionId(): number | null;
|
|
19
|
+
export declare function clearSwitchboardHostStore(): void;
|
|
20
|
+
export declare function _hostStoreSessionCountForTest(): number;
|
|
21
|
+
export declare function _hostStoreTotalBytesForTest(): number;
|