@overcy/hive 0.0.0-stage → 0.2.0

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 (133) hide show
  1. package/README.md +213 -2
  2. package/dist/api.d.ts +31 -0
  3. package/dist/api.js +83 -0
  4. package/dist/atomic.d.ts +1 -0
  5. package/dist/atomic.js +24 -0
  6. package/dist/binding.d.ts +5 -0
  7. package/dist/binding.js +16 -0
  8. package/dist/bootstrap/deps.d.ts +3 -0
  9. package/dist/bootstrap/deps.js +35 -0
  10. package/dist/bootstrap/doctor.d.ts +29 -0
  11. package/dist/bootstrap/doctor.js +80 -0
  12. package/dist/bootstrap/engine.d.ts +29 -0
  13. package/dist/bootstrap/engine.js +160 -0
  14. package/dist/bootstrap/forwarder.d.ts +11 -0
  15. package/dist/bootstrap/forwarder.js +30 -0
  16. package/dist/bootstrap/identity.d.ts +7 -0
  17. package/dist/bootstrap/identity.js +52 -0
  18. package/dist/bootstrap/index.d.ts +36 -0
  19. package/dist/bootstrap/index.js +40 -0
  20. package/dist/bootstrap/kit.d.ts +9 -0
  21. package/dist/bootstrap/kit.js +56 -0
  22. package/dist/bootstrap/manifest.d.ts +73 -0
  23. package/dist/bootstrap/manifest.js +309 -0
  24. package/dist/bootstrap/model-access.d.ts +43 -0
  25. package/dist/bootstrap/model-access.js +74 -0
  26. package/dist/bootstrap/pin.d.ts +2 -0
  27. package/dist/bootstrap/pin.js +16 -0
  28. package/dist/bootstrap/plan.d.ts +49 -0
  29. package/dist/bootstrap/plan.js +69 -0
  30. package/dist/bootstrap/prompt.d.ts +3 -0
  31. package/dist/bootstrap/prompt.js +35 -0
  32. package/dist/bootstrap/registry.d.ts +85 -0
  33. package/dist/bootstrap/registry.js +38 -0
  34. package/dist/bootstrap/secrets.d.ts +11 -0
  35. package/dist/bootstrap/secrets.js +105 -0
  36. package/dist/bootstrap/steps/agents.d.ts +9 -0
  37. package/dist/bootstrap/steps/agents.js +75 -0
  38. package/dist/bootstrap/steps/auth.d.ts +8 -0
  39. package/dist/bootstrap/steps/auth.js +138 -0
  40. package/dist/bootstrap/steps/cron.d.ts +7 -0
  41. package/dist/bootstrap/steps/cron.js +74 -0
  42. package/dist/bootstrap/steps/drift.d.ts +5 -0
  43. package/dist/bootstrap/steps/drift.js +67 -0
  44. package/dist/bootstrap/steps/env.d.ts +6 -0
  45. package/dist/bootstrap/steps/env.js +108 -0
  46. package/dist/bootstrap/steps/files.d.ts +7 -0
  47. package/dist/bootstrap/steps/files.js +28 -0
  48. package/dist/bootstrap/steps/lanes.d.ts +14 -0
  49. package/dist/bootstrap/steps/lanes.js +153 -0
  50. package/dist/bootstrap/steps/model-access.d.ts +10 -0
  51. package/dist/bootstrap/steps/model-access.js +122 -0
  52. package/dist/bootstrap/steps/preflight.d.ts +3 -0
  53. package/dist/bootstrap/steps/preflight.js +49 -0
  54. package/dist/bootstrap/steps/reporter.d.ts +12 -0
  55. package/dist/bootstrap/steps/reporter.js +155 -0
  56. package/dist/bootstrap/system.d.ts +5 -0
  57. package/dist/bootstrap/system.js +69 -0
  58. package/dist/bootstrap/types.d.ts +157 -0
  59. package/dist/bootstrap/types.js +14 -0
  60. package/dist/cli.d.ts +2 -0
  61. package/dist/cli.js +23 -0
  62. package/dist/collect.d.ts +28 -0
  63. package/dist/collect.js +63 -0
  64. package/dist/commands/connect.d.ts +33 -0
  65. package/dist/commands/connect.js +306 -0
  66. package/dist/commands/doctor.d.ts +7 -0
  67. package/dist/commands/doctor.js +13 -0
  68. package/dist/commands/login.d.ts +3 -0
  69. package/dist/commands/login.js +118 -0
  70. package/dist/commands/logout.d.ts +2 -0
  71. package/dist/commands/logout.js +37 -0
  72. package/dist/commands/node-add.d.ts +7 -0
  73. package/dist/commands/node-add.js +56 -0
  74. package/dist/commands/node.d.ts +19 -0
  75. package/dist/commands/node.js +43 -0
  76. package/dist/commands/prEvents.d.ts +7 -0
  77. package/dist/commands/prEvents.js +32 -0
  78. package/dist/commands/setup.d.ts +15 -0
  79. package/dist/commands/setup.js +35 -0
  80. package/dist/commands/status.d.ts +18 -0
  81. package/dist/commands/status.js +71 -0
  82. package/dist/commands/threads.d.ts +6 -0
  83. package/dist/commands/threads.js +36 -0
  84. package/dist/config.d.ts +71 -0
  85. package/dist/config.js +121 -0
  86. package/dist/context.d.ts +26 -0
  87. package/dist/context.js +31 -0
  88. package/dist/crypto.d.ts +7 -0
  89. package/dist/crypto.js +50 -0
  90. package/dist/machine.d.ts +66 -0
  91. package/dist/machine.js +103 -0
  92. package/dist/node/cli.d.ts +25 -0
  93. package/dist/node/cli.js +130 -0
  94. package/dist/node/engine.d.ts +47 -0
  95. package/dist/node/engine.js +463 -0
  96. package/dist/node/ingress.d.ts +102 -0
  97. package/dist/node/ingress.js +473 -0
  98. package/dist/node/layout.d.ts +56 -0
  99. package/dist/node/layout.js +55 -0
  100. package/dist/node/leave.d.ts +8 -0
  101. package/dist/node/leave.js +32 -0
  102. package/dist/node/lock.d.ts +19 -0
  103. package/dist/node/lock.js +99 -0
  104. package/dist/node/modelAccess.d.ts +2 -0
  105. package/dist/node/modelAccess.js +44 -0
  106. package/dist/node/repair.d.ts +28 -0
  107. package/dist/node/repair.js +78 -0
  108. package/dist/node/services.d.ts +58 -0
  109. package/dist/node/services.js +171 -0
  110. package/dist/node/state.d.ts +127 -0
  111. package/dist/node/state.js +95 -0
  112. package/dist/node/steps.d.ts +74 -0
  113. package/dist/node/steps.js +158 -0
  114. package/dist/node/supervisor.d.ts +22 -0
  115. package/dist/node/supervisor.js +95 -0
  116. package/dist/node/tick.d.ts +47 -0
  117. package/dist/node/tick.js +278 -0
  118. package/dist/node/toolchain.d.ts +50 -0
  119. package/dist/node/toolchain.js +230 -0
  120. package/dist/nodeContract.d.ts +101 -0
  121. package/dist/nodeContract.js +192 -0
  122. package/dist/package.d.ts +3 -0
  123. package/dist/package.js +5 -0
  124. package/dist/prEvents.d.ts +109 -0
  125. package/dist/prEvents.js +374 -0
  126. package/dist/run.d.ts +19 -0
  127. package/dist/run.js +487 -0
  128. package/dist/specs/device-client.json +920 -0
  129. package/dist/threads.d.ts +88 -0
  130. package/dist/threads.js +268 -0
  131. package/dist/version.d.ts +1 -0
  132. package/dist/version.js +1 -0
  133. package/package.json +35 -4
