@agentchatme/agent-core 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,32 +1,36 @@
1
1
  import {
2
- INTEGRATION_ENV,
3
- INTEGRATION_ENV_LEGACY,
4
- INTEGRATION_ENV_LEGACY_REMOVAL,
5
2
  MANUAL,
3
+ acquireAgentLock,
6
4
  acquireLeaderLock,
5
+ agentLockPath,
6
+ agentLockRefusal,
7
7
  beat,
8
+ clearStandby,
8
9
  credentialsPath,
9
10
  describeManualSync,
10
11
  idle,
11
- integrationDisabledBy,
12
12
  isRunnerFactory,
13
+ markStandby,
13
14
  resolveIdentity,
14
- resolveRunBudgetMs,
15
- resolveRunProfile,
15
+ standbyWaiting,
16
16
  textsCachePath,
17
17
  writeIntegrationStatus
18
- } from "./chunk-7LAAAXUO.js";
18
+ } from "./chunk-NAAHIK7Z.js";
19
19
  import {
20
+ INTEGRATION_ENV,
21
+ INTEGRATION_ENV_LEGACY,
22
+ INTEGRATION_ENV_LEGACY_REMOVAL,
20
23
  WINDOWS_SWEEP_TIMEOUT_MS,
24
+ clientIdentityOf,
21
25
  describeWindowsSweep,
26
+ integrationDisabledBy,
27
+ log,
22
28
  redactDiagnostic,
29
+ resolveRunBudgetMs,
30
+ resolveRunProfile,
23
31
  spawnRun,
24
32
  sweepWindowsDescendants
25
- } from "./chunk-AE4XHKHQ.js";
26
- import {
27
- clientIdentityOf,
28
- log
29
- } from "./chunk-QDM4EFI7.js";
33
+ } from "./chunk-AFDD53DD.js";
30
34
 
31
35
  // src/integration/run.ts
32
36
  import * as path2 from "path";
@@ -104,6 +108,7 @@ var HEARTBEAT_MS = 3e4;
104
108
  var STATUS_MS = 3e4;
105
109
  var HTTP_TIMEOUT_MS = 1e4;
106
110
  var RUNNER_DEADLINE_SLACK_MS = 6e4;
111
+ var RUNTIME_RECHECK_MS = 5 * 6e4;
107
112
  var PREFLIGHT_DEADLINE_MS = 6e4;
108
113
  var CYCLE_FAILURE_CHARS = 240;
