overvues 0.0.1 → 0.4.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.
Files changed (78) hide show
  1. package/README.md +58 -2
  2. package/dist/ansi.js +24 -0
  3. package/dist/attach-client.js +586 -0
  4. package/dist/auth-connect-browser.js +112 -0
  5. package/dist/auth-connect.js +306 -0
  6. package/dist/browser-bootstrap.js +190 -0
  7. package/dist/browser-loopback.js +289 -0
  8. package/dist/build-identity.js +6 -0
  9. package/dist/codex-reviewer-apparmor.json +4 -0
  10. package/dist/codex-reviewer-seccomp.json +1238 -0
  11. package/dist/codex-runtime-protocol.js +1 -0
  12. package/dist/codex-subscription.js +53 -0
  13. package/dist/config.js +297 -0
  14. package/dist/connect-comparison-code.js +26 -0
  15. package/dist/development-runner.js +109 -0
  16. package/dist/dns-doctor.js +390 -0
  17. package/dist/docker-names.js +47 -0
  18. package/dist/doctor.js +114 -0
  19. package/dist/gadget-job.js +804 -0
  20. package/dist/health-check.js +112 -0
  21. package/dist/help.js +71 -0
  22. package/dist/host-auth.js +22 -0
  23. package/dist/host-diagnostics.js +20 -0
  24. package/dist/host-runtime-identity.js +39 -0
  25. package/dist/host-runtime-metadata.js +56 -0
  26. package/dist/host-service.js +377 -0
  27. package/dist/host-stack.js +484 -0
  28. package/dist/host-supervisor.js +237 -0
  29. package/dist/host-update.js +387 -0
  30. package/dist/hub-address.js +100 -0
  31. package/dist/hub-client.js +459 -0
  32. package/dist/hub-kind.js +88 -0
  33. package/dist/identity.js +73 -0
  34. package/dist/index.js +185 -0
  35. package/dist/init.js +295 -0
  36. package/dist/isolated-run-cache.js +116 -0
  37. package/dist/local-stack.js +685 -0
  38. package/dist/machine-capacity.js +128 -0
  39. package/dist/managed-runner-image.js +13 -0
  40. package/dist/os-acted-record.js +49 -0
  41. package/dist/os-adapter.js +8190 -0
  42. package/dist/os-command.js +292 -0
  43. package/dist/os-handoff.js +274 -0
  44. package/dist/os-keychain.js +247 -0
  45. package/dist/os-machine.js +818 -0
  46. package/dist/os-owner.js +61 -0
  47. package/dist/os-private-file.js +98 -0
  48. package/dist/os-protocol.js +468 -0
  49. package/dist/os-session-store.js +133 -0
  50. package/dist/os-status.js +102 -0
  51. package/dist/picker.js +863 -0
  52. package/dist/portable-workspace-capability.js +60 -0
  53. package/dist/project-environment-capability.js +62 -0
  54. package/dist/project-environment.js +28 -0
  55. package/dist/project-preparation.js +134 -0
  56. package/dist/readiness.js +28 -0
  57. package/dist/redaction.js +27 -0
  58. package/dist/reviewer-isolation-capability.js +61 -0
  59. package/dist/runner-api-auth.js +80 -0
  60. package/dist/runner-command-fence.js +536 -0
  61. package/dist/runner-inspection.js +57 -0
  62. package/dist/runner-inventory.js +587 -0
  63. package/dist/runner-server.js +2520 -0
  64. package/dist/runner-session.js +470 -0
  65. package/dist/runner-slug-folder.js +39 -0
  66. package/dist/runner-slug.js +40 -0
  67. package/dist/setup.js +139 -0
  68. package/dist/shutdown.js +102 -0
  69. package/dist/splash.js +65 -0
  70. package/dist/staged-workspaces.js +441 -0
  71. package/dist/staging-disk.js +97 -0
  72. package/dist/terminal-lane.js +339 -0
  73. package/dist/terminal-recovery.js +502 -0
  74. package/licenses/capnweb.txt +23 -0
  75. package/licenses/moby-profiles.txt +212 -0
  76. package/licenses/ws.txt +22 -0
  77. package/package.json +28 -7
  78. package/cli.js +0 -2
