@moondeck/station 1.0.9 → 1.0.10

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/lib/agent-cli.ts CHANGED
@@ -942,10 +942,14 @@ async function main() {
942
942
  if (action === "status") { out(await api("GET", "/api/agent/crew-status")); return; }
943
943
  if (action === "store") { out(await api("GET", "/api/agent/crew-store")); return; }
944
944
  if (action === "suggest") {
945
- // The Astronaut suggests a persona; a person creates it (ADR-157 addendum).
946
- // From the Store (--template) or from scratch (--name and --brief).
947
- if (!flags.why || !(flags.template || flags.name)) {
948
- console.error('moondeck: crew suggest needs --template <slug> (see crew store), or --name and --brief for a new one, and --why "<reason>"');
945
+ // The Astronaut suggests a persona from scratch; a person creates it
946
+ // (ADR-157 addendum). Store agents are hired directly: crew add --template.
947
+ if (flags.template) {
948
+ console.error('moondeck: Store agents are hired directly: crew add --template <slug> --why "<reason>" (see storeTemplates in crew list); crew suggest is for a persona from scratch');
949
+ process.exit(1);
950
+ }
951
+ if (!flags.why || !flags.name) {
952
+ console.error('moondeck: crew suggest needs --name and --brief for a new persona, and --why "<reason>"');
949
953
  process.exit(1);
950
954
  }
951
955
  // --skill repeats, and parseFlags keeps only the last, so read them off the raw argv.
@@ -954,7 +958,6 @@ async function main() {
954
958
  if (rest[i] === "--skill" && rest[i + 1]) skills.push(...rest[++i].split(",").filter(Boolean));
955
959
  }
956
960
  const body = { why: flags.why };
957
- if (flags.template) body.template = flags.template;
958
961
  for (const k of ["name", "role", "summary", "brief", "model", "effort"]) if (flags[k]) body[k] = flags[k];
959
962
  if (flags.handle) body.handle = handleOf(flags.handle);
960
963
  if (flags.engine) body.engine = flags.engine;
@@ -964,19 +967,25 @@ async function main() {
964
967
  return;
965
968
  }
966
969
  if (action === "add") {
970
+ // A workspace persona by id, or a Store template by slug (ADR-171): the
971
+ // cloud reuses the workspace's persona for that role, or creates it.
967
972
  const personaId = pos[0];
968
- if (!personaId || !flags.why) {
969
- console.error('moondeck: crew add needs a persona id (see crew list) and --why "<reason>"');
973
+ const template = flags.template && flags.template !== "true" ? flags.template : undefined;
974
+ if (!flags.why || Boolean(personaId) === Boolean(template)) {
975
+ console.error('moondeck: crew add needs a persona id or --template <slug> (see crew list), and --why "<reason>"');
970
976
  process.exit(1);
971
977
  }
972
- const body = { personaId, why: flags.why };
978
+ const body = template ? { template, why: flags.why } : { personaId, why: flags.why };
973
979
  if (flags.as) body.handle = handleOf(flags.as);
974
980
  if (flags.engine) body.kind = flags.engine;
975
981
  if (flags.model) body.model = flags.model;
976
982
  if (flags.effort) body.effort = flags.effort;
977
983
  if (flags.account) body.account = flags.account === "default" ? null : flags.account;
978
984
  const r = await api("POST", "/api/agent/crew", body);
979
- out("added @" + r.agent.id + " (" + r.agent.label + ") on " + launch(r.agent) + ". It stays idle until you dispatch work to it.");
985
+ const from = r.hired
986
+ ? (r.hired.created ? " — created from the Store as persona " : " — the workspace's persona ") + r.hired.persona
987
+ : "";
988
+ out("added @" + r.agent.id + " (" + r.agent.label + ") on " + launch(r.agent) + from + ". It stays idle until you dispatch work to it.");
980
989
  return;
981
990
  }
982
991
  if (action === "model") {
@@ -1160,7 +1169,6 @@ async function main() {
1160
1169
  name: flags.name,
1161
1170
  prompt,
1162
1171
  projects: flags.projects ? String(flags.projects).split(",").map((s) => s.trim()).filter(Boolean) : [],
1163
- team: flags.team || null,
1164
1172
  agents: flags.agents ? String(flags.agents).split(",").map((s) => s.trim()).filter(Boolean) : [],
1165
1173
  parent: flags.parent || null,
1166
1174
  start: flags.start === "true",
@@ -1461,7 +1469,7 @@ async function main() {
1461
1469
  " moondeck files get <org|me>/<path> [<dest>] (download; default /workspace/files/<org|me>/<path>; -r is a folder, capped at 500 files / 1 GB)",
1462
1470
  " moondeck people list",
1463
1471
  " moondeck task list",
1464
- " moondeck task create --name <n> --prompt <text|-> [--projects id,id] [--team id] [--agents handle,handle] [--astronaut engine/model/effort] [--start --request-id <logical-run-id>]",
1472
+ " moondeck task create --name <n> --prompt <text|-> [--projects id,id] [--agents handle,handle] [--astronaut engine/model/effort] [--start --request-id <logical-run-id>]",
1465
1473
  " moondeck task watch <childId> [--after <cursor>] [--limit N]",
1466
1474
  " moondeck task usage <childId>",
1467
1475
  ' moondeck task send <childId> "text"',
@@ -1510,12 +1518,12 @@ async function main() {
1510
1518
  " Your literal instruction, including quotes and shell syntax.",
1511
1519
  " EOF",
1512
1520
  " moondeck task create --name <n> --prompt - reads stdin the same way.",
1513
- " moondeck crew list (Astronaut only: personas with summary, skills and permissions, engines, models, limits, roster)",
1521
+ " moondeck crew list (Astronaut only: personas with summary, skills and permissions, Store templates you can hire, engines, models, limits, roster)",
1514
1522
  " moondeck crew status (Astronaut only: each agent's engine, model, account; account usage; credits)",
1515
1523
  " moondeck crew store (Astronaut only: the Store's persona and skill templates, names and types only)",
1516
- ' moondeck crew suggest --template <slug> --why "<reason>" (Astronaut only: propose a persona from the Store; a person creates it)',
1517
- ' moondeck crew suggest --name <n> --brief <text> [--role <r>] [--summary <s>] [--handle <h>] [--engine <kind>] [--model <m>] [--effort <e>] [--skill <slug|id>]... --why "<reason>"',
1518
1524
  ' moondeck crew add <personaId> [--as <handle>] [--engine <kind>] [--model <m>] [--effort <e>] [--account <id|label|default>] --why "<reason>"',
1525
+ ' moondeck crew add --template <slug> [--as <handle>] [--engine <kind>] [--model <m>] [--effort <e>] [--account <id|label|default>] --why "<reason>" (Astronaut only: hire a Store agent; reuses the workspace persona for its role, else creates it)',
1526
+ ' moondeck crew suggest --name <n> --brief <text> [--role <r>] [--summary <s>] [--handle <h>] [--engine <kind> [--model <m>] [--effort <e>]] [--skill <slug|id>]... --why "<reason>" (Astronaut only: propose a persona from scratch; a person creates it; no --engine = auto engine)',
1519
1527
  ' moondeck crew model @agent [--engine <kind>] [--model <m|default>] [--effort <e|default>] [--account <id|label|default>] --why "<reason>"',
1520
1528
  ' moondeck crew remove @agent --why "<reason>"',
1521
1529
  " moondeck react <heart|check|x> [--msg #id] (no --msg = the message you were last handed)",
@@ -7519,6 +7519,43 @@ function skillNameList(names: readonly string[]): string {
7519
7519
  return shown.length > 1 ? `${shown.slice(0, -1).join(", ")} and ${shown[shown.length - 1]}` : shown[0]!;
7520
7520
  }
7521
7521
 
7522
+ /**
7523
+ * Durable checkpoints and bounded tests (2026-11-11 incident: a Cloud machine
7524
+ * froze under a full vitest run with nothing pushed). Every preamble carries
7525
+ * this, the Astronaut's too: it normally delegates edits, but may do cheap
7526
+ * checks or an authorized edit itself.
7527
+ */
7528
+ export const WIP_CHECKPOINT_BRIEF_LINES: readonly string[] = [
7529
+ "## Checkpoints and long commands",
7530
+ "",
7531
+ "Work that exists only on this machine's disk is lost if the machine freezes",
7532
+ "or is reclaimed. If you are the git owner for the checkout (a dispatch or the",
7533
+ "Astronaut brief names you explicitly, or you are the only agent writing in",
7534
+ "it): after each finished step, stage by explicit path, commit when something",
7535
+ "changed (never an empty commit), and push the CURRENT branch as a WIP",
7536
+ "checkpoint, but only if it is the task branch or a branch in this task's",
7537
+ "namespace (`uai/<taskId>/<name>`); never push any other branch. Do this",
7538
+ "BEFORE any long-running command: a build, a dev server, Playwright, or a test",
7539
+ "run. Open a draft PR early only once a person has authorized PRs; a",
7540
+ "checkpoint is not a merge or deploy, and it never widens what the task",
7541
+ "allows: if pushing or PRs are restricted, or the push is refused, report the",
7542
+ "blocker instead of working around it.",
7543
+ "If ownership is unclear, do not commit in a shared checkout: ask. If you do",
7544
+ "not own git, send the owner the files you changed, then WAIT for their",
7545
+ "checkpoint confirmation before the long command.",
7546
+ "The Astronaut normally delegates edits: its dispatch names the git owner and",
7547
+ "asks for all of this. When a human has it do an edit or check itself, the",
7548
+ "same rules apply to that step.",
7549
+ "",
7550
+ "Assume this machine is a small Cloud VM unless the task says otherwise. Run",
7551
+ "targeted tests only, the files your change touches, with explicit bounded",
7552
+ "workers, for example `pnpm vitest run <files> --maxWorkers=2 --minWorkers=1`.",
7553
+ "NEVER run the whole suite (`pnpm test`, `pnpm test:unit`, or `vitest run`",
7554
+ "with no file filter) on a Cloud machine; leave that to CI. Do not run a dev",
7555
+ "server and a browser test at the same time as a test run.",
7556
+ "",
7557
+ ];
7558
+
7522
7559
  export function buildSystemPreamble(
7523
7560
  roster: Roster,
7524
7561
  agent: RosterAgent,
@@ -7658,10 +7695,14 @@ export function buildSystemPreamble(
7658
7695
  "## Your crew",
7659
7696
  "",
7660
7697
  "You choose this task's crew. `node " + CONTAINER_CLI_PATH + " crew list` shows the",
7661
- "personas you can hire, the engines and models this task can run (with the",
7698
+ "personas and Store agents you can hire, the engines and models this task can run (with the",
7662
7699
  "Moondeck AI's prices), the plan's room, and the current roster. Change it",
7663
7700
  "one agent at a time, always with a reason the humans will read:",
7664
7701
  "- `crew add <personaId> [--as <handle>] [--engine <kind>] [--model <m>] [--effort <e>] --why \"…\"`",
7702
+ "- `crew add --template <slug> [--as <handle>] [...same options] --why \"…\"` hires a Store agent:",
7703
+ " the workspace's persona for that role, or a new one created from the template",
7704
+ "- A persona listed with `kind: null` is auto (no engine of its own): give it `--engine`,",
7705
+ " `--model` and `--effort` for the step, or it starts on the task's default engine",
7665
7706
  "- `crew model @agent [--engine <kind>] [--model <m>] [--effort <e>] --why \"…\"`",
7666
7707
  " (at least one of the three; `default` as the model or effort clears it to",
7667
7708
  " the engine's own default)",
@@ -8086,7 +8127,7 @@ export function buildSystemPreamble(
8086
8127
  `\`${(agent.permissions ?? []).join(", ")}\`. Commands: \`projects list\`,`,
8087
8128
  "`people list`, `task list`" +
8088
8129
  (agent.permissions?.includes("tasks.create")
8089
- ? ", `task create --name <n> --prompt <p> [--projects id,id] [--team id] [--agents handle,handle] [--astronaut engine/model/effort] [--start --request-id <logical-run-id>]`"
8130
+ ? ", `task create --name <n> --prompt <p> [--projects id,id] [--agents handle,handle] [--astronaut engine/model/effort] [--start --request-id <logical-run-id>]`"
8090
8131
  : "") +
8091
8132
  (agent.permissions?.includes("tasks.read")
8092
8133
  ? ", `task watch <childId> [--after <cursor>]`, `task usage <childId>`"
@@ -8196,6 +8237,7 @@ export function buildSystemPreamble(
8196
8237
  "",
8197
8238
  ]
8198
8239
  : []),
8240
+ ...WIP_CHECKPOINT_BRIEF_LINES,
8199
8241
  "## Commit policy",
8200
8242
  "",
8201
8243
  "When this task has an optional SSH signing key configured, Git signs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "description": "Moondeck Station: runs Moondeck tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Moondeck <team@moondeck.io>",
@@ -0,0 +1,196 @@
1
+ import { performance } from "node:perf_hooks";
2
+
3
+ export const BRIDGE_SILENCE_MS = 45_000;
4
+ export const BRIDGE_SETUP_MS = 60_000;
5
+ export const BRIDGE_FAILURE_MS = 10 * 60_000;
6
+ const TICK_GAP_MS = 5_000;
7
+
8
+ /** Only service launches with a restart path may use outage-driven exits.
9
+ * launchd additionally needs scheduleActivationRespawn immediately before exit. */
10
+ export function hasRecoverySupervisor(options: {
11
+ platform?: NodeJS.Platform;
12
+ env?: NodeJS.ProcessEnv;
13
+ parentPid?: number;
14
+ pid?: number;
15
+ underElectron?: boolean;
16
+ } = {}): boolean {
17
+ const platform = options.platform ?? process.platform;
18
+ if (platform === "linux") {
19
+ const env = options.env ?? process.env;
20
+ // Invocation IDs reach descendants too. Newer systemd identifies the
21
+ // directly executed process; older releases omit SYSTEMD_EXEC_PID.
22
+ return /^[a-f0-9]{32}$/i.test(env.INVOCATION_ID ?? "") &&
23
+ (env.SYSTEMD_EXEC_PID === undefined || env.SYSTEMD_EXEC_PID === String(options.pid ?? process.pid));
24
+ }
25
+ return platform === "darwin" && ((options.underElectron ?? Boolean(process.versions.electron)) || (options.parentPid ?? process.ppid) === 1);
26
+ }
27
+
28
+ /** Process-level recovery, independent of socket open/close and retry timers.
29
+ * A local send/open is not evidence that the cloud can answer. */
30
+ export class BridgeRecovery {
31
+ private lastEvidence: number;
32
+ private lastTick: number;
33
+ private pausedTime = 0;
34
+ private failed = false;
35
+ private attempting = false;
36
+ private warned = new Set<string>();
37
+ private retry: ReturnType<typeof setTimeout> | undefined;
38
+ private check: ReturnType<typeof setInterval> | undefined;
39
+ private cancelSetup: (() => void) | undefined;
40
+ private socketWatch: { lastTraffic: number; expire: () => void } | undefined;
41
+
42
+ constructor(private readonly options: {
43
+ connect: () => Promise<void>;
44
+ stopped: () => boolean;
45
+ unsafe: () => boolean;
46
+ supervised: boolean;
47
+ restart: (reason: string) => void;
48
+ report: (reason: string, error?: unknown) => void;
49
+ now?: () => number;
50
+ }) {
51
+ this.lastTick = this.now();
52
+ this.lastEvidence = this.lastTick;
53
+ }
54
+
55
+ private now(): number { return (this.options.now ?? (() => performance.now()))(); }
56
+
57
+ /** A suspended laptop or a delayed event loop must first get a chance to
58
+ * reconnect. This affects only JS deadlines; systemd's independent watchdog
59
+ * still receives no pulses while the loop is blocked. Socket expiry uses
60
+ * the raw clock so the old transport is retired promptly on wake. */
61
+ private activeNow(): number {
62
+ const now = this.now();
63
+ const gap = now - this.lastTick;
64
+ if (gap > TICK_GAP_MS) this.pausedTime += gap;
65
+ this.lastTick = now;
66
+ return now - this.pausedTime;
67
+ }
68
+
69
+ start(): void {
70
+ if (this.check) return;
71
+ this.check = setInterval(() => {
72
+ const now = this.activeNow();
73
+ if (this.options.stopped() || this.failed) return;
74
+ if (this.options.unsafe()) {
75
+ this.fail("remote operation cleanup failed");
76
+ } else if (now - this.lastEvidence >= BRIDGE_FAILURE_MS) {
77
+ this.fail("no bridge server evidence for 10 minutes");
78
+ }
79
+ if (this.socketWatch && this.now() - this.socketWatch.lastTraffic >= BRIDGE_SILENCE_MS) {
80
+ this.socketWatch.expire();
81
+ }
82
+ }, 1_000);
83
+ void this.attempt();
84
+ }
85
+
86
+ private async attempt(): Promise<void> {
87
+ if (this.failed || this.options.stopped()) return;
88
+ if (this.attempting) { this.scheduleRetry(1_000); return; }
89
+ this.attempting = true;
90
+ const started = this.activeNow();
91
+ let setup: ReturnType<typeof setTimeout>;
92
+ const checkSetup = (): void => {
93
+ const remaining = BRIDGE_SETUP_MS - (this.activeNow() - started);
94
+ if (remaining > 0) setup = setTimeout(checkSetup, remaining);
95
+ else this.fail("bridge setup or remote cleanup exceeded 60 seconds");
96
+ };
97
+ setup = setTimeout(checkSetup, BRIDGE_SETUP_MS);
98
+ const cancel = (): void => clearTimeout(setup);
99
+ this.cancelSetup = cancel;
100
+ try {
101
+ await this.options.connect();
102
+ } catch (error) {
103
+ // A new attempt must pass the main handler's generation cleanup gate.
104
+ this.fail("bridge setup threw", error);
105
+ if (!this.options.supervised) {
106
+ this.socketWatch?.expire();
107
+ this.scheduleRetry(1_000);
108
+ }
109
+ } finally {
110
+ cancel();
111
+ if (this.cancelSetup === cancel) this.cancelSetup = undefined;
112
+ this.attempting = false;
113
+ }
114
+ }
115
+
116
+ scheduleRetry(delay: number): void {
117
+ if (this.failed || this.options.stopped() || this.retry) return;
118
+ this.retry = setTimeout(() => {
119
+ this.retry = undefined;
120
+ void this.attempt();
121
+ }, delay);
122
+ }
123
+
124
+ guard<Args extends unknown[]>(handler: (...args: Args) => void): (...args: Args) => void {
125
+ return (...args) => {
126
+ try { handler(...args); } catch (error) {
127
+ this.fail("bridge event handler threw", error);
128
+ if (!this.options.supervised) {
129
+ this.socketWatch?.expire();
130
+ // A close handler may retire its watch before throwing. Retrying
131
+ // cannot depend on expire still owning that watch.
132
+ this.scheduleRetry(1_000);
133
+ }
134
+ }
135
+ };
136
+ }
137
+
138
+ watch(socket: { terminate(): void }, disconnected: () => void): {
139
+ received(): void;
140
+ retire(): void;
141
+ expire(): void;
142
+ } {
143
+ const watch = { lastTraffic: this.now(), expire: () => {} };
144
+ this.socketWatch = watch;
145
+ const retire = (): void => {
146
+ if (this.socketWatch === watch) this.socketWatch = undefined;
147
+ };
148
+ const expire = (): void => {
149
+ if (this.socketWatch !== watch || this.options.stopped() || this.failed) return;
150
+ retire();
151
+ try {
152
+ disconnected();
153
+ } catch (error) {
154
+ this.fail("bridge disconnect cleanup threw", error);
155
+ this.scheduleRetry(1_000);
156
+ } finally {
157
+ try { socket.terminate(); } catch (error) { this.fail("bridge termination threw", error); }
158
+ }
159
+ };
160
+ watch.expire = expire;
161
+ return {
162
+ expire,
163
+ retire,
164
+ received: () => {
165
+ if (this.socketWatch !== watch || this.failed) return;
166
+ watch.lastTraffic = this.now();
167
+ this.lastEvidence = this.activeNow();
168
+ this.warned.clear();
169
+ },
170
+ };
171
+ }
172
+
173
+ fail(reason: string, error?: unknown): void {
174
+ if (this.failed || this.options.stopped()) return;
175
+ if (!this.warned.has(reason)) {
176
+ this.warned.add(reason);
177
+ this.options.report(reason, error);
178
+ }
179
+ // Foreground runs must remain available for network recovery. Unsafe
180
+ // cleanup still fails closed; only an operator can restart that process.
181
+ if (!this.options.supervised) return;
182
+ this.failed = true;
183
+ this.stop();
184
+ this.options.restart(reason);
185
+ }
186
+
187
+ stop(): void {
188
+ clearInterval(this.check);
189
+ clearTimeout(this.retry);
190
+ this.cancelSetup?.();
191
+ this.cancelSetup = undefined;
192
+ this.check = undefined;
193
+ this.retry = undefined;
194
+ this.socketWatch = undefined;
195
+ }
196
+ }
package/src/cli.ts CHANGED
@@ -19,6 +19,7 @@
19
19
  // — from the wrong base. (main.ts loads it too, but `await import("./main")`
20
20
  // runs far too late.)
21
21
  import "./load-env";
22
+ import { startSystemdWatchdog } from "./systemd-watchdog";
22
23
 
23
24
  import {
24
25
  spawn,
@@ -225,6 +226,7 @@ function timestampServiceLogs(): void {
225
226
  }
226
227
 
227
228
  async function cmdRun(rest: string[] = []): Promise<void> {
229
+ startSystemdWatchdog();
228
230
  // ADR-133 sidecar mode: `uai-host run --task <id>` on the task's own
229
231
  // machine. The flag becomes the environment the rest of the process asks
230
232
  // (lib/sidecar.ts) — set before main.ts loads, since its boot reads it.
package/src/main.ts CHANGED
@@ -13,7 +13,8 @@ import {
13
13
  } from "../lib/agent-dependencies";
14
14
  import { PREVIEW_UPSTREAM_PROTOCOL_FEATURE, parsePreviewUpstream, tunnelPreviewUpstream } from "./preview-upstream";
15
15
  import { preparePreviewUpstream, previewRequestHeaders, isPreviewConnectFailure } from "../lib/preview-upstream";
16
- import { describeClose, suspendedFor } from "./bridge-diagnostics";
16
+ import { describeClose } from "./bridge-diagnostics";
17
+ import { BridgeRecovery, hasRecoverySupervisor, BRIDGE_SILENCE_MS } from "./bridge-recovery";
17
18
  import { startProcessWakeDetector } from "./process-wake";
18
19
  import { internalHostGatewayAdvertisable } from "../lib/custom-connection-launch";
19
20
  import "./load-env";
@@ -157,7 +158,7 @@ import { reinstallTrustInRunningTasks, unpinRunningTasks } from "../lib/secrets-
157
158
  import { currentTaskGatewayRegistration } from "../lib/task-gateway-state";
158
159
  import { followLeavingLegacy, proxyTaskEnvSnapshot } from "../lib/task-env-source";
159
160
  import { recoverActiveTaskGateways } from "../lib/task-gateway-recovery";
160
- import { addHostBreadcrumb, initHostObs, setHostObsTag } from "../lib/obs";
161
+ import { addHostBreadcrumb, captureHostError, initHostObs, setHostObsTag } from "../lib/obs";
161
162
  import {
162
163
  hostIdFilePath,
163
164
  packageVersion,
@@ -513,7 +514,6 @@ setContainerRuntimeOperationalCheck(() => containerRuntimeProblem() === null);
513
514
  initHostObs({ version: packageVersion() });
514
515
 
515
516
  const PING_INTERVAL_MS = 15_000;
516
- const DEAD_AFTER_MS = 45_000;
517
517
  // Reconnect backoff, capped low (~15s) on purpose: cloud deploys drop the
518
518
  // bridge for ~30-40s, and an unbounded backoff (the old 60s tail) left the host
519
519
  // "disconnected" for up to a minute after the cloud was back, needing a manual
@@ -616,6 +616,7 @@ let connectionRequestGeneration = 0;
616
616
  let inFlight = 0;
617
617
  let shutdownRequested = false;
618
618
  let shutdownExitCode = 0;
619
+ let shutdownDeadline: NodeJS.Timeout | undefined;
619
620
  const managedMutationDrain = new ManagedOperationDrain(maybeExit);
620
621
  const hostLogManager = createHostLogManager();
621
622
  const customConnectionOperations = new Map<AbortController, Promise<void>>();
@@ -633,12 +634,13 @@ const pendingRemoteOperationCleanups = new Set<Promise<void>>();
633
634
  let stopActiveRemoteOperations = (): Promise<void> => Promise.resolve();
634
635
 
635
636
  function trackRemoteOperationCleanup(cleanup: Promise<void>): Promise<void> {
636
- const tracked = cleanup.catch(() => {
637
+ const tracked = cleanup.catch((error: unknown) => {
637
638
  // A replacement generation must fail closed if an unforeseen manager bug
638
639
  // escapes its best-effort cleanup contract. Shutdown may still exit after
639
640
  // the failed cleanup settles so the service supervisor can recover.
640
641
  fatal = true;
641
- console.warn("[host-agent] remote operation cleanup failed");
642
+ console.warn("[host-agent] remote operation cleanup failed", error);
643
+ captureHostError(error, { phase: "bridge remote cleanup" });
642
644
  });
643
645
  pendingRemoteOperationCleanups.add(tracked);
644
646
  void tracked.finally(() => {
@@ -1489,7 +1491,18 @@ onLeavingLegacy(async () => {
1489
1491
  await Promise.all([engineLoginManager.stopAll(), engineConnectManager.idle()]);
1490
1492
  await Promise.all([managedMutationDrain.idle(), waitForRemoteOperationCleanups()]);
1491
1493
  });
1492
- void connect();
1494
+ const bridgeRecovery = new BridgeRecovery({
1495
+ connect,
1496
+ stopped: () => stopping,
1497
+ unsafe: () => fatal,
1498
+ supervised: hasRecoverySupervisor(),
1499
+ report: (reason, error) => {
1500
+ console.error(`[host-agent] ${reason}; ${hasRecoverySupervisor() ? "draining for supervisor recovery" : "no restart supervisor; continuing safe retries (failed cleanup requires operator restart)"}`, error ?? "");
1501
+ captureHostError(error ?? new Error(reason), { phase: "bridge recovery", reason });
1502
+ },
1503
+ restart: requestBridgeRecoveryRestart,
1504
+ });
1505
+ bridgeRecovery.start();
1493
1506
  // Local browser UI (ADR-028) — same single process, alongside the WSS client.
1494
1507
  // Best-effort: a UI bind failure must not take the host service down.
1495
1508
  // A task machine has no operator sitting at it (ADR-133): no local UI, no
@@ -3036,13 +3049,16 @@ async function connect(): Promise<void> {
3036
3049
  // file read/child-process event can never escape onto the new socket.
3037
3050
  if (!(await remoteOperationsReadyForConnect(requestGeneration))) return;
3038
3051
  console.log(`[host-agent] connecting ${bridgeUrl}`);
3039
- const socket = new WebSocket(bridgeUrl, { perMessageDeflate: WS_DEFLATE });
3052
+ const socket = new WebSocket(bridgeUrl, { perMessageDeflate: WS_DEFLATE, handshakeTimeout: BRIDGE_SILENCE_MS });
3040
3053
  ws = socket;
3041
3054
 
3042
- let lastTraffic = Date.now();
3043
3055
  let ready = false;
3044
3056
  let pingTimer: NodeJS.Timeout | null = null;
3045
- let deadTimer: NodeJS.Timeout | null = null;
3057
+ const liveness = bridgeRecovery.watch(socket, () => {
3058
+ console.warn("[host-agent] bridge inbound traffic timed out; terminating socket");
3059
+ handleClose(4000, Buffer.from("heartbeat timeout"));
3060
+ });
3061
+ let cleaned = false;
3046
3062
  let remoteOperationsActive = true;
3047
3063
  let remoteOperationCleanup: Promise<void> | null = null;
3048
3064
 
@@ -3133,6 +3149,9 @@ async function connect(): Promise<void> {
3133
3149
  };
3134
3150
 
3135
3151
  const cleanup = (): void => {
3152
+ if (cleaned) return;
3153
+ cleaned = true;
3154
+ liveness.retire();
3136
3155
  stopEngineUsageSubscription();
3137
3156
  // Connection loss revokes the serving gate before deferred transport
3138
3157
  // cleanup yields. A late close from a superseded socket must not revoke a
@@ -3145,7 +3164,8 @@ async function connect(): Promise<void> {
3145
3164
  }
3146
3165
  void stopRemoteOperations();
3147
3166
  if (pingTimer) clearInterval(pingTimer);
3148
- if (deadTimer) clearInterval(deadTimer);
3167
+ // Never clear a replacement generation's transport/auth state.
3168
+ if (requestGeneration !== connectionRequestGeneration || ws !== socket) return;
3149
3169
  eventFlushEnabled = false;
3150
3170
  credentialFramesReady = false;
3151
3171
  cancelEventFlushBackpressureTimer();
@@ -3159,7 +3179,8 @@ async function connect(): Promise<void> {
3159
3179
  }
3160
3180
  };
3161
3181
 
3162
- socket.on("open", () => {
3182
+ socket.on("open", bridgeRecovery.guard(() => {
3183
+ if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
3163
3184
  // Suspend synchronously before auth: cloud activation immediately starts
3164
3185
  // task reconciliation, which must observe `checking` until this proof
3165
3186
  // finishes instead of treating a dead daemon as an empty one.
@@ -3174,12 +3195,8 @@ async function connect(): Promise<void> {
3174
3195
  capabilities: buildCapabilities(),
3175
3196
  });
3176
3197
  flushStoppedTaskStatuses(socket);
3177
- ready = true;
3178
- reconnectAttempt = 0;
3179
- markConnected();
3180
- console.log(`[host-agent] connected as ${hostId}`);
3181
- setHostObsTag(hostId);
3182
- addHostBreadcrumb("bridge", "connected");
3198
+ // An open TCP/WebSocket is not an authenticated cloud response. The
3199
+ // first valid inbound frame below establishes connection health.
3183
3200
 
3184
3201
  // ADR-103: hold event transmission until the cloud names its replay
3185
3202
  // watermark (event.resume). A pre-103 cloud never will — after the
@@ -3196,31 +3213,16 @@ async function connect(): Promise<void> {
3196
3213
  }
3197
3214
  }, PING_INTERVAL_MS);
3198
3215
 
3199
- let lastTick = Date.now();
3200
- deadTimer = setInterval(() => {
3201
- const now = Date.now();
3202
- const suspended = suspendedFor(lastTick, now, 5_000);
3203
- lastTick = now;
3204
- if (suspended !== null) {
3205
- console.warn(
3206
- `[host-agent] this process was suspended for ~${Math.round(suspended / 1000)}s (system sleep?); ` +
3207
- "the cloud drops a connection that is silent for 45s",
3208
- );
3209
- }
3210
- if (now - lastTraffic > DEAD_AFTER_MS) {
3211
- console.warn("[host-agent] bridge heartbeat timed out");
3212
- socket.close(4000, "heartbeat timeout");
3213
- }
3214
- }, 5_000);
3215
- });
3216
+ }));
3216
3217
 
3217
- socket.on("message", (data, isBinary) => {
3218
- lastTraffic = Date.now();
3218
+ socket.on("message", bridgeRecovery.guard((data: WebSocket.RawData, isBinary: boolean) => {
3219
+ if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
3219
3220
  // A superseded socket is read-dead even if the transport has not emitted
3220
3221
  // close yet. Never let a late frame recreate work in shared managers or
3221
3222
  // attach binary data to the replacement connection's pending tunnel.
3222
3223
  if (!remoteOperationsActive) return;
3223
3224
  if (isBinary) {
3225
+ if (ready) liveness.received();
3224
3226
  const tunnelId = pendingBinaryTunnelId;
3225
3227
  pendingBinaryTunnelId = null;
3226
3228
  if (!tunnelId) return;
@@ -3231,6 +3233,15 @@ async function connect(): Promise<void> {
3231
3233
 
3232
3234
  const frame = parseCloudFrame(data);
3233
3235
  if (!frame) { replyToInvalidCustomConnectionFrame(socket, data); return; }
3236
+ liveness.received();
3237
+ if (!ready) {
3238
+ ready = true;
3239
+ reconnectAttempt = 0;
3240
+ markConnected();
3241
+ console.log(`[host-agent] connected as ${hostId}`);
3242
+ setHostObsTag(hostId);
3243
+ addHostBreadcrumb("bridge", "connected");
3244
+ }
3234
3245
  if (stopping && rejectFrameDuringShutdown(socket, frame)) return;
3235
3246
  if (signInBoxMode() && rejectFrameOnSignInBox(socket, frame)) return;
3236
3247
  if (!onOwnCredentials() && rejectCredentialFrameOffOwnCredentials(socket, frame)) return;
@@ -4056,16 +4067,18 @@ async function connect(): Promise<void> {
4056
4067
  break;
4057
4068
  }
4058
4069
  }
4059
- });
4070
+ }));
4060
4071
 
4061
- socket.on("error", (err) => {
4072
+ socket.on("error", bridgeRecovery.guard((err: Error) => {
4073
+ if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
4062
4074
  markCloudError(err.message);
4063
4075
  if (!stopping) {
4064
4076
  console.warn(`[host-agent] bridge error: ${err.message}`);
4065
4077
  }
4066
- });
4078
+ }));
4067
4079
 
4068
- socket.on("close", (code, reason) => {
4080
+ function handleClose(code: number, reason: Buffer): void {
4081
+ if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
4069
4082
  cleanup();
4070
4083
  // A note this connection carried is not known stored: the next start
4071
4084
  // sends it again, and the cloud keeps one per noteId.
@@ -4088,9 +4101,7 @@ async function connect(): Promise<void> {
4088
4101
  addHostBreadcrumb("bridge", "auth-rejected", {
4089
4102
  retryInMs: AUTH_REJECTED_RETRY_MS,
4090
4103
  });
4091
- setTimeout(() => {
4092
- void connect();
4093
- }, AUTH_REJECTED_RETRY_MS);
4104
+ bridgeRecovery.scheduleRetry(AUTH_REJECTED_RETRY_MS);
4094
4105
  return;
4095
4106
  }
4096
4107
  const delay = reconnectDelay();
@@ -4103,10 +4114,9 @@ async function connect(): Promise<void> {
4103
4114
  authed: ready,
4104
4115
  retryInMs: Math.round(delay),
4105
4116
  });
4106
- setTimeout(() => {
4107
- void connect();
4108
- }, delay);
4109
- });
4117
+ bridgeRecovery.scheduleRetry(delay);
4118
+ }
4119
+ socket.on("close", bridgeRecovery.guard(handleClose));
4110
4120
  }
4111
4121
 
4112
4122
  async function handleCommand(
@@ -6369,9 +6379,24 @@ function reconnectDelay(): number {
6369
6379
  return base * jitter;
6370
6380
  }
6371
6381
 
6382
+ function requestBridgeRecoveryRestart(): void {
6383
+ shutdownExitCode = 1;
6384
+ requestShutdown("SIGTERM");
6385
+ }
6386
+
6372
6387
  function requestShutdown(signal: NodeJS.Signals): void {
6388
+ if (shutdownRequested) return;
6389
+ shutdownRequested = true;
6390
+ // Self-initiated restarts never enter systemd's stop job/TimeoutStopSec.
6391
+ // Bound every drain, including a pending cleanup or in-flight command.
6392
+ shutdownDeadline = setTimeout(() => {
6393
+ console.error("[host-agent] shutdown drain exceeded 30 seconds; forcing exit");
6394
+ finishShutdown();
6395
+ }, 30_000);
6396
+ shutdownDeadline.unref();
6373
6397
  console.log(`[host-agent] ${signal} received; shutting down`);
6374
6398
  stopping = true;
6399
+ bridgeRecovery.stop();
6375
6400
  openRouterBudgets.stop();
6376
6401
  // Cancel human-paced operations without invalidating this socket's exact
6377
6402
  // generation: already-admitted one-shot config writes may still ack while
@@ -6419,7 +6444,6 @@ function requestShutdown(signal: NodeJS.Signals): void {
6419
6444
  stopProcessWakeDetector();
6420
6445
  stopRuntimeAutoRecheck();
6421
6446
  runtimeActivationTail.stop();
6422
- shutdownRequested = true;
6423
6447
  maybeExit();
6424
6448
  }
6425
6449
 
@@ -6448,8 +6472,13 @@ function maybeExit(): void {
6448
6472
  }
6449
6473
  if (ws.readyState === WebSocket.CLOSING) return;
6450
6474
  }
6451
- if (shutdownExitCode === MANAGED_UPDATE_RESTART_EXIT_CODE) {
6452
- // The drain is complete: this is the last thing the old generation does.
6475
+ finishShutdown();
6476
+ }
6477
+
6478
+ function finishShutdown(): void {
6479
+ clearTimeout(shutdownDeadline);
6480
+ if (shutdownExitCode !== 0 && shutdownExitCode !== 3) {
6481
+ // The drain completed or hit its deadline: the old generation exits now.
6453
6482
  // On a launchd host the respawn is scheduled from here rather than left
6454
6483
  // to KeepAlive — see activation-respawn.ts for the two 2026-09-06 stalls.
6455
6484
  const plan = scheduleActivationRespawn();
@@ -6465,7 +6494,7 @@ function maybeExit(): void {
6465
6494
  /**
6466
6495
  * Finish any in-flight bridge command, then let the service supervisor exec
6467
6496
  * the newly activated `runtime/current`. The non-zero status is intentional:
6468
- * Linux uses Restart=on-failure and the desktop supervisor restarts on any
6497
+ * Machine units use Restart=always and the desktop supervisor restarts on any
6469
6498
  * exit. launchd's KeepAlive is supposed to respawn it too but has been seen
6470
6499
  * not to (2026-09-06, twice), so maybeExit() also schedules an explicit
6471
6500
  * `launchctl kickstart` on macOS before the process exits.
@@ -0,0 +1,43 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ /** The CLI boots main.ts in-process: its PID is systemd's main PID. The
4
+ * root notifier sends as its parent PID (NotifyAccess=main), never an independent
5
+ * heartbeat loop that could keep a blocked Station falsely healthy. */
6
+ export function startSystemdWatchdog(options: {
7
+ env?: NodeJS.ProcessEnv;
8
+ pid?: number;
9
+ notify?: (done: (error: Error | null) => void) => void;
10
+ warn?: (message: string) => void;
11
+ } = {}): () => void {
12
+ const env = options.env ?? process.env;
13
+ const pid = options.pid ?? process.pid;
14
+ const usec = Number(env.WATCHDOG_USEC ?? env.UAI_SYSTEMD_WATCHDOG_USEC);
15
+ if (!env.NOTIFY_SOCKET || !Number.isSafeInteger(usec) || usec < 1_000_000 ||
16
+ (env.WATCHDOG_PID && Number(env.WATCHDOG_PID) !== pid)) return () => {};
17
+
18
+ const notify = options.notify ?? ((done) => {
19
+ // Keep the default notification barrier: the child stays alive until
20
+ // systemd has attributed its datagram. No shell and no detached child.
21
+ execFile("/usr/bin/systemd-notify", [`WATCHDOG_USEC=${usec}`, "WATCHDOG=1"], {
22
+ timeout: 5_000, killSignal: "SIGKILL", env,
23
+ }, (error) => done(error));
24
+ });
25
+ let pending = false;
26
+ let warned = false;
27
+ const pulse = (): void => {
28
+ if (pending) return;
29
+ pending = true;
30
+ const done = (error: Error | null): void => {
31
+ pending = false;
32
+ if (error && !warned) {
33
+ warned = true;
34
+ (options.warn ?? console.warn)("[host-agent] systemd watchdog notification failed; watchdog may be unarmed or expire if previously armed");
35
+ }
36
+ };
37
+ try { notify(done); } catch (error) { done(error as Error); }
38
+ };
39
+ pulse();
40
+ const timer = setInterval(pulse, Math.min(10_000, usec / 3_000));
41
+ timer.unref();
42
+ return () => clearInterval(timer);
43
+ }