@moondeck/station 1.0.4 → 1.0.6

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.
@@ -0,0 +1,246 @@
1
+ /**
2
+ * The Station's view of its task scripts' dependencies (owner ask 4,
3
+ * 2026-11-09): check-deps.sh reports what _common.sh would refuse over, and
4
+ * the Station advertises it as `agentDependencies`, so a host missing
5
+ * sqlite3 or the Compose plugin says so on its page instead of failing one
6
+ * task script at a time.
7
+ *
8
+ * Report-only. Nothing here gates a task: every --aws-host Station launched
9
+ * by an installer before 2026-11 lacks both, and runs machine tasks fine.
10
+ *
11
+ * The check follows the runtime the Station pinned, exactly as the task
12
+ * scripts do: Docker needs the docker CLI and the Compose plugin; the Apple
13
+ * runtime needs neither. Until a runtime is pinned (or in sidecar mode,
14
+ * where no task script runs) there is nothing to report.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { readFileSync } from "node:fs";
18
+
19
+ import {
20
+ AGENT_DEPENDENCY_NAME,
21
+ MAX_AGENT_DEPENDENCIES,
22
+ MAX_AGENT_DEPENDENCY_FIX_CHARS,
23
+ type AgentDependencyCapability,
24
+ } from "../src/protocol";
25
+ import { agentScriptPath } from "./agent";
26
+
27
+ export type AgentDependencyRuntime = "docker" | "apple-container";
28
+
29
+ /** How often the Station re-runs the check, so installing a package clears
30
+ * the state without a restart. */
31
+ export const AGENT_DEPENDENCY_RECHECK_MS = 5 * 60_000;
32
+ const CHECK_TIMEOUT_MS = 15_000;
33
+ const MAX_CHECK_OUTPUT_BYTES = 16 * 1024;
34
+
35
+ /** The `missing` list from check-deps.sh's stdout; throws on anything else. */
36
+ export function parseCheckDepsOutput(stdout: string): string[] {
37
+ const line = stdout.trim().split("\n").pop() ?? "";
38
+ let parsed: unknown;
39
+ try {
40
+ parsed = JSON.parse(line);
41
+ } catch {
42
+ throw new Error("check-deps.sh printed no JSON");
43
+ }
44
+ const missing = (parsed as { ok?: unknown; data?: { missing?: unknown } } | null)?.data?.missing;
45
+ if (
46
+ (parsed as { ok?: unknown } | null)?.ok !== true ||
47
+ !Array.isArray(missing) ||
48
+ missing.length > MAX_AGENT_DEPENDENCIES ||
49
+ !missing.every((name) => typeof name === "string" && AGENT_DEPENDENCY_NAME.test(name)) ||
50
+ new Set(missing).size !== missing.length
51
+ ) {
52
+ throw new Error("check-deps.sh printed an unexpected result");
53
+ }
54
+ return [...missing] as string[];
55
+ }
56
+
57
+ /** The environment the task scripts get for this runtime: the Station
58
+ * publishes UAI_TASK_RUNTIME=apple-container for Apple and clears it for
59
+ * Docker (lib/container-runtime.ts). */
60
+ export function checkDepsEnv(
61
+ runtime: AgentDependencyRuntime,
62
+ base: NodeJS.ProcessEnv = process.env,
63
+ ): NodeJS.ProcessEnv {
64
+ const next: NodeJS.ProcessEnv = { ...base };
65
+ if (runtime === "apple-container") next.UAI_TASK_RUNTIME = "apple-container";
66
+ else delete next.UAI_TASK_RUNTIME;
67
+ return next;
68
+ }
69
+
70
+ /** Runs this generation's check-deps.sh; resolves the missing list. */
71
+ export function runCheckDeps(
72
+ runtime: AgentDependencyRuntime,
73
+ options: { scriptPath?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number } = {},
74
+ ): Promise<string[]> {
75
+ const scriptPath = options.scriptPath ?? agentScriptPath("check-deps.sh");
76
+ return new Promise((resolve, reject) => {
77
+ const child = spawn(scriptPath, [], {
78
+ stdio: ["ignore", "pipe", "pipe"],
79
+ env: checkDepsEnv(runtime, options.env),
80
+ });
81
+ let stdout = "";
82
+ let stderr = "";
83
+ let settled = false;
84
+ const finish = (error: Error | null, missing?: string[]): void => {
85
+ if (settled) return;
86
+ settled = true;
87
+ clearTimeout(timer);
88
+ if (error) reject(error);
89
+ else resolve(missing ?? []);
90
+ };
91
+ const timer = setTimeout(() => {
92
+ child.kill("SIGKILL");
93
+ finish(new Error("check-deps.sh timed out"));
94
+ }, options.timeoutMs ?? CHECK_TIMEOUT_MS);
95
+ timer.unref?.();
96
+ child.stdout.on("data", (chunk: Buffer) => {
97
+ if (stdout.length < MAX_CHECK_OUTPUT_BYTES) stdout += chunk.toString("utf8");
98
+ });
99
+ child.stderr.on("data", (chunk: Buffer) => {
100
+ if (stderr.length < MAX_CHECK_OUTPUT_BYTES) stderr += chunk.toString("utf8");
101
+ });
102
+ child.on("error", (error) => finish(error));
103
+ child.on("close", (code) => {
104
+ if (code !== 0) {
105
+ finish(new Error(`check-deps.sh exited ${String(code)}${stderr.trim() ? `: ${stderr.trim().slice(-300)}` : ""}`));
106
+ return;
107
+ }
108
+ try {
109
+ finish(null, parseCheckDepsOutput(stdout));
110
+ } catch (error) {
111
+ finish(error instanceof Error ? error : new Error(String(error)));
112
+ }
113
+ });
114
+ });
115
+ }
116
+
117
+ /** The package each missing binary comes from, per OS the Station can name. */
118
+ const AL2023_PACKAGES: Readonly<Record<string, string>> = {
119
+ sqlite3: "sqlite",
120
+ jq: "jq",
121
+ git: "git",
122
+ docker: "docker",
123
+ };
124
+ const HOMEBREW_PACKAGES: Readonly<Record<string, string>> = {
125
+ sqlite3: "sqlite",
126
+ jq: "jq",
127
+ git: "git",
128
+ };
129
+
130
+ export interface HostOs {
131
+ platform: NodeJS.Platform;
132
+ /** /etc/os-release ID, when Linux. */
133
+ osReleaseId?: string;
134
+ }
135
+
136
+ export function currentHostOs(): HostOs {
137
+ if (process.platform !== "linux") return { platform: process.platform };
138
+ try {
139
+ const release = readFileSync("/etc/os-release", "utf8");
140
+ const id = /^ID="?([A-Za-z0-9._-]+)"?$/m.exec(release)?.[1];
141
+ return id ? { platform: "linux", osReleaseId: id } : { platform: "linux" };
142
+ } catch {
143
+ return { platform: "linux" };
144
+ }
145
+ }
146
+
147
+ /** A copyable install command for the packaged ones, when this OS has one.
148
+ * The Compose plugin is never in it: AL2023 does not package it. */
149
+ export function agentDependencyFix(missing: readonly string[], os: HostOs): string | undefined {
150
+ const [table, command] =
151
+ os.platform === "linux" && os.osReleaseId === "amzn"
152
+ ? [AL2023_PACKAGES, "sudo dnf install -y"]
153
+ : os.platform === "darwin"
154
+ ? [HOMEBREW_PACKAGES, "brew install"]
155
+ : [null, ""];
156
+ if (table === null) return undefined;
157
+ const packages = missing.flatMap((name) => (table[name] === undefined ? [] : [table[name]]));
158
+ if (packages.length === 0) return undefined;
159
+ const fix = `${command} ${[...new Set(packages)].join(" ")}`;
160
+ return fix.length <= MAX_AGENT_DEPENDENCY_FIX_CHARS ? fix : undefined;
161
+ }
162
+
163
+ export interface AgentDependencyMonitorDeps {
164
+ check(runtime: AgentDependencyRuntime): Promise<string[]>;
165
+ fix(missing: readonly string[]): string | undefined;
166
+ /** The advertised state changed: re-send capabilities. */
167
+ changed(): void;
168
+ warn?(message: string): void;
169
+ }
170
+
171
+ /**
172
+ * The last check's result, kept current. One check at a time; a request
173
+ * while one runs schedules exactly one more with the newest runtime. A
174
+ * check that cannot run reports nothing (absent), never "ok".
175
+ */
176
+ export class AgentDependencyMonitor {
177
+ #state: AgentDependencyCapability | undefined;
178
+ #running: Promise<void> | null = null;
179
+ #next: { runtime: AgentDependencyRuntime | null } | null = null;
180
+ readonly #deps: AgentDependencyMonitorDeps;
181
+
182
+ constructor(deps: AgentDependencyMonitorDeps) {
183
+ this.#deps = deps;
184
+ }
185
+
186
+ state(): AgentDependencyCapability | undefined {
187
+ return this.#state;
188
+ }
189
+
190
+ /** Re-run the check for `runtime` (null: none pinned, so nothing to report). */
191
+ recheck(runtime: AgentDependencyRuntime | null): Promise<void> {
192
+ this.#next = { runtime };
193
+ if (this.#running === null) {
194
+ this.#running = this.#drain().finally(() => {
195
+ this.#running = null;
196
+ });
197
+ }
198
+ return this.#running;
199
+ }
200
+
201
+ async #drain(): Promise<void> {
202
+ while (this.#next !== null) {
203
+ const { runtime } = this.#next;
204
+ this.#next = null;
205
+ let next: AgentDependencyCapability | undefined;
206
+ if (runtime === null) {
207
+ next = undefined;
208
+ } else {
209
+ try {
210
+ const missing = await this.#deps.check(runtime);
211
+ if (missing.length === 0) {
212
+ next = { status: "ok" };
213
+ } else {
214
+ const fix = this.#deps.fix(missing);
215
+ next = fix === undefined ? { status: "missing", missing } : { status: "missing", missing, fix };
216
+ }
217
+ } catch (error) {
218
+ this.#deps.warn?.(
219
+ `[agent-deps] dependency check failed: ${error instanceof Error ? error.message : String(error)}`,
220
+ );
221
+ next = undefined;
222
+ }
223
+ }
224
+ if (JSON.stringify(next) !== JSON.stringify(this.#state)) {
225
+ this.#state = next;
226
+ if (next?.status === "missing") {
227
+ this.#deps.warn?.(`[agent-deps] task scripts are missing on PATH: ${next.missing.join(", ")}`);
228
+ }
229
+ this.#deps.changed();
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ let recheckRequester: (() => void) | null = null;
236
+
237
+ /** main.ts binds the live monitor; tests and other entry points leave it unbound. */
238
+ export function setAgentDependencyRecheckRequester(requester: (() => void) | null): void {
239
+ recheckRequester = requester;
240
+ }
241
+
242
+ /** A task script just refused over a missing dependency: re-check now, so
243
+ * the host page shows it without waiting for the timer. */
244
+ export function requestAgentDependencyRecheck(): void {
245
+ recheckRequester?.();
246
+ }
package/lib/agent.ts CHANGED
@@ -119,6 +119,11 @@ function agentDir(): string {
119
119
  return env.agentDir ?? packageAgentScriptsDir();
120
120
  }
121
121
 
122
+ /** Absolute path of one of this generation's agent scripts. */
123
+ export function agentScriptPath(scriptName: string): string {
124
+ return resolve(agentDir(), scriptName);
125
+ }
126
+
122
127
  // ---------------------------------------------------------------------------
123
128
  // Result schemas. Each command shares the success envelope and produces a
124
129
  // command-specific `data` payload.
@@ -145,6 +150,9 @@ const TaskUpData = z.object({
145
150
  worktreePath: z.string(),
146
151
  codeServerPort: z.number().int().positive().optional(),
147
152
  previewPorts: PreviewPortRuntimesSchema.optional(),
153
+ /** F6: the task's machine had been terminated, and this start launched a
154
+ * fresh one; work only on the old machine is gone. A feed system note. */
155
+ environmentReplaced: z.literal(true).optional(),
148
156
  /** Degraded start: uai-init failed twice; surfaced as a feed system note. */
149
157
  initWarning: z.string().optional(),
150
158
  /** ADR-153: whether this start put the secrets proxy's CA, and its pins,
@@ -266,7 +274,7 @@ async function runAgent<T extends z.ZodTypeAny>(
266
274
  * (ADR-154: a start on cloud credentials gets none of the runner's). */
267
275
  withoutRunnerEnv: ReadonlySet<string> = new Set(),
268
276
  ): Promise<z.infer<T>> {
269
- const scriptPath = resolve(agentDir(), scriptName);
277
+ const scriptPath = agentScriptPath(scriptName);
270
278
  const runnerEnv = Object.fromEntries(
271
279
  Object.entries(process.env).filter(([name]) => !withoutRunnerEnv.has(name)),
272
280
  );
@@ -25,7 +25,8 @@
25
25
  */
26
26
 
27
27
  import type { CloudCredentialRuntime } from "./cloud-credential-runtime";
28
- import { readTaskRunEpochState, runningTaskRuns } from "./runtime-state";
28
+ import { getHostTask, readTaskRunEpochState, runningTaskRuns } from "./runtime-state";
29
+ import { isTerminal } from "./task-status";
29
30
 
30
31
  export type CredentialsMode = "legacy" | "pending" | "active";
31
32
 
@@ -281,14 +282,40 @@ let markRecovered!: () => void;
281
282
  let recoveredSignal = new Promise<void>((resolve) => (markRecovered = resolve));
282
283
  let recovered = false;
283
284
 
285
+ /**
286
+ * A task with no run left on this runner, whose failed boot cleanup is its
287
+ * own (`recoverAll`):
288
+ * - its row terminal (`finished`, `canceled`, `killed`, `shipped`): the
289
+ * cloud moves no terminal task back to `starting` (Resume takes only
290
+ * `stopped`/`error`, Start only `draft`, a wake only `stopped`);
291
+ * - or no row (orphan GC purges it even while credentials are pending) and
292
+ * no open assignment.
293
+ * Neither is reattached (recovery walks active rows only) or resumed
294
+ * (`runningTaskRuns`), and any later start of it is fenced: the registry
295
+ * runs its full cleanup before its gate may open (`owesCleanup`). Anything
296
+ * else, an unreadable or unknown status included, may still run and is
297
+ * not: its surviving agents would be reattached before its paths were
298
+ * proven gone.
299
+ */
300
+ export function taskHasNoRunLeft(taskId: string): boolean {
301
+ const task = getHostTask(taskId);
302
+ if (task !== null) {
303
+ return typeof task.statusMirror === "string" && isTerminal(task.statusMirror);
304
+ }
305
+ return readTaskRunEpochState(taskId)?.assignmentOpen !== true;
306
+ }
307
+
284
308
  /**
285
309
  * ADR-154 boot recovery (§5, §6): the composer's sweep of every task with
286
310
  * cleanup left from the last process, before any surviving agent is
287
311
  * reattached or any grant asked for. Once per process: after it succeeds,
288
312
  * a call does nothing, so a later runtime re-activation never sweeps the
289
313
  * credentials of tasks running now; concurrent calls share one sweep.
290
- * Rejects, every task attempted, when any could not be cleaned up: the
291
- * runner stays `pending`, and a later call tries again.
314
+ * Rejects, every task attempted, when a task that may still run could not
315
+ * be cleaned up: the runner stays `pending`, and a later call tries again.
316
+ * One with no run left (`taskHasNoRunLeft`) fails alone, kept for the next
317
+ * process's sweep and for any later start's fence (2026-11-09: a finished
318
+ * task's rows held the runner in `checking` for good).
292
319
  */
293
320
  export function recoverCloudCredentials(): Promise<void> {
294
321
  if (recovered) return Promise.resolve();
@@ -296,7 +323,7 @@ export function recoverCloudCredentials(): Promise<void> {
296
323
  const composer = runtime;
297
324
  if (composer === null) return Promise.reject(new Error("the station has no cloud credentials composer"));
298
325
  const sweep = composer
299
- .recover((taskId) => readTaskRunEpochState(taskId)?.highestRunEpoch ?? 0)
326
+ .recover((taskId) => readTaskRunEpochState(taskId)?.highestRunEpoch ?? 0, taskHasNoRunLeft)
300
327
  .then(() => {
301
328
  recovered = true;
302
329
  markRecovered();
@@ -240,6 +240,14 @@ export type CredentialSessionReaderFactory = (args: {
240
240
 
241
241
  export interface TaskCredentialLeaseRegistryOptions {
242
242
  runnerKind: "owned" | "task-machine";
243
+ /**
244
+ * The startup fence: whether the boot sweep isolated the task's failed
245
+ * cleanup and it still has durable cleanup left. A start of it with no
246
+ * predecessor here then runs the full cleanup first, as a recovered start
247
+ * does, and its gate stays closed unless that cleanup succeeds. A throw
248
+ * counts as owed. Absent: nothing is owed.
249
+ */
250
+ owesCleanup?(taskId: string): boolean;
243
251
  send(frame: LeaseRequestV1Frame | CredentialRefreshFrame): boolean;
244
252
  /**
245
253
  * Must synchronously stop new consumers/spawns for this assignment.
@@ -862,20 +870,32 @@ export class TaskCredentialLeaseRegistry {
862
870
  this.#endSynchronously(current, "superseded");
863
871
  }
864
872
 
865
- const needsStartupCleanup = Boolean(current || options.recovery);
873
+ // A predecessor's own startup and full cleanup cover every run through
874
+ // its epoch. With none here, a boot sweep's isolated failure (2026-11-09
875
+ // review) fences the start like a recovery: no gate opens over its
876
+ // credential paths not yet proven gone.
877
+ let recovery = options.recovery === true;
878
+ if (!current && !recovery && this.#opts.owesCleanup) {
879
+ try {
880
+ recovery = this.#opts.owesCleanup(assignment.taskId);
881
+ } catch {
882
+ recovery = true;
883
+ }
884
+ }
885
+ const needsStartupCleanup = Boolean(current || recovery);
866
886
  const state = this.#newState(
867
887
  assignment,
868
888
  needsStartupCleanup ? "recovering" : "waiting",
869
889
  );
870
890
  state.startup = current
871
891
  ? { kind: "predecessor", state: current }
872
- : options.recovery
892
+ : recovery
873
893
  ? { kind: "recovery" }
874
894
  : null;
875
895
  this.#tasks.set(assignment.taskId, state);
876
896
  const gateClosed = this.#closeGate(
877
897
  state,
878
- options.recovery ? "recovery" : "starting",
898
+ recovery ? "recovery" : "starting",
879
899
  );
880
900
 
881
901
  if (needsStartupCleanup) {
@@ -2385,7 +2405,18 @@ export class TaskCredentialLeaseRegistry {
2385
2405
  state: TaskState,
2386
2406
  reason: LeaseGateCloseReason,
2387
2407
  ): Promise<void> {
2388
- if (state.startup) await this.#finishStartup(state);
2408
+ if (state.startup) {
2409
+ try {
2410
+ await this.#finishStartup(state);
2411
+ } catch (error) {
2412
+ // A startup cleanup that failed (a fenced or recovered start whose
2413
+ // runtime could not be reached, a predecessor's) never blocks the
2414
+ // cloud's taskDown: its own full cleanup below covers every run
2415
+ // through this one, and only it may destroy the runtime and prove
2416
+ // it absent (2026-11-09 review). Anything else waits for it.
2417
+ if (reason !== "teardown") throw error;
2418
+ }
2419
+ }
2389
2420
  if (state.gateCloseFailed && this.#closeGate(state, reason)) {
2390
2421
  state.gateCloseFailed = false;
2391
2422
  }
@@ -421,6 +421,9 @@ export class CloudCredentialRuntime {
421
421
  this.registry = new TaskCredentialLeaseRegistry({
422
422
  ...deps.registry,
423
423
  runnerKind: deps.runnerKind,
424
+ // The startup fence: a start of a task whose boot cleanup was isolated
425
+ // runs that cleanup before its gate may open.
426
+ owesCleanup: (taskId) => this.coordinator.isolatedCleanupOwed(taskId),
424
427
  send: (frame) => deps.send(frame),
425
428
  closeTaskGate: (assignment) => this.#close(assignment),
426
429
  openTaskGate: (assignment, view) => this.#openGate(assignment, view),
@@ -764,11 +767,15 @@ export class CloudCredentialRuntime {
764
767
  * Boot recovery (ADR-154 §5, §6): every task with cleanup left from the
765
768
  * last process (a crash, a cleanup that failed) cleaned up, at the newer
766
769
  * of its recorded and its admitted run, before any grant is asked for.
767
- * Every task is attempted; then any failure fails the sweep.
770
+ * Every task is attempted; then any failure of a task `isolatable` does
771
+ * not name fails the sweep (TaskCredentialCleanupCoordinator.recoverAll).
768
772
  */
769
- recover(runEpochForTask: (taskId: string) => number): Promise<void> {
773
+ recover(
774
+ runEpochForTask: (taskId: string) => number,
775
+ isolatable?: (taskId: string) => boolean,
776
+ ): Promise<void> {
770
777
  if (this.#shutDown) return Promise.reject(new StartInterruptedError("shutdown"));
771
- return this.#track(this.coordinator.recoverAll(runEpochForTask));
778
+ return this.#track(this.coordinator.recoverAll(runEpochForTask, isolatable));
772
779
  }
773
780
 
774
781
  /**
@@ -164,13 +164,25 @@ export interface RuntimeDetectionDeps {
164
164
  }
165
165
 
166
166
  interface RuntimeAutoRecheckOptions extends RuntimeDetectionDeps {
167
- /** Fast first retry covers Docker Desktop / OrbStack boot ordering. */
167
+ /** First background probe: fast, for Docker Desktop / OrbStack starting
168
+ * late at login. */
168
169
  firstDelayMs?: number;
169
- /** Later retries stay cheap while a daemon or desktop app starts. */
170
- intervalMs?: number;
171
- /** Bound background probing; an explicit recheck remains available later. */
172
- maxAttempts?: number;
173
- }
170
+ /** Second probe; each later one doubles it, up to maxIntervalMs. */
171
+ backoffStartMs?: number;
172
+ /** Backoff ceiling: a runtime that comes back is noticed within this. */
173
+ maxIntervalMs?: number;
174
+ /** How long one background probe may hold the loop. A slower probe keeps
175
+ * running as the shared in-flight detection; the next tick joins it. */
176
+ probeDeadlineMs?: number;
177
+ log?: (line: string) => void;
178
+ }
179
+
180
+ /** Background recheck cadence while a recheckable runtime is unavailable:
181
+ * 5 s, then 60 s doubling to 300 s (5 s, 60, 120, 240, 300, 300, …). */
182
+ export const RUNTIME_AUTO_RECHECK_FIRST_DELAY_MS = 5_000;
183
+ export const RUNTIME_AUTO_RECHECK_BACKOFF_START_MS = 60_000;
184
+ export const RUNTIME_AUTO_RECHECK_MAX_INTERVAL_MS = 5 * 60_000;
185
+ export const RUNTIME_AUTO_RECHECK_PROBE_DEADLINE_MS = 10_000;
174
186
 
175
187
  /** Parse an operator override without letting a typo silently pick a backend. */
176
188
  export function runtimePreference(value: string | undefined): RuntimePreference {
@@ -649,45 +661,169 @@ export async function ensureContainerRuntimeForTask(
649
661
  return initializeContainerRuntime(deps);
650
662
  }
651
663
 
664
+ /** Only an unavailable runtime whose remedy IS a recheck is probed in the
665
+ * background. Restart-only verdicts (a replaced engine, a rejected
666
+ * selection, a remote endpoint, a bad UAI_RUNTIME) cannot heal by probing. */
667
+ function runtimeAutoRecheckApplies(): boolean {
668
+ return state.status === "no-runtime" && state.action === RUNTIME_RECHECK_COMMAND;
669
+ }
670
+
671
+ let activeAutoRecheck: {
672
+ nudge: (reason: string) => void;
673
+ stop: () => void;
674
+ } | null = null;
675
+
676
+ /**
677
+ * While the runtime is unavailable but recheckable, re-probe it with backoff
678
+ * until it answers, then stop: a fast first probe at 5 s (a daemon starting
679
+ * late at login), then 60 s doubling to a 5 min ceiling. A wake nudge probes
680
+ * at once and restarts that schedule from its 5 s step. Live
681
+ * 2026-11-06: a 1.0.4 station restarted while OrbStack was hung in dark-wake
682
+ * showed unavailable for 14 h because its probing gave up. The loop never
683
+ * runs while ready, keeps at most one probe in flight (initializeContainer-
684
+ * Runtime joins the shared detection, which the operator's `runtime recheck`
685
+ * also waits on), and at most one loop runs per process.
686
+ */
652
687
  export function startContainerRuntimeAutoRecheck(
653
688
  options: RuntimeAutoRecheckOptions = {},
654
689
  ): () => void {
655
- if (
656
- state.status !== "no-runtime" ||
657
- state.action === RUNTIME_RESTART_COMMAND ||
658
- (options.maxAttempts ?? 45) <= 0
659
- ) {
660
- return () => {};
661
- }
662
-
663
- const firstDelayMs = options.firstDelayMs ?? 5_000;
664
- const intervalMs = options.intervalMs ?? 20_000;
665
- const maxAttempts = options.maxAttempts ?? 45;
666
- let attempts = 0;
690
+ activeAutoRecheck?.stop();
691
+ if (!runtimeAutoRecheckApplies()) return () => {};
692
+
693
+ const firstDelayMs = options.firstDelayMs ?? RUNTIME_AUTO_RECHECK_FIRST_DELAY_MS;
694
+ const backoffStartMs =
695
+ options.backoffStartMs ?? RUNTIME_AUTO_RECHECK_BACKOFF_START_MS;
696
+ const maxIntervalMs = options.maxIntervalMs ?? RUNTIME_AUTO_RECHECK_MAX_INTERVAL_MS;
697
+ const probeDeadlineMs =
698
+ options.probeDeadlineMs ?? RUNTIME_AUTO_RECHECK_PROBE_DEADLINE_MS;
699
+ const log = options.log ?? ((line: string) => console.warn(line));
700
+ // Index into the schedule: 0 → firstDelayMs, n ≥ 1 → backoffStartMs·2^(n-1),
701
+ // capped at maxIntervalMs.
702
+ let step = 0;
703
+ const nextDelayMs = (): number => {
704
+ const ms =
705
+ step === 0
706
+ ? firstDelayMs
707
+ : Math.min(backoffStartMs * 2 ** Math.min(step - 1, 30), maxIntervalMs);
708
+ step += 1;
709
+ return ms;
710
+ };
667
711
  let stopped = false;
712
+ let probing = false;
713
+ let nudgedDuringProbe = false;
668
714
  let timer: NodeJS.Timeout | null = null;
669
715
 
670
- const schedule = (delayMs: number): void => {
716
+ const stop = (): void => {
717
+ stopped = true;
718
+ if (timer) clearTimeout(timer);
719
+ timer = null;
720
+ if (activeAutoRecheck === handle) activeAutoRecheck = null;
721
+ };
722
+
723
+ const schedule = (ms: number): void => {
671
724
  timer = setTimeout(() => {
672
725
  timer = null;
673
- if (stopped || state.status === "ready") return;
674
- attempts += 1;
675
- void initializeContainerRuntime(options).then((next) => {
676
- if (stopped || next.status === "ready" || attempts >= maxAttempts) {
677
- return;
678
- }
679
- schedule(intervalMs);
680
- });
681
- }, delayMs);
726
+ void probe();
727
+ }, ms);
682
728
  timer.unref?.();
683
729
  };
684
730
 
685
- schedule(firstDelayMs);
686
- return () => {
687
- stopped = true;
731
+ const probe = async (): Promise<void> => {
732
+ if (stopped) return;
733
+ if (!runtimeAutoRecheckApplies()) {
734
+ stop();
735
+ return;
736
+ }
737
+ probing = true;
738
+ nudgedDuringProbe = false;
739
+ let deadline: NodeJS.Timeout | null = null;
740
+ try {
741
+ await Promise.race([
742
+ initializeContainerRuntime(options),
743
+ new Promise<void>((resolve) => {
744
+ deadline = setTimeout(resolve, probeDeadlineMs);
745
+ deadline.unref?.();
746
+ }),
747
+ ]);
748
+ } catch {
749
+ // initializeContainerRuntime never rejects; keep the loop alive anyway.
750
+ } finally {
751
+ if (deadline) clearTimeout(deadline);
752
+ probing = false;
753
+ }
754
+ if (stopped) return;
755
+ if (!runtimeAutoRecheckApplies()) {
756
+ stop();
757
+ return;
758
+ }
759
+ if (nudgedDuringProbe) {
760
+ // A wake landed while a probe begun before it was in flight: that
761
+ // probe may have dialed a still-asleep daemon, so look once more now.
762
+ nudgedDuringProbe = false;
763
+ step = 0;
764
+ void probe();
765
+ return;
766
+ }
767
+ schedule(nextDelayMs());
768
+ };
769
+
770
+ const nudge = (reason: string): void => {
771
+ if (stopped) return;
772
+ log(`[host-agent] ${reason}: rechecking the unavailable container runtime now`);
773
+ step = 0;
774
+ if (probing) {
775
+ nudgedDuringProbe = true;
776
+ return;
777
+ }
688
778
  if (timer) clearTimeout(timer);
689
779
  timer = null;
780
+ void probe();
690
781
  };
782
+
783
+ const handle = { nudge, stop };
784
+ activeAutoRecheck = handle;
785
+ log(
786
+ `[host-agent] container runtime unavailable; rechecking automatically in ` +
787
+ `${Math.round(firstDelayMs / 1000)}s, then every ${Math.round(backoffStartMs / 1000)}s ` +
788
+ `backing off to ${Math.round(maxIntervalMs / 1000)}s`,
789
+ );
790
+ schedule(nextDelayMs());
791
+ return stop;
792
+ }
793
+
794
+ /**
795
+ * Converge the background recheck on the current state; main calls this on
796
+ * every runtime change. Ready stops it. Any other state keeps a running loop
797
+ * as it is (its backoff is not reset by an unrelated change; a restart-only
798
+ * verdict ends it at its next tick) or, when none runs, starts one if the
799
+ * state is recheckable — whatever the previous state was. Codex review,
800
+ * 2026-11-06: quarantine (restart-only) → a failed operator recheck
801
+ * (recheckable) left no loop running, since only a ready → unavailable edge
802
+ * started one, and wake nudges had nothing to nudge.
803
+ */
804
+ export function syncContainerRuntimeAutoRecheck(
805
+ options: RuntimeAutoRecheckOptions = {},
806
+ ): () => void {
807
+ if (state.status === "ready") {
808
+ activeAutoRecheck?.stop();
809
+ return () => {};
810
+ }
811
+ if (activeAutoRecheck) return activeAutoRecheck.stop;
812
+ return startContainerRuntimeAutoRecheck(options);
813
+ }
814
+
815
+ /** Whether a background recheck loop is running (status and tests). */
816
+ export function containerRuntimeAutoRecheckActive(): boolean {
817
+ return activeAutoRecheck !== null;
818
+ }
819
+
820
+ /** A detected wake (the process-level suspend detector): probe the unavailable
821
+ * runtime now instead of at the next backoff step. A no-op while ready or
822
+ * with no background recheck running. Returns whether a loop was nudged. */
823
+ export function nudgeContainerRuntimeAutoRecheck(reason: string): boolean {
824
+ if (!activeAutoRecheck) return false;
825
+ activeAutoRecheck.nudge(reason);
826
+ return true;
691
827
  }
692
828
 
693
829
  /** Pure detection seam kept injectable for deterministic startup tests. */
@@ -1427,6 +1563,7 @@ export function resetContainerRuntimeSelectionForTests(): void {
1427
1563
  if (process.env.NODE_ENV !== "test") {
1428
1564
  throw new Error("runtime selection reset is test-only");
1429
1565
  }
1566
+ activeAutoRecheck?.stop();
1430
1567
  pinnedDockerHost = null;
1431
1568
  pinnedRuntimeProvider = null;
1432
1569
  pinnedDockerEngineId = null;