@moondeck/station 1.0.8 → 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/images/standard/Dockerfile +3 -1
- package/images/standard/container/uai-init +66 -9
- package/lib/agent-cli.ts +22 -14
- package/lib/orchestrator.ts +44 -2
- package/lib/task-environment/machine-task-up.ts +81 -0
- package/package.json +1 -1
- package/src/bridge-recovery.ts +196 -0
- package/src/cli.ts +2 -0
- package/src/engine-models.ts +5 -3
- package/src/main.ts +80 -51
- package/src/systemd-watchdog.ts +43 -0
|
@@ -34,6 +34,7 @@ ENV MISE_VERSION=2026.11.1
|
|
|
34
34
|
|
|
35
35
|
# Qualified agent builds. These are execution-contract pins: per-command env
|
|
36
36
|
# freshness is requalified before any of them moves.
|
|
37
|
+
ENV UAI_CLAUDE_CODE_VERSION=2.1.322
|
|
37
38
|
ENV UAI_CODEX_CLI_VERSION=0.164.0
|
|
38
39
|
ENV UAI_CURSOR_AGENT_VERSION=2026.10.22-27dcf5f
|
|
39
40
|
ENV UAI_GROK_CLI_VERSION=1.0.70
|
|
@@ -277,7 +278,7 @@ RUN bash -lc '\
|
|
|
277
278
|
. /opt/asdf/asdf.sh; \
|
|
278
279
|
COREPACK_VERSION="$(sed -n "1p" /usr/local/share/uai/corepack-version)"; \
|
|
279
280
|
printf "%s" "$COREPACK_VERSION" | grep -Eq "^[0-9]+\\.[0-9]+\\.[0-9]+$"; \
|
|
280
|
-
npm install -g @anthropic-ai/claude-code "@openai/codex@$UAI_CODEX_CLI_VERSION" "corepack@$COREPACK_VERSION" \
|
|
281
|
+
npm install -g "@anthropic-ai/claude-code@$UAI_CLAUDE_CODE_VERSION" "@openai/codex@$UAI_CODEX_CLI_VERSION" "corepack@$COREPACK_VERSION" \
|
|
281
282
|
--registry=https://registry.npmjs.org/ \
|
|
282
283
|
--userconfig=/dev/null \
|
|
283
284
|
--globalconfig=/dev/uai-empty-npmrc; \
|
|
@@ -285,6 +286,7 @@ RUN bash -lc '\
|
|
|
285
286
|
curl -fsSL https://code-server.dev/install.sh | sh -s -- --method standalone --prefix /home/node/.local; \
|
|
286
287
|
asdf reshim nodejs; \
|
|
287
288
|
test "$(codex --version)" = "codex-cli $UAI_CODEX_CLI_VERSION"; \
|
|
289
|
+
test "$(claude --version)" = "$UAI_CLAUDE_CODE_VERSION (Claude Code)"; \
|
|
288
290
|
'
|
|
289
291
|
|
|
290
292
|
# Optional agent CLIs — installed ONLY when the host has them configured
|
|
@@ -371,16 +371,73 @@ if [ -f "$HOME/.ssh/id_ed25519.pub" ]; then
|
|
|
371
371
|
/usr/bin/git config --global tag.gpgsign true
|
|
372
372
|
fi
|
|
373
373
|
|
|
374
|
-
# Attribution policy: never co-author with the agents. Claude Code
|
|
375
|
-
# `
|
|
376
|
-
#
|
|
377
|
-
#
|
|
374
|
+
# Attribution policy: never co-author with the agents. Claude Code 2.x reads
|
|
375
|
+
# `attribution` ({commit,pr}: "" hides that attribution; sessionUrl: false drops
|
|
376
|
+
# the session link); older CLIs read the deprecated `includeCoAuthoredBy: false`.
|
|
377
|
+
# Both are MERGED into the user settings on every run: another writer (credential
|
|
378
|
+
# materialization, an image layer, a previous run) may have created the file
|
|
379
|
+
# first, and every other key in it is left exactly as found. Only a MISSING file
|
|
380
|
+
# is created. An existing file is left byte-for-byte alone (with a warning) when
|
|
381
|
+
# it is a symlink, not a regular file, or not exactly one JSON object (empty,
|
|
382
|
+
# whitespace-only and several concatenated documents all count as invalid).
|
|
383
|
+
# The result is written to an unpredictable, exclusively created (mktemp, 0600)
|
|
384
|
+
# sibling and renamed into place, so a pre-placed symlink cannot redirect the
|
|
385
|
+
# write, the file never gets a wider mode than it had (it may hold credentials
|
|
386
|
+
# in `env`), and the temp file is removed on every path. Codex is covered by the
|
|
378
387
|
# orchestrator's system preamble.
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
388
|
+
cc_dir="$HOME/.claude"
|
|
389
|
+
cc_settings="$cc_dir/settings.json"
|
|
390
|
+
cc_tmp=""
|
|
391
|
+
cc_skip() { log "warning: leaving $cc_settings untouched: $1"; }
|
|
392
|
+
cc_merge() {
|
|
393
|
+
jq -s '
|
|
394
|
+
if length == 1 and (.[0] | type) == "object" then .[0]
|
|
395
|
+
else error("not exactly one JSON object") end
|
|
396
|
+
| .includeCoAuthoredBy = false
|
|
397
|
+
| .attribution = (
|
|
398
|
+
(if (.attribution | type) == "object" then .attribution else {} end)
|
|
399
|
+
+ {commit: "", pr: "", sessionUrl: false}
|
|
400
|
+
)'
|
|
401
|
+
}
|
|
402
|
+
mkdir -p "$cc_dir" 2>/dev/null || true
|
|
403
|
+
if [ -L "$cc_settings" ]; then
|
|
404
|
+
cc_skip "it is a symlink"
|
|
405
|
+
elif [ -e "$cc_settings" ] && [ ! -f "$cc_settings" ]; then
|
|
406
|
+
cc_skip "it is not a regular file"
|
|
407
|
+
else
|
|
408
|
+
cc_tmp="$(umask 077; mktemp "$cc_dir/settings.json.XXXXXX" 2>/dev/null)" || cc_tmp=""
|
|
409
|
+
if [ -z "$cc_tmp" ]; then
|
|
410
|
+
cc_skip "could not create a temporary file in $cc_dir"
|
|
411
|
+
elif [ -e "$cc_settings" ]; then
|
|
412
|
+
if cc_merge < "$cc_settings" > "$cc_tmp" 2>/dev/null; then
|
|
413
|
+
if cmp -s "$cc_tmp" "$cc_settings"; then
|
|
414
|
+
:
|
|
415
|
+
else
|
|
416
|
+
# Same mode as the file being replaced (the temp file is 0600); never wider.
|
|
417
|
+
# If the mode cannot be copied, do not replace: the 0600 temp file would
|
|
418
|
+
# change the original's mode.
|
|
419
|
+
if ! chmod --reference="$cc_settings" "$cc_tmp" 2>/dev/null; then
|
|
420
|
+
cc_skip "could not copy its mode to the replacement"
|
|
421
|
+
elif mv -f "$cc_tmp" "$cc_settings" 2>/dev/null; then
|
|
422
|
+
cc_tmp=""
|
|
423
|
+
log "ensured ~/.claude/settings.json attribution policy (no co-author trailers)"
|
|
424
|
+
else
|
|
425
|
+
cc_skip "could not replace it"
|
|
426
|
+
fi
|
|
427
|
+
fi
|
|
428
|
+
else
|
|
429
|
+
cc_skip "not exactly one JSON object (or unreadable)"
|
|
430
|
+
fi
|
|
431
|
+
else
|
|
432
|
+
# Missing: create it, never replacing a file that appears meanwhile (ln fails if it exists).
|
|
433
|
+
if printf '{}' | cc_merge > "$cc_tmp" 2>/dev/null \
|
|
434
|
+
&& ln "$cc_tmp" "$cc_settings" 2>/dev/null; then
|
|
435
|
+
log "seeded ~/.claude/settings.json (no co-author trailers)"
|
|
436
|
+
else
|
|
437
|
+
cc_skip "could not create it"
|
|
438
|
+
fi
|
|
439
|
+
fi
|
|
440
|
+
[ -z "$cc_tmp" ] || rm -f -- "$cc_tmp"
|
|
384
441
|
fi
|
|
385
442
|
fi
|
|
386
443
|
|
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
|
|
946
|
-
//
|
|
947
|
-
if (
|
|
948
|
-
console.error('moondeck: crew
|
|
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
|
-
|
|
969
|
-
|
|
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
|
-
|
|
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] [--
|
|
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)",
|
package/lib/orchestrator.ts
CHANGED
|
@@ -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] [--
|
|
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",
|
|
@@ -602,6 +602,75 @@ async function seedEditorSettings(
|
|
|
602
602
|
});
|
|
603
603
|
}
|
|
604
604
|
|
|
605
|
+
/** Merge the no-co-author attribution policy into the machine's Claude user
|
|
606
|
+
* settings (machines do not run uai-init, which does the same for containers;
|
|
607
|
+
* keep the two in step). Only a MISSING file is created. An existing file is
|
|
608
|
+
* left byte-for-byte alone (exit 3, reason on stderr) when it is a symlink, not
|
|
609
|
+
* a regular file, or not exactly one JSON object (empty, whitespace-only and
|
|
610
|
+
* concatenated documents are all invalid). The result goes to an
|
|
611
|
+
* unpredictable, exclusively created (mode 0600) sibling and is renamed into
|
|
612
|
+
* place, so a pre-placed symlink cannot redirect the write, the file keeps its
|
|
613
|
+
* existing mode (it may hold credentials in env; never widened), and the temp
|
|
614
|
+
* file is removed on every path. */
|
|
615
|
+
const CLAUDE_ATTRIBUTION_MERGE_JS = `
|
|
616
|
+
const fs = require("fs"), path = require("path"), crypto = require("crypto");
|
|
617
|
+
const p = process.argv[1];
|
|
618
|
+
const dir = path.dirname(p);
|
|
619
|
+
const untouched = (why) => { console.error("leaving " + p + " untouched: " + why); process.exit(3); };
|
|
620
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
621
|
+
let st = null;
|
|
622
|
+
try { st = fs.lstatSync(p); } catch (e) { if (e.code !== "ENOENT") untouched(String(e.code)); }
|
|
623
|
+
if (st && st.isSymbolicLink()) untouched("it is a symlink");
|
|
624
|
+
if (st && !st.isFile()) untouched("it is not a regular file");
|
|
625
|
+
let s = {}, original = null;
|
|
626
|
+
if (st) {
|
|
627
|
+
try { original = fs.readFileSync(p, "utf8"); } catch (e) { untouched("unreadable"); }
|
|
628
|
+
try { s = JSON.parse(original); } catch (e) { untouched("not exactly one JSON object"); }
|
|
629
|
+
if (!s || typeof s !== "object" || Array.isArray(s)) untouched("not a JSON object");
|
|
630
|
+
}
|
|
631
|
+
s.includeCoAuthoredBy = false;
|
|
632
|
+
const a = s.attribution && typeof s.attribution === "object" && !Array.isArray(s.attribution) ? s.attribution : {};
|
|
633
|
+
s.attribution = { ...a, commit: "", pr: "", sessionUrl: false };
|
|
634
|
+
const out = JSON.stringify(s, null, 2) + "\\n";
|
|
635
|
+
if (out === original) process.exit(0);
|
|
636
|
+
const tmp = path.join(dir, "settings.json." + crypto.randomBytes(8).toString("hex") + ".tmp");
|
|
637
|
+
let fd = null, failed = null;
|
|
638
|
+
try {
|
|
639
|
+
fd = fs.openSync(tmp, "wx", 0o600);
|
|
640
|
+
fs.writeFileSync(fd, out);
|
|
641
|
+
fs.fchmodSync(fd, st ? st.mode & 0o777 : 0o600);
|
|
642
|
+
fs.closeSync(fd); fd = null;
|
|
643
|
+
if (st) fs.renameSync(tmp, p); else fs.linkSync(tmp, p);
|
|
644
|
+
} catch (e) {
|
|
645
|
+
failed = e;
|
|
646
|
+
} finally {
|
|
647
|
+
if (fd !== null) { try { fs.closeSync(fd); } catch (e) {} }
|
|
648
|
+
try { fs.unlinkSync(tmp); } catch (e) {}
|
|
649
|
+
}
|
|
650
|
+
if (failed) untouched(String(failed.code || failed.message));
|
|
651
|
+
`;
|
|
652
|
+
|
|
653
|
+
export async function ensureClaudeAttributionPolicy(
|
|
654
|
+
handle: TaskEnvironmentHandle<unknown>,
|
|
655
|
+
): Promise<void> {
|
|
656
|
+
const result = await handle.exec({
|
|
657
|
+
argv: [
|
|
658
|
+
"node",
|
|
659
|
+
"-e",
|
|
660
|
+
CLAUDE_ATTRIBUTION_MERGE_JS,
|
|
661
|
+
"/home/node/.claude/settings.json",
|
|
662
|
+
],
|
|
663
|
+
projectEnvProfile: "maintenance",
|
|
664
|
+
timeoutMs: GIT_STEP_TIMEOUT_MS,
|
|
665
|
+
maxOutputBytes: STEP_OUTPUT_BYTES,
|
|
666
|
+
});
|
|
667
|
+
if (result.exitCode !== 0) {
|
|
668
|
+
throw new Error(
|
|
669
|
+
`claude attribution merge exited ${result.exitCode}: ${Buffer.from(result.stderr).toString("utf8").trim()}`,
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
605
674
|
const execFileAsync = promisify(execFile);
|
|
606
675
|
/** Shared-files snapshots are reference docs, not repos; a tree past this
|
|
607
676
|
* is skipped with a warning rather than ballooning host memory. */
|
|
@@ -1204,6 +1273,18 @@ export function createMachineHostTaskEnvironmentProvider(
|
|
|
1204
1273
|
}
|
|
1205
1274
|
}
|
|
1206
1275
|
|
|
1276
|
+
// Attribution policy (no Claude co-author trailers) — uai-init does
|
|
1277
|
+
// this for containers; machines never run it. Best-effort.
|
|
1278
|
+
await stage(
|
|
1279
|
+
ensureClaudeAttributionPolicy(own).catch((error: unknown) => {
|
|
1280
|
+
console.warn(
|
|
1281
|
+
`[machine] task ${request.taskId}: claude attribution policy failed: ${
|
|
1282
|
+
error instanceof Error ? error.message : String(error)
|
|
1283
|
+
}`,
|
|
1284
|
+
);
|
|
1285
|
+
}),
|
|
1286
|
+
);
|
|
1287
|
+
|
|
1207
1288
|
// Editor pane: code-server on the machine (same flags as uai-init's
|
|
1208
1289
|
// container launch), idempotent across provision re-runs and resume.
|
|
1209
1290
|
// Best-effort — a missing binary degrades the Editor tab, never the task.
|
package/package.json
CHANGED
|
@@ -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/engine-models.ts
CHANGED
|
@@ -5,9 +5,11 @@
|
|
|
5
5
|
* here has no guide entry. Pure data: no runtime imports.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
// Claude Code's aliases, which follow its own model table
|
|
9
|
-
//
|
|
10
|
-
//
|
|
8
|
+
// Claude Code's aliases, which follow its own model table: fable = Claude
|
|
9
|
+
// Fable 5.2 as of Claude Code 2.1.321 (the images pin 2.1.322 via
|
|
10
|
+
// UAI_CLAUDE_CODE_VERSION; read 2026-11-10), opus = Opus 5.5, sonnet = Sonnet
|
|
11
|
+
// 5.5, haiku = Haiku 5.5. The CLI version decides which model an alias runs,
|
|
12
|
+
// so update this list and the pin together.
|
|
11
13
|
export const CLAUDE_MODELS: readonly string[] = ["fable", "opus", "sonnet", "haiku"];
|
|
12
14
|
|
|
13
15
|
// Codex model slugs accepted via `-c model=<slug>`. Keep the newest version of
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
3178
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
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
|
-
|
|
6452
|
-
|
|
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
|
-
*
|
|
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
|
+
}
|