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 @@
1
+ export const CODEX_RUNTIME_AUTH_PROTOCOL = 1;
@@ -0,0 +1,53 @@
1
+ import { HUB_URL, hubControlHeaders, } from "./config.js";
2
+ import { CLI } from "./identity.js";
3
+ export class HubSetupStatusError extends Error {
4
+ code;
5
+ status;
6
+ constructor(code, message, status) {
7
+ super(message);
8
+ this.name = "HubSetupStatusError";
9
+ this.code = code;
10
+ this.status = status;
11
+ }
12
+ }
13
+ export async function fetchHubSetupStatus(hubUrl = HUB_URL, headers = hubControlHeaders) {
14
+ const response = await fetch(`${hubUrl}/api/setup/status`, {
15
+ headers: {
16
+ Accept: "application/json",
17
+ ...headers,
18
+ },
19
+ });
20
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
21
+ const raw = await response.text();
22
+ if (!response.ok) {
23
+ if (response.status === 401 || response.status === 403) {
24
+ throw new HubSetupStatusError("auth-required", `This machine's hub credential no longer works. Connect it again with \`${CLI.command} host setup\`.`, response.status);
25
+ }
26
+ throw new HubSetupStatusError("http-error", `Failed to fetch setup status: ${response.status}`, response.status);
27
+ }
28
+ if (!contentType.includes("application/json")) {
29
+ // The sign-in gate sends a page, not JSON, to a caller it does not know.
30
+ const looksLikeAccessLogin = contentType.includes("text/html")
31
+ || /<html/i.test(raw);
32
+ throw new HubSetupStatusError(looksLikeAccessLogin ? "auth-required" : "invalid-response", looksLikeAccessLogin
33
+ ? `This machine's hub credential no longer works. Connect it again with \`${CLI.command} host setup\`.`
34
+ : "The hub returned an unexpected response while reading setup status.", response.status);
35
+ }
36
+ try {
37
+ const parsed = JSON.parse(raw);
38
+ if (!parsed
39
+ || typeof parsed !== "object"
40
+ || !Array.isArray(parsed.enabledHarnesses)
41
+ || typeof parsed.hostRegistered !== "boolean"
42
+ || typeof parsed.hostConnected !== "boolean") {
43
+ throw new Error("invalid setup status");
44
+ }
45
+ return parsed;
46
+ }
47
+ catch {
48
+ throw new HubSetupStatusError("invalid-response", "The hub returned malformed setup status JSON.", response.status);
49
+ }
50
+ }
51
+ export function isHubSetupStatusAuthError(error) {
52
+ return error instanceof HubSetupStatusError && error.code === "auth-required";
53
+ }
package/dist/config.js ADDED
@@ -0,0 +1,297 @@
1
+ import { hostname } from "node:os";
2
+ import { resolve } from "node:path";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { hubParentDomainsText, isAllowedHubUrl } from "./hub-address.js";
5
+ import { CLI, envVar } from "./identity.js";
6
+ export const HOME_DIR = process.env.HOME || process.env.USERPROFILE || "~";
7
+ // TILLER_CONFIG_DIR (OVERVUES_CONFIG_DIR for `overvues`) selects another runner
8
+ // profile (the startup bench runner uses ~/.config/tiller-bench): its config,
9
+ // .env and local state dir. The default is this program's own folder,
10
+ // ~/.config/tiller or ~/.config/overvues (identity.ts).
11
+ const CONFIG_DIR_ENV = envVar("CONFIG_DIR");
12
+ export const TILLER_CONFIG_DIR = process.env[CONFIG_DIR_ENV]?.trim()
13
+ ? resolve(process.env[CONFIG_DIR_ENV].trim())
14
+ : resolve(HOME_DIR, ".config", CLI.configDirName);
15
+ export const LOCAL_STATE_DIR = resolve(TILLER_CONFIG_DIR, "local");
16
+ export const CONFIG_PATH = process.env[envVar("CONFIG_PATH")] || resolve(TILLER_CONFIG_DIR, "config.json");
17
+ function parseDotEnv(content) {
18
+ const values = {};
19
+ for (const line of content.split(/\r?\n/)) {
20
+ const trimmed = line.trim();
21
+ if (!trimmed || trimmed.startsWith("#"))
22
+ continue;
23
+ const separator = trimmed.indexOf("=");
24
+ if (separator < 0)
25
+ continue;
26
+ const key = trimmed.slice(0, separator).trim();
27
+ if (!key)
28
+ continue;
29
+ let value = trimmed.slice(separator + 1).trim();
30
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
31
+ value = value.slice(1, -1);
32
+ }
33
+ values[key] = value;
34
+ }
35
+ return values;
36
+ }
37
+ export const loadedDotEnvValues = {};
38
+ /**
39
+ * The `.env` files `tiller` reads: the one `TILLER_DOTENV_PATH` names in the
40
+ * process environment (the installed service sets it) and the one in
41
+ * `tiller`'s own config folder, which only its owner can write.
42
+ *
43
+ * A `.env` in the folder `tiller` happens to be run from is never read. A
44
+ * file there can set any variable, and a project folder is written by
45
+ * agents and by whoever a repository was cloned from: `HUB_URL` would decide
46
+ * where this machine's credentials are sent, `TILLER_HUB_PARENT_DOMAINS`
47
+ * which addresses are accepted at all, and others which image, program or
48
+ * login is used.
49
+ */
50
+ export function dotEnvCandidates(env = process.env, configDir = TILLER_CONFIG_DIR) {
51
+ return [
52
+ env[envVar("DOTENV_PATH")],
53
+ resolve(configDir, ".env"),
54
+ ].filter((value) => Boolean(value && value.trim()));
55
+ }
56
+ function loadDotEnv() {
57
+ const candidates = dotEnvCandidates();
58
+ for (const candidate of candidates) {
59
+ if (!existsSync(candidate))
60
+ continue;
61
+ const parsed = parseDotEnv(readFileSync(candidate, "utf-8"));
62
+ for (const [key, value] of Object.entries(parsed)) {
63
+ if (process.env[key] == null) {
64
+ process.env[key] = value;
65
+ loadedDotEnvValues[key] = { path: candidate, value };
66
+ }
67
+ }
68
+ }
69
+ }
70
+ loadDotEnv();
71
+ function parseInteger(value, fallback) {
72
+ if (!value)
73
+ return fallback;
74
+ const parsed = Number.parseInt(value, 10);
75
+ return Number.isFinite(parsed) ? parsed : fallback;
76
+ }
77
+ function normalizeUrl(value) {
78
+ return (value ?? "").trim().replace(/\/+$/, "");
79
+ }
80
+ export function isMachineUuid(value) {
81
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
82
+ .test(value.trim());
83
+ }
84
+ export function normalizeTillerConfig(value) {
85
+ if (!value || typeof value !== "object" || Array.isArray(value))
86
+ return {};
87
+ const source = value;
88
+ const string = (key) => {
89
+ const candidate = source[key];
90
+ return typeof candidate === "string" && candidate.trim() ? candidate.trim() : undefined;
91
+ };
92
+ const configuredHubUrl = string("hubUrl");
93
+ const hubUrl = configuredHubUrl ? normalizeUrl(configuredHubUrl) : undefined;
94
+ const localRunnerPort = source.localRunnerPort;
95
+ const normalized = { ...source };
96
+ for (const key of [
97
+ "gatewayPort",
98
+ "cloudflaredConfigPath",
99
+ "gatewayTunnelName",
100
+ "gatewayTunnelId",
101
+ "gatewayTunnelToken",
102
+ "gatewayTargetPort",
103
+ "gatewayHostname",
104
+ "gatewayServiceToken",
105
+ "tunnelToken",
106
+ "codexGatewayAuthMode",
107
+ "selfHostSetupAttemptId",
108
+ "selfHostEnableToken",
109
+ "customDomainAttempt",
110
+ "promotion",
111
+ "namespace",
112
+ "publicHub",
113
+ "hostnameIdentity",
114
+ "machineHostname",
115
+ ]) {
116
+ delete normalized[key];
117
+ }
118
+ if (hubUrl)
119
+ normalized.hubUrl = hubUrl;
120
+ else
121
+ delete normalized.hubUrl;
122
+ for (const key of ["clientId", "clientSecret", "controlSecret", "displayName", "localRunnerImage"]) {
123
+ const valueString = string(key);
124
+ if (valueString)
125
+ normalized[key] = valueString;
126
+ else
127
+ delete normalized[key];
128
+ }
129
+ const machineId = string("machineId");
130
+ if (machineId && isMachineUuid(machineId))
131
+ normalized.machineId = machineId;
132
+ else
133
+ delete normalized.machineId;
134
+ delete normalized.skipCodexSubscriptionPrompt;
135
+ if (typeof localRunnerPort !== "number" || !Number.isInteger(localRunnerPort)) {
136
+ delete normalized.localRunnerPort;
137
+ }
138
+ return normalized;
139
+ }
140
+ export function loadConfig() {
141
+ try {
142
+ return normalizeTillerConfig(JSON.parse(readFileSync(CONFIG_PATH, "utf-8")));
143
+ }
144
+ catch {
145
+ return {};
146
+ }
147
+ }
148
+ export function configExists() {
149
+ return existsSync(CONFIG_PATH);
150
+ }
151
+ export function writeConfig(config) {
152
+ mkdirSync(TILLER_CONFIG_DIR, { recursive: true, mode: 0o700 });
153
+ chmodSync(TILLER_CONFIG_DIR, 0o700);
154
+ if (existsSync(CONFIG_PATH))
155
+ chmodSync(CONFIG_PATH, 0o600);
156
+ writeFileSync(CONFIG_PATH, `${JSON.stringify(normalizeTillerConfig(config), null, 2)}\n`, { mode: 0o600 });
157
+ chmodSync(CONFIG_PATH, 0o600);
158
+ }
159
+ export function authErrorMessage() {
160
+ const problems = [];
161
+ if (!HUB_URL) {
162
+ problems.push(`Hub URL required. Run \`${CLI.command}\` or \`${CLI.command} init\` to configure it, or set ${CLI.hubUrlEnv} / add hubUrl to ${CONFIG_PATH}`);
163
+ }
164
+ else if (!isAllowedHubUrl(HUB_URL) && !isLocalHubUrl(HUB_URL)) {
165
+ problems.push(`The saved Hub URL is not an exact https Hub origin under ${hubParentDomainsText()}. Run `
166
+ + `\`${CLI.command} host setup --hub-url https://<exact-host>.workers.dev\`.`);
167
+ }
168
+ return problems.length > 0 ? problems.join("\n") : null;
169
+ }
170
+ export const DEFAULT_LOCAL_RUNNER_IMAGE = "docker.io/jamieatlason/tiller-sandbox:stable";
171
+ /**
172
+ * A byte count such as `TILLER_STAGED_WORKSPACE_BUDGET_BYTES`: digits with an
173
+ * optional binary K, M, G or T suffix ("5G" is 5 GiB). Null when absent or
174
+ * malformed, so the caller's default applies.
175
+ */
176
+ export function parseByteSize(value) {
177
+ const match = /^\s*([0-9]+)\s*([KMGT]?)i?B?\s*$/i.exec(value ?? "");
178
+ if (!match)
179
+ return null;
180
+ const bytes = Number(match[1]) * 1024 ** ["", "K", "M", "G", "T"].indexOf(match[2].toUpperCase());
181
+ return Number.isSafeInteger(bytes) ? bytes : null;
182
+ }
183
+ let config = loadConfig();
184
+ export let HUB_URL = "";
185
+ export let MACHINE_ID = "";
186
+ export let MACHINE_DISPLAY_NAME = hostname();
187
+ export let TILLER_CLIENT_ID = "";
188
+ export let TILLER_CLIENT_SECRET = "";
189
+ export let CONTROL_SECRET = "";
190
+ export let LOCAL_RUNNER_PORT = CLI.defaultRunnerPort;
191
+ export let LOCAL_RUNNER_IMAGE = DEFAULT_LOCAL_RUNNER_IMAGE;
192
+ export let HAS_HUB_CLIENT_CREDENTIAL = false;
193
+ export let hubTransportHeaders = {};
194
+ export let hubControlHeaders = {};
195
+ /**
196
+ * Set when `HUB_URL` names a Hub other than the one the saved credentials
197
+ * are for: the sentence to show the person. The saved credentials are then
198
+ * not loaded at all.
199
+ */
200
+ export let SAVED_CREDENTIALS_WITHHELD = null;
201
+ function originOf(value) {
202
+ try {
203
+ return new URL(value).origin;
204
+ }
205
+ catch {
206
+ return null;
207
+ }
208
+ }
209
+ /**
210
+ * True when `hubUrl` is the Hub the saved client id, client secret and
211
+ * control secret were issued by: the `hubUrl` saved beside them. They are
212
+ * sent to that origin and to no other, whatever `HUB_URL`, a `--hub-url`
213
+ * option or a prompt says.
214
+ */
215
+ export function savedCredentialsAreFor(hubUrl, saved = loadConfig()) {
216
+ const savedOrigin = originOf(normalizeUrl(saved.hubUrl));
217
+ return savedOrigin !== null && savedOrigin === originOf(normalizeUrl(hubUrl));
218
+ }
219
+ let withheldNoticeShown = "";
220
+ export function reloadConfig() {
221
+ config = loadConfig();
222
+ HUB_URL = normalizeUrl(process.env[CLI.hubUrlEnv] || config.hubUrl);
223
+ const hasSavedCredentials = Boolean(config.clientId || config.clientSecret || config.controlSecret);
224
+ const useSaved = !hasSavedCredentials || savedCredentialsAreFor(HUB_URL, config);
225
+ SAVED_CREDENTIALS_WITHHELD = useSaved
226
+ ? null
227
+ : `${CLI.hubUrlEnv} is ${HUB_URL || "not a Hub address"}, but this machine's saved credentials are for ${normalizeUrl(config.hubUrl) || "no Hub"}. They are sent only there, so this run has no saved credentials. `
228
+ + `Unset ${CLI.hubUrlEnv} to use the saved Hub, or connect to the other one with \`${CLI.command} host setup --hub-url ${HUB_URL || "https://<exact-host>.workers.dev"}\`.`;
229
+ if (SAVED_CREDENTIALS_WITHHELD && withheldNoticeShown !== SAVED_CREDENTIALS_WITHHELD) {
230
+ withheldNoticeShown = SAVED_CREDENTIALS_WITHHELD;
231
+ process.stderr.write(`${CLI.logTag} ${SAVED_CREDENTIALS_WITHHELD}\n`);
232
+ }
233
+ const saved = useSaved ? config : {};
234
+ // The hub's credential comes only from the connection `tiller host setup`
235
+ // saved; no environment variable can stand in for it.
236
+ const rawClientId = saved.clientId || "";
237
+ const rawClientSecret = saved.clientSecret || "";
238
+ // Execution-machine identity is durable configuration generated by
239
+ // `tiller host setup`. An environment override could silently present this
240
+ // installation as a different machine and strand pinned workloads.
241
+ MACHINE_ID = config.machineId?.trim() || "";
242
+ MACHINE_DISPLAY_NAME = process.env[envVar("MACHINE_DISPLAY_NAME")]?.trim()
243
+ || config.displayName?.trim()
244
+ || hostname();
245
+ TILLER_CLIENT_ID = rawClientId;
246
+ TILLER_CLIENT_SECRET = rawClientSecret;
247
+ CONTROL_SECRET = saved.controlSecret?.trim() || "";
248
+ LOCAL_RUNNER_PORT = parseInteger(process.env[envVar("LOCAL_RUNNER_PORT")], config.localRunnerPort ?? CLI.defaultRunnerPort);
249
+ LOCAL_RUNNER_IMAGE =
250
+ process.env[envVar("LOCAL_RUNNER_IMAGE")] ||
251
+ config.localRunnerImage ||
252
+ DEFAULT_LOCAL_RUNNER_IMAGE;
253
+ HAS_HUB_CLIENT_CREDENTIAL = Boolean(TILLER_CLIENT_ID && TILLER_CLIENT_SECRET);
254
+ hubTransportHeaders = {
255
+ ...(TILLER_CLIENT_ID ? { "X-Tiller-Client-Id": TILLER_CLIENT_ID } : {}),
256
+ ...(TILLER_CLIENT_SECRET ? { "X-Tiller-Client-Secret": TILLER_CLIENT_SECRET } : {}),
257
+ };
258
+ hubControlHeaders = {
259
+ ...hubTransportHeaders,
260
+ ...(CONTROL_SECRET ? { "X-Tiller-Capability": CONTROL_SECRET } : {}),
261
+ };
262
+ }
263
+ reloadConfig();
264
+ export function ensureAuth() {
265
+ const message = authErrorMessage();
266
+ if (message) {
267
+ console.error(message);
268
+ process.exit(1);
269
+ }
270
+ }
271
+ export function isLocalHubUrl(value) {
272
+ try {
273
+ const host = new URL(value).hostname;
274
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
275
+ }
276
+ catch {
277
+ return false;
278
+ }
279
+ }
280
+ export function ensureHostAuth() {
281
+ if (SAVED_CREDENTIALS_WITHHELD && !isLocalHubUrl(HUB_URL))
282
+ throw new Error(SAVED_CREDENTIALS_WITHHELD);
283
+ const problems = [];
284
+ if (!HUB_URL || (!isAllowedHubUrl(HUB_URL) && !isLocalHubUrl(HUB_URL))) {
285
+ problems.push(`an exact Hub URL under ${hubParentDomainsText()}`);
286
+ }
287
+ if (!isMachineUuid(MACHINE_ID))
288
+ problems.push("a generated machine UUID");
289
+ if (!isLocalHubUrl(HUB_URL) && (!TILLER_CLIENT_ID || !TILLER_CLIENT_SECRET)) {
290
+ problems.push("a valid Hub service credential");
291
+ }
292
+ if (!isLocalHubUrl(HUB_URL) && !CONTROL_SECRET)
293
+ problems.push("a control credential");
294
+ if (problems.length > 0) {
295
+ throw new Error(`Execution machine configuration is missing ${problems.join(", ")}. Run \`${CLI.command} host setup --hub-url https://<exact-host>.workers.dev\`.`);
296
+ }
297
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A short code derived from the public key a `tiller` command made for one
3
+ * connection. `tiller` prints it in the terminal and the hub's connect page
4
+ * shows it. A page opened from a link someone else made carries a different
5
+ * key, so it shows a different code than any terminal the person is looking
6
+ * at. `packages/hub/api/cli/comparison-code.ts` is the same function;
7
+ * the two share a test vector.
8
+ */
9
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
10
+ export async function connectComparisonCode(publicKeyJwk) {
11
+ if (typeof publicKeyJwk.x !== "string"
12
+ || typeof publicKeyJwk.y !== "string"
13
+ || !/^[A-Za-z0-9_-]{43}$/.test(publicKeyJwk.x)
14
+ || !/^[A-Za-z0-9_-]{43}$/.test(publicKeyJwk.y))
15
+ throw new Error("Invalid connection public key");
16
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`tiller-connect-v1|P-256|${publicKeyJwk.x}|${publicKeyJwk.y}`)));
17
+ // Fifty bits, as ten characters of five bits each.
18
+ let bits = 0n;
19
+ for (const byte of digest.slice(0, 7))
20
+ bits = (bits << 8n) | BigInt(byte);
21
+ bits >>= 6n;
22
+ let code = "";
23
+ for (let index = 9; index >= 0; index -= 1)
24
+ code += ALPHABET[Number((bits >> BigInt(index * 5)) & 31n)];
25
+ return `${code.slice(0, 5)}-${code.slice(5)}`;
26
+ }
@@ -0,0 +1,109 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { envVar } from "./identity.js";
4
+ /** Where the image installs the harness (`npm install -g`); `/usr/local/libexec/tiller-harness` links here. */
5
+ export const HARNESS_DIST_CONTAINER_PATH = "/usr/lib/node_modules/@paperwing-dev/tiller-harness/dist";
6
+ const CHANNEL_TTL_MS = 60 * 1000;
7
+ const CHANNEL_FETCH_TIMEOUT_MS = 5 * 1000;
8
+ /** A development delay above this is a typo, not a choice. */
9
+ const MAX_DEVELOPMENT_DELAY_MS = 10 * 60 * 1000;
10
+ export const STAGING_HOLD_DEFAULT_MS = 10 * 60 * 1000;
11
+ export const STAGING_HOLD_MAX_MS = 60 * 60 * 1000;
12
+ /** Reads the Hub's build channel; null when the Hub cannot be asked or does not say. */
13
+ export async function fetchHubBuildChannel(hubUrl, headers, fetchImpl = fetch) {
14
+ if (!hubUrl)
15
+ return null;
16
+ try {
17
+ const response = await fetchImpl(`${hubUrl}/api/update/check`, {
18
+ headers: { Accept: "application/json", ...headers },
19
+ signal: AbortSignal.timeout(CHANNEL_FETCH_TIMEOUT_MS),
20
+ });
21
+ if (!response.ok)
22
+ return null;
23
+ const body = await response.json();
24
+ const channel = body?.currentRelease?.channel;
25
+ return channel === "development" || channel === "release" ? channel : null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /**
32
+ * Whether the Hub is a development build. Answers are kept for a minute; a
33
+ * failed read is not kept, so the next call asks again.
34
+ */
35
+ export class DevelopmentHubGate {
36
+ resolve;
37
+ now;
38
+ cached = null;
39
+ constructor(resolve, now = Date.now) {
40
+ this.resolve = resolve;
41
+ this.now = now;
42
+ }
43
+ async isDevelopment() {
44
+ if (this.cached && this.now() - this.cached.at < CHANNEL_TTL_MS)
45
+ return this.cached.channel === "development";
46
+ const channel = await this.resolve().catch(() => null);
47
+ if (channel)
48
+ this.cached = { channel, at: this.now() };
49
+ else
50
+ this.cached = null;
51
+ return channel === "development";
52
+ }
53
+ /** The last answer without asking again: false until the Hub has said development. */
54
+ knownDevelopment() {
55
+ return this.cached?.channel === "development";
56
+ }
57
+ }
58
+ /** A development delay in milliseconds from the environment, or null when unset or invalid. */
59
+ export function parseDevelopmentDelay(value) {
60
+ if (value === undefined || value.trim() === "")
61
+ return null;
62
+ if (!/^\d+$/.test(value.trim()))
63
+ return null;
64
+ const ms = Number(value.trim());
65
+ return Number.isSafeInteger(ms) && ms <= MAX_DEVELOPMENT_DELAY_MS ? ms : null;
66
+ }
67
+ export function readDevelopmentRunnerOptions(env = process.env) {
68
+ const harnessDir = env[envVar("DEV_HARNESS_DIR")]?.trim();
69
+ return {
70
+ harnessDir: harnessDir ? harnessDir : null,
71
+ stageDelayMs: parseDevelopmentDelay(env[envVar("STAGE_DELAY_MS")]),
72
+ refillDelayMs: parseDevelopmentDelay(env[envVar("REFILL_DELAY_MS")]),
73
+ };
74
+ }
75
+ export const HARNESS_OVERLAY_REFUSED = `${envVar("DEV_HARNESS_DIR")} is set, but the Hub is not a development build (its build channel is release, or the runner `
76
+ + `could not read it). The harness overlay is for development Hubs only; unset ${envVar("DEV_HARNESS_DIR")} to run the image's harness.`;
77
+ /** Checks the overlay directory looks like a built harness `dist`; throws with the reason otherwise. */
78
+ export function validateHarnessOverlayDir(dir) {
79
+ if (!isAbsolute(dir))
80
+ throw new Error(`${envVar("DEV_HARNESS_DIR")} must be an absolute path, got ${dir}.`);
81
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
82
+ throw new Error(`${envVar("DEV_HARNESS_DIR")} ${dir} is not a directory.`);
83
+ if (!existsSync(join(dir, "index.js"))) {
84
+ throw new Error(`${envVar("DEV_HARNESS_DIR")} ${dir} has no index.js; point it at packages/harness/dist after \`npm run build\` there.`);
85
+ }
86
+ return dir;
87
+ }
88
+ /**
89
+ * The startup bench's staging hold: while it lasts, creates adopt no staged
90
+ * volume and no stage run starts, so a timed start takes the mirror path. It
91
+ * ends by itself, so a bench that dies cannot leave staging off.
92
+ */
93
+ export class StagingHold {
94
+ now;
95
+ until = 0;
96
+ constructor(now = Date.now) {
97
+ this.now = now;
98
+ }
99
+ hold(ms) {
100
+ this.until = this.now() + Math.min(Math.max(ms, 0), STAGING_HOLD_MAX_MS);
101
+ return this.until;
102
+ }
103
+ release() {
104
+ this.until = 0;
105
+ }
106
+ active() {
107
+ return this.now() < this.until;
108
+ }
109
+ }