relay-companion 0.1.648 → 0.1.649
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.
|
@@ -25,7 +25,15 @@ function errorCode(error) {
|
|
|
25
25
|
[/recovery-bundle-publish-failed/, "recovery-publish-failed"], [/recovery-node-preservation-failed/, "recovery-node-failed"],
|
|
26
26
|
[/runtime-not-healthy|not-responsive/, "health-check-failed"], [/configuration-unavailable/, "configuration-unavailable"],
|
|
27
27
|
];
|
|
28
|
-
|
|
28
|
+
const matched = patterns.find(([pattern]) => pattern.test(text))?.[1];
|
|
29
|
+
if (matched) return matched;
|
|
30
|
+
// A reason that is itself a code (activation-busy, registration-restore-failed,
|
|
31
|
+
// runtime-registration-failed) says exactly what failed, so it is kept rather
|
|
32
|
+
// than flattened: 2026-11-26 a Mac's every failure read "unclassified" and its
|
|
33
|
+
// cause had to be inferred from timings. Free text never qualifies; the API
|
|
34
|
+
// stores an unknown code as a bounded label (packages/shared/src/tolerant.ts).
|
|
35
|
+
const code = /^([a-z][a-z0-9]*(?:-[a-z0-9]+){1,7})(?::|$)/.exec(text)?.[1];
|
|
36
|
+
return code && code.length <= 60 ? code : "unclassified";
|
|
29
37
|
}
|
|
30
38
|
// What kind of failure a background part hit, in the same closed vocabulary:
|
|
31
39
|
// never the message itself, which can hold paths or content. A server's error
|
|
@@ -76,7 +84,8 @@ function record(input, { homeDir = os.homedir(), now = Date.now, scope } = {}) {
|
|
|
76
84
|
component: pick(contract.components, input.component), stage: pick(contract.stages, input.stage),
|
|
77
85
|
outcome: pick(contract.outcomes, input.outcome), code: errorCode(input.code),
|
|
78
86
|
signingKeyId: String(input.code?.message || input.code || "").match(/unknown key (relay-runtime-release-v\d{1,6})\b/)?.[1] || null,
|
|
79
|
-
|
|
87
|
+
// Both the updater and (since 2026-11) the independent repair read stable-v3.
|
|
88
|
+
feed: input.stage === "discovery" ? input.channel === "stable" ? "stable-v3" : pick(["dev", "staging"], input.channel) : "unknown",
|
|
80
89
|
version: version(input.version), targetVersion: version(input.targetVersion),
|
|
81
90
|
channel: pick(contract.channels, input.channel),
|
|
82
91
|
elapsedMs: Number.isFinite(input.elapsedMs) ? Math.min(86400000, Math.max(0, Math.round(input.elapsedMs))) : null,
|
|
@@ -189,6 +189,11 @@ function collectInstallationHealth({ homeDir = os.homedir(), platform = process.
|
|
|
189
189
|
checkedAt: supervisor?.checkedAt > 0 ? new Date(supervisor.checkedAt).toISOString() : null,
|
|
190
190
|
desiredVersion: supervisor?.desiredVersion || null,
|
|
191
191
|
lastSuccessAt: supervisor?.lastSuccessAt > 0 ? new Date(supervisor.lastSuccessAt).toISOString() : null,
|
|
192
|
+
// When the runner tries again, how often it restarted the service and
|
|
193
|
+
// since when the runtime looked stale. Absent when the runner did not say.
|
|
194
|
+
...(supervisor?.retryAt > 0 ? { retryAt: new Date(supervisor.retryAt).toISOString() } : {}),
|
|
195
|
+
...(Number.isSafeInteger(supervisor?.restarts) && supervisor.restarts > 0 ? { restarts: Math.min(supervisor.restarts, 1000) } : {}),
|
|
196
|
+
...(supervisor?.staleSince > 0 ? { staleSince: new Date(supervisor.staleSince).toISOString() } : {}),
|
|
192
197
|
monitor: { state: monitor.state, repairStatus: monitor.repairStatus,
|
|
193
198
|
lastRepairAt: monitor.lastRepairAt > 0 ? new Date(monitor.lastRepairAt).toISOString() : null },
|
|
194
199
|
// Do not upload logs, URLs, usernames, or raw errors. These stay in doctor.
|
|
@@ -564,7 +564,8 @@ async function launch({ root = __dirname, run = runChild, now = Date.now, env =
|
|
|
564
564
|
const lostTransaction = /recovery-worker-exit-75|transaction-in-progress/i.test(report?.lastError || "");
|
|
565
565
|
const retryableReport = ["disabled", "backoff", "emergency-backoff", "restart-failed", "pill-repair-failed", "observation-unavailable", "reactivate-failed", "service-repair-failed", "service-repair-unhealthy"].includes(report?.status) || (report?.status === "failed" && (networkFailure || lostTransaction));
|
|
566
566
|
if (reported && retryableReport && result.reason !== "deadline") {
|
|
567
|
-
|
|
567
|
+
// Which runner status sent it back, for the fleet report (fleet-problems.js).
|
|
568
|
+
write(path.join(root, "launcher-status.json"), { schema: 1, at: now(), status: "runner-error", runtimeStatus: report.status, version: candidate.version });
|
|
568
569
|
log("done status=runner-error");
|
|
569
570
|
return { ok: false, status: "runner-error" };
|
|
570
571
|
}
|
|
@@ -33,7 +33,33 @@ function compare(a, b) {
|
|
|
33
33
|
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i] ? 1 : -1;
|
|
34
34
|
return 0;
|
|
35
35
|
}
|
|
36
|
-
|
|
36
|
+
// Where a stable computer learns the current release: the same signed records
|
|
37
|
+
// its updater follows (src/auto-update.js, src/runtime-cohort.js). Until
|
|
38
|
+
// 2026-11 this read companion-releases/stable/, the old-key bridge record that
|
|
39
|
+
// stays at 0.1.550 for installs that only know the old signing key (0.1.549
|
|
40
|
+
// and older), so a repair of a broken computer could install 0.1.550.
|
|
41
|
+
const RELEASE_ORIGIN = "https://api.sendrelays.com/v1/companion-releases";
|
|
42
|
+
const STABLE_RECORD = "stable-v3";
|
|
43
|
+
const COHORT_RECORD = "stable-v3-cohort";
|
|
44
|
+
const COHORT_MAX_EXPIRY_MS = 31 * 86400_000;
|
|
45
|
+
// The named-device cohort, checked the way src/runtime-cohort.js checks it:
|
|
46
|
+
// a listed, unexpired device takes a newer version; anything else, including
|
|
47
|
+
// any error, leaves it on the general stable version.
|
|
48
|
+
async function cohortVersion(general, { fetchImpl, trustStore, deviceId, now }) {
|
|
49
|
+
if (typeof deviceId !== "string" || !deviceId) return null;
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetchImpl(`${RELEASE_ORIGIN}/${COHORT_RECORD}/manifest.json?recovery=${now()}`, { cache: "no-store", signal: AbortSignal.timeout(15_000) });
|
|
52
|
+
if (!response.ok) return null;
|
|
53
|
+
const payload = JSON.parse(verifyReleaseEnvelope(await response.json(), trustStore).toString("utf8"));
|
|
54
|
+
const keys = Object.keys(payload || {}).sort().join(",");
|
|
55
|
+
if (keys !== "deviceIds,expiresAt,kind,product,schema,sourceSha,version" || payload.schema !== 1 || payload.product !== "Relay"
|
|
56
|
+
|| payload.kind !== "runtime-cohort" || !Array.isArray(payload.deviceIds) || !Number.isSafeInteger(payload.expiresAt)) return null;
|
|
57
|
+
if (payload.expiresAt <= now() || payload.expiresAt > now() + COHORT_MAX_EXPIRY_MS) return null;
|
|
58
|
+
if (!payload.deviceIds.includes(deviceId) || compare(payload.version, general) !== 1) return null;
|
|
59
|
+
return payload.version;
|
|
60
|
+
} catch { return null; }
|
|
61
|
+
}
|
|
62
|
+
async function discover(channel, { fetchImpl = fetch, trustStore = trust, homeDir = os.homedir(), now = Date.now } = {}) {
|
|
37
63
|
let version;
|
|
38
64
|
if (channel !== "stable") {
|
|
39
65
|
const response = await fetchImpl("https://registry.npmjs.org/-/package/relay-companion/dist-tags", { cache: "no-store", signal: AbortSignal.timeout(15_000) });
|
|
@@ -41,13 +67,26 @@ async function discover(channel, { fetchImpl = fetch, trustStore = trust } = {})
|
|
|
41
67
|
version = (await response.json())[channel];
|
|
42
68
|
if (compare(version, "0.0.0") !== 1) throw new Error("channel-version-invalid");
|
|
43
69
|
}
|
|
44
|
-
const route = version ? `v${version}` :
|
|
45
|
-
const response = await fetchImpl(
|
|
70
|
+
const route = version ? `v${version}` : STABLE_RECORD;
|
|
71
|
+
const response = await fetchImpl(`${RELEASE_ORIGIN}/${route}/manifest.json?recovery=${now()}`, { cache: "no-store", signal: AbortSignal.timeout(15_000) });
|
|
46
72
|
if (!response.ok) throw new Error(`manifest-http-${response.status}`);
|
|
47
73
|
const envelope = await response.json();
|
|
48
74
|
const payload = JSON.parse(verifyReleaseEnvelope(envelope, trustStore).toString("utf8"));
|
|
49
75
|
if (payload.product !== "Relay" || compare(payload.version, "0.0.0") !== 1 || (version && version !== payload.version)) throw new Error("release-identity-invalid");
|
|
50
|
-
return payload.version;
|
|
76
|
+
if (version) return payload.version;
|
|
77
|
+
const deviceId = read(path.join(homeDir, ".relay", "config.json"))?.deviceId;
|
|
78
|
+
return (await cohortVersion(payload.version, { fetchImpl, trustStore, deviceId, now })) || payload.version;
|
|
79
|
+
}
|
|
80
|
+
// The newest version this computer has run and proven healthy. A repair
|
|
81
|
+
// never installs anything older: whatever a release record says, going back
|
|
82
|
+
// past a release this computer ran is a downgrade, not a repair.
|
|
83
|
+
function provenFloor(root, channel) {
|
|
84
|
+
let floor = null;
|
|
85
|
+
for (const name of ["runtime-good.json", "runtime-previous-good.json"]) {
|
|
86
|
+
const value = read(path.join(root, "recovery", name));
|
|
87
|
+
if (value?.channel === channel && compare(value.version, "0.0.0") === 1 && (!floor || compare(value.version, floor) === 1)) floor = value.version;
|
|
88
|
+
}
|
|
89
|
+
return floor;
|
|
51
90
|
}
|
|
52
91
|
function busyLease(heartbeat, now = Date.now()) {
|
|
53
92
|
return Boolean(heartbeat && heartbeat.busy === true && Number.isFinite(heartbeat.at) && now >= heartbeat.at && now - heartbeat.at < HEARTBEAT_MS);
|
|
@@ -232,6 +271,21 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
232
271
|
}, { homeDir, now, scope: diagnosticScope });
|
|
233
272
|
let advertisedVersion = null, discoveryFailure = null;
|
|
234
273
|
const log = recoveryLogger(root, runId, now);
|
|
274
|
+
// A worker's exit code is all execute() sees (recovery-worker-exit-1). The
|
|
275
|
+
// worker leaves its own cause beside this status (src/recovery-entry.js);
|
|
276
|
+
// keep it with the error so status.json and the fleet report can say why.
|
|
277
|
+
const workerFailureFile = path.join(root, "recovery", "worker-failure.json");
|
|
278
|
+
const runWorker = async (...args) => {
|
|
279
|
+
const startedAt = Date.now();
|
|
280
|
+
try { return await run(...args); }
|
|
281
|
+
catch (error) {
|
|
282
|
+
const cause = read(workerFailureFile);
|
|
283
|
+
if (error && typeof error === "object" && cause?.message && Number(cause.at) >= startedAt - 1000) error.workerDetail = String(cause.message).slice(0, 600);
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const withCause = error => error?.workerDetail ? `${error.workerDetail} (${error.message})` : error.message;
|
|
288
|
+
const causeDetail = error => error?.workerDetail ? { lastErrorDetail: String(error.workerDetail).slice(0, 600) } : {};
|
|
235
289
|
if (recoveredConfig.restored) log("restored recovery settings from validated local copy");
|
|
236
290
|
const status = (value) => {
|
|
237
291
|
write(stateFile, { schema: 1, channel, runId, launcherVersion: require("../package.json").version, checkedAt: now(), lastSuccessAt: previous?.lastSuccessAt || null, advertisedVersion, discoveryError: discoveryFailure, ...value });
|
|
@@ -287,7 +341,15 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
287
341
|
if (!updatesEnabled || discoveryAttempted) return;
|
|
288
342
|
discoveryAttempted = true;
|
|
289
343
|
diagnostic("discovery", "started");
|
|
290
|
-
try {
|
|
344
|
+
try {
|
|
345
|
+
desiredVersion = await discoverImpl(channel, { homeDir, now }); advertisedVersion = desiredVersion;
|
|
346
|
+
diagnostic("discovery", "succeeded", null, desiredVersion); log(`discovered ${desiredVersion} on ${channel}`);
|
|
347
|
+
const floor = provenFloor(root, channel);
|
|
348
|
+
if (floor && compare(desiredVersion, floor) === -1) {
|
|
349
|
+
log(`${desiredVersion} is older than ${floor}, which this computer already ran healthily; repairing with ${floor} instead`);
|
|
350
|
+
desiredVersion = floor;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
291
353
|
catch (error) { discoveryError = error; discoveryFailure = diagnostics.errorCode(error); diagnostic("discovery", "failed", error); log(`discovery failed: ${error.message}`); }
|
|
292
354
|
};
|
|
293
355
|
try {
|
|
@@ -430,14 +492,14 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
430
492
|
status({ ok: true, status: "reactivating", ...base });
|
|
431
493
|
const activationAt = now();
|
|
432
494
|
try {
|
|
433
|
-
await
|
|
495
|
+
await runWorker(process.execPath, entry, [version, channel], { env: { ...env, RELAY_RECOVERY_WORKER: "1" } });
|
|
434
496
|
const observed = await ready({ version }, activationAt);
|
|
435
497
|
if (!observed.ok) throw new Error("reactivated-runtime-not-healthy");
|
|
436
498
|
return proven({ ok: true, status: "current", desiredVersion: base.desiredVersion, version, repair: "reactivate", restarts: 0, lastSuccessAt: now(), failures: 0 }, observed);
|
|
437
499
|
} catch (error) {
|
|
438
|
-
progress.fail(error
|
|
439
|
-
log(`reactivate failed: ${error
|
|
440
|
-
status({ ok: false, status: "reactivate-failed", ...base, lastError: String(error.message).slice(0, 300) });
|
|
500
|
+
progress.fail(withCause(error));
|
|
501
|
+
log(`reactivate failed: ${withCause(error)}`);
|
|
502
|
+
status({ ok: false, status: "reactivate-failed", ...base, lastError: String(error.message).slice(0, 300), ...causeDetail(error) });
|
|
441
503
|
// Fall through to the download rung below.
|
|
442
504
|
}
|
|
443
505
|
}
|
|
@@ -466,7 +528,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
466
528
|
status({ ok: false, status: "restoring-local", desiredVersion, version: target.version, runtimeHealthy: false });
|
|
467
529
|
try {
|
|
468
530
|
const activationAt = now();
|
|
469
|
-
await
|
|
531
|
+
await runWorker(process.execPath, path.join(target.packageRoot, "src", "recovery-entry.js"), [target.version, channel], { env: { ...env, RELAY_RECOVERY_WORKER: "1" } });
|
|
470
532
|
const observed = await ready({ version: target.version }, activationAt);
|
|
471
533
|
if (!observed.ok) throw Error("local-runtime-not-healthy");
|
|
472
534
|
diagnostic("local-fallback", "succeeded", null, target.version);
|
|
@@ -481,7 +543,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
481
543
|
return deferred || status({ ok: true, status: "deferred-update-in-flight", desiredVersion, version: current?.version, runtimeHealthy: false });
|
|
482
544
|
}
|
|
483
545
|
diagnostic("local-fallback", "failed", error, target.version);
|
|
484
|
-
progress.fail(error
|
|
546
|
+
progress.fail(withCause(error)); log('local recovery failed: ' + withCause(error));
|
|
485
547
|
}
|
|
486
548
|
}
|
|
487
549
|
if (!updatesEnabled) return status({ ok: true, status: "disabled", runtimeHealthy: runtimeVerified, runtimeAvailable: runtimeResponsive });
|
|
@@ -505,7 +567,8 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
505
567
|
const deferredBeforeDownload = deferToTransaction({ desiredVersion, ...repairState });
|
|
506
568
|
if (deferredBeforeDownload) return deferredBeforeDownload;
|
|
507
569
|
if (previous?.desiredVersion === desiredVersion && previous.retryAt > now()) return status({ ok: false, status: "backoff", desiredVersion, ...repairState,
|
|
508
|
-
failures: previous.failures, retryAt: previous.retryAt, lastError: previous.lastError
|
|
570
|
+
failures: previous.failures, retryAt: previous.retryAt, lastError: previous.lastError,
|
|
571
|
+
...(previous.lastErrorDetail ? { lastErrorDetail: previous.lastErrorDetail } : {}) });
|
|
509
572
|
// Ordinary upgrades wait for pressure to clear. An unavailable installation
|
|
510
573
|
// can use the final recovery route at a bounded cadence after local repairs.
|
|
511
574
|
if (memoryNow.pressured) {
|
|
@@ -535,7 +598,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
535
598
|
const activationAt = now();
|
|
536
599
|
const attemptId = crypto.randomUUID();
|
|
537
600
|
try {
|
|
538
|
-
await
|
|
601
|
+
await runWorker(process.execPath, entry, [desiredVersion, channel], { env: { ...env, RELAY_RECOVERY_WORKER: "1", RELAY_RECOVERY_ATTEMPT_ID: attemptId } });
|
|
539
602
|
const observed = await ready({ version: desiredVersion }, activationAt);
|
|
540
603
|
if (!observed.ok) throw new Error("replacement-not-healthy");
|
|
541
604
|
return proven({ ok: true, status: "current", desiredVersion, version: desiredVersion, repair: "download", restarts: 0, lastSuccessAt: now(), failures: 0 }, observed);
|
|
@@ -545,7 +608,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
545
608
|
const deferred = deferToTransaction({ desiredVersion, ...repairState });
|
|
546
609
|
if (deferred) return deferred;
|
|
547
610
|
if (workerLostLock(error)) return status({ ok: true, status: "deferred-update-in-flight", desiredVersion, ...repairState, runtimeHealthy: false });
|
|
548
|
-
if (policy.failure(channel, desiredVersion, { id: attemptId, reason: error
|
|
611
|
+
if (policy.failure(channel, desiredVersion, { id: attemptId, reason: withCause(error), since: activationAt })?.slept !== true) policy.interrupt();
|
|
549
612
|
throw error;
|
|
550
613
|
}
|
|
551
614
|
} catch (error) {
|
|
@@ -555,11 +618,11 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
|
|
|
555
618
|
let slept = false;
|
|
556
619
|
try { slept = policy.sleptSince?.(runStartedAt) === true; } catch {}
|
|
557
620
|
if (slept) return status({ ok: true, status: "deferred-asleep", desiredVersion: activeStatus?.desiredVersion || null, version: current?.version,
|
|
558
|
-
lastError: String(error.message).slice(0, 300) });
|
|
621
|
+
lastError: String(error.message).slice(0, 300), ...causeDetail(error) });
|
|
559
622
|
const failures = previous && previous.desiredVersion === activeStatus?.desiredVersion ? (previous.failures || 0) + 1 : 1;
|
|
560
623
|
return status({ ok: false, status: "failed", desiredVersion: activeStatus?.desiredVersion || null, version: current?.version,
|
|
561
624
|
restarts: activeStatus?.restarts, staleSince: activeStatus?.staleSince,
|
|
562
|
-
failures, lastError: String(error.message).slice(0, 300), retryAt: now() + Math.min(60 * 60_000, CHECK_MS * 2 ** Math.min(failures - 1, 4)) });
|
|
625
|
+
failures, lastError: String(error.message).slice(0, 300), ...causeDetail(error), retryAt: now() + Math.min(60 * 60_000, CHECK_MS * 2 ** Math.min(failures - 1, 4)) });
|
|
563
626
|
} finally {
|
|
564
627
|
// Only our fresh UUID directory; never remove a canonical or rollback release.
|
|
565
628
|
try { if (staged && path.dirname(staged) === downloads) fs.rmSync(staged, { recursive: true, force: true }); }
|
|
@@ -2,20 +2,112 @@
|
|
|
2
2
|
const fs = require("node:fs"), os = require("node:os"), path = require("node:path"), crypto = require("node:crypto");
|
|
3
3
|
function read(file) { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } }
|
|
4
4
|
function alive(pid) { if (!Number.isSafeInteger(pid) || pid < 1) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code !== "ESRCH"; } }
|
|
5
|
+
// When a process started, in ms, or null when it cannot be told. A process
|
|
6
|
+
// number alone does not identify a process: after a restart the system hands
|
|
7
|
+
// the same low numbers to its own services. 2026-11-27: a Mac's week-old call
|
|
8
|
+
// marker named PID 872, which after the restart belonged to Apple's audio
|
|
9
|
+
// converter, so every update waited on a call that had ended long before.
|
|
10
|
+
const { spawnSync } = require("node:child_process");
|
|
11
|
+
function processStartedAt(pid, { platform = process.platform, run = spawnSync } = {}) {
|
|
12
|
+
if (!Number.isSafeInteger(pid) || pid < 1) return null;
|
|
13
|
+
if (pid === process.pid) return ownStartedAt();
|
|
14
|
+
try {
|
|
15
|
+
if (platform === "win32") {
|
|
16
|
+
const result = run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
|
|
17
|
+
`$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue; if ($p) { [DateTimeOffset]::new($p.StartTime).ToUnixTimeMilliseconds() }`],
|
|
18
|
+
{ encoding: "utf8", timeout: 10_000, windowsHide: true });
|
|
19
|
+
const value = Number(String(result.stdout || "").trim());
|
|
20
|
+
return result.status === 0 && Number.isFinite(value) && value > 0 ? value : null;
|
|
21
|
+
}
|
|
22
|
+
// lstart is local wall time to the second, e.g. "Fri Nov 27 10:18:43 2026".
|
|
23
|
+
const result = run("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
|
|
24
|
+
const value = Date.parse(String(result.stdout || "").trim().replace(/\s+/g, " "));
|
|
25
|
+
return result.status === 0 && Number.isFinite(value) && value > 0 ? value : null;
|
|
26
|
+
} catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
let ownStart = null;
|
|
29
|
+
function ownStartedAt() { return ownStart ??= Math.round(Date.now() - process.uptime() * 1000); }
|
|
30
|
+
// Started after the marker was written: a different process now has that
|
|
31
|
+
// number, and the call it recorded is over. One second covers ps's whole-second
|
|
32
|
+
// start times. When the start cannot be told, the marker is still trusted: a
|
|
33
|
+
// genuine call is never cleared on a guess.
|
|
34
|
+
const REUSE_TOLERANCE_MS = 1_000;
|
|
35
|
+
// A process's start time does not change while it runs, so it is asked at most
|
|
36
|
+
// once a minute per number: a long genuine call must not cost a ps (or, on
|
|
37
|
+
// Windows, a PowerShell) every few seconds.
|
|
38
|
+
const startCache = new Map();
|
|
39
|
+
function cachedStartedAt(pid, now = Date.now()) {
|
|
40
|
+
const hit = startCache.get(pid);
|
|
41
|
+
if (hit && now - hit.at < 60_000) return hit.value;
|
|
42
|
+
const value = processStartedAt(pid);
|
|
43
|
+
startCache.set(pid, { value, at: now });
|
|
44
|
+
if (startCache.size > 64) startCache.delete(startCache.keys().next().value);
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function ownerReused(report, { startedAtOf = cachedStartedAt } = {}) {
|
|
48
|
+
const since = Number(report?.ownerStartedAt ?? report?.startedAt);
|
|
49
|
+
if (!Number.isFinite(since) || since <= 0) return false;
|
|
50
|
+
const started = startedAtOf(report.pid);
|
|
51
|
+
return Number.isFinite(started) && started > since + REUSE_TOLERANCE_MS;
|
|
52
|
+
}
|
|
53
|
+
/** Whether the process a marker names is the one that wrote it and is still running. */
|
|
54
|
+
function ownerRunning(report, options = {}) {
|
|
55
|
+
if (!report || !Number.isSafeInteger(report.pid) || report.pid < 1) return false;
|
|
56
|
+
return (options.alive || alive)(report.pid) && !ownerReused(report, options);
|
|
57
|
+
}
|
|
5
58
|
function paths(homeDir, configDir) { const root = path.join(configDir || path.join(homeDir, ".relay"), "recovery", "activity"); return { root, drain: path.join(root, "drain.json") }; }
|
|
6
|
-
|
|
59
|
+
// What each in-progress marker records, so a computer whose update waits on one
|
|
60
|
+
// can say what it waits on: the kind ("call" for an MCP tool call, "work" for a
|
|
61
|
+
// session operation or a Relay-run AI turn), a content-free label (the tool or
|
|
62
|
+
// operation name), which process owns it and when it started.
|
|
63
|
+
const LABEL = /^[a-z0-9_.:-]{1,80}$/;
|
|
64
|
+
function processRole() {
|
|
65
|
+
if (process.env.RELAY_PROCESS_ROLE && LABEL.test(process.env.RELAY_PROCESS_ROLE)) return process.env.RELAY_PROCESS_ROLE;
|
|
66
|
+
if (process.versions.electron) return "app";
|
|
67
|
+
const script = path.basename(String(process.argv[1] || "")).toLowerCase();
|
|
68
|
+
if (/mcp-broker/.test(script)) return "broker";
|
|
69
|
+
if (script === "relay.js" && process.argv.includes("daemon")) return "daemon";
|
|
70
|
+
return script.replace(/\.c?js$/, "").replace(/[^a-z0-9_.:-]+/g, "-").slice(0, 40) || "unknown";
|
|
71
|
+
}
|
|
72
|
+
function beginCall({ homeDir = os.homedir(), configDir, kind = "call", label = null } = {}) {
|
|
7
73
|
const { root, drain } = paths(homeDir, configDir);
|
|
8
74
|
const blocked = () => alive(read(drain)?.pid);
|
|
9
75
|
if (blocked()) throw Error("Relay is updating. Retry with the same idempotency key after it finishes.");
|
|
10
76
|
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
11
77
|
const file = path.join(root, `call-${crypto.randomUUID()}.json`);
|
|
12
|
-
|
|
78
|
+
const name = typeof label === "string" && LABEL.test(label) ? label : null;
|
|
79
|
+
fs.writeFileSync(file, JSON.stringify({ pid: process.pid, ownerStartedAt: ownStartedAt(), kind, ...(name ? { label: name } : {}), role: processRole(), startedAt: Date.now() }), { mode: 0o600, flag: "wx" });
|
|
13
80
|
const release = () => { try { fs.rmSync(file, { force: true }); } catch {} };
|
|
14
81
|
// Close admission racing the updater's drain barrier.
|
|
15
82
|
if (blocked()) { release(); throw Error("Relay is updating. Retry with the same idempotency key after it finishes."); }
|
|
16
83
|
return release;
|
|
17
84
|
}
|
|
18
|
-
|
|
85
|
+
/** Every in-progress marker, described; markers whose owner has exited are `alive: false`. */
|
|
86
|
+
function describeCalls({ homeDir = os.homedir(), configDir, now = Date.now, ...options } = {}) {
|
|
87
|
+
const { root } = paths(homeDir, configDir);
|
|
88
|
+
let names;
|
|
89
|
+
try { names = fs.readdirSync(root); } catch { return []; }
|
|
90
|
+
return names.filter(name => /^call-[a-f0-9-]+\.json$/.test(name)).map(name => {
|
|
91
|
+
const report = read(path.join(root, name));
|
|
92
|
+
const started = Number(report?.startedAt);
|
|
93
|
+
return {
|
|
94
|
+
kind: typeof report?.kind === "string" && LABEL.test(report.kind) ? report.kind : "unknown",
|
|
95
|
+
label: typeof report?.label === "string" && LABEL.test(report.label) ? report.label : null,
|
|
96
|
+
role: typeof report?.role === "string" && LABEL.test(report.role) ? report.role : "unknown",
|
|
97
|
+
pid: Number.isSafeInteger(report?.pid) ? report.pid : null,
|
|
98
|
+
alive: ownerRunning(report, options),
|
|
99
|
+
// The number is in use, but by a process started after the marker.
|
|
100
|
+
reused: Boolean(report) && Number.isSafeInteger(report.pid) && (options.alive || alive)(report.pid) && ownerReused(report, options),
|
|
101
|
+
startedAt: Number.isFinite(started) && started > 0 ? started : null,
|
|
102
|
+
ageMs: Number.isFinite(started) && started > 0 ? Math.max(0, now() - started) : null,
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
function summarizeCalls(calls) {
|
|
107
|
+
const age = ms => ms === null ? "age unknown" : ms >= 3_600_000 ? `${Math.floor(ms / 3_600_000)}h${Math.floor(ms % 3_600_000 / 60_000)}m` : ms >= 60_000 ? `${Math.floor(ms / 60_000)}m` : `${Math.round(ms / 1000)}s`;
|
|
108
|
+
return calls.map(call => `${call.kind}${call.label ? `:${call.label}` : ""} by ${call.role} pid ${call.pid ?? "?"} for ${age(call.ageMs)}`).join("; ");
|
|
109
|
+
}
|
|
110
|
+
async function drainCalls({ homeDir = os.homedir(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), attempts = 60, ...options } = {}) {
|
|
19
111
|
const { root, drain } = paths(homeDir);
|
|
20
112
|
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
21
113
|
const nonce = crypto.randomUUID();
|
|
@@ -27,16 +119,23 @@ async function drainCalls({ homeDir = os.homedir(), sleep = ms => new Promise(re
|
|
|
27
119
|
let busy = false;
|
|
28
120
|
for (const name of fs.readdirSync(root).filter(name => /^call-[a-f0-9-]+\.json$/.test(name))) {
|
|
29
121
|
const file = path.join(root, name), report = read(file);
|
|
30
|
-
|
|
122
|
+
// An unreadable marker cannot be proved over. One whose owner exited, or
|
|
123
|
+
// whose number now belongs to a later process, is over: remove it.
|
|
124
|
+
if (!report || !Number.isSafeInteger(report.pid) || report.pid < 1 || ownerRunning(report, options)) busy = true;
|
|
31
125
|
else fs.rmSync(file, { force: true });
|
|
32
126
|
}
|
|
33
127
|
if (!busy) return release;
|
|
34
128
|
await sleep(500);
|
|
35
129
|
}
|
|
36
|
-
|
|
130
|
+
// Say what is still running: this is the only record of why an update waited.
|
|
131
|
+
const blocking = describeCalls({ homeDir, ...options }).filter(call => call.alive);
|
|
132
|
+
const error = Error(`Relay calls still active; activation deferred without interrupting them: ${summarizeCalls(blocking) || "unreadable marker"}`);
|
|
133
|
+
error.code = "relay-calls-active";
|
|
134
|
+
error.blocking = blocking;
|
|
135
|
+
throw error;
|
|
37
136
|
} catch (e) { release(); throw e; }
|
|
38
137
|
}
|
|
39
|
-
function activeCalls({ homeDir = os.homedir(), configDir } = {}) {
|
|
138
|
+
function activeCalls({ homeDir = os.homedir(), configDir, ...options } = {}) {
|
|
40
139
|
const { root } = paths(homeDir, configDir);
|
|
41
140
|
let names;
|
|
42
141
|
try { names = fs.readdirSync(root); } catch(e) { return e.code === "ENOENT" ? 0 : null; }
|
|
@@ -44,8 +143,8 @@ function activeCalls({ homeDir = os.homedir(), configDir } = {}) {
|
|
|
44
143
|
for (const name of names.filter(name => /^call-[a-f0-9-]+\.json$/.test(name))) {
|
|
45
144
|
const report = read(path.join(root, name));
|
|
46
145
|
if (!report || !Number.isSafeInteger(report.pid) || report.pid < 1) return null; // cannot prove idle
|
|
47
|
-
if (
|
|
146
|
+
if (ownerRunning(report, options)) count++;
|
|
48
147
|
}
|
|
49
148
|
return count;
|
|
50
149
|
}
|
|
51
|
-
module.exports = { beginCall, drainCalls, activeCalls };
|
|
150
|
+
module.exports = { beginCall, drainCalls, activeCalls, describeCalls, summarizeCalls, ownerRunning, processStartedAt };
|
|
@@ -23,6 +23,28 @@ function updateLogStdio(platform = process.platform, homeDir = os.homedir()) {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// The deadline or exit that ended a worker, for the fleet report: appended to
|
|
27
|
+
// the update loop's error ring beside update-state.json (src/auto-update.js,
|
|
28
|
+
// recordUpdateError, same format). Never allowed to affect the worker's exit.
|
|
29
|
+
function recordWatchdogError(entry, message, { env = process.env, homeDir = os.homedir(), now = Date.now } = {}) {
|
|
30
|
+
try {
|
|
31
|
+
const store = env.RELAY_HOME || env.RELAY_COMPANION_HOME || path.join(homeDir, ".relay-companion");
|
|
32
|
+
const file = path.join(store, "update-errors.json");
|
|
33
|
+
let errors = [];
|
|
34
|
+
try { const stored = JSON.parse(fs.readFileSync(file, "utf8")); if (Array.isArray(stored?.errors)) errors = stored.errors.filter(item => item && typeof item === "object"); } catch {}
|
|
35
|
+
const detail = String(message || "").replace(/\s+/g, " ").trim().slice(0, 300);
|
|
36
|
+
const kind = path.basename(String(entry || "")).replace(/\.c?js$/, "").slice(0, 40) || null;
|
|
37
|
+
const reason = (/recovery-worker-(deadline-exceeded|exit-\d+)/.exec(detail) || [])[0] || "worker-failed";
|
|
38
|
+
const last = errors.at(-1);
|
|
39
|
+
if (last && last.status === "watchdog" && last.kind === kind && last.detail === detail) errors[errors.length - 1] = { ...last, at: now(), count: (Number(last.count) || 1) + 1 };
|
|
40
|
+
else errors.push({ at: now(), status: "watchdog", kind, reason, detail, count: 1 });
|
|
41
|
+
fs.mkdirSync(store, { recursive: true });
|
|
42
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
43
|
+
fs.writeFileSync(temporary, `${JSON.stringify({ schema: 1, errors: errors.slice(-6) })}\n`);
|
|
44
|
+
fs.renameSync(temporary, file);
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
|
|
26
48
|
if (require.main === module) {
|
|
27
49
|
if (process.versions.electron) throw Error("Relay update workers require the verified Node runtime, not Electron");
|
|
28
50
|
const [entry, mode, payload] = process.argv.slice(2);
|
|
@@ -34,15 +56,17 @@ if (require.main === module) {
|
|
|
34
56
|
const line = `[relay-update] worker entry missing: ${entry}`;
|
|
35
57
|
console.error(line);
|
|
36
58
|
if (logPath) { try { fs.appendFileSync(logPath, `${line}\n`); } catch {} }
|
|
59
|
+
recordWatchdogError(entry, "worker entry missing");
|
|
37
60
|
process.exit(0);
|
|
38
61
|
}
|
|
39
62
|
execute(process.execPath, entry, [mode, payload], { stdio }).catch(error => {
|
|
40
63
|
const line = `[relay-update] ${error.message}`;
|
|
41
64
|
console.error(line);
|
|
42
65
|
if (logPath) { try { fs.appendFileSync(logPath, `${line}\n`); } catch {} }
|
|
66
|
+
recordWatchdogError(entry, error.message);
|
|
43
67
|
// launchd must not resurrect a failed attempt with a stale target.
|
|
44
68
|
process.exitCode = 0;
|
|
45
69
|
});
|
|
46
70
|
}
|
|
47
71
|
|
|
48
|
-
module.exports = { updateLogStdio };
|
|
72
|
+
module.exports = { updateLogStdio, recordWatchdogError };
|
package/package.json
CHANGED