relay-companion 0.1.643 → 0.1.645

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.
@@ -16,7 +16,16 @@ function createDaemonProgress({ packageRoot, version, homeDir = os.homedir(), pi
16
16
  return {
17
17
  advance(phase = "running") { state = { ...state, phase, at: now(), sequence: state.sequence + 1 }; save(); },
18
18
  component(name, status) { if (state.components[name] !== status) { state.components[name] = status; save(); } },
19
- snapshot() { return { ...state, components: { ...state.components } }; },
19
+ // The last failure of each part, as a closed code (see diagnostics.cjs
20
+ // classifyFailure) and the job it happened in. Kept after the part
21
+ // recovers, so the fleet can see what last went wrong and when.
22
+ componentError(name, { stage, code, at }) {
23
+ const previous = state.componentErrors?.[name];
24
+ if (previous && previous.stage === stage && previous.code === code && at - previous.at < 60_000) return;
25
+ state = { ...state, componentErrors: { ...(state.componentErrors || {}), [name]: { stage, code, at } } };
26
+ save();
27
+ },
28
+ snapshot() { return { ...state, components: { ...state.components }, componentErrors: { ...(state.componentErrors || {}) } }; },
20
29
  async waiting(operation, phase = "offline") {
21
30
  // Explicit local control progress while authentication/network is pending.
22
31
  // It reports a wait, never successful delivery or signed-in operation.
@@ -4,7 +4,8 @@
4
4
  "recovery",
5
5
  "launcher",
6
6
  "collector",
7
- "unknown"
7
+ "unknown",
8
+ "daemon"
8
9
  ],
9
10
  "stages": [
10
11
  "discovery",
@@ -17,7 +18,15 @@
17
18
  "local-fallback",
18
19
  "services",
19
20
  "health",
20
- "unknown"
21
+ "unknown",
22
+ "inbox-background",
23
+ "attachments",
24
+ "task-wakes",
25
+ "agent-sessions",
26
+ "topics",
27
+ "tasks",
28
+ "process-query",
29
+ "report"
21
30
  ],
22
31
  "outcomes": [
23
32
  "started",
@@ -87,7 +96,13 @@
87
96
  "runtime-node-missing",
88
97
  "runtime-npm-missing",
89
98
  "interrupted-by-sleep",
90
- "check-timed-out"
99
+ "check-timed-out",
100
+ "file-corrupt",
101
+ "server-error",
102
+ "server-refused",
103
+ "component-stalled",
104
+ "worker-out-of-memory",
105
+ "collection-cancelled"
91
106
  ],
92
107
  "runtimeStates": [
93
108
  "active",
@@ -27,6 +27,18 @@ function errorCode(error) {
27
27
  ];
28
28
  return patterns.find(([pattern]) => pattern.test(text))?.[1] || "unclassified";
29
29
  }
30
+ // What kind of failure a background part hit, in the same closed vocabulary:
31
+ // never the message itself, which can hold paths or content. A server's error
32
+ // page or refusal, a local file that is corrupt, and a lock that could not be
33
+ // taken are told apart from the generic codes errorCode already knows.
34
+ function classifyFailure(error) {
35
+ const status = Number(error?.status || error?.statusCode || 0);
36
+ if (error?.code === "non_json_response" || status >= 500) return "server-error";
37
+ if (status >= 400) return "server-refused";
38
+ if (error?.name === "SyntaxError" || error instanceof SyntaxError) return "file-corrupt";
39
+ if (/lock unavailable|lock-unavailable/i.test(String(error?.message || ""))) return "transaction-lock-unavailable";
40
+ return errorCode(error) || "unclassified";
41
+ }
30
42
  function configIdentity(homeDir) {
31
43
  const config = read(path.join(homeDir, ".relay", "config.json"));
32
44
  // A new account must never upload its predecessor's diagnostic history.
@@ -155,4 +167,4 @@ function snapshot({ homeDir = os.homedir(), now = Date.now, env = process.env }
155
167
  discoveryError: errorCode(recovery?.discoveryError),
156
168
  };
157
169
  }
158
- module.exports = { record, snapshot, events, configIdentity, read, errorCode, version, contract, MAX_EVENTS, MAX_AGE_MS };
170
+ module.exports = { record, snapshot, events, configIdentity, read, errorCode, classifyFailure, version, contract, MAX_EVENTS, MAX_AGE_MS };
@@ -55,7 +55,11 @@ function macPillLaunch({ homeDir, current, run }) {
55
55
  const code = String(error?.code || error?.message || "unknown").split(/[:\s]/)[0].slice(0, 40);
56
56
  // A check that timed out learned nothing about the registration.
57
57
  if (code === "check-timed-out") return null;
58
- return { ok: false, reason: `registration-invalid: ${code}` };
58
+ // Which check failed (plutil-exit-1, wrong-label, ...), and whether macOS
59
+ // has the service loaded anyway: an invalid file that launchd still runs
60
+ // differs from one that will not start Relay after the next log-in.
61
+ const detail = /^[a-z0-9-]{1,30}$/.test(String(error?.detail || "")) ? `/${error.detail}` : "";
62
+ return { ok: false, reason: `registration-invalid: ${code}${detail}`.slice(0, 80), loaded: launchdLoaded(mac, run) };
59
63
  }
60
64
  if (record.releaseExecutable) {
61
65
  const identity = require("./mac-background-identity.cjs");
@@ -69,6 +73,14 @@ function macPillLaunch({ homeDir, current, run }) {
69
73
  return { ok: true, reason: null };
70
74
  }
71
75
 
76
+ // true or false when launchd answered; null when it could not be asked.
77
+ function launchdLoaded(mac, run) {
78
+ try {
79
+ const state = mac.registration(PILL_LABEL, { run });
80
+ return state.present ? true : state.known ? false : null;
81
+ } catch { return null; }
82
+ }
83
+
72
84
  function macPillLastExit(run) {
73
85
  const userId = typeof process.getuid === "function" ? process.getuid() : 0;
74
86
  const result = run("/bin/launchctl", ["print", `gui/${userId}/${PILL_LABEL}`]);
@@ -138,7 +150,15 @@ function collectInstallationHealth({ homeDir = os.homedir(), platform = process.
138
150
  const componentNames = ["inbox-background", "agent-sessions", "topics", "tasks"];
139
151
  const unhealthyComponents = progressMatches ? componentNames.filter(name => ["failed", "stalled"].includes(progress.components?.[name])) : [];
140
152
  const pill = pillLiveness({ homeDir, platform, env, live, current, run, now });
141
- let serviceHealth = { state: "healthy", reason: "ready", components: unhealthyComponents };
153
+ // Each part's last failure from the daemon's health file: which job and what
154
+ // kind (closed codes, never messages), newest first, from the last day.
155
+ const LABEL = /^[a-z0-9_-]{1,40}$/;
156
+ const errors = progressMatches ? Object.entries(progress.componentErrors || {})
157
+ .filter(([name, item]) => LABEL.test(name) && LABEL.test(item?.stage || "") && LABEL.test(item?.code || "")
158
+ && Number.isFinite(item.at) && item.at <= now && now - item.at < 24 * 60 * 60_000)
159
+ .sort((a, b) => b[1].at - a[1].at).slice(0, 4)
160
+ .map(([name, item]) => ({ component: name, stage: item.stage, code: item.code, at: new Date(item.at).toISOString() })) : [];
161
+ let serviceHealth = { state: "healthy", reason: "ready", components: unhealthyComponents, ...(errors.length ? { errors } : {}) };
142
162
  if (!activeVersion) serviceHealth = { ...serviceHealth, state: "unverified", reason: "runtime-not-active" };
143
163
  else if (!live?.daemon) serviceHealth = { ...serviceHealth, state: "failed", reason: "daemon-missing" };
144
164
  else if (!daemonResponsive) serviceHealth = { ...serviceHealth, state: "failed", reason: "daemon-not-responsive" };
@@ -25,10 +25,19 @@ function readRegistration(label, { homeDir = os.homedir(), run = defaultRun, fsI
25
25
  // plutil killed by the timeout says nothing about the file: a sleeping Mac's
26
26
  // brief wake ends mid-check (2026-11-20).
27
27
  if (decoded?.error?.code === "ETIMEDOUT" || (decoded?.signal && decoded?.status === null)) throw Error(`check-timed-out: ${label}`);
28
- if (!commandOk(decoded)) throw Error(`invalid-service-plist: ${label}`);
29
- const plist = JSON.parse(decoded.stdout);
30
- const args = plist.ProgramArguments;
31
- if (plist.Label !== label || !Array.isArray(args) || !args.every(x => typeof x === "string") || plist.Program) throw Error(`invalid-service-plist: ${label}`);
28
+ // `detail` says which check failed, in words that never hold a path or the
29
+ // file's contents, so the fleet can tell an unreadable file from one that
30
+ // names the wrong service (installation-health.cjs reports it).
31
+ const invalid = detail => Object.assign(Error(`invalid-service-plist: ${label}`), { detail });
32
+ if (!commandOk(decoded)) {
33
+ throw invalid(decoded?.error ? `plutil-${String(decoded.error.code || "error").toLowerCase().slice(0, 20)}` : `plutil-exit-${Number.isInteger(decoded?.status) ? decoded.status : "unknown"}`);
34
+ }
35
+ let plist;
36
+ try { plist = JSON.parse(decoded.stdout); } catch { throw invalid("plutil-output-unreadable"); }
37
+ const args = plist?.ProgramArguments;
38
+ if (plist?.Label !== label) throw invalid("wrong-label");
39
+ if (!Array.isArray(args) || !args.every(x => typeof x === "string")) throw invalid("no-program-arguments");
40
+ if (plist.Program) throw invalid("program-key");
32
41
  if (label === LABELS[0] && require("./node-contract.cjs").isElectronExecutable(args[0])) throw Error(`invalid-service-interpreter: ${label}`);
33
42
  const suffix = label === LABELS[0] ? /[\\/]bin[\\/]relay\.js$/ : /[\\/]overlay[\\/]main\.cjs$/;
34
43
  const script = args.find(x => /[\\/]node_modules[\\/]relay-companion[\\/]/.test(x) && suffix.test(x));
@@ -5,28 +5,53 @@ const PROBATION_MS = 15 * 60_000, OBSERVATION_GAP_MS = 7 * 60_000;
5
5
  const EMERGENCY_RETRY_MS = 15 * 60_000, RELEASE_COOLDOWN_MS = 30 * 60_000;
6
6
  const read = file => { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } };
7
7
 
8
- function recoveryPolicy({ root = path.join(os.homedir(), ".relay", "recovery"), now = Date.now } = {}) {
8
+ // A machine that is asleep, or only waking for a minute at a time with its
9
+ // lid closed, cannot download or verify anything; an update that fails then
10
+ // says nothing about the release. Sven's Mac, away for a weekend in
11
+ // 2026-11, failed 0.1.642 and 0.1.643 seven times that way and then refused
12
+ // 0.1.643 for 24 hours once he was back. So the update paths hold off while
13
+ // the machine is not properly awake (asleep()), and a failure the machine
14
+ // slept through is kept for the record but never counts towards the pause.
15
+ // Windows keeps its monotonic clock running through sleep, so there sleep
16
+ // cannot be told (sleep-clock.cjs) and nothing changes.
17
+ const machinePower = (root, now) => require("./sleep-clock.cjs").powerState({ heartbeat: read(path.join(root, "daemon.json")), now: now() });
18
+
19
+ function recoveryPolicy({ root = path.join(os.homedir(), ".relay", "recovery"), now = Date.now, power = () => machinePower(root, now) } = {}) {
20
+ const powerNow = () => { try { return power() || {}; } catch { return {}; } };
21
+ // Not properly awake: still resuming from a sleep, or in a run of brief wakes.
22
+ const asleep = () => ["resuming", "brief-wakes"].includes(powerNow().state);
23
+ // Did the machine sleep at any point since `since` (an attempt's start), or is it not properly awake now?
24
+ const sleptSince = since => {
25
+ const state = powerNow();
26
+ if (["resuming", "brief-wakes"].includes(state.state)) return true;
27
+ const wokeAt = Date.parse(state.lastWakeAt || "");
28
+ return Number.isFinite(since) && since > 0 && Number.isFinite(wokeAt) && wokeAt > since;
29
+ };
9
30
  const directory = (channel, version) => {
10
31
  if (!["stable", "dev", "staging"].includes(channel) || !/^\d+\.\d+\.\d+$/.test(version || "")) throw Error("invalid-release-policy-target");
11
32
  return path.join(root, "release-health", channel, version);
12
33
  };
13
- const failure = (channel, version, { id = crypto.randomUUID(), reason = "runtime-not-healthy" } = {}) => {
34
+ const failure = (channel, version, { id = crypto.randomUUID(), reason = "runtime-not-healthy", since = null } = {}) => {
14
35
  const dir = directory(channel, version), file = path.join(dir, 'failure-' + crypto.createHash("sha256").update(id).digest("hex") + '.json');
15
36
  // Independent immutable event files avoid lost increments when the daemon,
16
37
  // worker and watchdog report concurrently. A request ID deduplicates reports.
17
- if (fs.existsSync(file)) return;
18
- atomicFile(file, JSON.stringify({ at: now(), reason: String(reason).slice(0, 300) }));
38
+ if (fs.existsSync(file)) return { slept: read(file)?.slept === true };
39
+ const slept = sleptSince(since);
40
+ atomicFile(file, JSON.stringify({ at: now(), reason: String(reason).slice(0, 300), ...(slept ? { slept: true } : {}) }));
41
+ // The machine slept: the release was not judged, so its probation stands.
42
+ if (slept) return { slept: true };
19
43
  const probationFile = path.join(root, "probation.json");
20
44
  if (read(probationFile)?.identity?.startsWith(`${channel}:${version}:`)) {
21
45
  try { fs.unlinkSync(probationFile); } catch (error) { if (error.code !== "ENOENT") throw error; }
22
46
  }
47
+ return { slept: false };
23
48
  };
24
49
  const decision = (channel, version) => {
25
50
  const dir = directory(channel, version), healthyAt = read(path.join(dir, "proven.json"))?.at ?? -1;
26
51
  let names = [];
27
52
  try { names = fs.readdirSync(dir); } catch (error) { if (error.code !== "ENOENT") throw error; }
28
53
  const events = names.filter(name => /^failure-[a-f0-9]{64}\.json$/.test(name)).sort().map(name => ({ ...read(path.join(dir, name)), name }))
29
- .filter(event => Number.isFinite(event?.at) && event.at >= healthyAt);
54
+ .filter(event => Number.isFinite(event?.at) && event.at >= healthyAt && event.slept !== true);
30
55
  const lastAt = events.reduce((last, event) => Math.max(last, event.at), 0);
31
56
  const wait = Math.min(24 * 60 * 60_000, RELEASE_COOLDOWN_MS * 2 ** Math.min(Math.max(0, events.length - 1), 6));
32
57
  // Anchor a clock correction once. Recomputing min(lastAt, now) on every
@@ -42,7 +67,7 @@ function recoveryPolicy({ root = path.join(os.homedir(), ".relay", "recovery"),
42
67
  return { blocked: events.length > 0 && now() < retryAt, retryAt, failures: events.length };
43
68
  };
44
69
  return {
45
- failure, decision,
70
+ failure, decision, asleep, sleptSince,
46
71
  observe(channel, observed) {
47
72
  const current = observed.current, at = now(), file = path.join(root, "probation.json");
48
73
  // Only strong readiness probes supply an identity. Legacy process/heartbeat
@@ -223,6 +223,7 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
223
223
  if (!config) return { ok: false, status: "configuration-unavailable" };
224
224
  const channel = channelFrom(config, env);
225
225
  const policy = policyFactory({ root: path.join(root, "recovery"), now });
226
+ const runStartedAt = now();
226
227
  const previous = read(stateFile);
227
228
  const runId = env.RELAY_RECOVERY_RUN_ID || crypto.randomUUID();
228
229
  const diagnosticScope = diagnostics.configIdentity(homeDir)?.scope || null;
@@ -496,6 +497,9 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
496
497
  if (quarantine.blocked) return status({ ok: true, status: "deferred-release-cooldown", desiredVersion, runtimeHealthy: runtimeVerified, runtimeAvailable: runtimeResponsive, retryAt: quarantine.retryAt, failures: quarantine.failures });
497
498
  const busy = busyDecision(heartbeat, { homeDir, now: now() });
498
499
  if (busy) return status({ ok: true, status: busy, desiredVersion, ...repairState });
500
+ // A sleeping or briefly waking machine cannot finish a download; wait
501
+ // until it is properly awake (recovery-policy.cjs).
502
+ if (policy.asleep?.()) return status({ ok: true, status: "deferred-asleep", desiredVersion, ...repairState });
499
503
  // Never start a five-minute download to race an installer that is already
500
504
  // running; the daemon's updater discovers the same release we just did.
501
505
  const deferredBeforeDownload = deferToTransaction({ desiredVersion, ...repairState });
@@ -541,12 +545,17 @@ async function recoverLocked({ homeDir = os.homedir(), env = process.env, now =
541
545
  const deferred = deferToTransaction({ desiredVersion, ...repairState });
542
546
  if (deferred) return deferred;
543
547
  if (workerLostLock(error)) return status({ ok: true, status: "deferred-update-in-flight", desiredVersion, ...repairState, runtimeHealthy: false });
544
- policy.failure(channel, desiredVersion, { id: attemptId, reason: error.message });
545
- policy.interrupt();
548
+ if (policy.failure(channel, desiredVersion, { id: attemptId, reason: error.message, since: activationAt })?.slept !== true) policy.interrupt();
546
549
  throw error;
547
550
  }
548
551
  } catch (error) {
549
552
  const activeStatus = read(stateFile);
553
+ // The machine slept during this run: the failure says nothing, so it
554
+ // neither counts nor delays the next run.
555
+ let slept = false;
556
+ try { slept = policy.sleptSince?.(runStartedAt) === true; } catch {}
557
+ if (slept) return status({ ok: true, status: "deferred-asleep", desiredVersion: activeStatus?.desiredVersion || null, version: current?.version,
558
+ lastError: String(error.message).slice(0, 300) });
550
559
  const failures = previous && previous.desiredVersion === activeStatus?.desiredVersion ? (previous.failures || 0) + 1 : 1;
551
560
  return status({ ok: false, status: "failed", desiredVersion: activeStatus?.desiredVersion || null, version: current?.version,
552
561
  restarts: activeStatus?.restarts, staleSince: activeStatus?.staleSince,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "relay-companion",
3
- "version": "0.1.643",
3
+ "version": "0.1.645",
4
4
  "description": "Install Relay for Claude Code, Cowork, and Codex, then sign in from the Relay pill.",
5
5
  "homepage": "https://sendrelays.com/get-started",
6
6
  "repository": {