@commonlyai/cli 0.1.399 → 0.1.400

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.399",
3
+ "version": "0.1.400",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -45,6 +45,9 @@ import {
45
45
 
46
46
  import { daemonLogsDir, daemonSeatLogPath, readLogTail } from '../lib/daemon-logs.js';
47
47
  import { watchWindowsLauncher } from '../lib/daemon-service-windows.js';
48
+ import {
49
+ DAEMON_LOCK_EXIT, acquireDaemonLock, daemonLockPath, daemonLockWaitMs,
50
+ } from '../lib/daemon-lock.js';
48
51
  import {
49
52
  UNSANDBOXED_FLAG, clearUnsandboxedOptIn, hostSandboxReport, loadUnsandboxedOptIn, saveUnsandboxedOptIn, unsandboxedFlagRefusal,
50
53
  } from '../lib/sandbox/windows-unsandboxed.js';
@@ -375,6 +378,7 @@ export const firstSupervisionPass = async ({
375
378
  onLauncherGone,
376
379
  isEnded = () => false,
377
380
  armLauncherWatch = watchWindowsLauncher,
381
+ releaseLock = async () => {},
378
382
  }) => {
379
383
  let launcherGone = false;
380
384
  armLauncherWatch({
@@ -385,9 +389,19 @@ export const firstSupervisionPass = async ({
385
389
  });
386
390
  const stopped = () => launcherGone || isEnded();
387
391
  if (stopped()) return false;
388
- await supervisor.tick();
389
- if (stopped()) return false;
390
- await supervisor.heartbeat();
392
+ try {
393
+ await supervisor.tick();
394
+ if (stopped()) return false;
395
+ await supervisor.heartbeat();
396
+ } catch (error) {
397
+ // F637 review: a throw here (a later seat's token read, say) comes after
398
+ // earlier seats have started. The caller's catch can't reach them or the
399
+ // lock, so stop them and free the lock before the error goes on, as the
400
+ // runtime-failure and shutdown paths do.
401
+ supervisor.stop();
402
+ await releaseLock();
403
+ throw error;
404
+ }
391
405
  return !stopped();
392
406
  };
393
407
 
@@ -727,6 +741,20 @@ Examples:
727
741
  process.exitCode = process.platform === 'darwin' ? 0 : stopped.exitCode;
728
742
  return;
729
743
  }
744
+ // F637: one daemon per machine credential. Taken before the first
745
+ // request, so a refused copy never touches the server. It waits ~10 s
746
+ // first: a restart's old daemon is still exiting when the new one starts.
747
+ const lock = await acquireDaemonLock({
748
+ lockPath: daemonLockPath({ home: homedir() }),
749
+ waitMs: daemonLockWaitMs(),
750
+ });
751
+ if (!lock.ok) {
752
+ const holder = lock.holderPid ? `pid ${lock.holderPid}` : 'another process';
753
+ console.error(`${new Date().toISOString()} another Commonly daemon (${holder}) is already running for ${record.machineName}; this copy exits (${DAEMON_LOCK_EXIT}).`);
754
+ process.exitCode = DAEMON_LOCK_EXIT;
755
+ return;
756
+ }
757
+ const releaseLock = () => { void lock.release(); };
730
758
  const client = createClient({ instance: record.instanceUrl, token: record.daemonToken });
731
759
  const logsDir = daemonLogsDir();
732
760
  if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true });
@@ -775,6 +803,7 @@ Examples:
775
803
  clearInterval(pollTimer);
776
804
  clearInterval(heartbeatTimer);
777
805
  supervisor.stop();
806
+ releaseLock();
778
807
  // Without the marker launchd would restart forever. A successful
779
808
  // exit parks it on macOS; systemd honors 77 directly.
780
809
  process.exitCode = saved || process.platform !== 'darwin' ? 77 : 0;
@@ -825,6 +854,7 @@ Examples:
825
854
  clearInterval(pollTimer);
826
855
  clearInterval(heartbeatTimer);
827
856
  supervisor.stop();
857
+ releaseLock();
828
858
  process.exit(0);
829
859
  };
830
860
  // Under the Windows launcher, the launcher's exit is the stop
@@ -838,8 +868,12 @@ Examples:
838
868
  shutdown();
839
869
  },
840
870
  isEnded: () => terminalEnded,
871
+ releaseLock: () => lock.release(),
841
872
  });