109
114
  function reasonOf(source, frameReason) {
@@ -231,6 +236,16 @@ var Integration = class {
231
236
  statusTimer = null;
232
237
  socket = "idle";
233
238
  lastError = null;
239
+ /** When the first run that did not get done since the last good one ended; null while runs succeed. */
240
+ failingSince = null;
241
+ /** Runs that did not get done since then. */
242
+ failingRuns = 0;
243
+ /** What the runtime's own check says while runs fail (status `runs_failing`); null when it has not failed one. */
244
+ runsFailing = null;
245
+ lastRecheckAt = 0;
246
+ recheckInFlight = null;
247
+ /** Aborts a runtime check in flight when the integration stops (its probes are killed, not left running). */
248
+ recheckAbort = new AbortController();
234
249
  stopping = false;
235
250
  stopped = null;
236
251
  invites = 0;
@@ -276,7 +291,8 @@ var Integration = class {
276
291
  this.stopping = true;
277
292
  if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
278
293
  if (this.statusTimer) clearInterval(this.statusTimer);
279
- this.stopped = this.loop.stop();
294
+ this.recheckAbort.abort();
295
+ this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve()]).then(() => void 0);
280
296
  this.texts.stop();
281
297
  this.manual?.stop();
282
298
  this.socket = "closed";
@@ -316,6 +332,11 @@ var Integration = class {
316
332
  runtime: this.options.runner.name,
317
333
  handle: this.options.cfg.handle,
318
334
  profile: this.options.profile,
335
+ workdir: this.options.cfg.workdir,
336
+ standby: null,
337
+ runs_failing: this.runsFailing,
338
+ unservable: null,
339
+ ...this.options.statusExtra?.() ?? {},
319
340
  socket: this.stopping ? "closed" : this.socket,
320
341
  wakes: status.coalescer.wakes,
321
342
  wakes_absorbed: status.coalescer.absorbed,
@@ -364,16 +385,19 @@ var Integration = class {
364
385
  const onAbort = () => controller.abort();
365
386
  if (request.signal.aborted) controller.abort();
366
387
  else request.signal.addEventListener("abort", onAbort, { once: true });
388
+ const identityLine = this.texts.current()?.identity_line;
367
389
  let outcome;
368
390
  try {
369
391
  outcome = await withDeadline(
370
392
  this.options.runner.start({
371
393
  kind,
372
394
  wake,
373
- prompt: `${request.prompt}
395
+ // No pointer, no trailing blank lines.
396
+ prompt: this.options.manualPointer.trim().length > 0 ? `${request.prompt}
374
397
 
375
- ${this.options.manualPointer}`,
398
+ ${this.options.manualPointer}` : request.prompt,
376
399
  runId,
400
+ ...identityLine !== void 0 && identityLine.trim().length > 0 ? { identityLine } : {},
377
401
  budgetMs,
378
402
  signal: controller.signal
379
403
  }),
@@ -420,9 +444,71 @@ ${this.options.manualPointer}`,
420
444
  if (outcome.state !== "ok") {
421
445
  log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""} \u2014 the cards stay on the tray; the next wake (or the server's re-wake) finds them`);
422
446
  }
447
+ this.noteRunHealth(outcome, this.lastRun.ended_at);
423
448
  this.writeStatus();
424
449
  return outcome.state === "ok" ? { status: "completed" } : { status: outcome.state === "not_started" ? "not_started" : "failed", ...outcome.detail !== void 0 ? { detail: outcome.detail } : {} };
425
450
  }
451
+ /**
452
+ * A run that did not get done may be the runtime itself (signed out, the
453
+ * binary gone, a flag an upgrade dropped): checked again, at most once per
454
+ * `RUNTIME_RECHECK_MS`, and said in status until a run succeeds. Wakes keep
455
+ * starting runs meanwhile — each is the quickest way back — and are counted.
456
+ */
457
+ noteRunHealth(outcome, endedAt) {
458
+ if (outcome.state === "ok") {
459
+ if (this.runsFailing !== null) log.info(`runs work again (${this.failingRuns} run(s) missed since ${this.failingSince})`);
460
+ this.failingSince = null;
461
+ this.failingRuns = 0;
462
+ this.runsFailing = null;
463
+ this.lastRecheckAt = 0;
464
+ return;
465
+ }
466
+ this.failingSince ??= endedAt;
467
+ this.failingRuns += 1;
468
+ if (this.runsFailing !== null) this.runsFailing = { ...this.runsFailing, runs_missed: this.failingRuns };
469
+ const recheckMs = this.options.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
470
+ if (this.recheckInFlight === null && !this.stopping && (this.lastRecheckAt === 0 || Date.now() - this.lastRecheckAt >= recheckMs)) {
471
+ this.recheckInFlight = this.recheckRuntime().finally(() => {
472
+ this.recheckInFlight = null;
473
+ });
474
+ }
475
+ }
476
+ async recheckRuntime() {
477
+ this.lastRecheckAt = Date.now();
478
+ const pre = await withDeadline(this.options.runner.preflight({ signal: this.recheckAbort.signal }), PREFLIGHT_DEADLINE_MS, () => ({
479
+ ok: false,
480
+ detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
481
+ })).catch((err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` }));
482
+ if (this.failingSince === null || this.stopping) return;
483
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
484
+ if (!pre.ok) {
485
+ const reason = `${this.options.runner.name}: ${pre.detail ?? "its check failed"}`;
486
+ if (this.runsFailing?.reason !== reason) log.warn(`runs failing \u2014 ${reason} (since ${this.failingSince}, ${this.failingRuns} run(s) missed); status says so until a run succeeds`);
487
+ this.runsFailing = { reason, since: this.failingSince, runs_missed: this.failingRuns, checked_at: checkedAt };
488
+ } else if (this.runsFailing !== null) {
489
+ this.runsFailing = {
490
+ ...this.runsFailing,
491
+ reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ""}`,
492
+ checked_at: checkedAt
493
+ };
494
+ }
495
+ this.writeStatus();
496
+ }
497
+ /**
498
+ * Whether this integration can serve its agent: not while the server refuses
499
+ * its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor
500
+ * while runs fail for a runtime reason (`runs_failing`). The supervisor then
501
+ * gives the agent up so a healthy listener for it can serve.
502
+ */
503
+ health() {
504
+ if (this.socket === "blocked") return { ok: false, reason: `the server refuses this home's key${this.lastError ? ` (${this.lastError})` : ""}`, runsFailing: null };
505
+ if (this.runsFailing !== null) return { ok: false, reason: `runs failing: ${this.runsFailing.reason}`, runsFailing: this.runsFailing };
506
+ return { ok: true };
507
+ }
508
+ /** Test seam: resolves when a runtime check started by a failed run has finished. */
509
+ async runtimeCheckDone() {
510
+ await this.recheckInFlight;
511
+ }
426
512
  onEvent(event) {
427
513
  switch (event.type) {
428
514
  case "wake": {
@@ -467,10 +553,24 @@ ${this.options.manualPointer}`,
467
553
  var POLL_MS = 5e3;
468
554
  var TICK_MS = 250;
469
555
  var MAX_BACKOFF_MS = 5 * 6e4;
556
+ var STANDBY_POLL_MS = 3e4;
557
+ var UNSERVABLE_RECHECK_MS = 6e4;
558
+ var BLOCKED_RETRY_MS = 5 * 6e4;
470
559
  var SHUTDOWN_GRACE_MS = 1e4;
471
560
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
472
561
  var KEEP_LOG_BYTES = 1024 * 1024;
473
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
562
+ function sleepUnless(ms, signal) {
563
+ if (signal?.aborted === true) return Promise.resolve();
564
+ return new Promise((resolve3) => {
565
+ const done = () => {
566
+ clearTimeout(timer);
567
+ signal?.removeEventListener("abort", done);
568
+ resolve3();
569
+ };
570
+ const timer = setTimeout(done, ms);
571
+ signal?.addEventListener("abort", done, { once: true });
572
+ });
573
+ }
474
574
  function fingerprint(home, envKey) {
475
575
  const id = resolveIdentity(home, { envKey });
476
576
  return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
@@ -495,6 +595,8 @@ ${keep.toString("utf-8")}`
495
595
  } catch {
496
596
  }
497
597
  }
598
+ var StandbyError = class extends Error {
599
+ };
498
600
  async function runIntegration(opts) {
499
601
  const home = path2.resolve(opts.home);
500
602
  const workdir = path2.resolve(opts.workdir);
@@ -503,8 +605,21 @@ async function runIntegration(opts) {
503
605
  const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
504
606
  boundDaemonLog(home);
505
607
  if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
506
- const lock = acquireLeaderLock(home);
608
+ let nudged = false;
609
+ const stopChecks = new AbortController();
610
+ if (opts.signal?.aborted === true) stopChecks.abort();
611
+ else opts.signal?.addEventListener("abort", () => stopChecks.abort(), { once: true });
612
+ const lock = await acquireLeaderLock(home, { ...opts.lease ?? {}, signal: stopChecks.signal });
507
613
  if (lock === null) return 1;
614
+ let homeLost = null;
615
+ let starting = null;
616
+ lock.onLost((why) => {
617
+ homeLost = why;
618
+ nudged = true;
619
+ starting?.stop();
620
+ live?.stop();
621
+ log.error(`lost this home's daemon lock (${why}) \u2014 another daemon serves ${home} now; this one exits`);
622
+ });
508
623
  const envKey = opts.credentialsFromHomeOnly !== true;
509
624
  const identityOf = () => resolveIdentity(home, { envKey });
510
625
  const disabledBy = integrationDisabledBy(env);
@@ -515,6 +630,37 @@ async function runIntegration(opts) {
515
630
  let failures = 0;
516
631
  let lastFailure = null;
517
632
  let shuttingDown = false;
633
+ let agentLock = null;
634
+ let agentLost = null;
635
+ let standby = null;
636
+ let unservable = null;
637
+ let lastRunner = null;
638
+ let cachedCfg = null;
639
+ let agentLockFile = null;
640
+ let prepared = null;
641
+ let standbyCheck = null;
642
+ const runnerFor = (cfg, fp) => {
643
+ if (prepared === null || prepared.fp !== fp) prepared = { fp, runner: isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner };
644
+ return prepared.runner;
645
+ };
646
+ const preflightOf = async (runner) => {
647
+ const deadlineMs = opts.preflightDeadlineMs ?? PREFLIGHT_DEADLINE_MS;
648
+ return withDeadline(runner.preflight({ signal: stopChecks.signal }), deadlineMs, () => ({ ok: false, detail: `preflight did not answer within ${Math.round(deadlineMs / 1e3)} s` })).catch(
649
+ (err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` })
650
+ );
651
+ };
652
+ const releaseAgent = () => {
653
+ agentLock?.release();
654
+ agentLock = null;
655
+ agentLost = null;
656
+ };
657
+ const stopWaiting = () => {
658
+ if (agentLockFile !== null) clearStandby(agentLockFile, home);
659
+ };
660
+ const leaseErrors = () => {
661
+ const count = lock.renewErrors + (agentLock?.renewErrors ?? 0);
662
+ return count === 0 ? null : { count, last: agentLock?.lastRenewError ?? lock.lastRenewError };
663
+ };
518
664
  const offStatus = (handle) => writeIntegrationStatus(home, {
519
665
  version: 2,
520
666
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -522,6 +668,7 @@ async function runIntegration(opts) {
522
668
  runtime: opts.runner.name,
523
669
  handle,
524
670
  profile,
671
+ workdir,
525
672
  socket: disabled ? "off" : "idle",
526
673
  wakes: 0,
527
674
  wakes_absorbed: 0,
@@ -536,7 +683,11 @@ async function runIntegration(opts) {
536
683
  retry_rung: 0,
537
684
  retry_due_at: null,
538
685
  last_error: lastFailure,
539
- texts: null
686
+ texts: null,
687
+ standby,
688
+ runs_failing: unservable?.runsFailing ?? null,
689
+ unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },
690
+ lease_errors: leaseErrors()
540
691
  });
541
692
  const disconnect = (why) => {
542
693
  if (live === null) return;
@@ -544,18 +695,19 @@ async function runIntegration(opts) {
544
695
  live.stop();
545
696
  live = null;
546
697
  liveFingerprint = null;
698
+ releaseAgent();
547
699
  idle(home);
548
700
  };
549
701
  const shutdown = (sig) => {
550
702
  if (shuttingDown) return;
551
703
  shuttingDown = true;
704
+ stopChecks.abort();
552
705
  log.info(`${sig} \u2014 shutting down`);
553
706
  };
554
707
  const onSigint = () => shutdown("SIGINT");
555
708
  const onSigterm = () => shutdown("SIGTERM");
556
709
  process.on("SIGINT", onSigint);
557
710
  process.on("SIGTERM", onSigterm);
558
- let nudged = false;
559
711
  try {
560
712
  fs.mkdirSync(home, { recursive: true });
561
713
  const watcher = fs.watch(home, (_event, filename) => {
@@ -584,19 +736,98 @@ async function runIntegration(opts) {
584
736
  if (shuttingDown || opts.signal?.aborted) break;
585
737
  const fp = fingerprint(home, envKey);
586
738
  const identityChanged = fp !== observedFingerprint;
739
+ if (homeLost !== null) break;
587
740
  if (identityChanged) {
588
741
  disconnect(fp === null ? "signed out" : "identity changed");
589
742
  observedFingerprint = fp;
590
743
  failures = 0;
591
744
  lastFailure = null;
745
+ stopWaiting();
746
+ standby = null;
747
+ unservable = null;
748
+ cachedCfg = null;
749
+ agentLockFile = null;
592
750
  if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null);
593
751
  }
594
752
  if (fp === null) {
595
753
  } else if (disabled) {
596
- } else if (fp !== liveFingerprint) {
754
+ } else if (live !== null && fp === liveFingerprint) {
755
+ const health = live.health();
756
+ if (agentLost !== null) {
757
+ const why = agentLost;
758
+ disconnect(`the agent lock is no longer this home's (${why})`);
759
+ lastFailure = `@${cachedCfg?.cfg.handle ?? "?"}: ${why}; another listener serves this agent now`;
760
+ } else if (!health.ok) {
761
+ const handle = cachedCfg?.cfg.handle ?? "?";
762
+ const kind = health.runsFailing === null ? "key_refused" : "runs_failing";
763
+ if (kind === "key_refused" || agentLockFile !== null && standbyWaiting(agentLockFile, home)) {
764
+ const retryMs = opts.unservableRecheckMs ?? (kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS);
765
+ unservable = { kind, detail: health.reason, since: (/* @__PURE__ */ new Date()).toISOString(), retryAt: Date.now() + retryMs, runsFailing: health.runsFailing };
766
+ disconnect(`this home cannot serve @${handle} (${health.reason}): giving it up to ${kind === "key_refused" ? "any healthy listener" : "the healthy listener waiting for it"}`);
767
+ lastFailure = `this home cannot serve @${handle}: ${health.reason}. It holds no socket and starts no run while another listener can serve @${handle}; it looks again every ${Math.round(retryMs / 1e3)} s${kind === "runs_failing" ? " (the runtime checked first: a check that passes clears this)" : " (signing in again here clears this at once)"}, and takes @${handle} back whenever no other listener holds it.`;
768
+ log.warn(lastFailure);
769
+ offStatus(handle);
770
+ }
771
+ }
772
+ } else if (live === null) {
597
773
  try {
598
- const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey });
599
- const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner;
774
+ if (unservable !== null && Date.now() < unservable.retryAt) throw new StandbyError(unservable.detail);
775
+ const waiting = unservable;
776
+ if (waiting !== null && waiting.kind === "runs_failing" && lastRunner !== null) {
777
+ const before = waiting;
778
+ const checker = lastRunner;
779
+ const pre = await preflightOf(checker);
780
+ standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${checker.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
781
+ if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
782
+ if (pre.ok) unservable = null;
783
+ else unservable = { ...before, detail: `runs failing: ${checker.name}: ${pre.detail ?? "its check failed"}`, retryAt: Date.now() + (opts.unservableRecheckMs ?? UNSERVABLE_RECHECK_MS) };
784
+ }
785
+ if (cachedCfg === null || cachedCfg.fp !== fp) cachedCfg = { fp, cfg: await resolveDaemonConfig({ home, workdir, client: opts.client, envKey }) };
786
+ const cfg = cachedCfg.cfg;
787
+ agentLockFile = agentLockPath({ apiBase: cfg.apiBase, handle: cfg.handle });
788
+ const attempt = await acquireAgentLock({ apiBase: cfg.apiBase, handle: cfg.handle, home }, process.env, { ...opts.lease ?? {}, signal: stopChecks.signal });
789
+ if (shuttingDown || opts.signal?.aborted) {
790
+ if (attempt.ok) attempt.lease.release();
791
+ throw new StandbyError("stopping");
792
+ }
793
+ if (!attempt.ok) {
794
+ const current = unservable;
795
+ if (current !== null) {
796
+ unservable = { ...current, retryAt: Date.now() + (opts.unservableRecheckMs ?? (current.kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS)) };
797
+ throw new StandbyError(current.detail);
798
+ }
799
+ standby = { home: attempt.holder?.home ?? null, pid: attempt.holder?.pid ?? null, since: attempt.holder?.acquired_at ?? null };
800
+ const recheckMs = opts.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
801
+ if (standbyCheck === null || standbyCheck.fp !== fp || Date.now() - standbyCheck.at >= recheckMs) {
802
+ const runner2 = runnerFor(cfg, fp);
803
+ const pre = await preflightOf(runner2);
804
+ if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
805
+ standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${runner2.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
806
+ }
807
+ if (standbyCheck.ok) markStandby(attempt.path, home);
808
+ else clearStandby(attempt.path, home);
809
+ const refusal = agentLockRefusal({ handle: cfg.handle, home }, attempt.holder, attempt.path);
810
+ const msg = standbyCheck.ok ? refusal : `${refusal} Its own runtime does not check out (${standbyCheck.detail ?? "its check failed"}), so it does not offer to take over from a holder whose runs fail.`;
811
+ if (msg !== lastFailure) log.warn(msg);
812
+ lastFailure = msg;
813
+ throw new StandbyError(msg);
814
+ }
815
+ stopWaiting();
816
+ if (standby !== null) log.info(`@${cfg.handle}: the other listener stopped; this one serves the agent now`);
817
+ if (unservable !== null) log.info(`@${cfg.handle}: no other listener holds the agent; this home serves it again (${unservable.detail})`);
818
+ standby = null;
819
+ unservable = null;
820
+ const lease = attempt.lease;
821
+ agentLock = lease;
822
+ lease.onLost((why) => {
823
+ if (agentLock !== lease) return;
824
+ agentLost = why;
825
+ nudged = true;
826
+ starting?.stop();
827
+ live?.stop();
828
+ });
829
+ const runner = runnerFor(cfg, fp);
830
+ lastRunner = runner;
600
831
  const candidate = new Integration({
601
832
  cfg,
602
833
  runner,
@@ -605,31 +836,51 @@ async function runIntegration(opts) {
605
836
  ...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
606
837
  profile,
607
838
  budgetMs,
608
- ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}
839
+ ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {},
840
+ ...opts.runtimeRecheckMs !== void 0 ? { runtimeRecheckMs: opts.runtimeRecheckMs } : {},
841
+ ...opts.quietMs !== void 0 ? { quietMs: opts.quietMs } : {},
842
+ ...opts.maxMs !== void 0 ? { maxMs: opts.maxMs } : {},
843
+ ...opts.paceMs !== void 0 ? { paceMs: opts.paceMs } : {},
844
+ statusExtra: () => ({ lease_errors: leaseErrors() })
609
845
  });
610
- await candidate.start();
846
+ starting = candidate;
847
+ try {
848
+ await candidate.start();
849
+ } finally {
850
+ starting = null;
851
+ }
852
+ if (agentLost !== null || homeLost !== null) {
853
+ candidate.stop();
854
+ throw new StandbyError(`the agent lock is no longer this home's (${agentLost ?? homeLost})`);
855
+ }
611
856
  live = candidate;
612
857
  liveFingerprint = fp;
613
858
  failures = 0;
614
859
  lastFailure = null;
615
860
  } catch (err) {
616
- const msg = String(err instanceof Error ? err.message : err);
617
- if (msg !== lastFailure) {
618
- log.warn(`not connecting yet: ${msg}`);
619
- lastFailure = msg;
620
- offStatus(identityOf()?.handle ?? null);
621
- }
622
- failures += 1;
861
+ releaseAgent();
623
862
  live = null;
624
863
  liveFingerprint = null;
864
+ if (err instanceof StandbyError) {
865
+ offStatus(cachedCfg?.cfg.handle ?? identityOf()?.handle ?? null);
866
+ } else {
867
+ const msg = String(err instanceof Error ? err.message : err);
868
+ if (msg !== lastFailure) {
869
+ log.warn(`not connecting yet: ${msg}`);
870
+ lastFailure = msg;
871
+ offStatus(identityOf()?.handle ?? null);
872
+ }
873
+ failures += 1;
874
+ }
625
875
  idle(home);
626
876
  }
627
877
  }
628
- const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
878
+ const pollMs = opts.pollMs ?? POLL_MS;
879
+ const waitMs = homeLost !== null || agentLost !== null ? 0 : standby !== null || unservable !== null ? opts.standbyPollMs ?? STANDBY_POLL_MS : failures === 0 ? pollMs : Math.min(pollMs * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
629
880
  nudged = false;
630
881
  const deadline = Date.now() + waitMs;
631
882
  while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {
632
- await sleep(TICK_MS);
883
+ await sleepUnless(opts.tickMs ?? TICK_MS, opts.signal);
633
884
  }
634
885
  }
635
886
  process.off("SIGINT", onSigint);
@@ -639,8 +890,11 @@ async function runIntegration(opts) {
639
890
  if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1e3)}s of being interrupted \u2014 exiting anyway`);
640
891
  live = null;
641
892
  }
893
+ releaseAgent();
894
+ stopWaiting();
642
895
  idle(home);
643
896
  lock.release();
897
+ if (homeLost !== null) return 1;
644
898
  if (shuttingDown) {
645
899
  log.info("shutdown complete");
646
900
  (opts.exit ?? process.exit)(0);