@@ -0,0 +1,237 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { CONFIG_PATH, HOME_DIR } from "./config.js";
5
+ import { getActiveSystemdServices, installSystemSystemdService, installUserSystemdService, resolveHostServiceCommand, restartSystemdService, stopSystemdService, systemSystemdUnitPath, userSystemdUnitPathForHome, } from "./host-service.js";
6
+ import { CLI, envVar } from "./identity.js";
7
+ export class HostSupervisorRestartError extends Error {
8
+ result;
9
+ constructor(message, result) {
10
+ super(message);
11
+ this.result = result;
12
+ this.name = "HostSupervisorRestartError";
13
+ }
14
+ }
15
+ // `dev.tiller.host` or `dev.overvues.host` (identity.ts), so the two programs keep separate LaunchAgents.
16
+ export const LAUNCHD_LABEL = CLI.launchdLabel;
17
+ export const LAUNCHD_FILE_NAME = `${LAUNCHD_LABEL}.plist`;
18
+ function run(command, args) {
19
+ const result = spawnSync(command, args, {
20
+ encoding: "utf8",
21
+ stdio: ["ignore", "pipe", "pipe"],
22
+ timeout: 15_000,
23
+ });
24
+ return {
25
+ ok: result.status === 0,
26
+ stdout: result.stdout?.trim() ?? "",
27
+ stderr: result.stderr?.trim() ?? "",
28
+ };
29
+ }
30
+ function xml(value) {
31
+ return value
32
+ .replaceAll("&", "&")
33
+ .replaceAll("<", "&lt;")
34
+ .replaceAll(">", "&gt;")
35
+ .replaceAll('"', "&quot;")
36
+ .replaceAll("'", "&apos;");
37
+ }
38
+ export function launchdPlistPath(homeDir = HOME_DIR) {
39
+ return resolve(homeDir, "Library", "LaunchAgents", LAUNCHD_FILE_NAME);
40
+ }
41
+ export function buildLaunchdPlist(options) {
42
+ const homeDir = options.homeDir ?? HOME_DIR;
43
+ const configPath = options.configPath ?? resolve(homeDir, ".config", CLI.configDirName, "config.json");
44
+ const logsDir = resolve(homeDir, "Library", "Logs");
45
+ const programArguments = [options.command, ...options.args]
46
+ .map((argument) => ` <string>${xml(argument)}</string>`)
47
+ .join("\n");
48
+ return [
49
+ '<?xml version="1.0" encoding="UTF-8"?>',
50
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
51
+ '<plist version="1.0">',
52
+ "<dict>",
53
+ " <key>Label</key>",
54
+ ` <string>${LAUNCHD_LABEL}</string>`,
55
+ " <key>ProgramArguments</key>",
56
+ " <array>",
57
+ programArguments,
58
+ " </array>",
59
+ " <key>EnvironmentVariables</key>",
60
+ " <dict>",
61
+ " <key>HOME</key>",
62
+ ` <string>${xml(homeDir)}</string>`,
63
+ " <key>PATH</key>",
64
+ ` <string>${xml(options.pathEnv ?? process.env.PATH ?? "")}</string>`,
65
+ ` <key>${envVar("CONFIG_PATH")}</key>`,
66
+ ` <string>${xml(configPath)}</string>`,
67
+ " </dict>",
68
+ " <key>WorkingDirectory</key>",
69
+ ` <string>${xml(homeDir)}</string>`,
70
+ " <key>RunAtLoad</key>",
71
+ " <true/>",
72
+ " <key>KeepAlive</key>",
73
+ " <true/>",
74
+ " <key>ProcessType</key>",
75
+ " <string>Background</string>",
76
+ " <key>StandardOutPath</key>",
77
+ ` <string>${xml(resolve(logsDir, CLI.hostLogFileName))}</string>`,
78
+ " <key>StandardErrorPath</key>",
79
+ ` <string>${xml(resolve(logsDir, CLI.hostLogFileName))}</string>`,
80
+ "</dict>",
81
+ "</plist>",
82
+ "",
83
+ ].join("\n");
84
+ }
85
+ class SystemdHostSupervisor {
86
+ scope;
87
+ options;
88
+ constructor(scope, options) {
89
+ this.scope = scope;
90
+ this.options = options;
91
+ }
92
+ inspect() {
93
+ const expectedDefinitionPath = this.scope === "user"
94
+ ? userSystemdUnitPathForHome(HOME_DIR)
95
+ : systemSystemdUnitPath();
96
+ const active = (this.options.getActiveSystemdServices ?? getActiveSystemdServices)().find((service) => service.scope === this.scope);
97
+ const definitionPath = active?.unitPath ?? expectedDefinitionPath;
98
+ return {
99
+ platform: "systemd",
100
+ installed: Boolean(active) || existsSync(definitionPath),
101
+ running: Boolean(active),
102
+ definitionPath,
103
+ serviceName: CLI.systemdServiceName,
104
+ scope: this.scope,
105
+ configPath: active?.configPath ?? null,
106
+ };
107
+ }
108
+ installOrUpdate() {
109
+ const installed = this.scope === "user"
110
+ ? (this.options.installUserSystemdService ?? installUserSystemdService)()
111
+ : (this.options.installSystemSystemdService ?? installSystemSystemdService)();
112
+ return {
113
+ ...this.inspect(),
114
+ installed: true,
115
+ definitionPath: installed.unitPath,
116
+ started: installed.started,
117
+ daemonReloaded: installed.daemonReloaded,
118
+ enabled: installed.enabled,
119
+ lingerEnabled: installed.lingerEnabled,
120
+ ...(installed.serviceUser ? { serviceUser: installed.serviceUser } : {}),
121
+ configPath: installed.configPath,
122
+ };
123
+ }
124
+ restart() {
125
+ const result = (this.options.restartSystemdService ?? restartSystemdService)(this.scope);
126
+ if (!result.ok) {
127
+ throw new HostSupervisorRestartError(`Could not restart ${result.command}${result.stderr ? `: ${result.stderr}` : ""}`, result);
128
+ }
129
+ return this.inspect();
130
+ }
131
+ stop() {
132
+ const result = (this.options.stopSystemdService ?? stopSystemdService)(this.scope);
133
+ if (!result.ok) {
134
+ throw new Error(`Could not stop ${result.command}${result.stderr ? `: ${result.stderr}` : ""}`);
135
+ }
136
+ return this.inspect();
137
+ }
138
+ }
139
+ class LaunchdHostSupervisor {
140
+ options;
141
+ domain = `gui/${typeof process.getuid === "function" ? process.getuid() : 0}`;
142
+ definitionPath = launchdPlistPath();
143
+ constructor(options) {
144
+ this.options = options;
145
+ }
146
+ inspect() {
147
+ const status = run("launchctl", ["print", `${this.domain}/${LAUNCHD_LABEL}`]);
148
+ return {
149
+ platform: "launchd",
150
+ installed: existsSync(this.definitionPath),
151
+ running: status.ok,
152
+ definitionPath: this.definitionPath,
153
+ serviceName: LAUNCHD_LABEL,
154
+ configPath: this.options.configPath ?? CONFIG_PATH,
155
+ };
156
+ }
157
+ installOrUpdate() {
158
+ const command = resolveHostServiceCommand();
159
+ mkdirSync(resolve(HOME_DIR, "Library", "LaunchAgents"), { recursive: true });
160
+ mkdirSync(resolve(HOME_DIR, "Library", "Logs"), { recursive: true });
161
+ writeFileSync(this.definitionPath, buildLaunchdPlist({
162
+ command: command.command,
163
+ args: command.args,
164
+ homeDir: HOME_DIR,
165
+ pathEnv: process.env.PATH ?? "",
166
+ configPath: this.options.configPath ?? CONFIG_PATH,
167
+ }), { mode: 0o600 });
168
+ run("launchctl", ["bootout", `${this.domain}/${LAUNCHD_LABEL}`]);
169
+ const bootstrap = run("launchctl", ["bootstrap", this.domain, this.definitionPath]);
170
+ if (!bootstrap.ok) {
171
+ throw new Error(`Could not install ${LAUNCHD_LABEL}${bootstrap.stderr ? `: ${bootstrap.stderr}` : ""}`);
172
+ }
173
+ const kickstart = run("launchctl", ["kickstart", "-k", `${this.domain}/${LAUNCHD_LABEL}`]);
174
+ return {
175
+ ...this.inspect(),
176
+ installed: true,
177
+ started: kickstart.ok,
178
+ };
179
+ }
180
+ restart() {
181
+ const result = run("launchctl", ["kickstart", "-k", `${this.domain}/${LAUNCHD_LABEL}`]);
182
+ if (!result.ok) {
183
+ throw new Error(`Could not restart ${LAUNCHD_LABEL}${result.stderr ? `: ${result.stderr}` : ""}`);
184
+ }
185
+ return this.inspect();
186
+ }
187
+ stop() {
188
+ const result = run("launchctl", ["bootout", `${this.domain}/${LAUNCHD_LABEL}`]);
189
+ if (!result.ok) {
190
+ throw new Error(`Could not stop ${LAUNCHD_LABEL}${result.stderr ? `: ${result.stderr}` : ""}`);
191
+ }
192
+ return this.inspect();
193
+ }
194
+ }
195
+ export function createHostSupervisor(platform = process.platform, options = {}) {
196
+ if (platform === "linux") {
197
+ return new SystemdHostSupervisor(options.systemdScope ?? "user", options);
198
+ }
199
+ if (platform === "darwin")
200
+ return new LaunchdHostSupervisor(options);
201
+ throw new Error("Persistent execution-machine services are supported on Linux and macOS.");
202
+ }
203
+ export function selectHostSupervisor(platform = process.platform, options = {}) {
204
+ if (platform !== "linux") {
205
+ return createHostSupervisor(platform, options);
206
+ }
207
+ const activeServices = (options.getActiveSystemdServices ?? getActiveSystemdServices)();
208
+ const sharedOptions = {
209
+ ...options,
210
+ getActiveSystemdServices: () => activeServices,
211
+ };
212
+ const candidates = ["user", "system"].map((scope) => {
213
+ const supervisor = createHostSupervisor(platform, {
214
+ ...sharedOptions,
215
+ systemdScope: scope,
216
+ });
217
+ return { scope, supervisor, inspection: supervisor.inspect() };
218
+ });
219
+ const installed = candidates.filter((candidate) => candidate.inspection.installed);
220
+ if (installed.length > 1) {
221
+ throw new Error(`Both user and system ${CLI.systemdServiceName.replace(/\.service$/, "")} services are installed. Remove one before continuing.`);
222
+ }
223
+ const preferredScope = options.preferredSystemdScope;
224
+ if (preferredScope
225
+ && installed.length === 1
226
+ && installed[0].scope !== preferredScope) {
227
+ throw new Error(`A ${installed[0].scope} ${CLI.systemdServiceName.replace(/\.service$/, "")} service is already installed. Reuse it or remove it before installing a ${preferredScope} service.`);
228
+ }
229
+ const scope = preferredScope
230
+ ?? installed[0]?.scope
231
+ ?? options.systemdScope
232
+ ?? "user";
233
+ return createHostSupervisor(platform, {
234
+ ...options,
235
+ systemdScope: scope,
236
+ });
237
+ }
@@ -0,0 +1,387 @@
1
+ import { stdin as input, stdout as output } from "node:process";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { resolve } from "node:path";
4
+ import { ansi } from "./ansi.js";
5
+ import { HOST_PACKAGE_VERSION } from "./host-runtime-identity.js";
6
+ import { CONFIG_PATH, DEFAULT_LOCAL_RUNNER_IMAGE, HUB_URL, isLocalHubUrl, loadConfig, loadedDotEnvValues, reloadConfig, writeConfig, } from "./config.js";
7
+ import { hubParentDomainsText, isAllowedHubUrl } from "./hub-address.js";
8
+ import { getActiveSystemdServices, restartSystemdService, } from "./host-service.js";
9
+ import { readActiveHostPidRecord } from "./host-stack.js";
10
+ import { checkLocalRunnerHealth, pullLocalRunnerImage, } from "./local-stack.js";
11
+ import { HostSupervisorRestartError, selectHostSupervisor, } from "./host-supervisor.js";
12
+ import { isManagedLocalRunnerImageRef, } from "./managed-runner-image.js";
13
+ import { fetchHostUpdateCheck, resolveHostUpdateTargetImage, } from "./host-runtime-metadata.js";
14
+ import { CLI, envVar } from "./identity.js";
15
+ export { isManagedLocalRunnerImageRef, parseManagedLocalRunnerImageSourceId, } from "./managed-runner-image.js";
16
+ function hostLog(message) {
17
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${message}\n`);
18
+ }
19
+ function normalizeUrl(value) {
20
+ return (value ?? "").trim().replace(/\/+$/, "");
21
+ }
22
+ function normalizeImageRef(value) {
23
+ return (value ?? "").trim() || DEFAULT_LOCAL_RUNNER_IMAGE;
24
+ }
25
+ function pathsEqual(left, right) {
26
+ return resolve(left) === resolve(right);
27
+ }
28
+ function validateExpectedTarget(target) {
29
+ if (!target || typeof target.releaseId !== "string" || !/^[a-f0-9]{40}$/.test(target.releaseId) || /^0{40}$/.test(target.releaseId) ||
30
+ typeof target.packageVersion !== "string" || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(target.packageVersion) || target.packageVersion.length > 100 ||
31
+ typeof target.runtimeImage !== "string" || !/^docker\.io\/jamieatlason\/tiller-sandbox@sha256:[a-f0-9]{64}$/.test(target.runtimeImage)) {
32
+ throw new Error("Expected host update target requires an exact release ID, digest-pinned managed runtime image, and CLI package version.");
33
+ }
34
+ return { releaseId: target.releaseId, runtimeImage: target.runtimeImage, packageVersion: target.packageVersion };
35
+ }
36
+ export function parseHostUpdateArgs(argv) {
37
+ const options = {};
38
+ const target = {};
39
+ const targetFlags = {
40
+ "--expect-release-id": "releaseId", "--expect-runtime-image": "runtimeImage", "--expect-cli-version": "packageVersion",
41
+ };
42
+ for (let index = 0; index < argv.length; index++) {
43
+ const arg = argv[index];
44
+ if (arg === "--dry-run") {
45
+ options.dryRun = true;
46
+ continue;
47
+ }
48
+ if (arg === "--yes" || arg === "-y") {
49
+ options.yes = true;
50
+ continue;
51
+ }
52
+ const separator = arg.indexOf("=");
53
+ const flag = separator === -1 ? arg : arg.slice(0, separator);
54
+ const field = targetFlags[flag];
55
+ if (Object.hasOwn(targetFlags, flag)) {
56
+ const value = separator === -1 ? argv[++index] : arg.slice(separator + 1);
57
+ if (!value || value.startsWith("-") || value !== value.trim())
58
+ throw new Error(`${flag} requires an exact value`);
59
+ if (target[field] !== undefined)
60
+ throw new Error(`${flag} may only be supplied once`);
61
+ target[field] = value;
62
+ continue;
63
+ }
64
+ throw new Error(`Unknown host update option: ${arg}`);
65
+ }
66
+ if (Object.keys(target).length)
67
+ options.expectedTarget = validateExpectedTarget(target);
68
+ return options;
69
+ }
70
+ export function describeLocalRunnerImageOverride(env, dotenvValues) {
71
+ const name = envVar("LOCAL_RUNNER_IMAGE");
72
+ const value = env[name]?.trim();
73
+ if (!value)
74
+ return null;
75
+ const dotenv = dotenvValues[name];
76
+ if (dotenv) {
77
+ return `${name} is set by ${dotenv.path}. Remove that .env override before running \`${CLI.command} host update\`.`;
78
+ }
79
+ return `${name} is set in the shell environment. Unset it before running \`${CLI.command} host update\`.`;
80
+ }
81
+ async function defaultConfirm(message) {
82
+ if (!input.isTTY || !output.isTTY) {
83
+ return false;
84
+ }
85
+ const rl = createInterface({ input, output });
86
+ try {
87
+ const answer = (await rl.question(`${message} [y/N] `)).trim().toLowerCase();
88
+ return answer === "y" || answer === "yes";
89
+ }
90
+ finally {
91
+ rl.close();
92
+ }
93
+ }
94
+ function buildServiceBlockers(activeServices, configPath) {
95
+ if (activeServices.length > 1) {
96
+ return [`Both the user and system ${CLI.systemdServiceName.replace(/\.service$/, "")} systemd services are active. Stop one service before running \`${CLI.command} host update\`.`];
97
+ }
98
+ return activeServices.flatMap((service) => {
99
+ if (!service.configPath) {
100
+ return [`Could not determine which config path the active ${service.scope} systemd service reads. Reinstall the service or stop it before running \`${CLI.command} host update\`.`];
101
+ }
102
+ if (!pathsEqual(service.configPath, configPath)) {
103
+ return [
104
+ `The active ${service.scope} systemd service reads ${service.configPath}, but this command would update ${configPath}. Run \`${CLI.command} host update\` as the service user so it updates the service config.`,
105
+ ];
106
+ }
107
+ return [];
108
+ });
109
+ }
110
+ function describeServiceState(activeServices) {
111
+ if (activeServices.length === 0)
112
+ return "none active";
113
+ return activeServices
114
+ .map((service) => `${service.scope} active${service.configPath ? ` [config ${service.configPath}]` : " [config unknown]"}`)
115
+ .join(", ");
116
+ }
117
+ function describeManualProcess(manualHost) {
118
+ return manualHost ? `active [pid ${manualHost.pid}]` : "not detected";
119
+ }
120
+ function describeRestartAction(activeServices, manualHost) {
121
+ if (activeServices.length === 1) {
122
+ const service = activeServices[0];
123
+ return service.scope === "user"
124
+ ? "restart active user systemd service"
125
+ : "restart active system systemd service when root or passwordless sudo is available; otherwise print manual restart instructions";
126
+ }
127
+ if (manualHost) {
128
+ return `manual restart required for the active \`${CLI.command} host\` process`;
129
+ }
130
+ return `no active host process; start \`${CLI.command} host\` when ready`;
131
+ }
132
+ function printDryRun(options) {
133
+ options.log("Host runtime update dry run");
134
+ options.log(`config path: ${options.configPath}`);
135
+ options.log(`current image: ${options.currentImage}`);
136
+ options.log(`target image: ${options.targetImage}`);
137
+ if (options.expectedTarget) {
138
+ options.log(`expected published release: ${options.expectedTarget.releaseId}`);
139
+ options.log(`required CLI package: ${options.expectedTarget.packageVersion}; invoking CLI: ${HOST_PACKAGE_VERSION}`);
140
+ }
141
+ options.log("CLI package: unchanged; install the required package version separately if needed");
142
+ options.log("workload containers: unchanged");
143
+ options.log(`systemd services: ${describeServiceState(options.activeServices)}`);
144
+ if (options.supervisor) {
145
+ options.log(`${options.supervisor.platform} service: ${options.supervisor.installed ? "installed" : "not installed"}, ${options.supervisor.running ? "running" : "not running"}`);
146
+ }
147
+ options.log(`manual host process: ${describeManualProcess(options.manualHost)}`);
148
+ options.log(`restart action: ${describeRestartAction(options.activeServices, options.manualHost)}`);
149
+ if (options.blockers.length > 0) {
150
+ options.log("blockers:");
151
+ for (const blocker of options.blockers) {
152
+ options.log(`- ${blocker}`);
153
+ }
154
+ }
155
+ }
156
+ async function waitForRequiredHealth(label, check, targetImage, previousInstanceId, timeoutMs = 30_000) {
157
+ const deadline = Date.now() + timeoutMs;
158
+ let lastDetail = "not ready";
159
+ while (Date.now() < deadline) {
160
+ const result = await check();
161
+ if (result.ok && result.identity?.runtimeImage === targetImage && result.identity.packageVersion === HOST_PACKAGE_VERSION &&
162
+ result.identity.instanceId !== previousInstanceId)
163
+ return result.identity;
164
+ lastDetail = !result.ok ? result.detail ?? "not ready" : !result.identity
165
+ ? "running host does not report its identity; install the required CLI package and restart it"
166
+ : result.identity.instanceId === previousInstanceId ? "the previous host process is still responding"
167
+ : `running package/runtime does not match ${HOST_PACKAGE_VERSION} / ${targetImage}`;
168
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 500));
169
+ }
170
+ throw new Error(`${label} health check failed after restart: ${lastDetail}`);
171
+ }
172
+ function printManualRestartInstructions(log, activeService, manualHost) {
173
+ log("Action required on this computer. The runtime image is ready, but the running host has not been verified on the target.");
174
+ if (activeService?.scope === "system") {
175
+ log("Runtime refreshed. Restart the system service manually:");
176
+ log(` sudo systemctl restart ${activeService.serviceName}`);
177
+ log(` journalctl -u ${activeService.serviceName} -f`);
178
+ return;
179
+ }
180
+ if (manualHost) {
181
+ log(`Runtime refreshed. Restart the active \`${CLI.command} host\` process [pid ${manualHost.pid}] manually.`);
182
+ return;
183
+ }
184
+ log(`Runtime refreshed. Start \`${CLI.command} host\` when you want this machine to serve workloads.`);
185
+ }
186
+ async function runPostRestartHealthChecks(deps) {
187
+ const identity = await waitForRequiredHealth("Local runner", deps.checkLocalRunnerHealth, deps.targetImage, deps.previousInstanceId);
188
+ deps.log("restarted host reports the requested runtime and installed CLI version; existing workload containers remain unchanged");
189
+ return identity;
190
+ }
191
+ export async function runHostUpdate(options = {}, deps = {}) {
192
+ const expectedTarget = options.expectedTarget === undefined ? undefined : validateExpectedTarget(options.expectedTarget);
193
+ const log = deps.log ?? hostLog;
194
+ const env = deps.env ?? process.env;
195
+ const configPath = deps.configPath ?? CONFIG_PATH;
196
+ const dotenvValues = deps.loadedDotEnvValues ?? loadedDotEnvValues;
197
+ const readConfig = deps.loadConfig ?? loadConfig;
198
+ const saveConfig = deps.writeConfig ?? writeConfig;
199
+ const refreshConfig = deps.reloadConfig ?? reloadConfig;
200
+ const fetchUpdateCheck = deps.fetchUpdateCheck ?? fetchHostUpdateCheck;
201
+ const platform = deps.platform ?? process.platform;
202
+ const activeServices = platform === "linux"
203
+ ? (deps.getActiveSystemdServices ?? getActiveSystemdServices)()
204
+ : [];
205
+ const supervisor = platform === "linux" || platform === "darwin"
206
+ ? (deps.hostSupervisor
207
+ ?? (activeServices.length > 1
208
+ ? null
209
+ : selectHostSupervisor(platform, {
210
+ ...(activeServices[0]?.scope
211
+ ? { preferredSystemdScope: activeServices[0].scope }
212
+ : {}),
213
+ getActiveSystemdServices: () => activeServices,
214
+ restartSystemdService: deps.restartSystemdService ?? restartSystemdService,
215
+ })))
216
+ : null;
217
+ const supervisorInspection = supervisor?.inspect() ?? null;
218
+ const manualHost = activeServices.length === 0 && !supervisorInspection?.running
219
+ ? (deps.readActiveHostPidRecord ?? readActiveHostPidRecord)()
220
+ : null;
221
+ const config = readConfig();
222
+ const hubUrl = normalizeUrl(options.hubUrlOverride || env[CLI.hubUrlEnv] || config.hubUrl || HUB_URL);
223
+ const overrideBlocker = describeLocalRunnerImageOverride(env, dotenvValues);
224
+ const blockers = [];
225
+ if (expectedTarget && expectedTarget.packageVersion !== HOST_PACKAGE_VERSION) {
226
+ blockers.push(`This update requires CLI ${expectedTarget.packageVersion}, but the invoking CLI is ${HOST_PACKAGE_VERSION}. Install ${CLI.npmPackage}@${expectedTarget.packageVersion} using this installation's package management, then rerun the same guarded command. No runtime or service was changed.`);
227
+ }
228
+ if (overrideBlocker) {
229
+ blockers.push(overrideBlocker);
230
+ }
231
+ if (!hubUrl) {
232
+ blockers.push(`Hub URL required. Run \`${CLI.command} host setup\` first, or add hubUrl to ${configPath}.`);
233
+ }
234
+ else if (!isAllowedHubUrl(hubUrl) && !isLocalHubUrl(hubUrl)) {
235
+ blockers.push(`The saved Hub URL is not an exact https Hub origin under ${hubParentDomainsText()}. Run `
236
+ + `\`${CLI.command} host setup --hub-url https://<exact-host>.workers.dev\`.`);
237
+ }
238
+ const updateCheck = hubUrl && blockers.length === 0
239
+ ? await fetchUpdateCheck(hubUrl)
240
+ : null;
241
+ const advertisedImage = updateCheck ? resolveHostUpdateTargetImage(updateCheck.currentRelease) : null;
242
+ const targetImage = expectedTarget?.runtimeImage ?? advertisedImage ?? "(unavailable until hub URL is configured)";
243
+ if (expectedTarget && updateCheck && (updateCheck.currentRelease.channel !== "release" ||
244
+ updateCheck.currentRelease.releaseId !== expectedTarget.releaseId || advertisedImage !== expectedTarget.runtimeImage)) {
245
+ blockers.push(`The Hub does not advertise the selected published release and runtime image. This guarded command will not select a different target. Resume or reconcile the same coordinated update before retrying; a development hub is followed with \`${CLI.command} host update\` and no selected target.`);
246
+ }
247
+ const currentImage = normalizeImageRef(config.localRunnerImage);
248
+ const imageChanged = currentImage !== targetImage;
249
+ if (!isManagedLocalRunnerImageRef(currentImage)) {
250
+ blockers.push(`${CLI.command} host update cannot safely manage custom images. The configured localRunnerImage is ${currentImage}. Remove the custom image or update it manually.`);
251
+ }
252
+ if (platform === "linux") {
253
+ blockers.push(...buildServiceBlockers(activeServices, configPath));
254
+ }
255
+ else if (platform !== "darwin") {
256
+ blockers.push("Persistent execution-machine services are supported on Linux and macOS.");
257
+ }
258
+ if (options.dryRun) {
259
+ printDryRun({
260
+ log,
261
+ configPath,
262
+ currentImage,
263
+ targetImage,
264
+ activeServices,
265
+ supervisor: supervisorInspection,
266
+ manualHost,
267
+ blockers,
268
+ expectedTarget,
269
+ });
270
+ return {
271
+ ok: blockers.length === 0,
272
+ changed: false,
273
+ targetImage,
274
+ blockers,
275
+ restart: "not-attempted",
276
+ };
277
+ }
278
+ if (blockers.length > 0) {
279
+ return {
280
+ ok: false,
281
+ changed: false,
282
+ targetImage,
283
+ blockers,
284
+ restart: "not-attempted",
285
+ };
286
+ }
287
+ if (!options.yes) {
288
+ const confirmed = await (deps.confirm ?? defaultConfirm)(imageChanged
289
+ ? `Update the execution-machine runtime image from ${currentImage} to ${targetImage}? Existing workloads keep their current containers.`
290
+ : `Refresh the execution-machine service at ${targetImage}? Existing workloads keep their current containers.`);
291
+ if (!confirmed) {
292
+ throw new Error("Update cancelled. Re-run with `--yes` to confirm non-interactively.");
293
+ }
294
+ }
295
+ await (deps.pullImage ?? pullLocalRunnerImage)(targetImage);
296
+ const currentRelease = (await fetchUpdateCheck(hubUrl)).currentRelease;
297
+ if (resolveHostUpdateTargetImage(currentRelease) !== targetImage || currentRelease.hubVersion !== updateCheck?.currentRelease.hubVersion ||
298
+ currentRelease.releaseId !== updateCheck?.currentRelease.releaseId || currentRelease.channel !== updateCheck?.currentRelease.channel) {
299
+ return { ok: false, changed: false, targetImage, restart: "not-attempted",
300
+ blockers: ["The Hub release changed while preparing this update. The downloaded image is retained, but configuration and services were not changed. Refresh the coordinated update before retrying."] };
301
+ }
302
+ const latestConfig = readConfig();
303
+ if (normalizeImageRef(latestConfig.localRunnerImage) !== currentImage || normalizeUrl(latestConfig.hubUrl) !== normalizeUrl(config.hubUrl) ||
304
+ latestConfig.machineId !== config.machineId || latestConfig.localRunnerPort !== config.localRunnerPort) {
305
+ return { ok: false, changed: false, targetImage, restart: "not-attempted",
306
+ blockers: ["Host configuration changed while preparing this update. Nothing was overwritten; inspect the current configuration before retrying."] };
307
+ }
308
+ if (imageChanged) {
309
+ saveConfig({
310
+ ...latestConfig,
311
+ localRunnerImage: targetImage,
312
+ });
313
+ refreshConfig();
314
+ log(`pinned localRunnerImage to ${targetImage}`);
315
+ }
316
+ else {
317
+ log(`localRunnerImage already pinned to ${targetImage}`);
318
+ }
319
+ log("existing workload containers were left unchanged");
320
+ log("CLI package was left unchanged; install the required package version separately if needed");
321
+ if (supervisor && supervisorInspection?.installed) {
322
+ const check = deps.checkLocalRunnerHealth ?? checkLocalRunnerHealth;
323
+ const previous = await check();
324
+ try {
325
+ supervisor.restart();
326
+ }
327
+ catch (error) {
328
+ if (supervisorInspection.platform === "systemd"
329
+ && supervisorInspection.scope === "system"
330
+ && error instanceof HostSupervisorRestartError) {
331
+ if (error.result.stderr) {
332
+ log(`${ansi.yellow}Could not restart system service automatically: ${error.result.stderr}${ansi.reset}`);
333
+ }
334
+ else {
335
+ log(`${ansi.yellow}Could not restart system service automatically.${ansi.reset}`);
336
+ }
337
+ printManualRestartInstructions(log, activeServices[0] ?? null, null);
338
+ return {
339
+ ok: true,
340
+ changed: true,
341
+ targetImage,
342
+ blockers: [],
343
+ restart: "manual-required",
344
+ };
345
+ }
346
+ throw error;
347
+ }
348
+ log(`restarted ${supervisorInspection.platform} service`);
349
+ const runningHost = await runPostRestartHealthChecks({
350
+ log,
351
+ checkLocalRunnerHealth: check,
352
+ targetImage,
353
+ previousInstanceId: previous.identity?.instanceId,
354
+ });
355
+ return {
356
+ ok: true,
357
+ changed: true,
358
+ targetImage,
359
+ blockers: [],
360
+ restart: "verified",
361
+ runningHost,
362
+ };
363
+ }
364
+ const activeService = activeServices[0] ?? null;
365
+ if (!activeService) {
366
+ printManualRestartInstructions(log, null, manualHost);
367
+ return {
368
+ ok: true,
369
+ changed: true,
370
+ targetImage,
371
+ blockers: [],
372
+ restart: "manual-required",
373
+ };
374
+ }
375
+ throw new Error(`The active ${activeService.scope} systemd service could not be inspected through the host supervisor.`);
376
+ }
377
+ export async function runHostUpdateCommand(options = {}) {
378
+ const result = await runHostUpdate(options);
379
+ if (!result.ok) {
380
+ if (!options.dryRun) {
381
+ for (const blocker of result.blockers) {
382
+ hostLog(`${ansi.red}${blocker}${ansi.reset}`);
383
+ }
384
+ }
385
+ process.exitCode = 1;
386
+ }
387
+ }