842
- if (!started) return;
873
+ if (!started) {
874
+ releaseLock();
875
+ return;
876
+ }
843
877
  const runtimeFailure = (error) => {
844
878
  if (terminalEnded) return;
845
879
  terminalEnded = true;
@@ -847,6 +881,7 @@ Examples:
847
881
  clearInterval(pollTimer);
848
882
  clearInterval(heartbeatTimer);
849
883
  supervisor.stop();
884
+ releaseLock();
850
885
  process.exitCode = 75;
851
886
  };
852
887
  pollTimer = setInterval(() => { void supervisor.tick().catch(runtimeFailure); }, Number(opts.poll) || DEFAULT_POLL_MS);
package/src/lib/api.js CHANGED
@@ -38,6 +38,17 @@ const summarizeTextError = (text, status) => {
38
38
  return line.length > MAX_TEXT_ERROR ? `${line.slice(0, MAX_TEXT_ERROR)}…` : line;
39
39
  };
40
40
 
41
+ // F637: a 429's Retry-After, in ms, from delta-seconds or an HTTP date (RFC
42
+ // 9110 10.2.3). A date already past is 0; anything unreadable is undefined.
43
+ export const parseRetryAfterMs = (value, nowMs = Date.now()) => {
44
+ const text = String(value ?? '').trim();
45
+ if (!text) return undefined;
46
+ if (/^\d+$/.test(text)) return Number(text) * 1000;
47
+ if (/^[+-]?\d/.test(text)) return undefined;
48
+ const at = Date.parse(text);
49
+ return Number.isNaN(at) ? undefined : Math.max(0, at - nowMs);
50
+ };
51
+
41
52
  const handleResponse = async (res, session = null) => {
42
53
  const text = await res.text();
43
54
  let body;
@@ -53,6 +64,8 @@ const handleResponse = async (res, session = null) => {
53
64
  const err = new Error(msg);
54
65
  err.status = res.status;
55
66
  err.body = body;
67
+ const retryAfterMs = parseRetryAfterMs(res.headers?.get?.('retry-after'));
68
+ if (retryAfterMs !== undefined) err.retryAfterMs = retryAfterMs;
56
69
  throw err;
57
70
  }
58
71
  return body;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * One `commonly daemon run` per machine credential (F637).
3
+ *
4
+ * A Windows install piled up ~140 daemons on one key, each polling the server
5
+ * on its own 30 s timers, and nothing refused the second copy. The lock is a
6
+ * listening local socket: a named pipe on Windows, a unix socket under
7
+ * ~/.commonly/daemon elsewhere. The OS frees it when the holder dies, however
8
+ * it dies, so it never goes stale the way a pid file does (and a reused pid
9
+ * can never pass for the holder).
10
+ *
11
+ * The holder answers anyone who connects with one JSON line, `{"pid":<n>}`,
12
+ * and hangs up, so a refused daemon can name the copy that is already running.
13
+ */
14
+
15
+ import { createHash } from 'crypto';
16
+ import { existsSync, mkdirSync, unlinkSync } from 'fs';
17
+ import { createConnection, createServer } from 'net';
18
+ import { dirname, join } from 'path';
19
+
20
+ // The exit code of a daemon that found another one holding the lock. The
21
+ // Windows launcher waits on it and tries again; it never disables the task.
22
+ export const DAEMON_LOCK_EXIT = 79;
23
+
24
+ // A restart's old node exits within ~2 s of its launcher ending, so a new
25
+ // daemon waits this long before it gives up.
26
+ export const DAEMON_LOCK_WAIT_MS = 10_000;
27
+ const RETRY_EVERY_MS = 500;
28
+ const PID_READ_TIMEOUT_MS = 1_000;
29
+
30
+ // A unix socket path is capped near 104 bytes on macOS (108 on Linux).
31
+ const MAX_SOCKET_PATH = 100;
32
+
33
+ // Keyed by the home alone. A home holds exactly one machine record
34
+ // (~/.commonly/daemon/machine.json), and `daemon run --instance` refuses any
35
+ // instance but the registered one, so one daemon per home is the rule. Keying
36
+ // by machineDbId would let an old daemon still running across a
37
+ // `daemon register` (a new machineDbId) sit beside the new one.
38
+ export const daemonLockId = ({ home }) => createHash('sha256')
39
+ .update(String(home))
40
+ .digest('hex')
41
+ .slice(0, 16);
42
+
43
+ export const daemonLockPath = ({ home, platform = process.platform }) => {
44
+ const id = daemonLockId({ home });
45
+ if (platform === 'win32') return `\\\\.\\pipe\\commonly-daemon-${id}`;
46
+ const path = join(home, '.commonly', 'daemon', `daemon-${id}.sock`);
47
+ // A home too deep for a socket path falls back to /tmp; the id still
48
+ // carries the home, so two accounts never share one.
49
+ return Buffer.byteLength(path) <= MAX_SOCKET_PATH ? path : join('/tmp', `commonly-daemon-${id}.sock`);
50
+ };
51
+
52
+ const isPipe = (lockPath) => lockPath.startsWith('\\\\.\\pipe\\');
53
+
54
+ const listen = (server, lockPath) => new Promise((resolve, reject) => {
55
+ const onError = (error) => { server.off('listening', onListening); reject(error); };
56
+ const onListening = () => { server.off('error', onError); resolve(); };
57
+ server.once('error', onError);
58
+ server.once('listening', onListening);
59
+ server.listen(lockPath);
60
+ });
61
+
62
+ // Connect to whoever holds the path. `held` with the pid it sent (null when it
63
+ // sent nothing readable in time), or `free` when nothing is listening there.
64
+ const probe = (lockPath) => new Promise((resolve) => {
65
+ let settled = false;
66
+ let data = '';
67
+ const finish = (result) => {
68
+ if (settled) return;
69
+ settled = true;
70
+ clearTimeout(timer);
71
+ socket.destroy();
72
+ resolve(result);
73
+ };
74
+ const socket = createConnection(lockPath);
75
+ const timer = setTimeout(() => finish({ state: 'held', holderPid: null }), PID_READ_TIMEOUT_MS);
76
+ const parsePid = () => {
77
+ try {
78
+ const pid = JSON.parse(data.split('\n')[0])?.pid;
79
+ return Number.isInteger(pid) ? pid : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ };
84
+ socket.setEncoding('utf8');
85
+ socket.on('data', (chunk) => {
86
+ data += chunk;
87
+ if (data.includes('\n')) finish({ state: 'held', holderPid: parsePid() });
88
+ });
89
+ socket.on('end', () => finish({ state: 'held', holderPid: parsePid() }));
90
+ socket.on('error', (error) => {
91
+ if (error.code === 'ECONNREFUSED' || error.code === 'ENOENT') finish({ state: 'free' });
92
+ else finish({ state: 'held', holderPid: parsePid() });
93
+ });
94
+ });
95
+
96
+ const holderServer = () => {
97
+ const server = createServer((socket) => {
98
+ socket.on('error', () => {});
99
+ socket.end(`${JSON.stringify({ pid: process.pid })}\n`);
100
+ });
101
+ // A late client error must never end the daemon.
102
+ server.on('error', () => {});
103
+ return server;
104
+ };
105
+
106
+ const held = (server, lockPath) => {
107
+ // The lock never keeps the process alive on its own.
108
+ server.unref();
109
+ let released = false;
110
+ const unlinkOwn = () => {
111
+ if (isPipe(lockPath)) return;
112
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
113
+ };
114
+ // process.exit() skips the close below; the socket file goes with the exit.
115
+ const onExit = () => { if (!released) unlinkOwn(); };
116
+ process.once('exit', onExit);
117
+ const release = () => new Promise((resolve) => {
118
+ if (released) { resolve(); return; }
119
+ released = true;
120
+ process.off('exit', onExit);
121
+ // close() unlinks a unix socket server's path itself (libuv's
122
+ // uv__pipe_close, synchronously inside the call), so no unlink of our own
123
+ // here: a second one could remove the socket of a daemon that bound in
124
+ // between. The exit hook above covers exits that skip release.
125
+ server.close(() => resolve());
126
+ });
127
+ return { ok: true, lockPath, release };
128
+ };
129
+
130
+ /**
131
+ * One attempt: `{ ok: true, release }` when this process now holds the lock,
132
+ * `{ ok: false, holderPid }` when another process does.
133
+ */
134
+ export const tryAcquireDaemonLock = async ({ lockPath }) => {
135
+ if (!isPipe(lockPath)) {
136
+ const dir = dirname(lockPath);
137
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
138
+ }
139
+ for (let attempt = 0; attempt < 2; attempt += 1) {
140
+ const server = holderServer();
141
+ try {
142
+ // eslint-disable-next-line no-await-in-loop
143
+ await listen(server, lockPath);
144
+ return held(server, lockPath);
145
+ } catch (error) {
146
+ if (error.code !== 'EADDRINUSE') throw error;
147
+ }
148
+ // eslint-disable-next-line no-await-in-loop
149
+ const found = await probe(lockPath);
150
+ if (found.state === 'held') return { ok: false, holderPid: found.holderPid };
151
+ // Nothing answers: a socket file a killed holder left behind. A pipe is
152
+ // freed by the OS, so on Windows this is only a holder that just exited.
153
+ // Accepted race: two copies that probe the same stale socket within the
154
+ // same few microseconds can both unlink and both bind. POSIX service
155
+ // managers (launchd, systemd) already run one copy, so this needs two
156
+ // hand-started daemons racing a crashed one; Windows pipes can't hit it.
157
+ if (attempt === 0 && !isPipe(lockPath)) {
158
+ try { unlinkSync(lockPath); } catch { /* raced with another reclaim */ }
159
+ }
160
+ }
161
+ return { ok: false, holderPid: null };
162
+ };
163
+
164
+ const pause = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
165
+
166
+ /**
167
+ * Retries for `waitMs`, so the daemon of a restart can take over from the old
168
+ * one that is still exiting. Never makes a request to the server.
169
+ */
170
+ export const acquireDaemonLock = async ({
171
+ lockPath, waitMs = DAEMON_LOCK_WAIT_MS, retryEveryMs = RETRY_EVERY_MS, now = Date.now, sleep = pause,
172
+ }) => {
173
+ const deadline = now() + waitMs;
174
+ for (;;) {
175
+ // eslint-disable-next-line no-await-in-loop
176
+ const result = await tryAcquireDaemonLock({ lockPath });
177
+ if (result.ok || now() >= deadline) return result;
178
+ // eslint-disable-next-line no-await-in-loop
179
+ await sleep(Math.min(retryEveryMs, Math.max(0, deadline - now())));
180
+ }
181
+ };
182
+
183
+ // COMMONLY_DAEMON_LOCK_WAIT_MS shortens the wait (tests); bad values keep the default.
184
+ export const daemonLockWaitMs = (env = process.env) => {
185
+ const value = Number(env.COMMONLY_DAEMON_LOCK_WAIT_MS);
186
+ return Number.isFinite(value) && value >= 0 ? value : DAEMON_LOCK_WAIT_MS;
187
+ };
@@ -16,6 +16,9 @@
16
16
  * - A one-minute repeating trigger with `IgnoreNew` is the watchdog for the
17
17
  * launcher itself: while the task runs it starts nothing, and if the
18
18
  * launcher is killed the next minute brings it back.
19
+ * - Exit 79 means another daemon already holds this machine's lock (F637):
20
+ * the launcher waits 30 s and tries again, so the task stays running and
21
+ * takes over when the holder dies. It never disables the task for it.
19
22
  * - On 77/78 the launcher disables the task before it exits, so the watchdog
20
23
  * does not restart a daemon that has been told to stop. That is launchd's
21
24
  * "park on a successful exit" in Task Scheduler's terms; `daemon start` and
@@ -60,7 +63,8 @@ export const psQuote = (value) => `'${String(value).replace(/['‘’‚‛]/g,
60
63
 
61
64
  export const windowsLauncherScript = ({ nodePath, cliPath, logPath, envFile, taskName = WINDOWS_TASK_NAME }) => `# Commonly daemon launcher. Written by \`commonly daemon install\`; re-run that command instead of editing this file.
62
65
  # It loads the service environment, then keeps \`commonly daemon run\` alive: every exit restarts it after 5 s,
63
- # except 77 (this computer's key was revoked) and 78 (no valid local registration), which disable the task and stop.
66
+ # except 77 (this computer's key was revoked) and 78 (no valid local registration), which disable the task and stop,
67
+ # and 79 (another daemon already runs for this computer), which waits 30 s and tries again.
64
68
  $ErrorActionPreference = 'Continue'
65
69
  $node = ${psQuote(nodePath)}
66
70
  $cli = ${psQuote(cliPath)}
@@ -80,6 +84,7 @@ $env:COMMONLY_DAEMON_LAUNCHER_PID = "$PID"
80
84
  while ($true) {
81
85
  & $node $cli daemon run --foreground 2>&1 | ForEach-Object { "$_" } | Add-Content -LiteralPath $log -Encoding UTF8
82
86
  $code = $LASTEXITCODE
87
+ if ($code -eq 79) { Start-Sleep -Seconds 30; continue }
83
88
  if ($code -eq 77 -or $code -eq 78) {
84
89
  & schtasks.exe /Change /TN $task /DISABLE | Out-Null
85
90
  if ($LASTEXITCODE -eq 0) { exit $code }
@@ -187,15 +192,23 @@ export const installWindowsService = async ({
187
192
 
188
193
  export const LAUNCHER_PID_ENV = 'COMMONLY_DAEMON_LAUNCHER_PID';
189
194
 
190
- const pidAlive = (pid) => {
195
+ // F637: EPERM counts as gone. The real launcher runs as this same user at
196
+ // LeastPrivilege, so this process may always signal it; EPERM means the pid
197
+ // now belongs to another account's (or an elevated) process, i.e. the launcher
198
+ // exited and Windows reused its pid. Read as "alive", that kept an orphaned
199
+ // daemon polling forever.
200
+ export const launcherPidAlive = (pid, kill = process.kill.bind(process)) => {
191
201
  try {
192
- process.kill(pid, 0);
202
+ kill(pid, 0);
193
203
  return true;
194
- } catch (error) {
195
- return error.code === 'EPERM';
204
+ } catch {
205
+ return false;
196
206
  }
197
207
  };
198
208
 
209
+ // A write into the pipe of a launcher that has exited.
210
+ const PIPE_GONE = new Set(['EPIPE', 'ERR_STREAM_DESTROYED']);
211
+
199
212
  /**
200
213
  * `schtasks /End` terminates the launcher only; the node it started would
201
214
  * keep running, unsupervised and invisible to the task (seen on windows-latest,
@@ -207,7 +220,7 @@ const pidAlive = (pid) => {
207
220
  export const watchWindowsLauncher = ({
208
221
  env = process.env,
209
222
  platform = process.platform,
210
- isAlive = pidAlive,
223
+ isAlive = launcherPidAlive,
211
224
  onGone,
212
225
  everyMs = 2000,
213
226
  setIntervalFn = setInterval,
@@ -221,17 +234,31 @@ export const watchWindowsLauncher = ({
221
234
  // error would end the daemon before it stops its seats. So the streams
222
235
  // swallow errors from the moment the watch is armed, not only after the
223
236
  // launcher's exit is noticed up to two seconds later.
224
- for (const stream of streams) stream?.on?.('error', () => {});
237
+ //
238
+ // F637: a dead pipe is itself proof the launcher is gone (the pid check can
239
+ // be fooled by a reused pid), so EPIPE, or a write after the stream was
240
+ // destroyed, stops the daemon through the same onGone, once. Any other
241
+ // stream error is still swallowed.
242
+ let timer = null;
243
+ let gone = false;
244
+ const fire = () => {
245
+ if (gone) return;
246
+ gone = true;
247
+ if (timer !== null) clearIntervalFn(timer);
248
+ onGone(pid);
249
+ };
250
+ for (const stream of streams) {
251
+ stream?.on?.('error', (error) => { if (PIPE_GONE.has(error?.code)) fire(); });
252
+ }
225
253
  // Already gone when armed (the daemon is armed before its first tick): say
226
254
  // so now, rather than after a poll and a heartbeat logged into a dead pipe.
227
255
  if (!isAlive(pid)) {
228
- onGone(pid);
256
+ fire();
229
257
  return () => {};
230
258
  }
231
- const timer = setIntervalFn(() => {
259
+ timer = setIntervalFn(() => {
232
260
  if (isAlive(pid)) return;
233
- clearIntervalFn(timer);
234
- onGone(pid);
261
+ fire();
235
262
  }, everyMs);
236
263
  if (typeof timer?.unref === 'function') timer.unref();
237
264
  return () => clearIntervalFn(timer);
@@ -85,6 +85,12 @@ export const recordKeyFor = (row, loadToken) => {
85
85
  return scoped;
86
86
  };
87
87
 
88
+ // F637: how long a 429 holds both loops off, at the least.
89
+ export const RATE_LIMIT_MIN_WAIT_MS = 60_000;
90
+ // ...and at the most, whatever Retry-After says.
91
+ export const RATE_LIMIT_MAX_WAIT_MS = 10 * 60_000;
92
+ export const RATE_LIMIT_NOTICE = "the server is rate-limiting this computer's daemon key; more than one Commonly daemon may be running on it";
93
+
88
94
  export const createDaemonSupervisor = ({
89
95
  record,
90
96
  client,
@@ -112,6 +118,15 @@ export const createDaemonSupervisor = ({
112
118
  let reconnectAfter = 0;
113
119
  const recentStarts = [];
114
120
 
121
+ // F637: true from a 429 until the next success, so the duplicate-daemon
122
+ // notice is logged once per stretch of rate limiting.
123
+ let rateLimited = false;
124
+ // F637 review: bumped by every failure that sets a wait. A request records
125
+ // it when it starts, and its success clears the wait only if no failure came
126
+ // after that start: a heartbeat in flight when a tick got a 429 must not
127
+ // cut the cooldown short by succeeding (or, below, by failing some other way).
128
+ let failureEpoch = 0;
129
+
115
130
  const connectionFailure = (error, label) => {
116
131
  if (isTerminalAuthError(error)) {
117
132
  stopped = true;
@@ -119,13 +134,34 @@ export const createDaemonSupervisor = ({
119
134
  return;
120
135
  }
121
136
  reconnectFailures += 1;
122
- reconnectAfter = now() + reconnectDelayMs(reconnectFailures, random);
137
+ failureEpoch += 1;
138
+ if (error?.status === 429) {
139
+ // The server's limiter keys on this computer's daemon key. Retrying in
140
+ // a second or two keeps it shut, for every copy sharing the key, so wait
141
+ // at least a minute, or longer if the server asked for longer, but never
142
+ // past 10 minutes: a proxy or self-hosted limiter sending
143
+ // `Retry-After: 86400` must not silence the poll and heartbeat for a day.
144
+ const wait = Math.min(
145
+ Math.max(Number(error.retryAfterMs) || 0, RATE_LIMIT_MIN_WAIT_MS),
146
+ RATE_LIMIT_MAX_WAIT_MS,
147
+ );
148
+ reconnectAfter = Math.max(reconnectAfter, now() + wait);
149
+ if (!rateLimited) {
150
+ rateLimited = true;
151
+ log(RATE_LIMIT_NOTICE);
152
+ }
153
+ } else {
154
+ // Never shorter than a wait already set (a 429's cooldown).
155
+ reconnectAfter = Math.max(reconnectAfter, now() + reconnectDelayMs(reconnectFailures, random));
156
+ }
123
157
  log(`${label}: ${error.message}; reconnect after ${Math.round((reconnectAfter - now()) / 1000)}s`);
124
158
  };
125
159
 
126
- const connectionRestored = () => {
160
+ const connectionRestored = (startedAtEpoch) => {
161
+ if (startedAtEpoch !== failureEpoch) return;
127
162
  reconnectFailures = 0;
128
163
  reconnectAfter = 0;
164
+ rateLimited = false;
129
165
  };
130
166
 
131
167
  const persist = () => {
@@ -503,6 +539,7 @@ export const createDaemonSupervisor = ({
503
539
 
504
540
  const tick = async () => {
505
541
  if (stopped || now() < reconnectAfter) return;
542
+ const startedAtEpoch = failureEpoch;
506
543
  let assigned;
507
544
  try {
508
545
  assigned = await client.get('/api/agent-binding/assigned');
@@ -510,7 +547,7 @@ export const createDaemonSupervisor = ({
510
547
  connectionFailure(error, 'work-list fetch failed');
511
548
  return;
512
549
  }
513
- connectionRestored();
550
+ connectionRestored(startedAtEpoch);
514
551
  const rows = Array.isArray(assigned?.agents) ? assigned.agents : [];
515
552
 
516
553
  const bound = [];
@@ -601,13 +638,18 @@ export const createDaemonSupervisor = ({
601
638
 
602
639
  const heartbeat = async () => {
603
640
  if (stopped || now() < reconnectAfter) return;
641
+ const startedAtEpoch = failureEpoch;
604
642
  try {
643
+ const inventory = await runtimeInventory();
644
+ // F637 review: a 429 (or a stop) can land while the inventory is read;
645
+ // the post must honour it, not go out on the check made before.
646
+ if (stopped || now() < reconnectAfter) return;
605
647
  await client.post(`/api/machines/${record.machineDbId}/heartbeat`, {
606
648
  ...machineReport(),
607
649
  agents: agentStates(),
608
- runtimeInventory: await runtimeInventory(),
650
+ runtimeInventory: inventory,
609
651
  });
610
- connectionRestored();
652
+ connectionRestored(startedAtEpoch);
611
653
  } catch (error) {
612
654
  connectionFailure(error, 'heartbeat failed');
613
655
  }