@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,85 @@
1
+ import type { AppliesFn, ObserveFn, StepFn } from './types.ts';
2
+ export type Step = {
3
+ id: string;
4
+ /** Ids of earlier steps that must work before this one can. `planTick` blocks the step while one of them is failing. */
5
+ needs: readonly string[];
6
+ /** Whether the step is part of this node's checklist, else why it is left out. Reads `run.role`, which the `role` step sets. */
7
+ applies: AppliesFn;
8
+ /** Reads the machine and says how this step stands. Never writes. */
9
+ observe: ObserveFn;
10
+ /** Checks and fixes the step, then says what it did. Setup runs it on every run. */
11
+ repair: StepFn;
12
+ };
13
+ /**
14
+ * The one ordered list of setup steps. Setup walks it, `hive doctor` observes
15
+ * it, and the report to Hive reads its ids from it. A new step is one entry
16
+ * here, in the position it runs.
17
+ *
18
+ * Today's ten steps keep the behavior of the old fixed sequence, so each one
19
+ * needs the step before it. That is a chain, not a real dependency graph: it
20
+ * makes a failure stop everything after it, as setup always did. The steps that
21
+ * come next declare what they actually need.
22
+ */
23
+ export declare const STEPS: readonly [{
24
+ readonly id: "preflight";
25
+ readonly needs: readonly [];
26
+ readonly applies: AppliesFn;
27
+ readonly observe: ObserveFn;
28
+ readonly repair: StepFn;
29
+ }, {
30
+ readonly id: "login";
31
+ readonly needs: readonly ["preflight"];
32
+ readonly applies: AppliesFn;
33
+ readonly observe: ObserveFn;
34
+ readonly repair: StepFn;
35
+ }, {
36
+ readonly id: "role";
37
+ readonly needs: readonly ["login"];
38
+ readonly applies: AppliesFn;
39
+ readonly observe: ObserveFn;
40
+ readonly repair: StepFn;
41
+ }, {
42
+ readonly id: "enroll";
43
+ readonly needs: readonly ["role"];
44
+ readonly applies: AppliesFn;
45
+ readonly observe: ObserveFn;
46
+ readonly repair: StepFn;
47
+ }, {
48
+ readonly id: "model-access";
49
+ readonly needs: readonly ["enroll"];
50
+ readonly applies: AppliesFn;
51
+ readonly observe: ObserveFn;
52
+ readonly repair: StepFn;
53
+ }, {
54
+ readonly id: "lanes";
55
+ readonly needs: readonly ["model-access"];
56
+ readonly applies: AppliesFn;
57
+ readonly observe: ObserveFn;
58
+ readonly repair: StepFn;
59
+ }, {
60
+ readonly id: "env";
61
+ readonly needs: readonly ["lanes"];
62
+ readonly applies: AppliesFn;
63
+ readonly observe: ObserveFn;
64
+ readonly repair: StepFn;
65
+ }, {
66
+ readonly id: "cron";
67
+ readonly needs: readonly ["env"];
68
+ readonly applies: AppliesFn;
69
+ readonly observe: ObserveFn;
70
+ readonly repair: StepFn;
71
+ }, {
72
+ readonly id: "drift";
73
+ readonly needs: readonly ["cron"];
74
+ readonly applies: AppliesFn;
75
+ readonly observe: ObserveFn;
76
+ readonly repair: StepFn;
77
+ }, {
78
+ readonly id: "reporter";
79
+ readonly needs: readonly ["drift"];
80
+ readonly applies: AppliesFn;
81
+ readonly observe: ObserveFn;
82
+ readonly repair: StepFn;
83
+ }];
84
+ export type StepId = (typeof STEPS)[number]['id'];
85
+ export declare function stepById(id: string): (typeof STEPS)[number];
@@ -0,0 +1,38 @@
1
+ import { appliesCron, cronStep, observeCron } from "./steps/cron.js";
2
+ import { appliesDrift, driftStep, observeDrift } from "./steps/drift.js";
3
+ import { enrollStep, loginStep, observeEnroll, observeLogin, observeRole, roleStep } from "./steps/auth.js";
4
+ import { envStep, observeEnv } from "./steps/env.js";
5
+ import { appliesLanes, lanesStep, observeLanes } from "./steps/lanes.js";
6
+ import { modelAccessStep, observeModelAccess } from "./steps/model-access.js";
7
+ import { observePreflight, preflight } from "./steps/preflight.js";
8
+ import { appliesReporter, observeReporter, reporterStep } from "./steps/reporter.js";
9
+ /** A step applies to every node unless it says otherwise. */
10
+ const always = () => true;
11
+ /**
12
+ * The one ordered list of setup steps. Setup walks it, `hive doctor` observes
13
+ * it, and the report to Hive reads its ids from it. A new step is one entry
14
+ * here, in the position it runs.
15
+ *
16
+ * Today's ten steps keep the behavior of the old fixed sequence, so each one
17
+ * needs the step before it. That is a chain, not a real dependency graph: it
18
+ * makes a failure stop everything after it, as setup always did. The steps that
19
+ * come next declare what they actually need.
20
+ */
21
+ export const STEPS = [
22
+ { id: 'preflight', needs: [], applies: always, observe: observePreflight, repair: preflight },
23
+ { id: 'login', needs: ['preflight'], applies: always, observe: observeLogin, repair: loginStep },
24
+ { id: 'role', needs: ['login'], applies: always, observe: observeRole, repair: roleStep },
25
+ { id: 'enroll', needs: ['role'], applies: always, observe: observeEnroll, repair: enrollStep },
26
+ { id: 'model-access', needs: ['enroll'], applies: always, observe: observeModelAccess, repair: modelAccessStep },
27
+ { id: 'lanes', needs: ['model-access'], applies: appliesLanes, observe: observeLanes, repair: lanesStep },
28
+ { id: 'env', needs: ['lanes'], applies: always, observe: observeEnv, repair: envStep },
29
+ { id: 'cron', needs: ['env'], applies: appliesCron, observe: observeCron, repair: cronStep },
30
+ { id: 'drift', needs: ['cron'], applies: appliesDrift, observe: observeDrift, repair: driftStep },
31
+ { id: 'reporter', needs: ['drift'], applies: appliesReporter, observe: observeReporter, repair: reporterStep },
32
+ ];
33
+ export function stepById(id) {
34
+ const found = STEPS.find((step) => step.id === id);
35
+ if (!found)
36
+ throw new Error(`${id} is not a setup step.`);
37
+ return found;
38
+ }
@@ -0,0 +1,11 @@
1
+ import type { ModelAccessStore } from './model-access.ts';
2
+ import type { Exec, Host } from './types.ts';
3
+ export type SecretStore = {
4
+ kind: 'keychain' | 'file';
5
+ get: (name: string) => Promise<string | null>;
6
+ set: (name: string, value: string) => Promise<boolean>;
7
+ };
8
+ export declare function keychainSecrets(exec: Exec, os: NodeJS.Platform): SecretStore | null;
9
+ export declare function fileModelAccess(configDir: string): ModelAccessStore;
10
+ export declare function keychainModelAccess(secrets: SecretStore): ModelAccessStore;
11
+ export declare function makeModelAccessStore(exec: Exec, host: Host, configDir: string): Promise<ModelAccessStore>;
@@ -0,0 +1,105 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { readText, writeAtomic } from "./steps/files.js";
4
+ const SERVICE = 'hive';
5
+ export function keychainSecrets(exec, os) {
6
+ if (os === 'darwin') {
7
+ return {
8
+ kind: 'keychain',
9
+ async get(name) {
10
+ const result = await exec('security', ['find-generic-password', '-s', SERVICE, '-a', name, '-w']);
11
+ return result.code === 0 ? result.stdout.replace(/\n$/, '') : null;
12
+ },
13
+ async set(name, value) {
14
+ if ((await this.get(name)) === value)
15
+ return false;
16
+ const quoted = `"${value.replace(/(["\\])/g, '\\$1')}"`;
17
+ const result = await exec('security', ['-i'], { input: `add-generic-password -U -s ${SERVICE} -a ${name} -w ${quoted}\n` });
18
+ if (result.code !== 0)
19
+ throw new Error('The macOS keychain refused the secret.');
20
+ return true;
21
+ },
22
+ };
23
+ }
24
+ if (os === 'linux') {
25
+ return {
26
+ kind: 'keychain',
27
+ async get(name) {
28
+ const result = await exec('secret-tool', ['lookup', 'service', SERVICE, 'account', name]);
29
+ return result.code === 0 && result.stdout !== '' ? result.stdout.replace(/\n$/, '') : null;
30
+ },
31
+ async set(name, value) {
32
+ if ((await this.get(name)) === value)
33
+ return false;
34
+ const result = await exec('secret-tool', ['store', '--label', `hive ${name}`, 'service', SERVICE, 'account', name], { input: value });
35
+ if (result.code !== 0)
36
+ throw new Error('The system keyring refused the secret.');
37
+ return true;
38
+ },
39
+ };
40
+ }
41
+ return null;
42
+ }
43
+ const ACCESS_NAME = 'model-access';
44
+ export function fileModelAccess(configDir) {
45
+ const path = join(configDir, 'model-access.json');
46
+ return {
47
+ kind: 'file',
48
+ async read() {
49
+ const text = await readText(path);
50
+ return text === null ? null : JSON.parse(text);
51
+ },
52
+ write: (access) => writeAtomic(path, `${JSON.stringify(access, null, 2)}\n`, 0o600),
53
+ };
54
+ }
55
+ export function keychainModelAccess(secrets) {
56
+ return {
57
+ kind: 'keychain',
58
+ async read() {
59
+ const text = await secrets.get(ACCESS_NAME);
60
+ return text === null ? null : JSON.parse(text);
61
+ },
62
+ async write(access) {
63
+ await secrets.set(ACCESS_NAME, JSON.stringify(access));
64
+ },
65
+ };
66
+ }
67
+ async function keychainPresent(exec, os) {
68
+ if (os !== 'darwin')
69
+ return true;
70
+ const result = await exec('security', ['default-keychain']).catch(() => null);
71
+ const path = result?.code === 0 ? /"([^"]+)"/.exec(result.stdout)?.[1] : undefined;
72
+ return path !== undefined && existsSync(path);
73
+ }
74
+ export async function makeModelAccessStore(exec, host, configDir) {
75
+ const file = fileModelAccess(configDir);
76
+ const keychain = keychainSecrets(exec, host.os);
77
+ if (!keychain || !(await keychainPresent(exec, host.os)))
78
+ return file;
79
+ const inKeychain = keychainModelAccess(keychain);
80
+ let active = inKeychain;
81
+ return {
82
+ get kind() {
83
+ return active.kind;
84
+ },
85
+ async read() {
86
+ const saved = await inKeychain.read().catch(() => null);
87
+ if (saved)
88
+ return saved;
89
+ const fromFile = await file.read();
90
+ if (fromFile)
91
+ active = file;
92
+ return fromFile;
93
+ },
94
+ async write(access) {
95
+ try {
96
+ await inKeychain.write(access);
97
+ active = inKeychain;
98
+ }
99
+ catch {
100
+ active = file;
101
+ await file.write(access);
102
+ }
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,9 @@
1
+ export declare const CLAUDE_ENV_KEYS: readonly ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"];
2
+ export declare const CODEX_ENV_KEY = "HIVE_LOCAL_KEY";
3
+ export declare function writeClaudeEnv(home: string, wanted: Record<string, string>): Promise<boolean>;
4
+ export declare function codexConfig(existing: string, proxy: {
5
+ baseUrl: string;
6
+ } | null): string;
7
+ export declare function writeCodexConfig(dir: string, proxy: {
8
+ baseUrl: string;
9
+ } | null, file?: string): Promise<boolean>;
@@ -0,0 +1,75 @@
1
+ import { chmod, mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { SetupError } from "../types.js";
4
+ import { readText, writeAtomic } from "./files.js";
5
+ export const CLAUDE_ENV_KEYS = ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN'];
6
+ export const CODEX_ENV_KEY = 'HIVE_LOCAL_KEY';
7
+ const TOP_BEGIN = '# BEGIN hive usage (top)';
8
+ const TOP_END = '# END hive usage (top)';
9
+ const TABLE_BEGIN = '# BEGIN hive usage';
10
+ const TABLE_END = '# END hive usage';
11
+ export async function writeClaudeEnv(home, wanted) {
12
+ const dir = join(home, '.claude');
13
+ const path = join(dir, 'settings.json');
14
+ const text = await readText(path);
15
+ let settings = {};
16
+ if (text !== null && text.trim() !== '') {
17
+ try {
18
+ settings = JSON.parse(text);
19
+ }
20
+ catch {
21
+ throw new SetupError(`${path} is not valid JSON, so Claude Code's usage settings were not written. Fix or move it, then run setup again.`);
22
+ }
23
+ }
24
+ const env = { ...(settings.env ?? {}) };
25
+ for (const key of CLAUDE_ENV_KEYS)
26
+ delete env[key];
27
+ Object.assign(env, wanted);
28
+ const next = `${JSON.stringify({ ...settings, env }, null, 2)}\n`;
29
+ if (text === next) {
30
+ await chmod(path, 0o600);
31
+ return false;
32
+ }
33
+ await mkdir(dir, { recursive: true, mode: 0o700 });
34
+ await writeAtomic(path, next, 0o600);
35
+ return true;
36
+ }
37
+ function strip(lines, begin, end) {
38
+ const kept = [];
39
+ let inside = false;
40
+ for (const line of lines) {
41
+ if (line === begin)
42
+ inside = true;
43
+ else if (line === end)
44
+ inside = false;
45
+ else if (!inside)
46
+ kept.push(line);
47
+ }
48
+ return kept;
49
+ }
50
+ export function codexConfig(existing, proxy) {
51
+ let lines = strip(strip(existing.split('\n'), TOP_BEGIN, TOP_END), TABLE_BEGIN, TABLE_END);
52
+ while (lines.length > 0 && lines[lines.length - 1] === '')
53
+ lines.pop();
54
+ if (proxy) {
55
+ const userOwnsProvider = lines.some((line) => /^\s*model_provider\s*=/.test(line));
56
+ const top = userOwnsProvider ? [] : [TOP_BEGIN, 'model_provider = "hive"', TOP_END];
57
+ const table = [TABLE_BEGIN, '[model_providers.hive]', 'name = "Hive"', `base_url = "${proxy.baseUrl}"`, `env_key = "${CODEX_ENV_KEY}"`, 'wire_api = "responses"', TABLE_END];
58
+ lines = [...top, ...(top.length > 0 && lines.length > 0 ? [''] : []), ...lines, ...(lines.length > 0 || top.length > 0 ? [''] : []), ...table];
59
+ }
60
+ return lines.length === 0 ? '' : `${lines.join('\n')}\n`;
61
+ }
62
+ export async function writeCodexConfig(dir, proxy, file = 'config.toml') {
63
+ const path = join(dir, file);
64
+ const text = await readText(path);
65
+ const next = codexConfig(text ?? '', proxy);
66
+ if (text === null && next === '')
67
+ return false;
68
+ if (text === next) {
69
+ await chmod(path, 0o600);
70
+ return false;
71
+ }
72
+ await mkdir(dir, { recursive: true, mode: 0o700 });
73
+ await writeAtomic(path, next, 0o600);
74
+ return true;
75
+ }
@@ -0,0 +1,8 @@
1
+ import { type ObserveFn, type StepFn } from '../types.ts';
2
+ export declare const ENROLLED: string[];
3
+ export declare const loginStep: StepFn;
4
+ export declare const observeLogin: ObserveFn;
5
+ export declare const roleStep: StepFn;
6
+ export declare const observeRole: ObserveFn;
7
+ export declare const observeEnroll: ObserveFn;
8
+ export declare const enrollStep: StepFn;
@@ -0,0 +1,138 @@
1
+ import { connect } from "../../commands/connect.js";
2
+ import { login } from "../../commands/login.js";
3
+ import { allows } from "../../machine.js";
4
+ import { nodeNameFrom, defaultNodeName } from "../../collect.js";
5
+ import { isRole, ROLES, SetupError } from "../types.js";
6
+ export const ENROLLED = ['connected', 'degraded', 'paused', 'recovering', 'rotating'];
7
+ async function needsLogin(run) {
8
+ const { ctx } = run;
9
+ const state = (await ctx.store.state()).state;
10
+ if (ENROLLED.includes(state))
11
+ return false;
12
+ if (state === 'unconfigured' || state === 'revoked')
13
+ return true;
14
+ const user = await ctx.store.read('user.json');
15
+ return !user || user.url !== ctx.url || Date.parse(user.expires_at) <= ctx.now().getTime();
16
+ }
17
+ export const loginStep = async (run) => {
18
+ const { ctx } = run;
19
+ if (run.opts.registrationToken !== undefined && !ENROLLED.includes((await ctx.store.state()).state)) {
20
+ const state = (await ctx.store.state()).state;
21
+ if (state === 'logged_in' || state === 'authorizing') {
22
+ if (run.opts.dryRun)
23
+ return { status: 'would', detail: 'drop the saved sign-in and enroll with the registration token' };
24
+ await ctx.store.applyAndRun('LOGOUT');
25
+ return { status: 'done', detail: 'dropped the saved sign-in, enrolling with the registration token' };
26
+ }
27
+ return { status: 'skipped', detail: 'enrolling with a registration token, no sign-in needed' };
28
+ }
29
+ if (!(await needsLogin(run))) {
30
+ const user = await ctx.store.read('user.json');
31
+ return { status: 'unchanged', detail: user ? `signed in as ${user.user.email}` : 'this machine is already enrolled' };
32
+ }
33
+ if (run.opts.dryRun)
34
+ return { status: 'would', detail: 'sign in with a code you approve in the browser' };
35
+ const stale = await ctx.store.read('user.json');
36
+ if (stale && stale.url !== ctx.url) {
37
+ ctx.io.err(`The saved sign-in is for ${stale.url}, not ${ctx.url}. It is dropped here and never sent to this server.`);
38
+ await ctx.store.remove('user.json');
39
+ if (allows((await ctx.store.state()).state, 'LOGOUT'))
40
+ await ctx.store.applyAndRun('LOGOUT');
41
+ }
42
+ if ((await login(ctx, run.signal)) !== 0)
43
+ throw new SetupError('Sign-in did not finish. Run the setup again to retry.');
44
+ const user = await ctx.store.read('user.json');
45
+ return { status: 'done', detail: `signed in as ${user?.user.email ?? 'your account'}` };
46
+ };
47
+ const SIGN_IN_FIX = 'Run `hive login` and approve the code, or run `hive setup --token hvr_...` with a registration token from the app.';
48
+ export const observeLogin = async (run) => {
49
+ const { ctx } = run;
50
+ const state = (await ctx.store.state()).state;
51
+ if (run.opts.registrationToken !== undefined && !ENROLLED.includes(state))
52
+ return { status: 'skipped', detail: 'enrolling with a registration token, no sign-in needed', fix: null };
53
+ if (!(await needsLogin(run))) {
54
+ const user = await ctx.store.read('user.json');
55
+ return { status: 'ok', detail: user ? `signed in as ${user.user.email}` : 'this machine is already enrolled', fix: null };
56
+ }
57
+ const detail = state === 'revoked' ? 'this machine was revoked in Hive and has no sign-in' : state === 'unconfigured' ? 'not signed in, and this machine is not enrolled' : 'the saved sign-in is missing, expired or for another server';
58
+ return { status: 'failing', detail, fix: SIGN_IN_FIX };
59
+ };
60
+ async function teamDefaultRole(run) {
61
+ const user = await run.ctx.store.read('user.json');
62
+ if (!user || user.url !== run.ctx.url)
63
+ return null;
64
+ try {
65
+ const response = await run.ctx.api.json('GET', '/api/v0/nodes', { token: user.token, signal: run.signal });
66
+ const role = response.team?.default_role;
67
+ return isRole(role) ? role : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ export const roleStep = async (run) => {
74
+ const saved = run.saved.applied.role_seen ?? null;
75
+ let role = run.desired.role ?? (await teamDefaultRole(run));
76
+ let source = run.opts.role ? 'from --role' : run.desired.role ? 'kept from the last run' : 'from the team settings';
77
+ if (!role) {
78
+ if (run.deps.prompt.interactive) {
79
+ role = (await run.deps.prompt.choose('Which role does this node have?', ROLES, 'worker'));
80
+ source = 'chosen at the prompt';
81
+ }
82
+ else if (run.opts.dryRun) {
83
+ return { status: 'would', detail: 'choose a role (pass --role primary, worker, lite or proxy-only)' };
84
+ }
85
+ else {
86
+ throw new SetupError('No role chosen. Pass --role primary, worker, lite or proxy-only.');
87
+ }
88
+ }
89
+ run.role = role;
90
+ run.desired.role = role;
91
+ if (run.opts.dryRun)
92
+ return { status: saved === role ? 'unchanged' : 'would', detail: `${role} (${source})` };
93
+ run.saved.applied.role_seen = role;
94
+ if (saved === role)
95
+ return { status: 'unchanged', detail: `${role} (${source})` };
96
+ return { status: 'done', detail: saved ? `${saved} to ${role}` : `${role} (${source})` };
97
+ };
98
+ export const observeRole = async (run) => {
99
+ const saved = run.saved.applied.role_seen ?? null;
100
+ const role = run.desired.role ?? (await teamDefaultRole(run));
101
+ if (!role)
102
+ return { status: 'failing', detail: 'no role chosen', fix: 'Run `hive setup --role primary`, `worker`, `lite` or `proxy-only`.' };
103
+ run.role = role;
104
+ run.desired.role = role;
105
+ if (saved === role)
106
+ return { status: 'ok', detail: role, fix: null };
107
+ return { status: 'stale', detail: `${role}, not recorded by a setup run yet${saved ? ` (it recorded ${saved})` : ''}`, fix: 'Run `hive setup`.' };
108
+ };
109
+ export const observeEnroll = async (run) => {
110
+ const { ctx } = run;
111
+ const state = (await ctx.store.state()).state;
112
+ const node = await ctx.store.read('node.json');
113
+ const key = await ctx.store.read('key.json');
114
+ if (node && node.url !== ctx.url)
115
+ return { status: 'failing', detail: `enrolled at ${node.url}, not ${ctx.url}`, fix: `Point HIVE_URL back at ${node.url}, or run \`hive logout\` and delete ${ctx.store.dir} to move this machine.` };
116
+ if (node && key && ENROLLED.includes(state))
117
+ return { status: 'ok', detail: `enrolled as ${node.name} in ${node.team.name}`, fix: null };
118
+ return { status: 'failing', detail: node && key ? `enrolled, but the connection is ${state}` : 'this machine is not enrolled', fix: 'Run `hive setup`, which registers this machine, or `hive setup --token hvr_...`.' };
119
+ };
120
+ export const enrollStep = async (run) => {
121
+ const { ctx, deps } = run;
122
+ const state = (await ctx.store.state()).state;
123
+ const node = await ctx.store.read('node.json');
124
+ const key = await ctx.store.read('key.json');
125
+ if (node && node.url !== ctx.url)
126
+ throw new SetupError(`This node is enrolled at ${node.url}, not ${ctx.url}. Run hive logout and delete ${ctx.store.dir} to move it.`);
127
+ if (node && key && ENROLLED.includes(state))
128
+ return { status: 'unchanged', detail: `enrolled as ${node.name} in ${node.team.name}` };
129
+ const enrollment = { cores: deps.host.cores, ram_gb: deps.host.ramGb, ...(run.role ? { role: run.role } : {}) };
130
+ const name = run.opts.name ? nodeNameFrom(run.opts.name) : defaultNodeName();
131
+ if (run.opts.dryRun)
132
+ return { status: 'would', detail: `register ${name} with ${enrollment.cores} cores, ${enrollment.ram_gb} GB, role ${run.role ?? 'unset'}, lane slots follow from the lane install` };
133
+ const code = await connect(ctx, { once: true, rebind: false, rotate: false, enrollment, ...(run.opts.registrationToken ? { token: run.opts.registrationToken } : {}), ...(run.opts.name ? { name: run.opts.name } : {}), ...(run.opts.team ? { team: run.opts.team } : {}) }, run.signal);
134
+ if (code !== 0)
135
+ throw new SetupError(run.opts.registrationToken ? 'Enrolling with the registration token failed. If it expired, was used or was revoked, create a new one in the app under team settings, Connect a node, then run the setup again.' : 'Enrolling this machine failed. Run the setup again to retry.');
136
+ const enrolled = await ctx.store.read('node.json');
137
+ return { status: 'done', detail: `enrolled as ${enrolled?.name ?? name}; lane slots are reported after the lane install` };
138
+ };
@@ -0,0 +1,7 @@
1
+ import { type AppliesFn, type ObserveFn, type SetupRun, type StepFn } from '../types.ts';
2
+ export declare function hiveBlockMarkers(run: SetupRun): Promise<string[] | null>;
3
+ /** A proxy-only node has nothing to do here unless an earlier role left a crontab block behind. */
4
+ export declare const appliesCron: AppliesFn;
5
+ /** Asks `apply-cron.sh --dry-run` whether the crontab differs, which writes nothing. */
6
+ export declare const observeCron: ObserveFn;
7
+ export declare const cronStep: StepFn;
@@ -0,0 +1,74 @@
1
+ import { join } from 'node:path';
2
+ import { SetupError } from "../types.js";
3
+ import { releaseDirReady, scriptEnv } from "./lanes.js";
4
+ import { tail } from "./files.js";
5
+ const BEGIN_MARKER = /^# BEGIN hive (?:primary|worker|lite)$/gm;
6
+ export async function hiveBlockMarkers(run) {
7
+ const listing = await run.deps.exec(run.ctx.env.HIVE_CRONTAB ?? 'crontab', ['-l']).catch(() => null);
8
+ if (!listing)
9
+ return null;
10
+ if (listing.code === 0)
11
+ return listing.stdout.match(BEGIN_MARKER) ?? [];
12
+ return /no crontab/i.test(listing.stderr) ? [] : null;
13
+ }
14
+ const NO_CRON = 'proxy-only machines run no scheduled jobs';
15
+ /** A proxy-only node has nothing to do here unless an earlier role left a crontab block behind. */
16
+ export const appliesCron = (run) => (run.role === 'proxy-only' && !run.saved.applied.cron_role ? { skip: NO_CRON } : true);
17
+ /** Asks `apply-cron.sh --dry-run` whether the crontab differs, which writes nothing. */
18
+ export const observeCron = async (run) => {
19
+ if (run.role === 'proxy-only') {
20
+ const previous = run.saved.applied.cron_role;
21
+ return { status: previous ? 'stale' : 'skipped', detail: previous ? `the ${previous} crontab block is still installed on a proxy-only node` : NO_CRON, fix: previous ? 'Run `hive setup`, which removes it.' : null };
22
+ }
23
+ const pin = run.deps.pin.release;
24
+ if (!pin || !(await releaseDirReady(run, pin)))
25
+ return { status: 'failing', detail: 'no overcy-hive release is installed, so there is no crontab to render', fix: 'Fix the lanes step first, then run `hive setup`.' };
26
+ const role = run.role ?? 'worker';
27
+ const previous = run.saved.applied.cron_role;
28
+ const args = [join(run.paths.releaseDir(pin.version), 'install', 'apply-cron.sh'), role, ...(previous && previous !== role ? ['--force'] : []), '--dry-run'];
29
+ const result = await run.deps.exec('bash', args, { env: scriptEnv(run, pin) });
30
+ if (result.code !== 0)
31
+ return { status: 'failing', detail: `the crontab check failed: ${tail(result)}`, fix: 'Run `hive setup` and read its error.' };
32
+ if (/^(changed|would):/m.test(result.stdout))
33
+ return { status: 'stale', detail: `the crontab does not match the ${role} jobs${previous && previous !== role ? ` (it has ${previous})` : ''}`, fix: 'Run `hive setup`, which re-renders the crontab.' };
34
+ return { status: 'ok', detail: `crontab already matches the ${role} jobs`, fix: null };
35
+ };
36
+ export const cronStep = async (run) => {
37
+ if (run.role === 'proxy-only') {
38
+ const previous = run.saved.applied.cron_role;
39
+ const installed = run.saved.applied.cron_release;
40
+ if (!previous)
41
+ return { status: 'skipped', detail: NO_CRON };
42
+ if (run.opts.dryRun)
43
+ return { status: 'would', detail: `remove the ${previous} crontab` };
44
+ const dir = installed ? run.paths.releaseDir(installed) : null;
45
+ const result = dir
46
+ ? await run.deps.exec('bash', [join(dir, 'install', 'apply-cron.sh'), previous, '--remove'], { env: { HIVE_CONFIG: run.paths.envFile, HIVE_RELEASE_DIR: dir } })
47
+ : { code: 1, stdout: '', stderr: 'the release that installed the crontab is unknown' };
48
+ if (result.code !== 0)
49
+ throw new SetupError(`Removing the ${previous} crontab failed: ${tail(result)}`);
50
+ delete run.saved.applied.cron_role;
51
+ delete run.saved.applied.cron_release;
52
+ return { status: 'done', detail: `removed the ${previous} crontab` };
53
+ }
54
+ const pin = run.deps.pin.release;
55
+ if (!pin || !(await releaseDirReady(run, pin))) {
56
+ if (run.opts.dryRun)
57
+ return { status: 'would', detail: `render and apply the ${run.role ?? 'chosen'} crontab from the pinned release` };
58
+ throw new SetupError('No overcy-hive release is installed, so there is no crontab to render.');
59
+ }
60
+ const role = run.role ?? 'worker';
61
+ const previous = run.saved.applied.cron_role;
62
+ const args = [join(run.paths.releaseDir(pin.version), 'install', 'apply-cron.sh'), role, ...(previous && previous !== role ? ['--force'] : []), ...(run.opts.dryRun ? ['--dry-run'] : [])];
63
+ const result = await run.deps.exec('bash', args, { env: scriptEnv(run, pin) });
64
+ if (result.code !== 0)
65
+ throw new SetupError(`Applying the crontab failed: ${tail(result)}`);
66
+ const changed = /^(changed|would):/m.test(result.stdout);
67
+ if (!run.opts.dryRun && (role === 'primary' || role === 'worker' || role === 'lite')) {
68
+ run.saved.applied.cron_role = role;
69
+ run.saved.applied.cron_release = pin.version;
70
+ }
71
+ if (!changed)
72
+ return { status: 'unchanged', detail: `crontab already matches the ${role} jobs` };
73
+ return { status: run.opts.dryRun ? 'would' : previous === undefined ? 'done' : 'repaired', detail: `${run.opts.dryRun ? 'apply' : 'applied'} the ${role} crontab${previous && previous !== role ? ` (was ${previous})` : ''}` };
74
+ };
@@ -0,0 +1,5 @@
1
+ import { type AppliesFn, type ObserveFn, type StepFn } from '../types.ts';
2
+ export declare function eventId(text: string): string;
3
+ export declare const appliesDrift: AppliesFn;
4
+ export declare const observeDrift: ObserveFn;
5
+ export declare const driftStep: StepFn;
@@ -0,0 +1,67 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { collectStatus } from "../../collect.js";
4
+ import { SetupError } from "../types.js";
5
+ import { sha256Hex } from "./files.js";
6
+ export function eventId(text) {
7
+ return sha256Hex(`${sha256Hex(text)}\n0\n${text}`);
8
+ }
9
+ async function report(run, text) {
10
+ const node = await run.ctx.store.read('node.json');
11
+ const key = await run.ctx.store.read('key.json');
12
+ if (!node || !key)
13
+ throw new SetupError('This node is not enrolled, so the drift result cannot be reported.');
14
+ const now = run.ctx.now();
15
+ const body = await collectStatus(node.name, node.kind, run.paths.lanesDir, now, run.laneSlots);
16
+ const id = eventId(text);
17
+ const corrected = (skewMs) => {
18
+ const sentAt = new Date(now.getTime() + skewMs).toISOString().replace(/\.\d{3}Z$/, 'Z');
19
+ return { ...body, sent_at: sentAt, events: [{ id, at: sentAt, text }] };
20
+ };
21
+ await run.ctx.api.json('POST', '/api/v0/nodes/me/status', { token: node.token, key, body: corrected, signal: run.signal });
22
+ }
23
+ const NO_DRIFT = 'proxy-only machines have no lane scripts to compare';
24
+ export const appliesDrift = (run) => (run.role === 'proxy-only' ? { skip: NO_DRIFT } : true);
25
+ /** Runs the lane install's own read-only `drift-check.sh --local` and words the result as the event Hive gets. */
26
+ async function inspect(run, script) {
27
+ const result = await run.deps.exec('bash', [script, '--local'], { env: { HIVE_CONFIG: run.paths.envFile } });
28
+ const findings = result.stdout.split('\n').filter((line) => /^(differs|missing|unfrozen|nomanifest)\b/.test(line));
29
+ const clean = result.code === 0 && findings.length === 0;
30
+ const release = run.saved.applied.release ?? 'unknown';
31
+ const text = clean ? `HIVE-SETUP drift-check clean role=${run.role ?? 'unknown'} release=${release}` : `HIVE-SETUP drift-check found ${findings.length} difference(s) role=${run.role ?? 'unknown'} release=${release}: ${findings.slice(0, 5).join('; ')}`.replace(/\n/g, ' ');
32
+ return { missing: result.code === 127, findings, clean, text, signature: sha256Hex(text) };
33
+ }
34
+ export const observeDrift = async (run) => {
35
+ if (run.role === 'proxy-only')
36
+ return { status: 'skipped', detail: NO_DRIFT, fix: null };
37
+ const script = join(run.paths.lanesDir, 'drift-check.sh');
38
+ const seen = await inspect(run, script);
39
+ if (seen.missing)
40
+ return { status: 'failing', detail: `drift-check is not installed at ${script}`, fix: 'Run `hive setup`, which installs the lane scripts.' };
41
+ if (!seen.clean)
42
+ return { status: 'failing', detail: `drift-check found ${seen.findings.length} difference(s): ${seen.findings.slice(0, 3).join('; ')}`, fix: 'Run `hive setup`, which restores the lane scripts from the release.' };
43
+ if (run.saved.applied.drift !== seen.signature)
44
+ return { status: 'stale', detail: 'drift-check is clean, and Hive has not got the result yet', fix: 'Run `hive setup`, which reports it.' };
45
+ return { status: 'ok', detail: 'drift-check is clean and already reported', fix: null };
46
+ };
47
+ export const driftStep = async (run) => {
48
+ if (run.role === 'proxy-only')
49
+ return { status: 'skipped', detail: NO_DRIFT };
50
+ const script = join(run.paths.lanesDir, 'drift-check.sh');
51
+ if (run.opts.dryRun && !(await access(script).then(() => true, () => false)))
52
+ return { status: 'would', detail: 'run drift-check once and report the result to Hive' };
53
+ const { missing, findings, clean, text, signature } = await inspect(run, script);
54
+ if (missing)
55
+ throw new SetupError(`drift-check is not installed at ${script}.`);
56
+ let reported = false;
57
+ if (run.saved.applied.drift !== signature) {
58
+ if (run.opts.dryRun)
59
+ return { status: 'would', detail: `report the drift-check result to Hive (${clean ? 'clean' : `${findings.length} difference(s)`})` };
60
+ await report(run, text);
61
+ run.saved.applied.drift = signature;
62
+ reported = true;
63
+ }
64
+ if (!clean)
65
+ throw new SetupError(`drift-check found ${findings.length} difference(s) after the install: ${findings.slice(0, 3).join('; ')}`);
66
+ return reported ? { status: 'done', detail: 'drift-check is clean, result reported to Hive' } : { status: 'unchanged', detail: 'drift-check is clean and already reported' };
67
+ };
@@ -0,0 +1,6 @@
1
+ import { type ObserveFn, type SetupRun, type StepFn } from '../types.ts';
2
+ export declare function userKeys(text: string): Map<string, string>;
3
+ export declare function mergeEnv(existing: string, managed: Record<string, string>): string;
4
+ export declare function managedEnv(run: SetupRun, existing: string): Record<string, string>;
5
+ export declare const observeEnv: ObserveFn;
6
+ export declare const envStep: StepFn;