@@ -0,0 +1,55 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * The supervisor's exit codes. The keeper (install.sh, plan item 7) acts on them, so they are
5
+ * one exported constant and are documented in docs/supervisor.md.
6
+ */
7
+ export const EXIT = {
8
+ /** The supervisor swapped `cli/current` and wants the keeper to start it again at once. */
9
+ RESTART: 75,
10
+ /** Hive revoked or removed this node. The supervisor wrote `node/revoked` before it exited. */
11
+ REVOKED: 77,
12
+ };
13
+ export const DEFAULT_STATE_DIR = '/var/lib/hive';
14
+ /** Where install.sh puts the root-owned helpers, `servicectl` among them. `HIVE_LIB_DIR` moves it for tests. */
15
+ export const DEFAULT_LIB_DIR = '/usr/local/lib/hive';
16
+ export function stateRoot(env) {
17
+ return env.HIVE_STATE_DIR && env.HIVE_STATE_DIR !== '' ? env.HIVE_STATE_DIR : DEFAULT_STATE_DIR;
18
+ }
19
+ export function layoutOf(env) {
20
+ const root = stateRoot(env);
21
+ const nodeDir = join(root, 'node');
22
+ const reportDir = join(root, 'report');
23
+ const lib = env.HIVE_LIB_DIR && env.HIVE_LIB_DIR !== '' ? env.HIVE_LIB_DIR : DEFAULT_LIB_DIR;
24
+ return {
25
+ root,
26
+ nodeDir,
27
+ lockFile: join(nodeDir, 'supervisor.lock'),
28
+ supervisorState: join(nodeDir, 'supervisor.json'),
29
+ desiredCache: join(nodeDir, 'desired.json'),
30
+ revokedMarker: join(nodeDir, 'revoked'),
31
+ repairRequest: join(nodeDir, 'repair-request'),
32
+ reportDir,
33
+ reportFile: join(reportDir, 'report.json'),
34
+ cliDir: join(root, 'cli'),
35
+ cliCurrent: join(root, 'cli', 'current'),
36
+ cliPrevious: join(root, 'cli', 'previous'),
37
+ modelKey: join(nodeDir, 'model-key.json'),
38
+ backupsDir: join(nodeDir, 'backups'),
39
+ binDir: join(root, 'bin'),
40
+ toolsDir: join(root, 'bin', 'tools'),
41
+ engineHome: env.HIVE_T3_HOME && env.HIVE_T3_HOME !== '' ? env.HIVE_T3_HOME : join(root, 'engine'),
42
+ serviceEnv: join(root, 'engine-config', 'service.env'),
43
+ ingressConfigDir: join(root, 'ingress', 'config'),
44
+ ingressStateDir: join(root, 'ingress', 'state'),
45
+ servicectl: join(lib, 'servicectl'),
46
+ releaseVerify: join(lib, 'release-verify'),
47
+ };
48
+ }
49
+ /**
50
+ * Node mode: this machine keeps its identity under the state root. It holds when `HIVE_STATE_DIR` is set or
51
+ * `/var/lib/hive/node` already exists. Anything else is a personal machine that keeps `~/.config/hive`.
52
+ */
53
+ export function nodeMode(env) {
54
+ return (env.HIVE_STATE_DIR !== undefined && env.HIVE_STATE_DIR !== '') || existsSync(join(DEFAULT_STATE_DIR, 'node'));
55
+ }
@@ -0,0 +1,8 @@
1
+ import type { Context } from '../context.ts';
2
+ /**
3
+ * `hive node leave`: tells Hive this node is going, in a request signed with the node key. Hive removes the node and
4
+ * revokes its token and key. `install.sh --uninstall` runs it before it removes anything. Exit 0 when Hive removed
5
+ * the node or had already, and when the machine was never enrolled. Exit 1 when Hive could not be told, so the
6
+ * caller can say to remove the node in Hive.
7
+ */
8
+ export declare function leaveHive(ctx: Context, signal: AbortSignal): Promise<number>;
@@ -0,0 +1,32 @@
1
+ import { ApiError } from "../api.js";
2
+ import { loadIdentity } from "./supervisor.js";
3
+ /** The codes Hive answers once a node is gone. The node's key no longer works, so there is nothing left to tell. */
4
+ const GONE = ['node_removed', 'token_invalid'];
5
+ /**
6
+ * `hive node leave`: tells Hive this node is going, in a request signed with the node key. Hive removes the node and
7
+ * revokes its token and key. `install.sh --uninstall` runs it before it removes anything. Exit 0 when Hive removed
8
+ * the node or had already, and when the machine was never enrolled. Exit 1 when Hive could not be told, so the
9
+ * caller can say to remove the node in Hive.
10
+ */
11
+ export async function leaveHive(ctx, signal) {
12
+ const identity = await loadIdentity(ctx);
13
+ if (identity === null) {
14
+ ctx.io.out(`This machine is not enrolled (no node identity in ${ctx.store.dir}), so there is nothing to tell Hive.`);
15
+ return 0;
16
+ }
17
+ const { node, key } = identity;
18
+ try {
19
+ await ctx.api.json('POST', '/api/v0/nodes/me/leave', { token: node.token, key, signal, timeoutMs: 20_000 });
20
+ ctx.io.out(`Hive removed ${node.name} from ${node.team.name}. Its token and key no longer work.`);
21
+ return 0;
22
+ }
23
+ catch (error) {
24
+ if (error instanceof ApiError && GONE.includes(error.code)) {
25
+ ctx.io.out(`Hive already shows ${node.name} as removed.`);
26
+ return 0;
27
+ }
28
+ const why = error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof Error ? error.message : String(error);
29
+ ctx.io.err(`Could not tell Hive that ${node.name} is leaving: ${why}`);
30
+ return 1;
31
+ }
32
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The exclusive lock on a node's state dir.
3
+ *
4
+ * Node has no flock(2), so the lock comes from util-linux `flock`: open the file, then run `flock -xn 3` with that
5
+ * descriptor as the child's fd 3. The lock sits on the open file description. It stays held after the helper
6
+ * exits, and the kernel drops it when this process dies, so a crash never leaves a stale lock. The keeper's sh and
7
+ * `install.sh` can take the same lock with `flock`.
8
+ *
9
+ * macOS ships no `flock`, so there the lock is a pid file created with O_EXCL. It is stale when its pid is gone.
10
+ */
11
+ export type Lock = {
12
+ kind: 'flock' | 'pidfile';
13
+ release: () => void;
14
+ };
15
+ export type LockKind = Lock['kind'];
16
+ /** Takes the lock, or returns null when another process holds it. `kind` forces one method, for tests. */
17
+ export declare function tryLock(path: string, kind?: LockKind): Lock | null;
18
+ /** True when another process holds the lock. It takes nothing and creates nothing. */
19
+ export declare function lockHeld(path: string, kind?: LockKind): boolean;
@@ -0,0 +1,99 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ const flockAvailable = () => spawnSync('flock', ['--version'], { stdio: 'ignore' }).error === undefined;
5
+ function takeFlock(path) {
6
+ const fd = openSync(path, 'a+', 0o600);
7
+ const result = spawnSync('flock', ['-xn', '3'], { stdio: ['ignore', 'ignore', 'ignore', fd] });
8
+ if (result.error !== undefined) {
9
+ closeSync(fd);
10
+ return 'unavailable';
11
+ }
12
+ if (result.status === 0) {
13
+ let open = true;
14
+ return {
15
+ kind: 'flock',
16
+ release: () => {
17
+ if (open)
18
+ closeSync(fd);
19
+ open = false;
20
+ },
21
+ };
22
+ }
23
+ closeSync(fd);
24
+ // Exit 1 is "held by someone else". Any other status means the helper itself failed.
25
+ return result.status === 1 ? null : 'unavailable';
26
+ }
27
+ function alive(pid) {
28
+ try {
29
+ process.kill(pid, 0);
30
+ return true;
31
+ }
32
+ catch (error) {
33
+ return error.code === 'EPERM';
34
+ }
35
+ }
36
+ function takePidfile(path) {
37
+ for (let attempt = 0; attempt < 2; attempt++) {
38
+ try {
39
+ const fd = openSync(path, 'wx', 0o600);
40
+ writeSync(fd, `${process.pid}\n`);
41
+ closeSync(fd);
42
+ return {
43
+ kind: 'pidfile',
44
+ release: () => {
45
+ try {
46
+ if (readFileSync(path, 'utf8').trim() === String(process.pid))
47
+ unlinkSync(path);
48
+ }
49
+ catch {
50
+ // Already gone.
51
+ }
52
+ },
53
+ };
54
+ }
55
+ catch (error) {
56
+ if (error.code !== 'EEXIST')
57
+ throw error;
58
+ }
59
+ const holder = Number.parseInt(readFileSync(path, 'utf8'), 10);
60
+ if (Number.isInteger(holder) && holder > 0 && alive(holder))
61
+ return null;
62
+ try {
63
+ unlinkSync(path);
64
+ }
65
+ catch {
66
+ // Another process cleaned it first. Try once more.
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ /** Takes the lock, or returns null when another process holds it. `kind` forces one method, for tests. */
72
+ export function tryLock(path, kind) {
73
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
74
+ if (kind !== 'pidfile' && (kind === 'flock' || flockAvailable())) {
75
+ const taken = takeFlock(path);
76
+ if (taken !== 'unavailable')
77
+ return taken;
78
+ if (kind === 'flock')
79
+ throw new Error('flock failed to run.');
80
+ }
81
+ return takePidfile(path);
82
+ }
83
+ /** True when another process holds the lock. It takes nothing and creates nothing. */
84
+ export function lockHeld(path, kind) {
85
+ if (!existsSync(path))
86
+ return false;
87
+ let lock;
88
+ try {
89
+ lock = tryLock(path, kind);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ if (lock === null)
95
+ return true;
96
+ lock.release();
97
+ // A pid file is removed on release. A flock file stays, and it was free.
98
+ return false;
99
+ }
@@ -0,0 +1,2 @@
1
+ import type { NodeStep } from './steps.ts';
2
+ export declare const modelAccessStep: NodeStep;
@@ -0,0 +1,44 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { writeAtomic } from "../atomic.js";
3
+ import { applyEngineEnv, readModelKey } from "./engine.js";
4
+ /**
5
+ * The `model-access` step, method `byok`. Hive holds the team's Anthropic API key as a node secret and names it in
6
+ * desired state with a `SecretRef`. The secret's value is the key itself, as plain text. The supervisor keeps it 0600
7
+ * in `node/model-key.json`, and the engine gets it as `ANTHROPIC_API_KEY` through `service.env`. The key is the team's
8
+ * own and every agent needs it, so agents running as `hive` can read it. A forwarder that hides it comes later.
9
+ */
10
+ const addKey = (run) => `Add one in Hive > Nodes > ${run.node.name}.`;
11
+ async function observeModelAccess(run) {
12
+ const access = run.desired?.model_access;
13
+ if (access === undefined)
14
+ return { status: 'needs_action', detail: `no model access yet. ${addKey(run).replace('Add one', 'Add a BYOK key')}`, fix: 'hive_button' };
15
+ if (access.method === 'direct')
16
+ return { status: 'ok', detail: 'direct: agents use their own sign-in' };
17
+ if (access.method !== 'byok')
18
+ return { status: 'needs_action', detail: `${access.method} is not supported on this node yet, use byok`, fix: 'human' };
19
+ if (access.secret === undefined)
20
+ return { status: 'needs_action', detail: `no BYOK key yet. ${addKey(run)}`, fix: 'hive_button' };
21
+ const stored = await readModelKey(run);
22
+ if (stored === null || stored.name !== access.secret.name || stored.version !== access.secret.version)
23
+ return { status: 'stale', detail: `BYOK key version ${access.secret.version} is not on the node yet` };
24
+ return { status: 'ok', detail: `byok, key version ${stored.version}` };
25
+ }
26
+ async function repairModelAccess(run) {
27
+ const ref = run.desired?.model_access?.method === 'byok' ? run.desired.model_access.secret : undefined;
28
+ if (ref === undefined)
29
+ return;
30
+ const secret = await run.ctx.api.json('GET', `/api/v0/nodes/me/secrets/${ref.name}`, { query: { version: String(ref.version) }, token: run.node.token, key: run.key, signal: run.signal });
31
+ const value = typeof secret.value === 'string' ? secret.value.trim() : '';
32
+ if (value === '' || /[\r\n\0]/.test(value))
33
+ throw new Error(`Hive's secret ${ref.name} version ${ref.version} is not one line of text, so it is not an API key`);
34
+ await mkdir(run.layout.nodeDir, { recursive: true, mode: 0o700 });
35
+ await writeAtomic(run.layout.modelKey, `${JSON.stringify({ method: 'byok', name: ref.name, version: ref.version, value })}\n`, 0o600);
36
+ // The engine step ran earlier in this tick, so this step rewrites service.env and restarts the engine itself.
37
+ await applyEngineEnv(run);
38
+ }
39
+ export const modelAccessStep = {
40
+ id: 'model-access',
41
+ needs: ['desired'],
42
+ observe: observeModelAccess,
43
+ repair: repairModelAccess,
44
+ };
@@ -0,0 +1,28 @@
1
+ import type { Context } from '../context.ts';
2
+ import { type Report } from '../nodeContract.ts';
3
+ export declare const REPAIR_POLL_MS = 500;
4
+ export declare const REPAIR_TIMEOUT_MS: number;
5
+ export type RepairOutcome = {
6
+ ok: true;
7
+ report: Report;
8
+ ranHere: boolean;
9
+ } | {
10
+ ok: false;
11
+ error: string;
12
+ code: number;
13
+ };
14
+ /**
15
+ * Asks for a repair pass and returns once it is done, with the report it produced.
16
+ *
17
+ * One loop, so two repairs at once end with one writer:
18
+ * 1. Try the state lock. If this process gets it, it runs the tick itself, which also settles any request.
19
+ * 2. Otherwise a supervisor (or another one-shot repair) is running. Write a request and wait until the request
20
+ * file is gone, which that process does after the tick that handled it, or until the lock frees.
21
+ * 3. Go back to step 1.
22
+ *
23
+ * A request that was overwritten by a second requester stays until a tick that started after it has run, and that
24
+ * tick covers this one too, so waiting for the file to go is enough.
25
+ */
26
+ export declare function repairNow(ctx: Context, by: string, signal: AbortSignal, timeoutMs?: number): Promise<RepairOutcome>;
27
+ /** The report as the table `hive doctor` prints: one row per step. */
28
+ export declare function renderNodeReport(report: Report): string[];
@@ -0,0 +1,78 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { writeAtomic } from "../atomic.js";
5
+ import { parseReport } from "../nodeContract.js";
6
+ import { EXIT, layoutOf } from "./layout.js";
7
+ import { tryLock } from "./lock.js";
8
+ import { prepareDirs, runOneTick } from "./supervisor.js";
9
+ export const REPAIR_POLL_MS = 500;
10
+ export const REPAIR_TIMEOUT_MS = 5 * 60_000;
11
+ async function readReport(layout) {
12
+ try {
13
+ return parseReport(JSON.parse(await readFile(layout.reportFile, 'utf8')));
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ async function writeRequest(layout, by, now) {
20
+ await prepareDirs(layout);
21
+ await writeAtomic(layout.repairRequest, `${JSON.stringify({ id: randomUUID(), at: now.toISOString(), by })}\n`, 0o600);
22
+ }
23
+ /**
24
+ * Asks for a repair pass and returns once it is done, with the report it produced.
25
+ *
26
+ * One loop, so two repairs at once end with one writer:
27
+ * 1. Try the state lock. If this process gets it, it runs the tick itself, which also settles any request.
28
+ * 2. Otherwise a supervisor (or another one-shot repair) is running. Write a request and wait until the request
29
+ * file is gone, which that process does after the tick that handled it, or until the lock frees.
30
+ * 3. Go back to step 1.
31
+ *
32
+ * A request that was overwritten by a second requester stays until a tick that started after it has run, and that
33
+ * tick covers this one too, so waiting for the file to go is enough.
34
+ */
35
+ export async function repairNow(ctx, by, signal, timeoutMs = REPAIR_TIMEOUT_MS) {
36
+ const layout = layoutOf(ctx.env);
37
+ let waited = 0;
38
+ let requested = false;
39
+ for (;;) {
40
+ const lock = tryLock(layout.lockFile);
41
+ if (lock !== null) {
42
+ try {
43
+ const result = await runOneTick(ctx, signal);
44
+ if ('error' in result)
45
+ return { ok: false, error: result.error, code: 1 };
46
+ if (result.revoked !== null)
47
+ return { ok: false, error: `Hive revoked this node (${result.revoked}).`, code: EXIT.REVOKED };
48
+ return { ok: true, report: result.report, ranHere: true };
49
+ }
50
+ finally {
51
+ lock.release();
52
+ }
53
+ }
54
+ if (!requested) {
55
+ await writeRequest(layout, by, ctx.now());
56
+ requested = true;
57
+ }
58
+ await ctx.sleep(REPAIR_POLL_MS, signal);
59
+ if (signal.aborted)
60
+ return { ok: false, error: 'Interrupted.', code: 130 };
61
+ waited += REPAIR_POLL_MS;
62
+ if (!existsSync(layout.repairRequest)) {
63
+ const report = await readReport(layout);
64
+ if (report !== null)
65
+ return { ok: true, report, ranHere: false };
66
+ }
67
+ if (waited >= timeoutMs)
68
+ return { ok: false, error: `The supervisor did not handle the repair request within ${Math.round(timeoutMs / 1000)} seconds. Check that \`hive node run\` is healthy.`, code: 1 };
69
+ }
70
+ }
71
+ const PAD = 14;
72
+ /** The report as the table `hive doctor` prints: one row per step. */
73
+ export function renderNodeReport(report) {
74
+ const lines = report.steps.map((step) => `${step.status.padEnd(10)}${step.id.padEnd(PAD)}${step.detail ?? ''}${step.fix && step.status !== 'ok' && step.status !== 'repaired' ? ` (fix: ${step.fix})` : ''}`);
75
+ const bad = report.steps.filter((step) => step.status !== 'ok' && step.status !== 'repaired');
76
+ lines.push(bad.length === 0 ? `Every step is ok. Desired revision ${report.applied_revision} applied.` : `${bad.length} step(s) need attention. Hive has this report.`);
77
+ return lines;
78
+ }
@@ -0,0 +1,58 @@
1
+ import type { TickRun } from './steps.ts';
2
+ /** The helpers the engine, ingress and model-access steps share: service control, artifacts, files. */
3
+ export type Unit = 'engine' | 'ingress';
4
+ export type Verb = 'start' | 'stop' | 'restart';
5
+ /**
6
+ * Asks the init adapter to act on the engine or the ingress, through install.sh's `servicectl`. Under systemd that is
7
+ * `systemctl`, which polkit allows for hive-node on these two units only. Under the foreground keeper it is one line
8
+ * on the keeper's request FIFO. The supervisor never starts either service as its own child, so a CLI swap or a
9
+ * supervisor crash leaves them running.
10
+ */
11
+ export declare function serviceControl(run: TickRun, verb: Verb, unit: Unit): Promise<void>;
12
+ export declare function nodeArch(): 'x64' | 'arm64';
13
+ /** A downloaded file. `sha256` is hex, `sha512` is base64, as npm's `integrity` writes it after `sha512-`. */
14
+ export type Download = {
15
+ file: string;
16
+ sha256: string;
17
+ sha512: string;
18
+ bytes: number;
19
+ };
20
+ /** Hive's answer for one artifact. A CLI release also carries the manifest it was signed as. */
21
+ export type ArtifactAnswer = {
22
+ url: string;
23
+ version?: string;
24
+ manifest?: string;
25
+ key_id?: string;
26
+ signature?: string;
27
+ };
28
+ /**
29
+ * Asks Hive where to download a release artifact. Hive answers the node-signed route with a short-lived URL,
30
+ * presigned for R2 or S3, or a signed local URL for the `dev` channel.
31
+ */
32
+ export declare function requestArtifact(run: TickRun, name: string, route: string): Promise<ArtifactAnswer>;
33
+ /**
34
+ * Downloads `url` into `dir`, so a later rename stays on one filesystem. The download carries no node signature,
35
+ * because a presigned URL refuses extra auth. `timeoutMs` ends a download that stalls, so it cannot hold the tick.
36
+ */
37
+ export declare function download(run: TickRun, url: string, name: string, dir: string, timeoutMs?: number): Promise<Download>;
38
+ /** Fetches a binary for `bin/`: asks Hive for its URL, then downloads it into `dir`, which the service users can reach. */
39
+ export declare function fetchArtifact(run: TickRun, name: string, route: string, dir: string): Promise<Download>;
40
+ /**
41
+ * Unpacks a tarball into a fresh staging directory and returns the directory that holds `binary`: the staging
42
+ * directory itself, or its one top-level directory. OvercyCode archives have a top directory, Caddy's do not.
43
+ * Everything unpacked is made readable, and directories and executables searchable, by every user, and writable by
44
+ * none but the supervisor: tar applies the supervisor's umask, and the engine and the ingress run as other users.
45
+ */
46
+ export declare function unpack(run: TickRun, archive: string, stage: string, binary: string): Promise<string>;
47
+ export declare function isExecutable(path: string): Promise<boolean>;
48
+ /** Points `link` at `target` with one rename, so a reader sees the old link or the new one, never neither. */
49
+ export declare function switchLink(link: string, target: string): Promise<void>;
50
+ export declare function linkTarget(link: string): Promise<string | null>;
51
+ export declare function readText(path: string): Promise<string | null>;
52
+ /** Writes the file when its content or mode differs. Returns whether it wrote. */
53
+ export declare function writeIfChanged(path: string, content: string, mode: number): Promise<boolean>;
54
+ export declare const sha256: (text: string) => string;
55
+ /** A value for a file that sh sources with `set -a`: single-quoted, with each `'` closed, escaped and reopened. */
56
+ export declare function shQuote(value: string): string;
57
+ /** Keeps the newest `keep` entries of a directory, by name, and removes the rest. Names sort by time where it matters. */
58
+ export declare function prune(dir: string, keep: number, spare?: readonly string[]): Promise<void>;
@@ -0,0 +1,171 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createWriteStream } from 'node:fs';
3
+ import { chmod, mkdir, readdir, readFile, readlink, rename, rm, stat, symlink } from 'node:fs/promises';
4
+ import { arch } from 'node:os';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { Readable, Transform } from 'node:stream';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { writeAtomic } from "../atomic.js";
9
+ /**
10
+ * Asks the init adapter to act on the engine or the ingress, through install.sh's `servicectl`. Under systemd that is
11
+ * `systemctl`, which polkit allows for hive-node on these two units only. Under the foreground keeper it is one line
12
+ * on the keeper's request FIFO. The supervisor never starts either service as its own child, so a CLI swap or a
13
+ * supervisor crash leaves them running.
14
+ */
15
+ export async function serviceControl(run, verb, unit) {
16
+ const result = await run.exec(run.layout.servicectl, [verb, unit]);
17
+ if (result.code !== 0)
18
+ throw new Error(`servicectl ${verb} ${unit} failed (${result.code}): ${(result.stderr || result.stdout).trim().slice(-300) || 'no output'}`);
19
+ }
20
+ export function nodeArch() {
21
+ const here = arch();
22
+ if (here !== 'x64' && here !== 'arm64')
23
+ throw new Error(`${here} is not supported, use x64 or arm64.`);
24
+ return here;
25
+ }
26
+ /**
27
+ * Asks Hive where to download a release artifact. Hive answers the node-signed route with a short-lived URL,
28
+ * presigned for R2 or S3, or a signed local URL for the `dev` channel.
29
+ */
30
+ export async function requestArtifact(run, name, route) {
31
+ const answer = await run.ctx.api.json('GET', `/api/v0/nodes/me/artifacts/${name}/${route}/${nodeArch()}`, { token: run.node.token, key: run.key, signal: run.signal });
32
+ if (typeof answer.url !== 'string')
33
+ throw new Error(`Hive's answer for ${name} ${route} has no download URL.`);
34
+ const out = { url: answer.url };
35
+ for (const field of ['version', 'manifest', 'key_id', 'signature']) {
36
+ if (typeof answer[field] === 'string')
37
+ out[field] = answer[field];
38
+ }
39
+ return out;
40
+ }
41
+ /**
42
+ * Downloads `url` into `dir`, so a later rename stays on one filesystem. The download carries no node signature,
43
+ * because a presigned URL refuses extra auth. `timeoutMs` ends a download that stalls, so it cannot hold the tick.
44
+ */
45
+ export async function download(run, url, name, dir, timeoutMs) {
46
+ const signal = timeoutMs === undefined ? run.signal : AbortSignal.any([run.signal, AbortSignal.timeout(timeoutMs)]);
47
+ const response = await fetch(url, { signal, redirect: 'follow' });
48
+ if (!response.ok || response.body === null)
49
+ throw new Error(`Downloading ${name} answered ${response.status}.`);
50
+ await mkdir(dir, { recursive: true });
51
+ const file = join(dir, `.download-${name}-${process.pid}.tar.gz`);
52
+ const hash = createHash('sha256');
53
+ const hash512 = createHash('sha512');
54
+ let bytes = 0;
55
+ const count = new Transform({
56
+ transform(chunk, _encoding, done) {
57
+ hash.update(chunk);
58
+ hash512.update(chunk);
59
+ bytes += chunk.length;
60
+ done(null, chunk);
61
+ },
62
+ });
63
+ await pipeline(Readable.fromWeb(response.body), count, createWriteStream(file, { mode: 0o600 }), { signal });
64
+ return { file, sha256: hash.digest('hex'), sha512: hash512.digest('base64'), bytes };
65
+ }
66
+ /** Fetches a binary for `bin/`: asks Hive for its URL, then downloads it into `dir`, which the service users can reach. */
67
+ export async function fetchArtifact(run, name, route, dir) {
68
+ const answer = await requestArtifact(run, name, route);
69
+ await openDir(dir);
70
+ return download(run, answer.url, name, dir);
71
+ }
72
+ /**
73
+ * Makes `dir` and its parents up to `bin/` readable by every user. The supervisor runs with umask 0007 and `bin/` is
74
+ * not setgid, so without this `hive` and `hive-ingress` could not reach the binaries they run.
75
+ */
76
+ async function openDir(dir) {
77
+ await mkdir(dir, { recursive: true });
78
+ for (let at = dir; basename(at) !== 'bin' && at !== dirname(at); at = dirname(at))
79
+ await chmod(at, 0o755);
80
+ }
81
+ /**
82
+ * Unpacks a tarball into a fresh staging directory and returns the directory that holds `binary`: the staging
83
+ * directory itself, or its one top-level directory. OvercyCode archives have a top directory, Caddy's do not.
84
+ * Everything unpacked is made readable, and directories and executables searchable, by every user, and writable by
85
+ * none but the supervisor: tar applies the supervisor's umask, and the engine and the ingress run as other users.
86
+ */
87
+ export async function unpack(run, archive, stage, binary) {
88
+ await rm(stage, { recursive: true, force: true });
89
+ await openDir(stage);
90
+ const result = await run.exec('tar', ['-xzf', archive, '-C', stage]);
91
+ if (result.code !== 0)
92
+ throw new Error(`The archive did not unpack: ${result.stderr.trim().slice(-300)}`);
93
+ const opened = await run.exec('chmod', ['-R', 'u+rwX,go+rX,go-w', stage]);
94
+ if (opened.code !== 0)
95
+ throw new Error(`The unpacked files could not be opened to the service users: ${opened.stderr.trim().slice(-300)}`);
96
+ for (const candidate of [stage, ...(await topDirs(stage))]) {
97
+ if (await isExecutable(join(candidate, binary)))
98
+ return candidate;
99
+ }
100
+ throw new Error(`The archive has no executable ${binary}.`);
101
+ }
102
+ async function topDirs(dir) {
103
+ const entries = await readdir(dir, { withFileTypes: true });
104
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => join(dir, entry.name));
105
+ }
106
+ export async function isExecutable(path) {
107
+ try {
108
+ const info = await stat(path);
109
+ return info.isFile() && (info.mode & 0o111) !== 0;
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ /** Points `link` at `target` with one rename, so a reader sees the old link or the new one, never neither. */
116
+ export async function switchLink(link, target) {
117
+ const temp = `${link}.${process.pid}.new`;
118
+ await rm(temp, { force: true });
119
+ await symlink(target, temp);
120
+ await rename(temp, link);
121
+ }
122
+ export async function linkTarget(link) {
123
+ try {
124
+ return await readlink(link);
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ export async function readText(path) {
131
+ try {
132
+ return await readFile(path, 'utf8');
133
+ }
134
+ catch (error) {
135
+ if (error.code === 'ENOENT')
136
+ return null;
137
+ throw error;
138
+ }
139
+ }
140
+ /** Writes the file when its content or mode differs. Returns whether it wrote. */
141
+ export async function writeIfChanged(path, content, mode) {
142
+ const current = await readText(path);
143
+ if (current === content) {
144
+ const info = await stat(path);
145
+ if ((info.mode & 0o777) === mode)
146
+ return false;
147
+ await chmod(path, mode);
148
+ return true;
149
+ }
150
+ await mkdir(dirname(path), { recursive: true });
151
+ await writeAtomic(path, content, mode);
152
+ return true;
153
+ }
154
+ export const sha256 = (text) => createHash('sha256').update(text).digest('hex');
155
+ /** A value for a file that sh sources with `set -a`: single-quoted, with each `'` closed, escaped and reopened. */
156
+ export function shQuote(value) {
157
+ return `'${value.replaceAll("'", `'\\''`)}'`;
158
+ }
159
+ /** Keeps the newest `keep` entries of a directory, by name, and removes the rest. Names sort by time where it matters. */
160
+ export async function prune(dir, keep, spare = []) {
161
+ let names;
162
+ try {
163
+ names = (await readdir(dir)).filter((name) => !name.startsWith('.')).sort();
164
+ }
165
+ catch {
166
+ return;
167
+ }
168
+ const doomed = names.slice(0, Math.max(0, names.length - keep)).filter((name) => !spare.includes(name));
169
+ for (const name of doomed)
170
+ await rm(join(dir, name), { recursive: true, force: true });
171
+ }