@slack/radar-mcp 1.20.0 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -17
- package/dist/mcp/api-paths.d.ts +11 -0
- package/dist/mcp/api-paths.js +56 -20
- package/dist/mcp/dashboard-identity.d.ts +6 -0
- package/dist/mcp/dashboard-identity.js +11 -0
- package/dist/mcp/index.js +138 -36
- package/dist/mcp/logs-result.d.ts +1 -0
- package/dist/mcp/logs-result.js +1 -0
- package/dist/mcp/network-detail.d.ts +5 -0
- package/dist/mcp/network-detail.js +86 -0
- package/dist/mcp/radar-export-get.d.ts +30 -0
- package/dist/mcp/radar-export-get.js +49 -0
- package/dist/mcp/radar-response.d.ts +11 -1
- package/dist/mcp/radar-response.js +23 -3
- package/dist/mcp/session-backfill.d.ts +9 -3
- package/dist/mcp/session-backfill.js +76 -17
- package/dist/mcp/session-detail.js +54 -2
- package/dist/mcp/session-enable.d.ts +1 -0
- package/dist/mcp/session-enable.js +146 -15
- package/dist/mcp/session-query.js +53 -11
- package/dist/mcp/snapshot.js +42 -26
- package/dist/mcp/sources-gate.js +5 -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 +18 -0
- package/dist/mcp/switchboard-tools.js +178 -0
- package/dist/mcp/tools.d.ts +4 -1
- package/dist/mcp/tools.js +114 -23
- 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 +43 -0
- package/dist/shared/android.js +227 -19
- package/dist/shared/constants.d.ts +19 -4
- package/dist/shared/constants.js +19 -4
- package/dist/shared/event-spool.js +3 -2
- package/dist/shared/feature-flags.d.ts +1 -0
- package/dist/shared/feature-flags.js +1 -0
- package/dist/shared/form-body.d.ts +18 -0
- package/dist/shared/form-body.js +251 -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/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 +4 -1
- 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 +118 -0
- package/dist/shared/switchboard.js +487 -0
- package/dist/shared/transport.d.ts +43 -3
- package/dist/shared/version.d.ts +2 -0
- package/dist/shared/version.js +18 -0
- package/dist/shared/wire.d.ts +46 -1
- package/dist/web/install-app.d.ts +57 -8
- package/dist/web/install-app.js +270 -60
- package/dist/web/macapp/RadarApp.swift +340 -22
- package/dist/web/public/index.html +216 -12
- package/dist/web/public/next/app.js +43 -22
- package/dist/web/public/next/db.js +4 -1
- package/dist/web/public/next/feed.js +604 -59
- package/dist/web/public/next/filters.js +158 -40
- package/dist/web/public/next/flags.js +3 -0
- package/dist/web/public/next/form-body.js +252 -0
- package/dist/web/public/next/inspector.js +171 -14
- package/dist/web/public/next/prefs.js +5 -2
- package/dist/web/public/next/registry.js +35 -3
- package/dist/web/public/next/store.js +947 -69
- 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 +712 -0
- package/dist/web/public/next/voice.js +552 -0
- package/dist/web/server.d.ts +20 -9
- package/dist/web/server.js +834 -174
- package/dist/web/spec.d.ts +11 -6
- package/dist/web/spec.js +62 -6
- package/package.json +4 -4
- package/dist/web/log-session.js +0 -166
|
@@ -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
|
@@ -6,7 +6,7 @@ export interface RadarEvent {
|
|
|
6
6
|
[key: string]: unknown;
|
|
7
7
|
}
|
|
8
8
|
export interface ParsedSSE {
|
|
9
|
-
type: "network" | "rtm" | "clog" | "log" | "trace" | `${string}_detail`;
|
|
9
|
+
type: "network" | "rtm" | "clog" | "log" | "trace" | "switchboard" | `${string}_detail`;
|
|
10
10
|
event: RadarEvent;
|
|
11
11
|
}
|
|
12
12
|
export declare const localNetworkBuffer: RadarEvent[];
|
|
@@ -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;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// The host's bounded copy of every switchboard record it streamed live, so an export can still
|
|
2
|
+
// reach a call's true start after the small device ring evicts it.
|
|
3
|
+
//
|
|
4
|
+
// Sizes are each record's JSON length, not heap/RSS, so real memory runs higher than the caps.
|
|
5
|
+
// Cleared on an explicit disable, a device switch, a deliberate clear, and process exit, never on
|
|
6
|
+
// a transient device blip.
|
|
7
|
+
import { SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES } from "./switchboard.js";
|
|
8
|
+
// Well above the device ring (up to 10000), so the host copy outlives a device-side eviction.
|
|
9
|
+
export const SWITCHBOARD_HOST_STORE_MAX_RECORDS = 50000;
|
|
10
|
+
// Session ids restart with the app process, so without a cap stale entries would pile up.
|
|
11
|
+
export const SWITCHBOARD_HOST_STORE_MAX_SESSIONS = 8;
|
|
12
|
+
// The per-session byte cap alone still allows MAX_SESSIONS * SAFETY_CAP_BYTES resident; this is
|
|
13
|
+
// the real ceiling, enforced by evicting whole sessions.
|
|
14
|
+
export const SWITCHBOARD_HOST_STORE_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
let nextSeq = 0;
|
|
16
|
+
// Evicted in Map insertion order. A reset session is deleted and re-inserted, moving it to the
|
|
17
|
+
// back, which is right since it is starting a new call.
|
|
18
|
+
const sessions = new Map();
|
|
19
|
+
let totalBytes = 0;
|
|
20
|
+
function evictOldestSession() {
|
|
21
|
+
const oldestSessionId = sessions.keys().next().value;
|
|
22
|
+
if (oldestSessionId === undefined)
|
|
23
|
+
return;
|
|
24
|
+
const oldest = sessions.get(oldestSessionId);
|
|
25
|
+
if (oldest)
|
|
26
|
+
totalBytes -= oldest.bytes;
|
|
27
|
+
sessions.delete(oldestSessionId);
|
|
28
|
+
}
|
|
29
|
+
function estimateBytes(e) {
|
|
30
|
+
try {
|
|
31
|
+
return Buffer.byteLength(JSON.stringify(e), "utf8");
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Never throw into the stream path.
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Record one live switchboard event. A session_id restarts with the app process, so the same id
|
|
40
|
+
* can name two calls; the entry resets on a second session/begin, or on an id at or below the
|
|
41
|
+
* newest held one with a later timestamp (ids climb within a call). Otherwise the previous call's
|
|
42
|
+
* tail would export as bogus host-recovered records on the new call. A lower id without a later
|
|
43
|
+
* timestamp is a late arrival and is inserted in id order.
|
|
44
|
+
*
|
|
45
|
+
* Duplicates are checked first, so a redelivered begin (even with no timestamp on either copy)
|
|
46
|
+
* does not wipe the entry.
|
|
47
|
+
*/
|
|
48
|
+
export function recordSwitchboardStreamed(event) {
|
|
49
|
+
const id = event.id;
|
|
50
|
+
const sessionId = event.session_id;
|
|
51
|
+
if (typeof id !== "number" || !Number.isFinite(id))
|
|
52
|
+
return;
|
|
53
|
+
if (typeof sessionId !== "number" || !Number.isFinite(sessionId))
|
|
54
|
+
return;
|
|
55
|
+
let entry = sessions.get(sessionId);
|
|
56
|
+
let lateArrival = false;
|
|
57
|
+
if (entry) {
|
|
58
|
+
const held = entry.records.get(id);
|
|
59
|
+
// undefined === undefined counts as a match on purpose (the begin-redelivery case above).
|
|
60
|
+
if (held && held.timestamp === event.timestamp)
|
|
61
|
+
return; // true duplicate, not a restart signal
|
|
62
|
+
const newestHeldId = entry.order.length ? entry.order[entry.order.length - 1] : null;
|
|
63
|
+
const newestHeldRecord = newestHeldId !== null ? entry.records.get(newestHeldId) : undefined;
|
|
64
|
+
const isBegin = event.kind === "session" && event.event === "begin" && entry.order.length > 0;
|
|
65
|
+
const idAtOrBelowNewest = newestHeldId !== null && id <= newestHeldId;
|
|
66
|
+
const isLaterThanNewest = typeof event.timestamp === "number" && typeof newestHeldRecord?.timestamp === "number" && event.timestamp > newestHeldRecord.timestamp;
|
|
67
|
+
const isRegression = idAtOrBelowNewest && isLaterThanNewest;
|
|
68
|
+
if (isBegin || isRegression) {
|
|
69
|
+
totalBytes -= entry.bytes;
|
|
70
|
+
sessions.delete(sessionId);
|
|
71
|
+
entry = undefined;
|
|
72
|
+
}
|
|
73
|
+
else if (idAtOrBelowNewest) {
|
|
74
|
+
lateArrival = true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (!entry) {
|
|
78
|
+
entry = { records: new Map(), order: [], sizes: new Map(), bytes: 0, seq: nextSeq++ };
|
|
79
|
+
sessions.set(sessionId, entry);
|
|
80
|
+
while (sessions.size > SWITCHBOARD_HOST_STORE_MAX_SESSIONS)
|
|
81
|
+
evictOldestSession();
|
|
82
|
+
}
|
|
83
|
+
if (entry.records.has(id))
|
|
84
|
+
return;
|
|
85
|
+
// At the cap, an id older than everything held would be evicted straight back off.
|
|
86
|
+
if (entry.order.length >= SWITCHBOARD_HOST_STORE_MAX_RECORDS && id < entry.order[0])
|
|
87
|
+
return;
|
|
88
|
+
const size = estimateBytes(event);
|
|
89
|
+
entry.records.set(id, event);
|
|
90
|
+
entry.sizes.set(id, size);
|
|
91
|
+
if (lateArrival) {
|
|
92
|
+
// Binary search, since a device streaming ids out of order would make a linear scan per insert.
|
|
93
|
+
let lo = 0;
|
|
94
|
+
let hi = entry.order.length;
|
|
95
|
+
while (lo < hi) {
|
|
96
|
+
const mid = (lo + hi) >> 1;
|
|
97
|
+
if (entry.order[mid] > id)
|
|
98
|
+
hi = mid;
|
|
99
|
+
else
|
|
100
|
+
lo = mid + 1;
|
|
101
|
+
}
|
|
102
|
+
entry.order.splice(lo, 0, id);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
entry.order.push(id);
|
|
106
|
+
}
|
|
107
|
+
entry.bytes += size;
|
|
108
|
+
totalBytes += size;
|
|
109
|
+
while (entry.order.length > 0 && (entry.order.length > SWITCHBOARD_HOST_STORE_MAX_RECORDS || entry.bytes > SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES)) {
|
|
110
|
+
const evictId = entry.order.shift();
|
|
111
|
+
const evictSize = entry.sizes.get(evictId) ?? 0;
|
|
112
|
+
entry.bytes -= evictSize;
|
|
113
|
+
totalBytes -= evictSize;
|
|
114
|
+
entry.sizes.delete(evictId);
|
|
115
|
+
entry.records.delete(evictId);
|
|
116
|
+
}
|
|
117
|
+
// Can evict the session just written to, if it is the oldest-inserted.
|
|
118
|
+
while (totalBytes > SWITCHBOARD_HOST_STORE_MAX_TOTAL_BYTES && sessions.size > 0)
|
|
119
|
+
evictOldestSession();
|
|
120
|
+
}
|
|
121
|
+
/** One session's held records in id order; [] for a session never seen live or already cleared. */
|
|
122
|
+
export function getHostSwitchboardRecords(sessionId) {
|
|
123
|
+
const entry = sessions.get(sessionId);
|
|
124
|
+
if (!entry)
|
|
125
|
+
return [];
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const id of entry.order) {
|
|
128
|
+
const record = entry.records.get(id);
|
|
129
|
+
if (record)
|
|
130
|
+
out.push(record);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
/** Ranked by newest record timestamp, not id: ids restart with the app process, timestamps do not. */
|
|
135
|
+
export function newestHostSwitchboardSessionId() {
|
|
136
|
+
let bestId = null;
|
|
137
|
+
let bestTimestamp = -Infinity;
|
|
138
|
+
let bestRecordId = -Infinity;
|
|
139
|
+
let bestSeq = -1;
|
|
140
|
+
for (const [id, entry] of sessions) {
|
|
141
|
+
const highestHeldId = entry.order.length > 0 ? entry.order[entry.order.length - 1] : -Infinity;
|
|
142
|
+
const highestHeldRecord = entry.order.length > 0 ? entry.records.get(entry.order[entry.order.length - 1]) : undefined;
|
|
143
|
+
const timestamp = typeof highestHeldRecord?.timestamp === "number" && Number.isFinite(highestHeldRecord.timestamp) ? highestHeldRecord.timestamp : -Infinity;
|
|
144
|
+
const better = bestId === null ||
|
|
145
|
+
timestamp > bestTimestamp ||
|
|
146
|
+
(timestamp === bestTimestamp && highestHeldId > bestRecordId) ||
|
|
147
|
+
(timestamp === bestTimestamp && highestHeldId === bestRecordId && entry.seq > bestSeq);
|
|
148
|
+
if (better) {
|
|
149
|
+
bestId = id;
|
|
150
|
+
bestTimestamp = timestamp;
|
|
151
|
+
bestRecordId = highestHeldId;
|
|
152
|
+
bestSeq = entry.seq;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return bestId;
|
|
156
|
+
}
|
|
157
|
+
export function clearSwitchboardHostStore() {
|
|
158
|
+
sessions.clear();
|
|
159
|
+
totalBytes = 0;
|
|
160
|
+
}
|
|
161
|
+
export function _hostStoreSessionCountForTest() {
|
|
162
|
+
return sessions.size;
|
|
163
|
+
}
|
|
164
|
+
export function _hostStoreTotalBytesForTest() {
|
|
165
|
+
return totalBytes;
|
|
166
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare function capitalizeSwitchboardNote(note: string): string;
|
|
2
|
+
export declare const CLIP_PEAK = 0.99;
|
|
3
|
+
export declare function switchboardClockLabel(clock: string): string;
|
|
4
|
+
export declare const SAVED_TURN_DROP_OUTCOMES: readonly string[];
|
|
5
|
+
export declare const SAVED_TURN_KEPT_OUTCOMES: readonly string[];
|
|
6
|
+
export declare const SAVED_TURN_OUTCOMES: readonly string[];
|
|
7
|
+
export declare const SWITCHBOARD_CONTROL_CHARS: RegExp;
|
|
8
|
+
export declare function stripSwitchboardControlChars(s: string): string;
|
|
9
|
+
export declare function switchboardDeviceToken(name: string): string;
|
|
10
|
+
export declare function savedTurnCountWord(outcome: string): string;
|
|
11
|
+
export declare function savedTurnLabel(outcome: unknown, hasThread: unknown): string;
|
|
12
|
+
export declare function savedTurnCountEntries(counts: unknown): {
|
|
13
|
+
outcome: string;
|
|
14
|
+
count: number | null;
|
|
15
|
+
}[];
|