@overcy/hive 0.0.1 → 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 (134) hide show
  1. package/README.md +209 -4
  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 +33 -7
  134. package/bin/hive.js +0 -2
@@ -0,0 +1,155 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { nodeMode } from "../../node/layout.js";
4
+ import { SetupError } from "../types.js";
5
+ import { readText, sha256Hex, tail, writeIfChanged } from "./files.js";
6
+ const LABEL = 'ai.overcy.hive.connect';
7
+ const UNIT = 'hive-connect.service';
8
+ /** On a node the supervisor reports, and a second loop (`hive connect`) would refuse to run beside it. */
9
+ export const appliesReporter = (run) => (nodeMode(run.ctx.env) ? { skip: 'the supervisor reports on a node (hive node run)' } : true);
10
+ export function reporterService(host) {
11
+ return host.os === 'darwin'
12
+ ? { kind: 'launchd', name: LABEL, file: join(host.home, 'Library', 'LaunchAgents', `${LABEL}.plist`) }
13
+ : { kind: 'systemd', name: UNIT, file: join(host.home, '.config', 'systemd', 'user', UNIT) };
14
+ }
15
+ const xml = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
16
+ function serviceEnv(run) {
17
+ const env = {
18
+ HIVE_URL: run.desired.server,
19
+ HIVE_CONFIG_DIR: run.paths.configDir,
20
+ PATH: run.ctx.env.PATH && run.ctx.env.PATH !== '' ? run.ctx.env.PATH : '/usr/local/bin:/usr/bin:/bin',
21
+ };
22
+ if (run.role !== 'proxy-only')
23
+ env.HIVE_LANES_DIR = run.paths.lanesDir;
24
+ if (run.laneSlots !== null && run.role !== 'proxy-only')
25
+ env.HIVE_BOX_SLOTS = String(run.laneSlots);
26
+ return env;
27
+ }
28
+ export function reporterCommand(run) {
29
+ return [run.deps.host.execPath, run.deps.host.cliPath, 'connect'];
30
+ }
31
+ const systemdQuote = (arg) => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `"${arg.replace(/(["\\])/g, '\\$1')}"`);
32
+ export function launchdPlist(run, logPath) {
33
+ const args = reporterCommand(run).map((arg) => ` <string>${xml(arg)}</string>`).join('\n');
34
+ const env = Object.entries(serviceEnv(run)).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join('\n');
35
+ return `<?xml version="1.0" encoding="UTF-8"?>
36
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
37
+ <plist version="1.0">
38
+ <dict>
39
+ <key>Label</key>
40
+ <string>${LABEL}</string>
41
+ <key>ProgramArguments</key>
42
+ <array>
43
+ ${args}
44
+ </array>
45
+ <key>EnvironmentVariables</key>
46
+ <dict>
47
+ ${env}
48
+ </dict>
49
+ <key>RunAtLoad</key>
50
+ <true/>
51
+ <key>KeepAlive</key>
52
+ <true/>
53
+ <key>StandardOutPath</key>
54
+ <string>${xml(logPath)}</string>
55
+ <key>StandardErrorPath</key>
56
+ <string>${xml(logPath)}</string>
57
+ </dict>
58
+ </plist>
59
+ `;
60
+ }
61
+ export function systemdUnit(run) {
62
+ const env = Object.entries(serviceEnv(run)).map(([key, value]) => `Environment="${key}=${value.replace(/"/g, '\\"')}"`).join('\n');
63
+ return `[Unit]
64
+ Description=Hive status reporter
65
+ After=network-online.target
66
+
67
+ [Service]
68
+ ExecStart=${reporterCommand(run).map(systemdQuote).join(' ')}
69
+ ${env}
70
+ Restart=always
71
+ RestartSec=30
72
+
73
+ [Install]
74
+ WantedBy=default.target
75
+ `;
76
+ }
77
+ const lingerCommand = (run) => `sudo loginctl enable-linger ${run.deps.host.username}`;
78
+ const lingerOn = async (run) => /Linger=yes/.test((await run.deps.exec('loginctl', ['show-user', run.deps.host.username, '-p', 'Linger'])).stdout);
79
+ const unitContent = (run) => (run.deps.host.os === 'darwin' ? launchdPlist(run, join(run.paths.configDir, 'reporter.log')) : systemdUnit(run));
80
+ async function serviceRunning(run) {
81
+ const { exec, host } = run.deps;
82
+ return host.os === 'darwin' ? (await exec('launchctl', ['print', `gui/${host.uid}/${LABEL}`])).code === 0 : (await exec('systemctl', ['--user', 'is-active', '--quiet', UNIT])).code === 0;
83
+ }
84
+ export const observeReporter = async (run) => {
85
+ const { host } = run.deps;
86
+ const kind = host.os === 'darwin' ? 'launchd agent' : 'systemd user unit';
87
+ const current = await readText(reporterService(host).file);
88
+ if (current === null)
89
+ return { status: 'failing', detail: `the reporter service is not installed (${kind})`, fix: 'Run `hive setup`, which installs and starts it.' };
90
+ if (!(await serviceRunning(run)))
91
+ return { status: 'failing', detail: `the reporter service is installed but not running (${kind})`, fix: 'Run `hive setup`, which restarts it.' };
92
+ if (current !== unitContent(run))
93
+ return { status: 'stale', detail: `the reporter service file differs from what this CLI writes (${kind})`, fix: 'Run `hive setup`, which rewrites it.' };
94
+ if (host.os === 'linux' && !(await lingerOn(run)))
95
+ return { status: 'needs_action', detail: `the reporter runs, but it stops at logout and after a reboot until lingering is on (${kind})`, fix: `Run: ${lingerCommand(run)}` };
96
+ return { status: 'ok', detail: `the reporter service is installed and running (${kind})`, fix: null };
97
+ };
98
+ async function ensureLinger(run) {
99
+ const { exec, host } = run.deps;
100
+ const user = host.username;
101
+ const command = lingerCommand(run);
102
+ const has = () => lingerOn(run);
103
+ if (await has())
104
+ return { state: 'on', command };
105
+ if (run.opts.dryRun)
106
+ return { state: 'needs_action', command };
107
+ for (const [bin, args] of [['loginctl', ['enable-linger', user]], ['sudo', ['-n', 'loginctl', 'enable-linger', user]]]) {
108
+ if ((await exec(bin, args)).code === 0 && (await has()))
109
+ return { state: 'enabled', command };
110
+ }
111
+ return { state: 'needs_action', command };
112
+ }
113
+ export const reporterStep = async (run) => {
114
+ const outcome = await installReporter(run);
115
+ if (run.deps.host.os !== 'linux' || outcome.status === 'would')
116
+ return outcome;
117
+ const linger = await ensureLinger(run);
118
+ if (linger.state === 'needs_action')
119
+ return { status: 'needs_action', detail: `${outcome.detail}. It stops at logout and after a reboot until lingering is on. Run: ${linger.command}` };
120
+ if (linger.state === 'enabled')
121
+ return { status: 'done', detail: `${outcome.detail}; enabled lingering so it survives logout and reboot` };
122
+ return outcome;
123
+ };
124
+ const installReporter = async (run) => {
125
+ const { exec, host } = run.deps;
126
+ const mac = host.os === 'darwin';
127
+ const unitPath = reporterService(host).file;
128
+ const content = unitContent(run);
129
+ const domain = `gui/${host.uid}`;
130
+ const running = () => serviceRunning(run);
131
+ const current = await readText(unitPath);
132
+ const upToDate = current === content && (await running());
133
+ if (upToDate) {
134
+ run.saved.applied.reporter = sha256Hex(content);
135
+ return { status: 'unchanged', detail: `the reporter service is installed and running (${mac ? 'launchd' : 'systemd user unit'})` };
136
+ }
137
+ if (run.opts.dryRun)
138
+ return { status: 'would', detail: `install and start the reporter as a ${mac ? 'launchd agent' : 'systemd user unit'}` };
139
+ await mkdir(dirname(unitPath), { recursive: true });
140
+ await mkdir(run.paths.configDir, { recursive: true });
141
+ await writeIfChanged(unitPath, content, 0o644);
142
+ const commands = mac
143
+ ? [['launchctl', ['bootout', `${domain}/${LABEL}`]], ['launchctl', ['bootstrap', domain, unitPath]]]
144
+ : [['systemctl', ['--user', 'daemon-reload']], ['systemctl', ['--user', 'enable', UNIT]], ['systemctl', ['--user', 'restart', UNIT]]];
145
+ for (const [command, args] of commands) {
146
+ const result = await exec(command, args);
147
+ const optional = command === 'launchctl' && args[0] === 'bootout';
148
+ if (result.code !== 0 && !optional)
149
+ throw new SetupError(`${command} ${args[0]} failed: ${tail(result)}`);
150
+ }
151
+ if (!(await running()))
152
+ throw new SetupError('The reporter service was installed but is not running.');
153
+ run.saved.applied.reporter = sha256Hex(content);
154
+ return { status: current === null ? 'done' : 'repaired', detail: `${current === null ? 'installed' : 'repaired'} and started the reporter (${mac ? 'launchd agent' : 'systemd user unit'})` };
155
+ };
@@ -0,0 +1,5 @@
1
+ import type { Exec, Host } from './types.ts';
2
+ export declare function makeExec(baseEnv: NodeJS.ProcessEnv): Exec;
3
+ export declare function hostInfo(env: NodeJS.ProcessEnv): Promise<Host>;
4
+ export declare function currentUsername(lookup?: () => string, env?: NodeJS.ProcessEnv, uid?: number | null): string;
5
+ export declare function fetchBytes(url: string, signal: AbortSignal): Promise<Uint8Array>;
@@ -0,0 +1,69 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { cpus, arch, hostname, homedir, platform, totalmem, userInfo } from 'node:os';
3
+ import { statfs } from 'node:fs/promises';
4
+ import { fileURLToPath } from 'node:url';
5
+ const MAX_DOWNLOAD_BYTES = 256 * 1024 * 1024;
6
+ const CREDENTIAL_ENV = new Set(['HIVE_REGISTRATION_TOKEN', 'HIVE_LOCAL_KEY']);
7
+ export function makeExec(baseEnv) {
8
+ const inherited = Object.entries(baseEnv).filter(([key]) => !CREDENTIAL_ENV.has(key));
9
+ return (command, args, options = {}) => new Promise((resolve) => {
10
+ const env = {};
11
+ for (const [key, value] of [...inherited, ...Object.entries(options.env ?? {})])
12
+ if (typeof value === 'string')
13
+ env[key] = value;
14
+ const child = spawn(command, args, { env, cwd: options.cwd, timeout: 120_000, stdio: ['pipe', 'pipe', 'pipe'] });
15
+ let stdout = '';
16
+ let stderr = '';
17
+ child.stdout.on('data', (chunk) => (stdout += chunk.toString('utf8')));
18
+ child.stderr.on('data', (chunk) => (stderr += chunk.toString('utf8')));
19
+ child.on('error', (error) => resolve({ code: 127, stdout, stderr: `${stderr}${error.message}` }));
20
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
21
+ child.stdin.on('error', () => undefined);
22
+ child.stdin.end(options.input ?? '');
23
+ });
24
+ }
25
+ export async function hostInfo(env) {
26
+ const home = env.HOME && env.HOME !== '' ? env.HOME : homedir();
27
+ let freeDiskGb = null;
28
+ try {
29
+ const fs = await statfs(home);
30
+ freeDiskGb = Math.floor((fs.bavail * fs.bsize) / 1024 ** 3);
31
+ }
32
+ catch {
33
+ freeDiskGb = null;
34
+ }
35
+ return {
36
+ os: platform(),
37
+ arch: arch(),
38
+ node: process.versions.node,
39
+ cores: Math.max(1, cpus().length),
40
+ ramGb: Math.max(1, Math.round(totalmem() / 1024 ** 3)),
41
+ execPath: process.execPath,
42
+ cliPath: fileURLToPath(new URL(`../cli.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`, import.meta.url)),
43
+ hostname: hostname(),
44
+ username: currentUsername(undefined, env),
45
+ home,
46
+ uid: typeof process.getuid === 'function' ? process.getuid() : 0,
47
+ freeDiskGb,
48
+ };
49
+ }
50
+ export function currentUsername(lookup = () => userInfo().username, env = process.env, uid = typeof process.getuid === 'function' ? process.getuid() : null) {
51
+ try {
52
+ return lookup();
53
+ }
54
+ catch {
55
+ return env.USER || env.LOGNAME || (uid === null ? 'unknown' : `uid-${uid}`);
56
+ }
57
+ }
58
+ export async function fetchBytes(url, signal) {
59
+ const response = await fetch(url, { signal, redirect: 'follow' });
60
+ if (!response.ok)
61
+ throw new Error(`Downloading ${url} answered ${response.status}.`);
62
+ const declared = Number(response.headers.get('content-length') ?? 0);
63
+ if (declared > MAX_DOWNLOAD_BYTES)
64
+ throw new Error(`Refusing to download ${declared} bytes from ${url}.`);
65
+ const bytes = new Uint8Array(await response.arrayBuffer());
66
+ if (bytes.byteLength > MAX_DOWNLOAD_BYTES)
67
+ throw new Error(`Refusing a download of ${bytes.byteLength} bytes from ${url}.`);
68
+ return bytes;
69
+ }
@@ -0,0 +1,157 @@
1
+ import type { Context } from '../context.ts';
2
+ import type { Health } from './plan.ts';
3
+ import type { StepId } from './registry.ts';
4
+ import type { KitSource } from './kit.ts';
5
+ import type { ModelAccessSource, ModelAccessStore } from './model-access.ts';
6
+ export declare const ROLES: readonly ["primary", "worker", "lite", "proxy-only"];
7
+ export type Role = (typeof ROLES)[number];
8
+ export declare function normalizeRole(value: string): Role | null;
9
+ export declare function isRole(value: unknown): value is Role;
10
+ export type BootstrapOptions = {
11
+ apiUrl: string;
12
+ role?: Role;
13
+ registrationToken?: string;
14
+ slots?: number;
15
+ hiveProxy: 'install' | 'skip';
16
+ kitRelease?: string;
17
+ dryRun?: boolean;
18
+ name?: string;
19
+ team?: string;
20
+ configureAgents?: boolean;
21
+ saveApiUrl?: boolean;
22
+ toolchain?: string;
23
+ };
24
+ export type ResolvedOptions = BootstrapOptions & {
25
+ dryRun: boolean;
26
+ };
27
+ export type OutcomeStatus = 'done' | 'repaired' | 'unchanged' | 'skipped' | 'failed' | 'would' | 'needs_action';
28
+ export type Outcome = {
29
+ status: OutcomeStatus;
30
+ detail: string;
31
+ };
32
+ export type StepResult = Outcome & {
33
+ step: StepId;
34
+ };
35
+ export declare class SetupError extends Error {
36
+ constructor(message: string);
37
+ }
38
+ export type ExecOptions = {
39
+ env?: Record<string, string>;
40
+ input?: string;
41
+ cwd?: string;
42
+ };
43
+ export type ExecResult = {
44
+ code: number;
45
+ stdout: string;
46
+ stderr: string;
47
+ };
48
+ export type Exec = (command: string, args: string[], options?: ExecOptions) => Promise<ExecResult>;
49
+ export type Host = {
50
+ os: NodeJS.Platform;
51
+ arch: string;
52
+ node: string;
53
+ cores: number;
54
+ ramGb: number;
55
+ execPath: string;
56
+ cliPath: string;
57
+ hostname: string;
58
+ username: string;
59
+ home: string;
60
+ uid: number;
61
+ freeDiskGb: number | null;
62
+ };
63
+ export type Pin = {
64
+ release: {
65
+ version: string;
66
+ url: string;
67
+ sha256: string;
68
+ files?: Record<string, string>;
69
+ } | null;
70
+ proxy: {
71
+ version: string;
72
+ };
73
+ };
74
+ export type Prompter = {
75
+ interactive: boolean;
76
+ choose: (question: string, choices: readonly string[], fallback: string) => Promise<string>;
77
+ confirm: (question: string) => Promise<boolean>;
78
+ };
79
+ export type SetupDeps = {
80
+ exec: Exec;
81
+ host: Host;
82
+ pin: Pin;
83
+ fetchBytes: (url: string, signal: AbortSignal) => Promise<Uint8Array>;
84
+ prompt: Prompter;
85
+ kit: KitSource;
86
+ modelAccessSource: ModelAccessSource;
87
+ modelAccessStore: ModelAccessStore;
88
+ probeForwarder: (port: number) => Promise<boolean>;
89
+ journalFault?: (point: 'after-pending' | 'before-done' | 'after-sibling' | 'after-mkdir', step: string) => void | Promise<void>;
90
+ };
91
+ export type AppliedState = {
92
+ release?: string;
93
+ slots?: number;
94
+ cron_release?: string;
95
+ role_seen?: Role;
96
+ env_hash?: string;
97
+ cron_role?: Role;
98
+ model_access?: string;
99
+ model_access_store?: 'keychain' | 'file';
100
+ drift?: string;
101
+ reporter?: string;
102
+ };
103
+ export type DesiredConfig = {
104
+ role: Role | null;
105
+ server: string;
106
+ slots: number | null;
107
+ toolchain: string | null;
108
+ kit_release: string | null;
109
+ };
110
+ /**
111
+ * What `setup.json` holds. There is no resume cursor: every run starts at the
112
+ * first step and each step checks, then repairs. An older file may still carry
113
+ * `state` and `since`. They are ignored and dropped on the next write.
114
+ */
115
+ export type SetupFile = {
116
+ last_error: string | null;
117
+ desired: DesiredConfig | null;
118
+ applied: AppliedState;
119
+ };
120
+ export type Paths = {
121
+ configDir: string;
122
+ hiveHome: string;
123
+ dataDir: string;
124
+ envFile: string;
125
+ lanesDir: string;
126
+ releaseDir: (version: string) => string;
127
+ };
128
+ export type SetupRun = {
129
+ ctx: Context;
130
+ opts: ResolvedOptions;
131
+ deps: SetupDeps;
132
+ paths: Paths;
133
+ signal: AbortSignal;
134
+ saved: SetupFile;
135
+ desired: DesiredConfig;
136
+ role: Role | null;
137
+ laneSlots: number | null;
138
+ results: StepResult[];
139
+ local: {
140
+ port: number;
141
+ key: string;
142
+ } | null;
143
+ };
144
+ export type StepFn = (run: SetupRun) => Promise<Outcome>;
145
+ /** What a read-only look at one step found. `fix` is what to do about it, or null when healthy. */
146
+ export type Observation = {
147
+ status: Health;
148
+ detail: string;
149
+ fix: string | null;
150
+ };
151
+ /** Reads the machine and changes nothing on disk or on the network. It may set in-memory fields on `run` that later steps read. */
152
+ export type ObserveFn = (run: SetupRun) => Promise<Observation>;
153
+ /** `true` when the step is part of this node's checklist, else the reason it is left out. */
154
+ export type Applicability = true | {
155
+ skip: string;
156
+ };
157
+ export type AppliesFn = (run: SetupRun) => Applicability;
@@ -0,0 +1,14 @@
1
+ export const ROLES = ['primary', 'worker', 'lite', 'proxy-only'];
2
+ export function normalizeRole(value) {
3
+ const cleaned = value.trim().toLowerCase().replace(/[\s_]+/g, '-');
4
+ return ROLES.includes(cleaned) ? cleaned : null;
5
+ }
6
+ export function isRole(value) {
7
+ return typeof value === 'string' && ROLES.includes(value);
8
+ }
9
+ export class SetupError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'SetupError';
13
+ }
14
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "./run.js";
3
+ const controller = new AbortController();
4
+ let interrupts = 0;
5
+ for (const signal of ['SIGINT', 'SIGTERM']) {
6
+ process.on(signal, () => {
7
+ interrupts += 1;
8
+ if (interrupts > 1)
9
+ process.exit(130);
10
+ controller.abort();
11
+ });
12
+ }
13
+ const io = {
14
+ out: (line) => process.stdout.write(`${line}\n`),
15
+ err: (line) => process.stderr.write(`${line}\n`),
16
+ };
17
+ try {
18
+ process.exitCode = await run(process.argv.slice(2), process.env, io, controller.signal);
19
+ }
20
+ catch (error) {
21
+ io.err(error instanceof Error ? error.message : String(error));
22
+ process.exitCode = 1;
23
+ }
@@ -0,0 +1,28 @@
1
+ export type StatusBody = {
2
+ schema_version: '0';
3
+ sent_at: string;
4
+ source: {
5
+ kind: 'box' | 'agent';
6
+ id: string;
7
+ };
8
+ box: {
9
+ cpus: number;
10
+ load: [number, number, number];
11
+ disk_used_percent: number;
12
+ limits?: {
13
+ lane_max: number;
14
+ };
15
+ };
16
+ lanes?: {
17
+ name: string;
18
+ log_idle_minutes: number | null;
19
+ }[];
20
+ };
21
+ export declare function nodeNameFrom(raw: string): string;
22
+ export declare function defaultNodeName(): string;
23
+ export declare function diskUsedPercent(path?: string): Promise<number>;
24
+ export declare function collectLanes(dir: string, now: number): Promise<{
25
+ name: string;
26
+ log_idle_minutes: number | null;
27
+ }[]>;
28
+ export declare function collectStatus(name: string, kind: 'machine' | 'session', lanesDir: string | null, now?: Date, laneMax?: number | null): Promise<StatusBody>;
@@ -0,0 +1,63 @@
1
+ import { readdir, stat, statfs } from 'node:fs/promises';
2
+ import { cpus, hostname, loadavg } from 'node:os';
3
+ import { join } from 'node:path';
4
+ const WIRE_KIND = { machine: 'box', session: 'agent' };
5
+ export function nodeNameFrom(raw) {
6
+ const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^-+|-+$/g, '').slice(0, 128);
7
+ return cleaned === '' ? 'node' : cleaned;
8
+ }
9
+ export function defaultNodeName() {
10
+ return nodeNameFrom(hostname());
11
+ }
12
+ export async function diskUsedPercent(path = '/') {
13
+ const fs = await statfs(path);
14
+ const total = fs.blocks;
15
+ if (total === 0)
16
+ return 0;
17
+ const used = total - fs.bfree;
18
+ const available = fs.bavail;
19
+ return Math.max(0, Math.min(100, Math.round((used / (used + available)) * 100)));
20
+ }
21
+ export async function collectLanes(dir, now) {
22
+ let entries;
23
+ try {
24
+ entries = await readdir(dir, { withFileTypes: true });
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ const lanes = [];
30
+ for (const entry of entries) {
31
+ if (!entry.isDirectory() || !/^[A-Za-z0-9._-]{1,128}$/.test(entry.name))
32
+ continue;
33
+ let newest = null;
34
+ for (const file of await readdir(join(dir, entry.name)).catch(() => [])) {
35
+ if (!file.endsWith('.log'))
36
+ continue;
37
+ const info = await stat(join(dir, entry.name, file)).catch(() => null);
38
+ if (info && (newest === null || info.mtimeMs > newest))
39
+ newest = info.mtimeMs;
40
+ }
41
+ lanes.push({ name: entry.name, log_idle_minutes: newest === null ? null : Math.max(0, Math.floor((now - newest) / 60_000)) });
42
+ }
43
+ return lanes.slice(0, 500);
44
+ }
45
+ export async function collectStatus(name, kind, lanesDir, now = new Date(), laneMax = null) {
46
+ const [one = 0, five = 0, fifteen = 0] = loadavg();
47
+ const body = {
48
+ schema_version: '0',
49
+ sent_at: now.toISOString().replace(/\.\d{3}Z$/, 'Z'),
50
+ source: { kind: WIRE_KIND[kind], id: name },
51
+ box: {
52
+ cpus: Math.max(1, cpus().length),
53
+ load: [round2(one), round2(five), round2(fifteen)],
54
+ disk_used_percent: await diskUsedPercent().catch(() => 0),
55
+ },
56
+ };
57
+ if (laneMax !== null)
58
+ body.box.limits = { lane_max: laneMax };
59
+ if (lanesDir)
60
+ body.lanes = await collectLanes(lanesDir, now.getTime());
61
+ return body;
62
+ }
63
+ const round2 = (n) => Math.round(n * 100) / 100;
@@ -0,0 +1,33 @@
1
+ import { type NodeFile, type KeyFile } from '../config.ts';
2
+ import type { Context } from '../context.ts';
3
+ import { type ConnectionState } from '../machine.ts';
4
+ export type Enrollment = {
5
+ cores?: number;
6
+ ram_gb?: number;
7
+ role?: string;
8
+ slots?: number;
9
+ };
10
+ export type ConnectOptions = {
11
+ once: boolean;
12
+ name?: string;
13
+ team?: string;
14
+ rebind: boolean;
15
+ rotate: boolean;
16
+ reconnect?: string;
17
+ token?: string;
18
+ tokenFile?: string;
19
+ intervalSeconds?: number;
20
+ enrollment?: Enrollment;
21
+ };
22
+ export declare function connect(ctx: Context, options: ConnectOptions, signal: AbortSignal): Promise<number>;
23
+ export type Heartbeat = {
24
+ state: ConnectionState; /** What Hive's answer says the desired revision is, or null when it did not say. */
25
+ desiredRevision: number | null; /** Why the post did not land, or null. */
26
+ error: string | null;
27
+ };
28
+ /**
29
+ * One status post. `laneMax` overrides `HIVE_BOX_SLOTS`, so the supervisor can report the slots Hive asked for.
30
+ * `stamp` is the post's `sent_at`. Hive keeps one post per second and node, so two posts in one second need distinct stamps.
31
+ * The answer's `desired_revision` is how a node learns that Hive changed something.
32
+ */
33
+ export declare function postOnce(ctx: Context, node: NodeFile, key: KeyFile, lanesDir: string | null, signal: AbortSignal, laneMax?: number | null, stamp?: Date): Promise<Heartbeat>;