relay-companion 0.1.634 → 0.1.635
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 +2 -0
- package/bootstrap/installation-health.cjs +98 -4
- package/bootstrap/mac-background-identity.cjs +84 -11
- package/bootstrap/mac-registration-transaction.cjs +6 -1
- package/bootstrap/mac-service-recovery.cjs +42 -5
- package/bootstrap/recovery-readiness.cjs +37 -6
- package/bootstrap/recovery-runner.cjs +20 -4
- package/bootstrap/relay-setup.cjs +160 -26
- package/bootstrap/runtime-health.cjs +29 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
This is the public, auditable source for the `relay-companion` npm package and Relay desktop runtime.
|
|
4
4
|
|
|
5
|
+
[Relay](https://sendrelays.com) sends messages, files and context from your AI to someone else's AI. It works in Claude, ChatGPT, Claude Code and Codex, and the other person needs nothing installed to read and reply. Read [what Relay is](https://sendrelays.com/what-is-relay) and [ways people use it](https://sendrelays.com/use-cases).
|
|
6
|
+
|
|
5
7
|
To **create a Relay link without installing anything**, use the [SendRelays guest HTTP API instructions](https://sendrelays.com/guest-links.txt). Agents with an HTTP POST tool can create text links and exchange private replies without an account or local MCP. Web search alone cannot submit the request. This package is for the installed, connected account experience.
|
|
6
8
|
|
|
7
9
|
Relay connects Claude Code, Cowork, and Codex to a shared inbox. The first-contact package has no install lifecycle and, in thin-installer releases, no dependencies. `setup` downloads the exact platform runtime from `api.sendrelays.com`, checks its signed manifest and SHA-512 digest, and only then activates it.
|
|
@@ -3,9 +3,85 @@ const fs = require("node:fs");
|
|
|
3
3
|
const os = require("node:os");
|
|
4
4
|
const path = require("node:path");
|
|
5
5
|
const crypto = require("node:crypto");
|
|
6
|
-
const {
|
|
6
|
+
const { spawnSync } = require("node:child_process");
|
|
7
|
+
const { runtimeProcessCommands, exactRuntimeHealth, linuxPillStatusPath } = require("./runtime-health.cjs");
|
|
7
8
|
const { progressPath, PROGRESS_FRESH_MS } = require("./daemon-progress.cjs");
|
|
8
9
|
function read(file) { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } }
|
|
10
|
+
const defaultRun = (command, args) => spawnSync(command, args, { encoding: "utf8", timeout: 5_000, windowsHide: true });
|
|
11
|
+
const commandOk = (result) => Boolean(result && !result.error && result.status === 0);
|
|
12
|
+
const PILL_LABEL = "work.relay.companion.pill";
|
|
13
|
+
|
|
14
|
+
// What the operating system says about the app (the pill), as opposed to what
|
|
15
|
+
// the updater believes it did. Sven's pill was dead for two days on 2026-10-10
|
|
16
|
+
// while the daemon kept reporting in and the fleet showed his machine healthy:
|
|
17
|
+
// the launch agent's program path pointed at a deleted release. Whether a pill
|
|
18
|
+
// process exists, whether its absence was chosen, how it last exited and whether
|
|
19
|
+
// its registered launch path still resolves are the facts that would have said
|
|
20
|
+
// so on the first day. Intent comes with it, so a pill someone quit or put away
|
|
21
|
+
// is never an alarm.
|
|
22
|
+
function pillLiveness({ homeDir, platform, env = process.env, live, current, run = defaultRun, now = Date.now() } = {}) {
|
|
23
|
+
const running = live?.pill === true;
|
|
24
|
+
let intent = "running";
|
|
25
|
+
try { if (require("./recovery-intent.cjs").stopped(homeDir)) intent = "stopped"; } catch {}
|
|
26
|
+
const statusPath = linuxPillStatusPath({ homeDir, env });
|
|
27
|
+
let lastSeenAt = null;
|
|
28
|
+
try {
|
|
29
|
+
const modified = Number(fs.statSync(statusPath).mtimeMs);
|
|
30
|
+
if (modified > 0 && modified <= now) lastSeenAt = new Date(modified).toISOString();
|
|
31
|
+
} catch {}
|
|
32
|
+
const status = read(statusPath);
|
|
33
|
+
if (intent === "running" && running && (status?.pillHidden === true || status?.dismissed === true)) intent = "hidden";
|
|
34
|
+
const pill = { running, intent, lastSeenAt, lastExit: null, launch: null };
|
|
35
|
+
try {
|
|
36
|
+
if (platform === "darwin") {
|
|
37
|
+
pill.launch = macPillLaunch({ homeDir, current, run });
|
|
38
|
+
if (!running) pill.lastExit = macPillLastExit(run);
|
|
39
|
+
} else if (platform === "linux" && !running) {
|
|
40
|
+
pill.lastExit = linuxPillLastExit(run);
|
|
41
|
+
}
|
|
42
|
+
} catch {}
|
|
43
|
+
return pill;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Does the pill's registered launch path still lead to the release the launch
|
|
47
|
+
// file names? A dangling or re-pointed ~/.relay/runtime/Relay.app link is
|
|
48
|
+
// invisible to every process-based check until launchd fails to start the pill.
|
|
49
|
+
function macPillLaunch({ homeDir, current, run }) {
|
|
50
|
+
const mac = require("./mac-service-recovery.cjs");
|
|
51
|
+
let record;
|
|
52
|
+
try { record = mac.readRegistration(PILL_LABEL, { homeDir, run }); }
|
|
53
|
+
catch (error) {
|
|
54
|
+
// The first token only (ENOENT, invalid-service-plist, ...): never a path.
|
|
55
|
+
return { ok: false, reason: `registration-invalid: ${String(error?.code || error?.message || "unknown").split(/[:\s]/)[0].slice(0, 40)}` };
|
|
56
|
+
}
|
|
57
|
+
if (record.releaseExecutable) {
|
|
58
|
+
const identity = require("./mac-background-identity.cjs");
|
|
59
|
+
const link = identity.inspectStablePillLink({ homeDir });
|
|
60
|
+
if (!link.present || !link.resolves) return { ok: false, reason: "link-dangling" };
|
|
61
|
+
const expected = path.resolve(record.releaseExecutable, "..", "..", "..");
|
|
62
|
+
const target = link.target ? path.resolve(path.dirname(link.link), link.target) : null;
|
|
63
|
+
if (target && target !== expected) return { ok: false, reason: "link-wrong-release" };
|
|
64
|
+
}
|
|
65
|
+
if (current?.packageRoot && record.packageRoot !== current.packageRoot) return { ok: false, reason: "registration-not-active-runtime" };
|
|
66
|
+
return { ok: true, reason: null };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function macPillLastExit(run) {
|
|
70
|
+
const userId = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
71
|
+
const result = run("/bin/launchctl", ["print", `gui/${userId}/${PILL_LABEL}`]);
|
|
72
|
+
if (!commandOk(result)) return null;
|
|
73
|
+
const code = /\blast exit code = (\d+)/.exec(String(result.stdout || ""))?.[1];
|
|
74
|
+
return code === undefined ? null : { code: Number(code), reason: null };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function linuxPillLastExit(run) {
|
|
78
|
+
const result = run("systemctl", ["--user", "show", `${PILL_LABEL}.service`, "-p", "ExecMainStatus", "-p", "Result"]);
|
|
79
|
+
if (!commandOk(result)) return null;
|
|
80
|
+
const output = String(result.stdout || "");
|
|
81
|
+
const code = /\bExecMainStatus=(\d+)/.exec(output)?.[1];
|
|
82
|
+
const reason = /\bResult=([a-z-]+)/.exec(output)?.[1] || null;
|
|
83
|
+
return code === undefined && !reason ? null : { code: code === undefined ? null : Number(code), reason: reason ? reason.slice(0, 40) : null };
|
|
84
|
+
}
|
|
9
85
|
function installationId({ homeDir = os.homedir(), create = false } = {}) {
|
|
10
86
|
const file = path.join(homeDir, ".relay", "installation-id.json");
|
|
11
87
|
const existing = read(file);
|
|
@@ -36,7 +112,7 @@ function componentInventory(commands, activeVersion = null) {
|
|
|
36
112
|
return { components: components.slice(0, 12), duplicates, mixed };
|
|
37
113
|
}
|
|
38
114
|
function collectInstallationHealth({ homeDir = os.homedir(), platform = process.platform, arch = process.arch,
|
|
39
|
-
osVersion = os.release(), commands, now = Date.now() } = {}) {
|
|
115
|
+
osVersion = os.release(), commands, now = Date.now(), run = defaultRun, env = process.env } = {}) {
|
|
40
116
|
const root = path.join(homeDir, ".relay"), current = read(path.join(root, "runtime", "current.json"));
|
|
41
117
|
const activeVersion = current?.active === true ? current.version : null;
|
|
42
118
|
const processCommands = commands || runtimeProcessCommands(platform);
|
|
@@ -54,10 +130,15 @@ function collectInstallationHealth({ homeDir = os.homedir(), platform = process.
|
|
|
54
130
|
&& (!progressSupported || progressFresh));
|
|
55
131
|
const componentNames = ["inbox-background", "agent-sessions", "topics", "tasks"];
|
|
56
132
|
const unhealthyComponents = progressMatches ? componentNames.filter(name => ["failed", "stalled"].includes(progress.components?.[name])) : [];
|
|
133
|
+
const pill = pillLiveness({ homeDir, platform, env, live, current, run, now });
|
|
57
134
|
let serviceHealth = { state: "healthy", reason: "ready", components: unhealthyComponents };
|
|
58
135
|
if (!activeVersion) serviceHealth = { ...serviceHealth, state: "unverified", reason: "runtime-not-active" };
|
|
59
136
|
else if (!live?.daemon) serviceHealth = { ...serviceHealth, state: "failed", reason: "daemon-missing" };
|
|
60
137
|
else if (!daemonResponsive) serviceHealth = { ...serviceHealth, state: "failed", reason: "daemon-not-responsive" };
|
|
138
|
+
// A pill that was quit is waiting on the person; one that is simply gone is a
|
|
139
|
+
// failure of its own, named as such rather than folded into a process mismatch.
|
|
140
|
+
else if (!live?.pill && pill.intent === "stopped") serviceHealth = { ...serviceHealth, state: "waiting", reason: "pill-stopped" };
|
|
141
|
+
else if (!live?.pill) serviceHealth = { ...serviceHealth, state: "failed", reason: "pill-missing" };
|
|
61
142
|
else if (!live?.ok) serviceHealth = { ...serviceHealth, state: "failed", reason: "service-process-mismatch" };
|
|
62
143
|
else if (unhealthyComponents.length) serviceHealth = { ...serviceHealth, state: "degraded", reason: "component-failed" };
|
|
63
144
|
else if (progressMatches && ["offline", "signed-out"].includes(progress.phase)) serviceHealth = { ...serviceHealth, state: "waiting", reason: progress.phase };
|
|
@@ -69,7 +150,7 @@ function collectInstallationHealth({ homeDir = os.homedir(), platform = process.
|
|
|
69
150
|
};
|
|
70
151
|
return {
|
|
71
152
|
installationId: installationId({ homeDir }), os: platform, osVersion: osVersion.slice(0, 80), arch,
|
|
72
|
-
...inventory, daemonResponsive, health: serviceHealth,
|
|
153
|
+
...inventory, daemonResponsive, health: serviceHealth, pill,
|
|
73
154
|
recovery: supervisor || monitorFailure ? { status: supervisor?.status || monitor.state, version: supervisor?.launcherVersion || null,
|
|
74
155
|
checkedAt: supervisor?.checkedAt > 0 ? new Date(supervisor.checkedAt).toISOString() : null,
|
|
75
156
|
desiredVersion: supervisor?.desiredVersion || null,
|
|
@@ -90,9 +171,22 @@ function describeInstallationHealth(installation) {
|
|
|
90
171
|
const reason = installation?.health?.reason;
|
|
91
172
|
const message = ({ "daemon-missing": "Background service stopped", "daemon-not-responsive": "Background service is not responding",
|
|
92
173
|
"service-process-mismatch": "Relay services are not running together correctly", "component-failed": "An optional background component needs attention",
|
|
174
|
+
"pill-missing": "Relay app is not running", "pill-stopped": "Relay app was quit",
|
|
93
175
|
"recovery-failed": "Recovery needs attention", "offline": "Waiting for Relay's connection", "signed-out": "Waiting for sign-in",
|
|
94
176
|
"runtime-not-active": "Runtime health has not been verified", "legacy-readiness": "Background service running; readiness not verified",
|
|
95
177
|
"ready": "Relay is running" })[reason] || "Runtime health has not been verified";
|
|
96
178
|
return message + (["restarting", "reactivating", "restoring-local", "downloading"].includes(installation?.recovery?.status) ? "; recovery in progress" : "");
|
|
97
179
|
}
|
|
98
|
-
|
|
180
|
+
/** One doctor line about the app, from the OS facts above. */
|
|
181
|
+
function describePillLiveness(pill) {
|
|
182
|
+
if (!pill) return "not reported";
|
|
183
|
+
if (pill.running) return pill.intent === "hidden" ? "running, hidden by choice" : "running";
|
|
184
|
+
if (pill.intent === "stopped") return "not running; it was quit on purpose (relay pill starts it again)";
|
|
185
|
+
const parts = [`NOT running${pill.lastSeenAt ? ` since ${pill.lastSeenAt}` : ""}`];
|
|
186
|
+
if (pill.lastExit && pill.lastExit.code !== null) parts.push(`last exit code ${pill.lastExit.code}${pill.lastExit.reason ? ` (${pill.lastExit.reason})` : ""}`);
|
|
187
|
+
else if (pill.lastExit?.reason) parts.push(`last exit ${pill.lastExit.reason}`);
|
|
188
|
+
if (pill.launch && pill.launch.ok === false) parts.push(`cannot launch: ${pill.launch.reason}`);
|
|
189
|
+
parts.push("fix with: relay repair-installation");
|
|
190
|
+
return parts.join("; ");
|
|
191
|
+
}
|
|
192
|
+
module.exports = { installationId, componentInventory, collectInstallationHealth, recordTransport, describeInstallationHealth, describePillLiveness, pillLiveness };
|
|
@@ -74,33 +74,106 @@ function preferredMacElectronExecutable(electronPath, { existsSync = fs.existsSy
|
|
|
74
74
|
// behaviour), and a real directory at the link path is never replaced.
|
|
75
75
|
const STABLE_PILL_BUNDLE = Object.freeze([".relay", "runtime", "Relay.app"]);
|
|
76
76
|
|
|
77
|
+
function stablePillLink(homeDir) {
|
|
78
|
+
return path.join(homeDir, ...STABLE_PILL_BUNDLE);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Re-point the link at `bundle` atomically. A real directory at the link path
|
|
82
|
+
// is never replaced: false means the link could not be (and was not) changed.
|
|
83
|
+
function pointStablePillLink(bundle, { homeDir, fsImpl = fs, pid = process.pid } = {}) {
|
|
84
|
+
const link = stablePillLink(homeDir);
|
|
85
|
+
const existing = fsImpl.lstatSync(link, { throwIfNoEntry: false });
|
|
86
|
+
if (existing && !existing.isSymbolicLink()) return false;
|
|
87
|
+
if (existing && fsImpl.readlinkSync(link) === bundle) return true;
|
|
88
|
+
fsImpl.mkdirSync(path.dirname(link), { recursive: true });
|
|
89
|
+
const temporary = `${link}.${pid}.tmp`;
|
|
90
|
+
try { fsImpl.unlinkSync(temporary); } catch {}
|
|
91
|
+
fsImpl.symlinkSync(bundle, temporary, "dir");
|
|
92
|
+
fsImpl.renameSync(temporary, link);
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
|
|
77
96
|
function stablePillExecutable(electronExecutable, { homeDir, fsImpl = fs, pid = process.pid } = {}) {
|
|
78
97
|
const value = String(electronExecutable || "");
|
|
79
98
|
if (!homeDir || !value) return electronExecutable;
|
|
80
99
|
const bundle = path.resolve(value, "..", "..", "..");
|
|
81
100
|
if (path.extname(bundle) !== ".app" || path.basename(path.dirname(value)) !== "MacOS") return electronExecutable;
|
|
82
|
-
const link = path.join(homeDir, ...STABLE_PILL_BUNDLE);
|
|
83
101
|
try {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (!existing || fsImpl.readlinkSync(link) !== bundle) {
|
|
87
|
-
fsImpl.mkdirSync(path.dirname(link), { recursive: true });
|
|
88
|
-
const temporary = `${link}.${pid}.tmp`;
|
|
89
|
-
try { fsImpl.unlinkSync(temporary); } catch {}
|
|
90
|
-
fsImpl.symlinkSync(bundle, temporary, "dir");
|
|
91
|
-
fsImpl.renameSync(temporary, link);
|
|
92
|
-
}
|
|
93
|
-
const stable = path.join(link, "Contents", "MacOS", path.basename(value));
|
|
102
|
+
if (!pointStablePillLink(bundle, { homeDir, fsImpl, pid })) return electronExecutable;
|
|
103
|
+
const stable = path.join(stablePillLink(homeDir), "Contents", "MacOS", path.basename(value));
|
|
94
104
|
return fsImpl.statSync(stable).isFile() ? stable : electronExecutable;
|
|
95
105
|
} catch {
|
|
96
106
|
return electronExecutable;
|
|
97
107
|
}
|
|
98
108
|
}
|
|
99
109
|
|
|
110
|
+
// The link is ours to rewrite, so a pill plist that launches through it is
|
|
111
|
+
// only as good as the Electron bundle of the package it runs. 2026-10-10: a
|
|
112
|
+
// rolled-back activation restored the plist but left the link on the failed
|
|
113
|
+
// release, cleanup then deleted that release, and every later update refused
|
|
114
|
+
// to start because the link no longer resolved. Validate and repair against
|
|
115
|
+
// the registered package instead of wherever the link happens to point.
|
|
116
|
+
//
|
|
117
|
+
// Returns the same executable inside packageRoot's own bundle, or null when
|
|
118
|
+
// `executable` does not launch through the link.
|
|
119
|
+
function stablePillReleaseExecutable(executable, packageRoot, { homeDir, fsImpl = fs } = {}) {
|
|
120
|
+
if (!homeDir || !packageRoot) return null;
|
|
121
|
+
const prefix = path.join(stablePillLink(homeDir), "Contents", "MacOS") + path.sep;
|
|
122
|
+
const value = String(executable || "");
|
|
123
|
+
if (!value.startsWith(prefix) || value.slice(prefix.length).includes(path.sep)) return null;
|
|
124
|
+
// A real directory there is never re-pointed, so it is checked as it stands.
|
|
125
|
+
const lstat = typeof fsImpl.lstatSync === "function" ? fsImpl.lstatSync.bind(fsImpl) : fs.lstatSync;
|
|
126
|
+
try {
|
|
127
|
+
const existing = lstat(stablePillLink(homeDir), { throwIfNoEntry: false });
|
|
128
|
+
if (existing && !existing.isSymbolicLink()) return null;
|
|
129
|
+
} catch { return null; }
|
|
130
|
+
const existsSync = typeof fsImpl.existsSync === "function" ? fsImpl.existsSync.bind(fsImpl) : fs.existsSync;
|
|
131
|
+
const inventory = require("./runtime-executables.cjs").runtimeExecutableInventory(packageRoot, { platform: "darwin", existsSync });
|
|
132
|
+
const bundle = inventory.ok
|
|
133
|
+
? path.resolve(inventory.electronPath, "..", "..", "..")
|
|
134
|
+
: path.join(packageRoot, "node_modules", "electron", "dist", "Electron.app");
|
|
135
|
+
return path.join(bundle, "Contents", "MacOS", path.basename(value));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Point the link at the bundle a pill registration runs, before launchd starts
|
|
140
|
+
* it. `record` is a readRegistration result; a plist that names a release path
|
|
141
|
+
* directly needs nothing.
|
|
142
|
+
*/
|
|
143
|
+
function alignStablePillLink(record, { homeDir, fsImpl = fs } = {}) {
|
|
144
|
+
if (!record?.releaseExecutable) return { ok: true, changed: false };
|
|
145
|
+
const bundle = path.resolve(record.releaseExecutable, "..", "..", "..");
|
|
146
|
+
let before = null;
|
|
147
|
+
try { before = fsImpl.readlinkSync(stablePillLink(homeDir)); } catch {}
|
|
148
|
+
if (before === bundle) return { ok: true, changed: false };
|
|
149
|
+
// A real directory there is someone else's; leave it exactly as before.
|
|
150
|
+
if (!pointStablePillLink(bundle, { homeDir, fsImpl })) return { ok: true, changed: false, skipped: "stable-pill-link-not-symlink" };
|
|
151
|
+
return { ok: true, changed: true, from: before, to: bundle };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Where the link points and whether its executable exists, for doctor and cleanup. */
|
|
155
|
+
function inspectStablePillLink({ homeDir, fsImpl = fs } = {}) {
|
|
156
|
+
const link = stablePillLink(homeDir);
|
|
157
|
+
let stat;
|
|
158
|
+
try { stat = fsImpl.lstatSync(link, { throwIfNoEntry: false }); } catch { stat = null; }
|
|
159
|
+
if (!stat) return { present: false, link };
|
|
160
|
+
if (!stat.isSymbolicLink()) return { present: true, symlink: false, link, resolves: true };
|
|
161
|
+
let target = null;
|
|
162
|
+
try { target = fsImpl.readlinkSync(link); } catch {}
|
|
163
|
+
const resolves = [RELAY_MAC_EXECUTABLE_NAME, LEGACY_MAC_EXECUTABLE_NAME].some((name) => {
|
|
164
|
+
try { return fsImpl.statSync(path.join(link, "Contents", "MacOS", name)).isFile(); } catch { return false; }
|
|
165
|
+
});
|
|
166
|
+
return { present: true, symlink: true, link, target, resolves };
|
|
167
|
+
}
|
|
168
|
+
|
|
100
169
|
module.exports = {
|
|
101
170
|
LEGACY_MAC_EXECUTABLE_NAME,
|
|
102
171
|
STABLE_PILL_BUNDLE,
|
|
172
|
+
alignStablePillLink,
|
|
173
|
+
inspectStablePillLink,
|
|
103
174
|
stablePillExecutable,
|
|
175
|
+
stablePillLink,
|
|
176
|
+
stablePillReleaseExecutable,
|
|
104
177
|
RELAY_MAC_ASSOCIATED_BUNDLE_IDENTIFIERS,
|
|
105
178
|
RELAY_MAC_EXECUTABLE_NAME,
|
|
106
179
|
associatedBundleIdentifiersPlist,
|
|
@@ -4,7 +4,7 @@ const os = require("node:os");
|
|
|
4
4
|
const path = require("node:path");
|
|
5
5
|
const crypto = require("node:crypto");
|
|
6
6
|
const { spawnSync } = require("node:child_process");
|
|
7
|
-
const { LABELS, registration, readRegistration } = require("./mac-service-recovery.cjs");
|
|
7
|
+
const { LABELS, alignPillLink, registration, readRegistration } = require("./mac-service-recovery.cjs");
|
|
8
8
|
const defaultRun = (cmd, args, options = {}) => spawnSync(cmd, args, { encoding: "utf8", timeout: 10_000, windowsHide: true, ...options });
|
|
9
9
|
const snapshotPath = homeDir => path.join(homeDir, ".relay", "runtime", "mac-registrations.json");
|
|
10
10
|
const ok = r => Boolean(r && !r.error && r.status === 0);
|
|
@@ -119,6 +119,11 @@ async function restoreSnapshot({ homeDir = os.homedir(), fsImpl = fs, run = defa
|
|
|
119
119
|
return readRegistration(label, { homeDir, fsImpl, run, contents: saved.bytes });
|
|
120
120
|
});
|
|
121
121
|
if (records.some(record => record.packageRoot !== snapshot.previousRoot) || (expectedRoot && expectedRoot !== snapshot.previousRoot)) throw Error("registration-snapshot-target-mismatch");
|
|
122
|
+
// The restored pill plist names ~/.relay/runtime/Relay.app, which the failed
|
|
123
|
+
// activation re-pointed at its own release; that release is deleted once the
|
|
124
|
+
// rollback succeeds. Point the link back before anything is relaunched.
|
|
125
|
+
// Fail open: cleanup keeps whatever release the link still points into.
|
|
126
|
+
try { if (alignPillLink(records, { homeDir, fsImpl }).changed) changed = true; } catch {}
|
|
122
127
|
// Restore both durable files first. Interruption here is replayed from the
|
|
123
128
|
// intact snapshot; the application tree is never needed to regenerate them.
|
|
124
129
|
for (const record of records) {
|
|
@@ -30,11 +30,43 @@ function readRegistration(label, { homeDir = os.homedir(), run = defaultRun, fsI
|
|
|
30
30
|
const suffix = label === LABELS[0] ? /[\\/]bin[\\/]relay\.js$/ : /[\\/]overlay[\\/]main\.cjs$/;
|
|
31
31
|
const script = args.find(x => /[\\/]node_modules[\\/]relay-companion[\\/]/.test(x) && suffix.test(x));
|
|
32
32
|
if (!script || !path.isAbsolute(args[0]) || !path.isAbsolute(script) || (label === LABELS[0] && !args.includes("daemon"))) throw Error(`invalid-service-target: ${label}`);
|
|
33
|
-
for (const filename of [args[0], script]) if (!fsImpl.statSync(filename).isFile()) throw Error(`missing-service-target: ${label}`);
|
|
34
33
|
const packageRoot = script.replace(suffix, "");
|
|
34
|
+
// A pill that launches through ~/.relay/runtime/Relay.app is checked against
|
|
35
|
+
// its own package's Electron, not the link's current target; callers align
|
|
36
|
+
// the link before launchd starts it (see stablePillReleaseExecutable).
|
|
37
|
+
const releaseExecutable = label === LABELS[1]
|
|
38
|
+
? require("./mac-background-identity.cjs").stablePillReleaseExecutable(args[0], packageRoot, { homeDir, fsImpl })
|
|
39
|
+
: null;
|
|
40
|
+
for (const filename of [releaseExecutable || args[0], script]) if (!fsImpl.statSync(filename).isFile()) throw Error(`missing-service-target: ${label}`);
|
|
35
41
|
const pkg = JSON.parse(fsImpl.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
|
|
36
42
|
if (pkg.name !== "relay-companion") throw Error(`invalid-service-package: ${label}`);
|
|
37
|
-
return { label, file, bytes, executable: args[0], script, packageRoot, version: pkg.version };
|
|
43
|
+
return { label, file, bytes, executable: args[0], releaseExecutable, script, packageRoot, version: pkg.version };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Before launchd starts a pill registration, make the stable link it may launch
|
|
47
|
+
// through point at that registration's own bundle.
|
|
48
|
+
function alignPillLink(records, { homeDir, fsImpl = fs } = {}) {
|
|
49
|
+
const pill = records.find(record => record.label === LABELS[1]);
|
|
50
|
+
return require("./mac-background-identity.cjs").alignStablePillLink(pill, { homeDir, fsImpl });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Updaters from 0.1.613 to 0.1.634 refuse every activation while the link
|
|
54
|
+
// dangles, and their watchdog never gets past restarting the pill, so the only
|
|
55
|
+
// new code such a Mac runs is the candidate's CLI startup check. Every CLI start
|
|
56
|
+
// therefore repairs exactly this state: a dangling link, a committed runtime,
|
|
57
|
+
// and a pill plist that runs that runtime. Anything else is left alone.
|
|
58
|
+
function healDanglingPillLink({ homeDir = os.homedir(), platform = process.platform, run = defaultRun, fsImpl = fs } = {}) {
|
|
59
|
+
if (platform !== "darwin") return { changed: false };
|
|
60
|
+
const identity = require("./mac-background-identity.cjs");
|
|
61
|
+
const link = identity.inspectStablePillLink({ homeDir, fsImpl });
|
|
62
|
+
if (!link.present || !link.symlink || link.resolves) return { changed: false };
|
|
63
|
+
let current;
|
|
64
|
+
try { current = JSON.parse(fsImpl.readFileSync(path.join(homeDir, ".relay", "runtime", "current.json"), "utf8")); }
|
|
65
|
+
catch { return { changed: false, skipped: "runtime-pointer-unreadable" }; }
|
|
66
|
+
if (current?.active !== true || !current.packageRoot) return { changed: false, skipped: "runtime-not-active" };
|
|
67
|
+
const record = readRegistration(LABELS[1], { homeDir, run, fsImpl });
|
|
68
|
+
if (record.packageRoot !== current.packageRoot) return { changed: false, skipped: "registration-not-active-runtime" };
|
|
69
|
+
return identity.alignStablePillLink(record, { homeDir, fsImpl });
|
|
38
70
|
}
|
|
39
71
|
|
|
40
72
|
async function repairMacServiceRegistrations({
|
|
@@ -61,12 +93,16 @@ async function repairMacServiceRegistrations({
|
|
|
61
93
|
// registration. They may describe a candidate while the journal is inactive.
|
|
62
94
|
const records = LABELS.map(label => readRegistration(label, { homeDir, run, fsImpl }));
|
|
63
95
|
if (records[0].packageRoot !== records[1].packageRoot) throw Error("mixed-service-targets");
|
|
96
|
+
const link = alignPillLink(records, { homeDir, fsImpl });
|
|
97
|
+
if (link.changed) repaired.push("stable-pill-link");
|
|
64
98
|
for (const record of records) {
|
|
65
99
|
const observed = registration(record.label, { run, userId });
|
|
66
100
|
if (!observed.known) throw Error(`service-registration-query-failed: ${record.label}`);
|
|
67
|
-
|
|
101
|
+
// A pill running through the link that just moved would start its next
|
|
102
|
+
// Electron helper from the other bundle; restart it on the new one.
|
|
103
|
+
if (observed.present && observed.pid && isAlive(observed.pid) && !(link.changed && record.label === LABELS[1])) continue;
|
|
68
104
|
const args = observed.present
|
|
69
|
-
? ["kickstart", `gui/${userId}/${record.label}`]
|
|
105
|
+
? ["kickstart", ...(observed.pid ? ["-k"] : []), `gui/${userId}/${record.label}`]
|
|
70
106
|
: ["bootstrap", `gui/${userId}`, record.file];
|
|
71
107
|
if (require("./recovery-intent.cjs").stopped(homeDir)) return { ok: true, changed: repaired.length > 0, status: "intentionally-stopped" };
|
|
72
108
|
const result = run("/bin/launchctl", args);
|
|
@@ -96,6 +132,7 @@ async function restartMacRegisteredServices(target, {
|
|
|
96
132
|
if (!current?.active || current.packageRoot !== target.packageRoot) return { ok: false, reason: "runtime-changed" };
|
|
97
133
|
const records = LABELS.map(label => readRegistration(label, { homeDir, run }));
|
|
98
134
|
if (records.some(r => r.packageRoot !== target.packageRoot)) return { ok: false, reason: "runtime-changed" };
|
|
135
|
+
alignPillLink(records, { homeDir });
|
|
99
136
|
releaseDrain = await require("./update-activity.cjs").drainCalls({ homeDir, sleep });
|
|
100
137
|
for (const record of records) {
|
|
101
138
|
const observed = registration(record.label, { run, userId });
|
|
@@ -114,4 +151,4 @@ async function restartMacRegisteredServices(target, {
|
|
|
114
151
|
finally { releaseDrain?.(); lock.release(); }
|
|
115
152
|
}
|
|
116
153
|
|
|
117
|
-
module.exports = { LABELS, registration, readRegistration, repairMacServiceRegistrations, restartMacRegisteredServices };
|
|
154
|
+
module.exports = { LABELS, alignPillLink, healDanglingPillLink, registration, readRegistration, repairMacServiceRegistrations, restartMacRegisteredServices };
|
|
@@ -33,26 +33,41 @@ async function waitForRecoveryReady({ homeDir = os.homedir(), platform = process
|
|
|
33
33
|
heartbeatFreshMs = HEARTBEAT_FRESH_MS, probeTimeoutMs = PROBE_TIMEOUT_MS,
|
|
34
34
|
probe = require("./recovery-probe.cjs").probeRuntime,
|
|
35
35
|
requireProgress = false,
|
|
36
|
+
// What the caller's previous check proved: the identity it returned, the
|
|
37
|
+
// heartbeat it saw, and the loop sequence it saw. A runtime that is still
|
|
38
|
+
// that identity and has beaten and progressed since then has been watched
|
|
39
|
+
// for a minute already; one full sample showing that is the proof, and the
|
|
40
|
+
// stability window below is for runtimes nothing has vouched for yet.
|
|
41
|
+
continuity = null,
|
|
36
42
|
readCurrent = () => read(path.join(homeDir, ".relay", "runtime", "current.json")),
|
|
37
43
|
readHeartbeat = () => read(path.join(homeDir, ".relay", "recovery", "daemon.json")),
|
|
38
44
|
} = {}) {
|
|
39
45
|
const started = now();
|
|
40
46
|
let since = null, identity = null, firstBeat = null, lastSampleEnd = started;
|
|
41
47
|
let probeSeen = false, probeIdentity = null, legacy = false;
|
|
42
|
-
let firstProgress = null, firstProgressAt = null, progressAdvanced = false;
|
|
48
|
+
let firstProgress = null, firstProgressAt = null, progressAdvanced = false, lastProgressSequence = null;
|
|
49
|
+
// The daemon and pill pids a full enumeration and a matching probe both
|
|
50
|
+
// confirmed; while the window is open, samples check these for liveness.
|
|
51
|
+
let watched = null, lastAlive = false;
|
|
43
52
|
// Why the last sample did not count, for the log line a failed proof leaves.
|
|
44
53
|
let block = null, samples = 0, slowestSampleMs = 0;
|
|
45
54
|
let observationInvalid = false;
|
|
46
|
-
const reset = (key) => { since = null; firstBeat = null; identity = key; probeSeen = false; probeIdentity = null; legacy = false; firstProgress = null; firstProgressAt = null; progressAdvanced = false; };
|
|
55
|
+
const reset = (key) => { since = null; firstBeat = null; identity = key; probeSeen = false; probeIdentity = null; legacy = false; firstProgress = null; firstProgressAt = null; progressAdvanced = false; watched = null; };
|
|
47
56
|
const healthSummary = (value) => value ? JSON.stringify({ daemon: value.daemon, pill: value.pill, daemonCount: value.daemonCount, pillCount: value.pillCount, oldDaemon: value.oldDaemon, oldPill: value.oldPill, oldBroker: value.oldBroker }) : "null";
|
|
48
57
|
const probeSummary = (value) => value?.reason || value?.daemon?.reason || value?.pill?.reason || "answer-did-not-match-the-live-processes";
|
|
49
58
|
// The attempt bound also terminates a faulty/frozen clock in injected hosts.
|
|
50
59
|
for (let attempt = 0; attempt <= Math.ceil(timeoutMs / 1000); attempt++) {
|
|
51
60
|
const at = now(), current = readCurrent(), beat = readHeartbeat();
|
|
52
61
|
const gap = at - lastSampleEnd;
|
|
53
|
-
const
|
|
54
|
-
(current.version === target.version && (!target.packageRoot || target.packageRoot === current.packageRoot)))
|
|
55
|
-
|
|
62
|
+
const targeted = current?.active === true && current.packageRoot && (!target ||
|
|
63
|
+
(current.version === target.version && (!target.packageRoot || target.packageRoot === current.packageRoot)));
|
|
64
|
+
// The window opens and closes on a full process enumeration. In between,
|
|
65
|
+
// the pids that enumeration and the probe confirmed are checked for
|
|
66
|
+
// liveness instead: the final full sample still sees a stray old daemon,
|
|
67
|
+
// pill or broker, and a watched process that dies resets the window.
|
|
68
|
+
const completing = since !== null && at - since >= stableMs;
|
|
69
|
+
const full = watched === null || completing || !lastAlive || beat?.pid !== watched.daemon;
|
|
70
|
+
const live = targeted ? await health(current, { platform, full, watched: full ? null : watched }) : null;
|
|
56
71
|
const jobs = platform === "darwin" ? LABELS.map(label => inspect(label)) : [];
|
|
57
72
|
const responsive = live?.ok ? await probe(current, { homeDir, timeoutMs: probeTimeoutMs }) : { ok: false };
|
|
58
73
|
const sampled = now(), sampleMs = sampled - at;
|
|
@@ -88,9 +103,14 @@ async function waitForRecoveryReady({ homeDir = os.homedir(), platform = process
|
|
|
88
103
|
probeSeen = true;
|
|
89
104
|
legacy = responsive.legacy === true;
|
|
90
105
|
if (probeIdentityNow) probeIdentity = probeIdentityNow;
|
|
106
|
+
// Only a full enumeration plus a probe that named both pids may arm
|
|
107
|
+
// the cheap samples; a legacy probe names none, so legacy runtimes
|
|
108
|
+
// are enumerated every time.
|
|
109
|
+
if (full && !legacy && Number.isSafeInteger(responsive.pill?.pid)) watched = { daemon: beat.pid, pill: responsive.pill.pid };
|
|
91
110
|
const progress = responsive.daemon?.progress;
|
|
92
111
|
if (Number.isSafeInteger(progress?.sequence) && progress.sequence > 0 && ["running", "offline", "signed-out"].includes(progress.phase) && Number.isFinite(progress.at)
|
|
93
112
|
&& progress.at >= after && progress.at <= sampled && sampled - progress.at < heartbeatFreshMs) {
|
|
113
|
+
lastProgressSequence = progress.sequence;
|
|
94
114
|
if (firstProgress === null) { firstProgress = progress.sequence; firstProgressAt = progress.at; }
|
|
95
115
|
else if (progress.sequence > firstProgress && progress.at - firstProgressAt >= stableMs) progressAdvanced = true;
|
|
96
116
|
}
|
|
@@ -99,13 +119,24 @@ async function waitForRecoveryReady({ homeDir = os.homedir(), platform = process
|
|
|
99
119
|
// but cannot satisfy activation of a release requiring this capability.
|
|
100
120
|
const progressRequired = requireProgress || firstProgress !== null
|
|
101
121
|
|| (current?.packageRoot && fs.existsSync(path.join(current.packageRoot, "bootstrap", "daemon-progress.cjs")));
|
|
122
|
+
// One sample, the first: if it does not show the proven runtime beating
|
|
123
|
+
// and progressing since the previous check, the full window runs.
|
|
124
|
+
if (continuity && samples === 1 && full && !legacy && probeMatches && probeIdentityNow && !suspended
|
|
125
|
+
&& `${key}:${probeIdentityNow}` === continuity.identity
|
|
126
|
+
&& Number.isFinite(continuity.heartbeatAt) && beat.at > continuity.heartbeatAt
|
|
127
|
+
&& (!progressRequired || (Number.isSafeInteger(continuity.progressSequence) && Number.isSafeInteger(lastProgressSequence)
|
|
128
|
+
&& lastProgressSequence > continuity.progressSequence))) {
|
|
129
|
+
return { ok: true, current, heartbeatAt: beat.at, identity: `${key}:${probeIdentityNow}`, legacy: false,
|
|
130
|
+
progressSequence: lastProgressSequence, continued: true };
|
|
131
|
+
}
|
|
102
132
|
if (probeMatches && progressRequired && !progressAdvanced) block = "daemon-loop-not-advancing";
|
|
103
133
|
if (at - since >= stableMs && beat.at > firstBeat && probeSeen && (!progressRequired || progressAdvanced)) {
|
|
104
134
|
return { ok: true, current, heartbeatAt: beat.at,
|
|
105
|
-
identity: legacy ? null : `${key}:${probeIdentity || "legacy"}`, legacy };
|
|
135
|
+
identity: legacy ? null : `${key}:${probeIdentity || "legacy"}`, legacy, progressSequence: lastProgressSequence };
|
|
106
136
|
}
|
|
107
137
|
if (!block && at - since >= stableMs && !(beat.at > firstBeat)) block = "heartbeat-not-advancing";
|
|
108
138
|
}
|
|
139
|
+
lastAlive = alive;
|
|
109
140
|
lastSampleEnd = sampled;
|
|
110
141
|
if (at - started >= timeoutMs) break;
|
|
111
142
|
await sleep(1000);
|
|
@@ -186,7 +186,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
186
186
|
catch (error) { services = { ok: false, status: "service-repair-failed", lastError: error.message }; }
|
|
187
187
|
const serviceQueryUncertain = /^service-registration-query-failed/.test(services.lastError || "");
|
|
188
188
|
if (reservedService && (serviceQueryUncertain || services.status === "deferred-update-owner" || (services.ok && !services.changed))) progress.refund("services");
|
|
189
|
-
const ready = (target = null, after = 0) => verifyReady({ homeDir, platform, target, after, now, sleep, health });
|
|
189
|
+
const ready = (target = null, after = 0, extra = {}) => verifyReady({ homeDir, platform, target, after, now, sleep, health, ...extra });
|
|
190
190
|
const rememberReady = observed => {
|
|
191
191
|
progress.clearObservation();
|
|
192
192
|
const active = observed?.current || read(path.join(root, "runtime", "current.json"));
|
|
@@ -201,7 +201,11 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
201
201
|
}
|
|
202
202
|
return probation;
|
|
203
203
|
};
|
|
204
|
-
|
|
204
|
+
// What the next check needs to recognise this runtime as the one proven
|
|
205
|
+
// here: the readiness identity, the heartbeat and the loop sequence it saw.
|
|
206
|
+
const proven = (value, observed) => { const probation = rememberReady(observed); return status({ ...value, runtimeHealthy: !observed.legacy, runtimeAvailable: true, runtimeProven: probation.proven, probationRemainingMs: probation.remainingMs,
|
|
207
|
+
readyIdentity: observed.identity || null, heartbeatAt: Number.isFinite(observed.heartbeatAt) ? observed.heartbeatAt : null,
|
|
208
|
+
progressSequence: Number.isSafeInteger(observed.progressSequence) ? observed.progressSequence : null, readyContinued: observed.continued === true }); };
|
|
205
209
|
const stateFile = path.join(root, "recovery", "status.json");
|
|
206
210
|
const configFile = env.RELAY_CONFIG || path.join(env.RELAY_CONFIG_DIR || root, "config.json");
|
|
207
211
|
const recoveredConfig = require("./recovery-config.cjs").loadRecoveryConfig(configFile);
|
|
@@ -296,8 +300,21 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
296
300
|
if (!installedIsDesired) await discoverDesired();
|
|
297
301
|
if (live && platform === "darwin" && !services.ok) live.ok = false;
|
|
298
302
|
let readiness = null;
|
|
303
|
+
const cadence = platform === "darwin" && read(path.join(root, "recovery", "scheduler.json"))?.intervalSeconds !== 60 ? 5 * 60_000 : CHECK_MS;
|
|
299
304
|
if (installedIsDesired && heartbeatFresh && heartbeat.version === current.version && live.ok) {
|
|
300
|
-
|
|
305
|
+
// A runtime this runner proved healthy on its previous check, still the
|
|
306
|
+
// same daemon under the same release, is asked for one full sample
|
|
307
|
+
// showing it has beaten and worked since. The ten-second stability
|
|
308
|
+
// window remains for everything nothing has vouched for: a new daemon
|
|
309
|
+
// pid, a new release, a check that found it unhealthy, a runtime still
|
|
310
|
+
// on probation, or a previous check too long ago to count as recent.
|
|
311
|
+
const continuity = previous?.ok === true && previous.runtimeHealthy === true && previous.runtimeProven === true
|
|
312
|
+
&& ["current", "ahead"].includes(previous.status) && previous.version === current.version
|
|
313
|
+
&& typeof previous.readyIdentity === "string" && previous.readyIdentity.startsWith(`${current.packageRoot}:${heartbeat.pid}:`)
|
|
314
|
+
&& Number.isFinite(previous.checkedAt) && now() - previous.checkedAt <= 3 * cadence
|
|
315
|
+
? { identity: previous.readyIdentity, heartbeatAt: previous.heartbeatAt, progressSequence: previous.progressSequence ?? null }
|
|
316
|
+
: null;
|
|
317
|
+
const observed = await ready(current, 0, continuity ? { continuity } : {});
|
|
301
318
|
readiness = observed;
|
|
302
319
|
if (observed.ok) {
|
|
303
320
|
await discoverDesired();
|
|
@@ -330,7 +347,6 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
330
347
|
if (installedIsDesired) {
|
|
331
348
|
repairState.version = current.version;
|
|
332
349
|
repairState.restarts = progress.count(`restart:${current.packageRoot || current.version}`);
|
|
333
|
-
const cadence = platform === "darwin" && read(path.join(root, "recovery", "scheduler.json"))?.intervalSeconds !== 60 ? 5 * 60_000 : CHECK_MS;
|
|
334
350
|
const incarnation = read(path.join(root, "recovery", "daemon-progress.json"));
|
|
335
351
|
const identity = JSON.stringify([current.packageRoot, current.version, current.committedAt,
|
|
336
352
|
heartbeat?.pid, incarnation?.pid === heartbeat?.pid ? incarnation?.startedAt : null]);
|
|
@@ -12,7 +12,6 @@ const https = require("node:https");
|
|
|
12
12
|
const os = require("node:os");
|
|
13
13
|
const path = require("node:path");
|
|
14
14
|
const { spawnSync } = require("node:child_process");
|
|
15
|
-
const { pipeline } = require("node:stream/promises");
|
|
16
15
|
const { activateLinuxRuntimeServices, activateMacRuntimeServices, exactRuntimeHealth } = require("./runtime-health.cjs");
|
|
17
16
|
const { isTemporaryNodePath, relayOwnedNodePath } = require("./owned-node-runtime.cjs");
|
|
18
17
|
const {
|
|
@@ -192,7 +191,15 @@ function fetchBuffer(url, redirects = 0, maxBytes = 2 * 1024 * 1024) {
|
|
|
192
191
|
}
|
|
193
192
|
|
|
194
193
|
const MAX_ARTIFACT_BYTES = 750 * 1024 * 1024;
|
|
194
|
+
// Consecutive attempts that moved no bytes before a download gives up. An
|
|
195
|
+
// attempt that made progress never counts against this: a 346 MB runtime on a
|
|
196
|
+
// connection that drops every few MB finishes in many short attempts.
|
|
195
197
|
const ARTIFACT_DOWNLOAD_ATTEMPTS = 6;
|
|
198
|
+
// Wall-clock cap on one download, well inside the daemon's 20-minute wait for
|
|
199
|
+
// its update worker and the recovery runner's 25-minute cycle. What was
|
|
200
|
+
// downloaded stays on disk, so the next attempt resumes where this one stopped.
|
|
201
|
+
const ARTIFACT_DOWNLOAD_BUDGET_MS = 15 * 60_000;
|
|
202
|
+
const ARTIFACT_DOWNLOAD_MAX_ATTEMPTS = 500;
|
|
196
203
|
|
|
197
204
|
class PermanentArtifactDownloadError extends Error {}
|
|
198
205
|
|
|
@@ -252,26 +259,33 @@ function downloadArtifactAttempt({ parsed, file, artifact, offset, get, signal,
|
|
|
252
259
|
return finish(error);
|
|
253
260
|
}
|
|
254
261
|
let received = 0;
|
|
255
|
-
|
|
256
|
-
received += chunk.length;
|
|
257
|
-
if (received > expectedBytes) {
|
|
258
|
-
request.destroy(new PermanentArtifactDownloadError("Release artifact exceeded its signed size"));
|
|
259
|
-
} else onProgress?.({ receivedBytes: offset + received, totalBytes: artifact.bytes });
|
|
260
|
-
});
|
|
262
|
+
let fd = null;
|
|
261
263
|
try {
|
|
262
264
|
if (fs.statSync(file).size !== offset) {
|
|
263
265
|
throw new PermanentArtifactDownloadError("Relay artifact staging file changed during download");
|
|
264
266
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
+
fd = fs.openSync(file, "r+");
|
|
268
|
+
// Each chunk is on disk before the next is read. A piped write stream
|
|
269
|
+
// drops what it had buffered when the connection fails, so a dropped
|
|
270
|
+
// socket could lose the tail of what had arrived; here whatever arrived
|
|
271
|
+
// is exactly what the next attempt resumes from.
|
|
272
|
+
for await (const chunk of response) {
|
|
273
|
+
if (received + chunk.length > expectedBytes) {
|
|
274
|
+
throw new PermanentArtifactDownloadError("Release artifact exceeded its signed size");
|
|
275
|
+
}
|
|
276
|
+
await writeAt(fd, chunk, offset + received);
|
|
277
|
+
received += chunk.length;
|
|
278
|
+
onProgress?.({ receivedBytes: offset + received, totalBytes: artifact.bytes });
|
|
279
|
+
}
|
|
267
280
|
if (received !== expectedBytes) {
|
|
268
281
|
throw new Error(`Relay artifact download ended early (${received} != ${expectedBytes}).`);
|
|
269
282
|
}
|
|
270
|
-
|
|
271
|
-
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
283
|
+
fs.fsyncSync(fd);
|
|
272
284
|
finish();
|
|
273
285
|
} catch (error) {
|
|
274
286
|
finish(error);
|
|
287
|
+
} finally {
|
|
288
|
+
if (fd !== null) { try { fs.closeSync(fd); } catch {} }
|
|
275
289
|
}
|
|
276
290
|
});
|
|
277
291
|
// ClientRequest's socket timeout starts only after a socket is assigned.
|
|
@@ -289,6 +303,16 @@ function downloadArtifactAttempt({ parsed, file, artifact, offset, get, signal,
|
|
|
289
303
|
});
|
|
290
304
|
}
|
|
291
305
|
|
|
306
|
+
function writeAt(fd, chunk, position) {
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
fs.write(fd, chunk, 0, chunk.length, position, (error, written) => {
|
|
309
|
+
if (error) reject(error);
|
|
310
|
+
else if (written !== chunk.length) reject(new Error(`Relay artifact write was short (${written} of ${chunk.length} bytes)`));
|
|
311
|
+
else resolve();
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
292
316
|
function sha512File(file) {
|
|
293
317
|
return new Promise((resolve, reject) => {
|
|
294
318
|
const hash = crypto.createHash("sha512");
|
|
@@ -311,38 +335,127 @@ async function downloadVerifiedArtifact(url, file, artifact, options = {}) {
|
|
|
311
335
|
}
|
|
312
336
|
const get = options.get || https.get;
|
|
313
337
|
const sleep = options.sleep || ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
|
|
338
|
+
const now = options.now || Date.now;
|
|
339
|
+
// `attempts` is the no-progress budget: consecutive attempts that moved no
|
|
340
|
+
// bytes. Attempts that made progress only count against the wall-clock budget.
|
|
314
341
|
const attempts = options.attempts || ARTIFACT_DOWNLOAD_ATTEMPTS;
|
|
315
|
-
|
|
342
|
+
const budgetMs = options.budgetMs || ARTIFACT_DOWNLOAD_BUDGET_MS;
|
|
343
|
+
// With `resume`, a file left by an earlier run continues from its last byte.
|
|
344
|
+
// The complete file is hashed against the signed manifest either way, so a
|
|
345
|
+
// partial that was tampered with or belongs to another artifact is caught
|
|
346
|
+
// there and discarded; the next run then starts clean.
|
|
347
|
+
let resumedFrom = 0;
|
|
348
|
+
if (options.resume && fs.existsSync(file)) {
|
|
349
|
+
resumedFrom = fs.statSync(file).size;
|
|
350
|
+
if (resumedFrom > artifact.bytes) { fs.truncateSync(file, 0); resumedFrom = 0; }
|
|
351
|
+
} else {
|
|
352
|
+
fs.closeSync(fs.openSync(file, "wx", 0o600));
|
|
353
|
+
}
|
|
354
|
+
const startedAt = now();
|
|
316
355
|
let lastError;
|
|
317
|
-
|
|
356
|
+
let total = 0;
|
|
357
|
+
let withoutProgress = 0;
|
|
358
|
+
const discardPartial = () => { try { fs.rmSync(file, { force: true }); } catch {} };
|
|
359
|
+
for (;;) {
|
|
318
360
|
options.signal?.throwIfAborted();
|
|
319
361
|
const offset = fs.statSync(file).size;
|
|
320
|
-
if (offset > artifact.bytes) fail("Release artifact exceeded its signed size");
|
|
362
|
+
if (offset > artifact.bytes) { discardPartial(); fail("Release artifact exceeded its signed size"); }
|
|
321
363
|
if (offset === artifact.bytes) break;
|
|
364
|
+
if (withoutProgress >= attempts) break;
|
|
365
|
+
if (total >= ARTIFACT_DOWNLOAD_MAX_ATTEMPTS) break;
|
|
366
|
+
if (total > 0 && now() - startedAt >= budgetMs) { lastError = new Error(`download time budget of ${Math.round(budgetMs / 60_000)} minutes used up`); break; }
|
|
367
|
+
total += 1;
|
|
322
368
|
try {
|
|
323
|
-
options.onProgress?.({ receivedBytes: offset, totalBytes: artifact.bytes });
|
|
369
|
+
options.onProgress?.({ receivedBytes: offset, totalBytes: artifact.bytes, resumedFrom, attempt: total });
|
|
324
370
|
await downloadArtifactAttempt({ parsed, file, artifact, offset, get, signal: options.signal, onProgress: options.onProgress });
|
|
325
371
|
} catch (error) {
|
|
326
372
|
options.signal?.throwIfAborted();
|
|
327
373
|
lastError = error;
|
|
328
|
-
if (error instanceof PermanentArtifactDownloadError) throw error;
|
|
329
|
-
|
|
330
|
-
|
|
374
|
+
if (error instanceof PermanentArtifactDownloadError) { discardPartial(); throw error; }
|
|
375
|
+
const progressed = fs.statSync(file).size > offset;
|
|
376
|
+
withoutProgress = progressed ? 0 : withoutProgress + 1;
|
|
377
|
+
if (withoutProgress >= attempts) break;
|
|
378
|
+
// A connection that keeps delivering bytes is retried almost at once; one
|
|
379
|
+
// that delivers nothing backs off, up to half a minute between tries.
|
|
380
|
+
const backoff = progressed ? 1_000 : Math.min(30_000, 500 * (2 ** withoutProgress));
|
|
331
381
|
await sleep(backoff + Math.floor(Math.random() * 250));
|
|
332
382
|
}
|
|
333
383
|
}
|
|
334
384
|
const downloadedBytes = fs.statSync(file).size;
|
|
335
385
|
if (downloadedBytes !== artifact.bytes) {
|
|
336
|
-
|
|
386
|
+
const elapsed = Math.round((now() - startedAt) / 1000);
|
|
387
|
+
throw new Error(`Relay artifact download incomplete after ${total} attempts and ${elapsed}s (${downloadedBytes}/${artifact.bytes} bytes; ${downloadedBytes - resumedFrom} new this run): ${lastError?.message || lastError || "incomplete response"}`);
|
|
337
388
|
}
|
|
338
389
|
const actual = await sha512File(file);
|
|
339
390
|
options.signal?.throwIfAborted();
|
|
340
391
|
if (actual.length !== artifact.sha512.length || !crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(artifact.sha512))) {
|
|
341
|
-
|
|
392
|
+
discardPartial();
|
|
342
393
|
fail("Relay artifact checksum is invalid.");
|
|
343
394
|
}
|
|
344
395
|
}
|
|
345
396
|
|
|
397
|
+
const PARTIAL_ARTIFACT_SUFFIX = ".partial";
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Where an interrupted runtime download keeps its bytes between runs, and the
|
|
401
|
+
* exclusive hold on it. A flaky connection on 2026-10-10 reached 5-125 MB of a
|
|
402
|
+
* 346 MB runtime on each of several update attempts hours apart, and each
|
|
403
|
+
* attempt started again from zero because the staging directory was deleted
|
|
404
|
+
* with the failed transaction. The partial lives outside any staging or
|
|
405
|
+
* release directory, so nothing sweeps it, and is named by the artifact's
|
|
406
|
+
* signed digest, so a different build never resumes onto it.
|
|
407
|
+
*/
|
|
408
|
+
function prepareResumableArtifact({ homeDir = os.homedir(), version, artifact, now = Date.now, alive = (pid) => processAlive(pid) } = {}) {
|
|
409
|
+
const directory = path.join(homeDir, ".relay", "runtime", "downloads");
|
|
410
|
+
const digest = crypto.createHash("sha256").update(String(artifact?.sha512 || "")).digest("hex").slice(0, 16);
|
|
411
|
+
const file = path.join(directory, `runtime-${String(version).replace(/[^0-9A-Za-z.-]/g, "_")}-${digest}${PARTIAL_ARTIFACT_SUFFIX}`);
|
|
412
|
+
const lock = `${file}.lock`;
|
|
413
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
414
|
+
// One target at a time: a partial for another version or build is dead weight.
|
|
415
|
+
for (const name of fs.readdirSync(directory)) {
|
|
416
|
+
const candidate = path.join(directory, name);
|
|
417
|
+
if (candidate === file || candidate === lock) continue;
|
|
418
|
+
if (!name.endsWith(PARTIAL_ARTIFACT_SUFFIX) && !name.endsWith(`${PARTIAL_ARTIFACT_SUFFIX}.lock`)) continue;
|
|
419
|
+
if (name.endsWith(".lock")) {
|
|
420
|
+
let holder = null;
|
|
421
|
+
try { holder = JSON.parse(fs.readFileSync(candidate, "utf8")); } catch {}
|
|
422
|
+
if (Number.isInteger(holder?.pid) && alive(holder.pid)) continue;
|
|
423
|
+
}
|
|
424
|
+
try { fs.rmSync(candidate, { force: true }); } catch {}
|
|
425
|
+
}
|
|
426
|
+
let holder = null;
|
|
427
|
+
try { holder = JSON.parse(fs.readFileSync(lock, "utf8")); } catch {}
|
|
428
|
+
if (Number.isInteger(holder?.pid) && holder.pid !== process.pid && alive(holder.pid)) {
|
|
429
|
+
return { ok: false, reason: "partial-in-use", holderPid: holder.pid, file };
|
|
430
|
+
}
|
|
431
|
+
try { fs.rmSync(lock, { force: true }); } catch {}
|
|
432
|
+
try {
|
|
433
|
+
fs.writeFileSync(lock, JSON.stringify({ schema: 1, pid: process.pid, at: now() }), { mode: 0o600, flag: "wx" });
|
|
434
|
+
} catch (error) {
|
|
435
|
+
return { ok: false, reason: `partial-lock-failed: ${error.code || error.message}`, file };
|
|
436
|
+
}
|
|
437
|
+
let resumedFrom = 0;
|
|
438
|
+
try { resumedFrom = fs.statSync(file).size; } catch {}
|
|
439
|
+
return {
|
|
440
|
+
ok: true,
|
|
441
|
+
file,
|
|
442
|
+
resumedFrom,
|
|
443
|
+
release() { try { fs.rmSync(lock, { force: true }); } catch {} },
|
|
444
|
+
discard() { try { fs.rmSync(file, { force: true }); } catch {} },
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function moveFile(from, to) {
|
|
449
|
+
try { fs.renameSync(from, to); }
|
|
450
|
+
catch (error) {
|
|
451
|
+
if (error.code !== "EXDEV") throw error;
|
|
452
|
+
fs.copyFileSync(from, to);
|
|
453
|
+
fs.rmSync(from, { force: true });
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const megabytes = (bytes) => (bytes / (1024 * 1024)).toFixed(1);
|
|
458
|
+
|
|
346
459
|
function parseSignedManifest(bytes, { version, platformKey, publicKeyPem, trustStore = trust }) {
|
|
347
460
|
let envelope;
|
|
348
461
|
try { envelope = JSON.parse(bytes.toString("utf8")); } catch { fail("Relay release manifest is not valid JSON."); }
|
|
@@ -1142,23 +1255,42 @@ async function setup(argv = []) {
|
|
|
1142
1255
|
}
|
|
1143
1256
|
}
|
|
1144
1257
|
|
|
1145
|
-
async function stageVerifiedRuntime({ version, platformKey = releasePlatform(), destination
|
|
1258
|
+
async function stageVerifiedRuntime({ version, platformKey = releasePlatform(), destination, homeDir = os.homedir(), log = console.log,
|
|
1259
|
+
download = downloadVerifiedArtifact, fetchManifest = fetchBuffer, parseManifest = parseSignedManifest }) {
|
|
1146
1260
|
const manifestUrl = `${RELEASE_ORIGIN}${RELEASE_BASE_PATH}/v${version}/manifest.json`;
|
|
1147
1261
|
if (!destination) fail("Relay runtime destination is missing.");
|
|
1148
1262
|
if (fs.existsSync(destination)) {
|
|
1149
1263
|
fail("Relay refused to reuse a pre-existing runtime destination.");
|
|
1150
1264
|
}
|
|
1151
|
-
|
|
1152
|
-
const { artifact } =
|
|
1265
|
+
log("Checking Relay's signed release...");
|
|
1266
|
+
const { artifact } = parseManifest(await fetchManifest(manifestUrl), { version, platformKey });
|
|
1153
1267
|
fs.mkdirSync(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
1154
1268
|
const staging = fs.mkdtempSync(path.join(path.dirname(destination), `.relay-download-${version}-`));
|
|
1155
1269
|
const archivePath = path.join(staging, "runtime.tar.gz");
|
|
1156
1270
|
const extracted = path.join(staging, "root");
|
|
1271
|
+
// The bytes land in a partial file that outlives this staging directory, so
|
|
1272
|
+
// a download that fails part-way is continued by the next attempt instead of
|
|
1273
|
+
// started again. Only one process at a time may hold a given partial.
|
|
1274
|
+
let partial = null;
|
|
1275
|
+
try { partial = prepareResumableArtifact({ homeDir, version, artifact }); } catch (error) { partial = { ok: false, reason: error.message }; }
|
|
1276
|
+
const downloadPath = partial.ok ? partial.file : archivePath;
|
|
1157
1277
|
try {
|
|
1158
1278
|
fs.mkdirSync(extracted);
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1279
|
+
const total = megabytes(artifact.bytes);
|
|
1280
|
+
if (partial.ok && partial.resumedFrom > 0) log(`Downloading Relay's signed runtime, resuming at ${megabytes(partial.resumedFrom)} of ${total} MB...`);
|
|
1281
|
+
else log(`Downloading Relay's signed runtime (${total} MB)${partial.ok ? "" : `; not resumable: ${partial.reason}`}...`);
|
|
1282
|
+
let nextTenth = 1;
|
|
1283
|
+
await download(artifact.url, downloadPath, artifact, {
|
|
1284
|
+
resume: partial.ok,
|
|
1285
|
+
onProgress: ({ receivedBytes, totalBytes }) => {
|
|
1286
|
+
const tenth = Math.floor((receivedBytes * 10) / totalBytes);
|
|
1287
|
+
if (tenth < nextTenth || receivedBytes >= totalBytes) return;
|
|
1288
|
+
nextTenth = tenth + 1;
|
|
1289
|
+
log(`Downloaded ${megabytes(receivedBytes)} of ${total} MB (${tenth * 10}%)`);
|
|
1290
|
+
},
|
|
1291
|
+
});
|
|
1292
|
+
if (downloadPath !== archivePath) moveFile(downloadPath, archivePath);
|
|
1293
|
+
log("Verifying and installing Relay...");
|
|
1162
1294
|
validateArchiveListing(archivePath);
|
|
1163
1295
|
const unpackInvocation = tarInvocation({ archivePath, mode: "extract", destination: extracted });
|
|
1164
1296
|
const unpack = spawnSync(unpackInvocation.command, unpackInvocation.args, {
|
|
@@ -1174,6 +1306,7 @@ async function stageVerifiedRuntime({ version, platformKey = releasePlatform(),
|
|
|
1174
1306
|
fs.renameSync(extracted, destination);
|
|
1175
1307
|
return verifyExtractedRuntime(path.join(destination, "node_modules", PACKAGE_NAME), version, platformKey);
|
|
1176
1308
|
} finally {
|
|
1309
|
+
partial?.release?.();
|
|
1177
1310
|
fs.rmSync(staging, { recursive: true, force: true });
|
|
1178
1311
|
}
|
|
1179
1312
|
}
|
|
@@ -1248,6 +1381,7 @@ module.exports = {
|
|
|
1248
1381
|
isCanonicalCliShimSource,
|
|
1249
1382
|
releasePlatform,
|
|
1250
1383
|
parseSignedManifest,
|
|
1384
|
+
prepareResumableArtifact,
|
|
1251
1385
|
processAlive,
|
|
1252
1386
|
removeAbandonedRuntimeDownloads,
|
|
1253
1387
|
restoreRuntimeLinks,
|
|
@@ -56,13 +56,32 @@ function runtimeProcessCommands(platform, run = defaultRun, userId = typeof proc
|
|
|
56
56
|
return commandOk(result) ? parseRuntimeProcessCommands(result.stdout, platform, userId) : [];
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// Liveness of one known pid. EPERM is "exists, not ours to signal", so alive.
|
|
60
|
+
function processAlive(pid) {
|
|
61
|
+
const value = Number(pid);
|
|
62
|
+
if (!Number.isSafeInteger(value) || value <= 0) return false;
|
|
63
|
+
try { process.kill(value, 0); return true; } catch (error) { return error?.code === "EPERM"; }
|
|
64
|
+
}
|
|
65
|
+
|
|
59
66
|
function exactRuntimeHealth(target, {
|
|
60
67
|
platform = process.platform,
|
|
61
68
|
run = defaultRun,
|
|
62
69
|
commands = null,
|
|
63
70
|
userId = typeof process.getuid === "function" ? process.getuid() : 0,
|
|
71
|
+
// A sample taken between two full enumerations: the daemon and pill pids
|
|
72
|
+
// the last full sample and the probe confirmed are checked for liveness
|
|
73
|
+
// instead of listing every process on the machine. On Windows a full sample
|
|
74
|
+
// is a PowerShell/WMI query that costs about a second; the readiness window
|
|
75
|
+
// used to take one every second.
|
|
76
|
+
full = true,
|
|
77
|
+
watched = null,
|
|
78
|
+
alive = processAlive,
|
|
64
79
|
} = {}) {
|
|
65
80
|
const api = platform === "win32" ? path.win32 : path.posix;
|
|
81
|
+
if (!full && Number.isSafeInteger(watched?.daemon) && Number.isSafeInteger(watched?.pill)) {
|
|
82
|
+
const daemon = alive(watched.daemon), pill = alive(watched.pill);
|
|
83
|
+
return { ok: daemon && pill, known: true, cheap: true, daemon, pill, daemonCount: daemon ? 1 : 0, pillCount: pill ? 1 : 0, brokerCount: 0, oldBroker: false, oldDaemon: false, oldPill: false, packageRoot: target.packageRoot };
|
|
84
|
+
}
|
|
66
85
|
let observed = commands;
|
|
67
86
|
if (observed === null) {
|
|
68
87
|
const query = runtimeProcessQuery(platform);
|
|
@@ -467,7 +486,14 @@ async function restoreMissingPill(target, {
|
|
|
467
486
|
command = "systemctl"; args = ["--user", "start", unit];
|
|
468
487
|
} else if (platform === "darwin") {
|
|
469
488
|
const mac = require("./mac-service-recovery.cjs");
|
|
470
|
-
|
|
489
|
+
// An unusable registration is a failure, not a reason to wait: deferring
|
|
490
|
+
// refunds the runner's budget and it would retry this same step forever
|
|
491
|
+
// instead of escalating to reactivation or a download (Sven, 2026-10-12).
|
|
492
|
+
let record;
|
|
493
|
+
try {
|
|
494
|
+
record = mac.readRegistration(PILL_LABEL, { homeDir, run });
|
|
495
|
+
if (record.packageRoot === target.packageRoot) mac.alignPillLink([record], { homeDir });
|
|
496
|
+
} catch (error) { return { ok: false, reason: `pill-registration-invalid: ${error.message}` }; }
|
|
471
497
|
if (record.packageRoot !== target.packageRoot) return defer("runtime-changed");
|
|
472
498
|
const observed = mac.registration(PILL_LABEL, { run, userId });
|
|
473
499
|
if (!observed.known) return defer("service-registration-query-failed");
|
|
@@ -534,3 +560,5 @@ module.exports = {
|
|
|
534
560
|
terminateInstalledServiceProcesses,
|
|
535
561
|
WINDOWS_STOP_INSTALLED_SERVICES_PS,
|
|
536
562
|
};
|
|
563
|
+
|
|
564
|
+
module.exports.processAlive = processAlive;
|
package/package.json
CHANGED