@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,160 @@
1
+ import { join } from 'node:path';
2
+ import { SHARED_CONFIG, UnreadableFileError } from "../config.js";
3
+ import { resolveKit } from "./kit.js";
4
+ import { cronIntent, intentsFor, journalAhead, journalSettle } from "./manifest.js";
5
+ import { planTick } from "./plan.js";
6
+ import { STEPS, stepById } from "./registry.js";
7
+ import { hiveBlockMarkers } from "./steps/cron.js";
8
+ import { SetupError } from "./types.js";
9
+ const SETUP_FILE = 'setup.json';
10
+ export function initialSetupFile() {
11
+ return { last_error: null, desired: null, applied: {} };
12
+ }
13
+ export function makePaths(ctx, home) {
14
+ const dataDir = ctx.env.HIVE_DATA_DIR && ctx.env.HIVE_DATA_DIR !== '' ? ctx.env.HIVE_DATA_DIR : join(home, '.local', 'share', 'hive');
15
+ return {
16
+ configDir: ctx.store.dir,
17
+ hiveHome: ctx.env.HIVE_HOME && ctx.env.HIVE_HOME !== '' ? ctx.env.HIVE_HOME : join(home, '.hive'),
18
+ dataDir,
19
+ envFile: join(ctx.store.dir, 'hive.env'),
20
+ lanesDir: ctx.env.HIVE_LANES_DIR && ctx.env.HIVE_LANES_DIR !== '' ? ctx.env.HIVE_LANES_DIR : join(home, 'lanes'),
21
+ releaseDir: (version) => join(dataDir, version),
22
+ };
23
+ }
24
+ function resolveDesired(ctx, opts, saved) {
25
+ return {
26
+ role: opts.role ?? saved.desired?.role ?? null,
27
+ server: ctx.url,
28
+ slots: opts.slots ?? saved.desired?.slots ?? null,
29
+ toolchain: opts.toolchain ?? saved.desired?.toolchain ?? null,
30
+ kit_release: opts.kitRelease ?? saved.desired?.kit_release ?? null,
31
+ };
32
+ }
33
+ /**
34
+ * Reads `setup.json`. Only `desired`, `applied` and `last_error` are taken, so a
35
+ * file written before the resume cursor was removed loads cleanly and loses its
36
+ * `state` and `since` on the next write.
37
+ */
38
+ export async function readSetupFile(ctx) {
39
+ const stored = await ctx.store.read(SETUP_FILE).catch((error) => {
40
+ throw error instanceof UnreadableFileError ? new SetupError(error.message) : error;
41
+ });
42
+ if (stored === null || typeof stored !== 'object')
43
+ return initialSetupFile();
44
+ return { last_error: typeof stored.last_error === 'string' ? stored.last_error : null, desired: stored.desired ?? null, applied: { ...stored.applied } };
45
+ }
46
+ async function persist(ctx, saved, error) {
47
+ saved.last_error = error;
48
+ await ctx.store.write(SETUP_FILE, saved);
49
+ }
50
+ /** Builds the run that setup and `hive doctor` both hand to every step. Writes nothing. */
51
+ export async function prepareRun(ctx, opts, baseDeps, signal, saved, resolvePinnedKit = true) {
52
+ const paths = makePaths(ctx, baseDeps.host.home);
53
+ const desired = resolveDesired(ctx, opts, saved);
54
+ const deps = desired.kit_release === null || !resolvePinnedKit ? baseDeps : { ...baseDeps, pin: { ...baseDeps.pin, release: await resolveKit(baseDeps.kit, desired.kit_release, baseDeps.fetchBytes, signal) } };
55
+ saved.desired = desired;
56
+ return { ctx, opts, deps, paths, signal, saved, desired, role: desired.role, laneSlots: saved.applied.slots ?? null, results: [], local: null };
57
+ }
58
+ export async function runSteps(ctx, opts, baseDeps, signal) {
59
+ const saved = await readSetupFile(ctx);
60
+ const run = await prepareRun(ctx, opts, baseDeps, signal, saved);
61
+ const { deps, desired } = run;
62
+ const attempt = async (step, work, commit) => {
63
+ try {
64
+ if (opts.dryRun) {
65
+ await commit(await work());
66
+ return null;
67
+ }
68
+ const probe = step === 'cron' || step === 'init' ? () => hiveBlockMarkers(run) : undefined;
69
+ await journalAhead(run, step === 'cron' ? cronIntent(run) : intentsFor(step, run), probe);
70
+ await deps.journalFault?.('after-pending', step);
71
+ const settle = () => journalSettle(run, step === 'cron' ? probe : undefined);
72
+ const result = await work().catch(async (error) => {
73
+ await settle().catch(() => undefined);
74
+ throw error;
75
+ });
76
+ await deps.journalFault?.('before-done', step);
77
+ await settle();
78
+ await commit(result);
79
+ return null;
80
+ }
81
+ catch (error) {
82
+ const message = error instanceof Error ? error.message : String(error);
83
+ if (!opts.dryRun && step !== 'init')
84
+ await persist(ctx, saved, message).catch(() => undefined);
85
+ return { step: step === 'init' ? 'preflight' : step, message };
86
+ }
87
+ };
88
+ const report = (error) => ({
89
+ ok: error === null,
90
+ dry_run: opts.dryRun,
91
+ up_to_date: error === null && !opts.dryRun && run.results.every((r) => r.status === 'unchanged' || r.status === 'skipped'),
92
+ needs_action: run.results.some((r) => r.status === 'needs_action'),
93
+ role: run.role,
94
+ toolchain: desired.toolchain,
95
+ server: ctx.url,
96
+ steps: error ? [...run.results, { step: error.step, status: 'failed', detail: error.message }] : run.results,
97
+ error,
98
+ });
99
+ if (!opts.dryRun) {
100
+ const initFailure = await attempt('init', async () => {
101
+ if (opts.saveApiUrl)
102
+ await ctx.store.write(SHARED_CONFIG, { url: opts.apiUrl });
103
+ await persist(ctx, saved, saved.last_error);
104
+ }, async () => undefined);
105
+ if (initFailure)
106
+ return report(initFailure);
107
+ }
108
+ // Setup repairs every applicable step on every run, in STEPS order, and stops
109
+ // at the first failure. It does not read an observation first, because a
110
+ // step's repair is also what keeps `saved.applied` current. So every step
111
+ // starts as `stale`, and `planTick` hands back the next one that is not
112
+ // blocked. A step that settles is `ok`. A step the node does not need is
113
+ // `skipped`. A `needs_action` outcome blocks what follows it.
114
+ const status = new Map(STEPS.map((step) => [step.id, 'stale']));
115
+ for (;;) {
116
+ const next = planTick(STEPS.map((step) => ({ id: step.id, status: status.get(step.id) })), STEPS).repairs[0];
117
+ if (next === undefined)
118
+ break;
119
+ const step = stepById(next);
120
+ if (signal.aborted)
121
+ return report({ step: step.id, message: 'Interrupted. Run the setup again.' });
122
+ const gate = step.applies(run);
123
+ if (gate !== true) {
124
+ run.results.push({ step: step.id, status: 'skipped', detail: gate.skip });
125
+ status.set(step.id, 'skipped');
126
+ continue;
127
+ }
128
+ const failure = await attempt(step.id, () => step.repair(run), async (outcome) => {
129
+ if (!opts.dryRun)
130
+ await persist(ctx, saved, null);
131
+ run.results.push({ step: step.id, ...outcome });
132
+ status.set(step.id, outcome.status === 'needs_action' ? 'needs_action' : outcome.status === 'skipped' ? 'skipped' : 'ok');
133
+ });
134
+ if (failure)
135
+ return report(failure);
136
+ }
137
+ return report(null);
138
+ }
139
+ export function renderReport(report, url) {
140
+ const lines = report.steps.filter((s) => s.status !== 'failed').map((s) => `${`${s.status}:`.padEnd(10)} ${s.step.padEnd(13)} ${s.detail}`);
141
+ if (report.error) {
142
+ lines.push(`failed: ${report.error.step.padEnd(13)} ${report.error.message}`);
143
+ lines.push(`Setup stopped at ${report.error.step}. Run the same command again to retry from the start. Every step checks and repairs.`);
144
+ }
145
+ else if (report.needs_action) {
146
+ lines.push('Needs action: finish the step marked needs_action above, then run the same command again.');
147
+ }
148
+ else if (report.dry_run) {
149
+ lines.push('Dry run only. Nothing was changed.');
150
+ }
151
+ else if (report.up_to_date) {
152
+ lines.push('Already up to date. Nothing changed.');
153
+ }
154
+ else {
155
+ const changed = report.steps.filter((s) => s.status === 'done' || s.status === 'repaired').length;
156
+ lines.push(`Done. ${changed} step(s) changed, ${report.steps.length - changed} already right.`);
157
+ lines.push(`Next: open ${url} to see this node report.`);
158
+ }
159
+ return lines;
160
+ }
@@ -0,0 +1,11 @@
1
+ import type { ForwarderSettings } from './model-access.ts';
2
+ export declare const LOCAL_KEY_ENV = "HIVE_LOCAL_KEY";
3
+ export declare const LOCAL_PORT_ENV = "HIVE_LOCAL_PORT";
4
+ export declare function newLocalKey(): string;
5
+ export declare function newLocalPort(): number;
6
+ export declare function forwarderSettingsFrom(envText: string): ForwarderSettings | null;
7
+ export declare function allValues(envText: string): Map<string, string>;
8
+ export declare const baseUrls: (settings: ForwarderSettings) => {
9
+ anthropic: string;
10
+ openai: string;
11
+ };
@@ -0,0 +1,30 @@
1
+ import { randomBytes, randomInt } from 'node:crypto';
2
+ export const LOCAL_KEY_ENV = 'HIVE_LOCAL_KEY';
3
+ export const LOCAL_PORT_ENV = 'HIVE_LOCAL_PORT';
4
+ export function newLocalKey() {
5
+ return `hvl_${randomBytes(32).toString('base64url')}`;
6
+ }
7
+ export function newLocalPort() {
8
+ return randomInt(49200, 60000);
9
+ }
10
+ export function forwarderSettingsFrom(envText) {
11
+ const values = allValues(envText);
12
+ const port = Number(values.get(LOCAL_PORT_ENV));
13
+ const localKey = values.get(LOCAL_KEY_ENV);
14
+ if (!Number.isInteger(port) || port < 1024 || port > 65535 || !localKey)
15
+ return null;
16
+ return { host: '127.0.0.1', port, localKey, anthropicPath: '/anthropic', openaiPath: '/openai/v1' };
17
+ }
18
+ export function allValues(envText) {
19
+ const values = new Map();
20
+ for (const line of envText.split('\n')) {
21
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
22
+ if (match)
23
+ values.set(match[1], match[2].trim().replace(/^"(.*)"$/s, '$1'));
24
+ }
25
+ return values;
26
+ }
27
+ export const baseUrls = (settings) => ({
28
+ anthropic: `http://${settings.host}:${settings.port}${settings.anthropicPath}`,
29
+ openai: `http://${settings.host}:${settings.port}${settings.openaiPath}`,
30
+ });
@@ -0,0 +1,7 @@
1
+ import { type Api, type Fetch } from '../api.ts';
2
+ export type InstanceIdentity = {
3
+ document: string;
4
+ signature: string;
5
+ };
6
+ export declare function readInstanceIdentity(doFetch: Fetch, signal: AbortSignal): Promise<InstanceIdentity>;
7
+ export declare function exchangeIdentityForToken(api: Api, nodeId: string, identity: InstanceIdentity, signal: AbortSignal, sleep: (ms: number, signal?: AbortSignal) => Promise<void>): Promise<string>;
@@ -0,0 +1,52 @@
1
+ import { ApiError, NetworkError, AWS_IDENTITY_EXCHANGE_PATH } from "../api.js";
2
+ import { SetupError } from "./types.js";
3
+ const IMDS = 'http://169.254.169.254';
4
+ const IMDS_TIMEOUT_MS = 2000;
5
+ const SESSION_TTL_SECONDS = '60';
6
+ async function imds(doFetch, method, path, headers, signal) {
7
+ let response;
8
+ try {
9
+ response = await doFetch(`${IMDS}${path}`, { method, headers, redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(IMDS_TIMEOUT_MS)]) });
10
+ }
11
+ catch {
12
+ throw new SetupError('The instance metadata service is not reachable with IMDSv2, so there is no instance identity to exchange. Nothing was changed. Pass --token instead, or run this on an EC2 instance with IMDSv2 enabled.');
13
+ }
14
+ if (!response.ok)
15
+ throw new SetupError(`The instance metadata service refused ${path} (${response.status}). Nothing was changed. IMDSv2 must be enabled and reachable from this process.`);
16
+ return (await response.text()).trim();
17
+ }
18
+ export async function readInstanceIdentity(doFetch, signal) {
19
+ const session = await imds(doFetch, 'PUT', '/latest/api/token', { 'x-aws-ec2-metadata-token-ttl-seconds': SESSION_TTL_SECONDS }, signal);
20
+ if (session === '')
21
+ throw new SetupError('The instance metadata service returned no IMDSv2 session. Nothing was changed.');
22
+ const headers = { 'x-aws-ec2-metadata-token': session };
23
+ const document = await imds(doFetch, 'GET', '/latest/dynamic/instance-identity/document', headers, signal);
24
+ const signature = await imds(doFetch, 'GET', '/latest/dynamic/instance-identity/rsa2048', headers, signal);
25
+ if (document === '' || signature === '')
26
+ throw new SetupError('The instance identity document or its signature is empty. Nothing was changed.');
27
+ return { document, signature };
28
+ }
29
+ const RETRIES = 3;
30
+ export async function exchangeIdentityForToken(api, nodeId, identity, signal, sleep) {
31
+ for (let attempt = 0;; attempt++) {
32
+ try {
33
+ const response = await api.json('POST', AWS_IDENTITY_EXCHANGE_PATH, { body: { node_id: nodeId, document: identity.document, signature: identity.signature }, signal });
34
+ const token = response.registration_token;
35
+ if (typeof token !== 'string' || !token.startsWith('hvr_'))
36
+ throw new SetupError('The identity exchange answered without a registration token. Nothing was changed.');
37
+ return token;
38
+ }
39
+ catch (error) {
40
+ if (error instanceof SetupError)
41
+ throw error;
42
+ if (error instanceof ApiError && error.status < 500)
43
+ throw new SetupError(`${api.baseUrl} refused the identity exchange: ${error.code} (${error.status}). ${error.message} Nothing was changed.`);
44
+ const retryable = error instanceof NetworkError || error instanceof ApiError;
45
+ if (!retryable)
46
+ throw error;
47
+ if (attempt >= RETRIES)
48
+ throw new SetupError(`The identity exchange at ${api.baseUrl} kept failing (${error instanceof ApiError ? error.status : 'unreachable'}) after ${RETRIES} retries. Nothing was changed.`);
49
+ await sleep(500 * 2 ** attempt, signal);
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,36 @@
1
+ import type { Fetch } from '../api.ts';
2
+ import { type Context, type Io } from '../context.ts';
3
+ import { renderReport, type BootstrapReport } from './engine.ts';
4
+ import type { StepId } from './registry.ts';
5
+ import { type BootstrapOptions, type Role, type SetupDeps } from './types.ts';
6
+ export type BootstrapDeps = SetupDeps & {
7
+ ctx: Context;
8
+ signal: AbortSignal;
9
+ };
10
+ export type BootstrapDepsOptions = {
11
+ apiUrl: string;
12
+ env?: NodeJS.ProcessEnv;
13
+ io?: Io;
14
+ signal?: AbortSignal;
15
+ interactive?: boolean;
16
+ fetch?: Fetch;
17
+ overrides?: Partial<SetupDeps>;
18
+ };
19
+ export declare function createBootstrapDeps(options: BootstrapDepsOptions): Promise<BootstrapDeps>;
20
+ export declare function failedReport(opts: {
21
+ role?: Role | null;
22
+ toolchain?: string | null;
23
+ dryRun?: boolean;
24
+ }, server: string, step: StepId, message: string): BootstrapReport;
25
+ export declare function bootstrapNode(opts: BootstrapOptions, deps: BootstrapDeps): Promise<BootstrapReport>;
26
+ export { renderReport };
27
+ export type { BootstrapReport, Context, Io, Fetch };
28
+ export type { BootstrapOptions, SetupDeps, Role, Pin, StepResult, Exec, Host, Prompter } from './types.ts';
29
+ export type { ModelAccess, ModelAccessSource, ModelAccessStore } from './model-access.ts';
30
+ export { ROLES } from './types.ts';
31
+ export { INSTALL_MANIFEST_FILE, readInstallManifest, type EntryStatus, type InstallCrontab, type InstallManifest, type InstallService, type ManifestEntry } from './manifest.ts';
32
+ export { renderDoctor, runDoctor, type DoctorReport, type DoctorRow, type DoctorStatus } from './doctor.ts';
33
+ export { planTick, type Health, type Plan } from './plan.ts';
34
+ export { STEPS, type StepId } from './registry.ts';
35
+ export { OVERCY_HIVE_KIT, parseKitManifest, type KitSource } from './kit.ts';
36
+ export { exchangeIdentityForToken, readInstanceIdentity, type InstanceIdentity } from './identity.ts';
@@ -0,0 +1,40 @@
1
+ import { makeContext } from "../context.js";
2
+ import { makeSetupDeps } from "./deps.js";
3
+ import { renderReport, runSteps } from "./engine.js";
4
+ import { SetupError } from "./types.js";
5
+ const stdio = {
6
+ out: (line) => void process.stdout.write(`${line}\n`),
7
+ err: (line) => void process.stderr.write(`${line}\n`),
8
+ };
9
+ export async function createBootstrapDeps(options) {
10
+ const env = { ...(options.env ?? process.env), HIVE_URL: options.apiUrl };
11
+ const ctx = makeContext(env, options.io ?? stdio, options.fetch ? { fetch: options.fetch } : {});
12
+ const setupDeps = await makeSetupDeps(ctx, options.interactive ?? false, options.overrides);
13
+ return { ...setupDeps, ctx, signal: options.signal ?? new AbortController().signal };
14
+ }
15
+ export function failedReport(opts, server, step, message) {
16
+ return { ok: false, dry_run: opts.dryRun ?? false, up_to_date: false, needs_action: false, role: opts.role ?? null, toolchain: opts.toolchain ?? null, server, steps: [{ step, status: 'failed', detail: message }], error: { step, message } };
17
+ }
18
+ const isFilesystemError = (error) => error instanceof Error && typeof error.syscall === 'string' && /^E[A-Z0-9]+$/.test(error.code ?? '');
19
+ export async function bootstrapNode(opts, deps) {
20
+ const { ctx, signal, ...setupDeps } = deps;
21
+ if (ctx.url !== opts.apiUrl.replace(/\/+$/, ''))
22
+ throw new SetupError(`The context talks to ${ctx.url} but the options name ${opts.apiUrl}.`);
23
+ const resolved = { ...opts, dryRun: opts.dryRun ?? false };
24
+ try {
25
+ return await runSteps(ctx, resolved, setupDeps, signal);
26
+ }
27
+ catch (error) {
28
+ if (error instanceof SetupError || isFilesystemError(error))
29
+ return failedReport(resolved, ctx.url, 'preflight', error.message);
30
+ throw error;
31
+ }
32
+ }
33
+ export { renderReport };
34
+ export { ROLES } from "./types.js";
35
+ export { INSTALL_MANIFEST_FILE, readInstallManifest } from "./manifest.js";
36
+ export { renderDoctor, runDoctor } from "./doctor.js";
37
+ export { planTick } from "./plan.js";
38
+ export { STEPS } from "./registry.js";
39
+ export { OVERCY_HIVE_KIT, parseKitManifest } from "./kit.js";
40
+ export { exchangeIdentityForToken, readInstanceIdentity } from "./identity.js";
@@ -0,0 +1,9 @@
1
+ import { type Pin } from './types.ts';
2
+ export type KitRelease = NonNullable<Pin['release']>;
3
+ export type KitSource = {
4
+ manifestUrl: (release: string) => string;
5
+ };
6
+ export declare const OVERCY_HIVE_KIT: KitSource;
7
+ export declare function parseKitManifest(text: string, release: string): KitRelease;
8
+ export declare function resolveKit(source: KitSource, release: string, fetchBytes: (url: string, signal: AbortSignal) => Promise<Uint8Array>, signal: AbortSignal): Promise<KitRelease>;
9
+ export declare function verifyKitFiles(files: Record<string, string>, read: (path: string) => Promise<Uint8Array | null>, release: string): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { posix } from 'node:path';
2
+ import { SetupError } from "./types.js";
3
+ import { sha256Hex } from "./steps/files.js";
4
+ export const OVERCY_HIVE_KIT = {
5
+ manifestUrl: (release) => `https://github.com/OvercyAI/hive-kit/releases/download/${encodeURIComponent(release)}/hive-kit.manifest.json`,
6
+ };
7
+ const HEX = /^[0-9a-f]{64}$/;
8
+ export function parseKitManifest(text, release) {
9
+ let parsed;
10
+ try {
11
+ parsed = JSON.parse(text);
12
+ }
13
+ catch {
14
+ throw new SetupError(`The overcy-hive ${release} manifest is not JSON. Nothing was installed.`);
15
+ }
16
+ const m = parsed;
17
+ if (parsed === null || typeof parsed !== 'object' || typeof m.version !== 'string' || typeof m.url !== 'string' || typeof m.sha256 !== 'string' || !HEX.test(m.sha256.toLowerCase())) {
18
+ throw new SetupError(`The overcy-hive ${release} manifest needs a version, a url and a 64 character sha256. Nothing was installed.`);
19
+ }
20
+ if (m.version !== release)
21
+ throw new SetupError(`The overcy-hive manifest is for ${m.version}, not ${release}. Nothing was installed.`);
22
+ if (!m.url.startsWith('https://'))
23
+ throw new SetupError(`The overcy-hive ${release} manifest points at a download that is not https. Nothing was installed.`);
24
+ const files = {};
25
+ if (m.files !== undefined) {
26
+ if (m.files === null || typeof m.files !== 'object' || Array.isArray(m.files))
27
+ throw new SetupError(`The overcy-hive ${release} manifest has a malformed files table. Nothing was installed.`);
28
+ for (const [path, digest] of Object.entries(m.files)) {
29
+ if (typeof digest !== 'string' || !HEX.test(digest.toLowerCase()) || posix.isAbsolute(path) || path.split('/').includes('..')) {
30
+ throw new SetupError(`The overcy-hive ${release} manifest has an unsafe or malformed entry (${path}). Nothing was installed.`);
31
+ }
32
+ files[path] = digest.toLowerCase();
33
+ }
34
+ }
35
+ return { version: m.version, url: m.url, sha256: m.sha256.toLowerCase(), files };
36
+ }
37
+ export async function resolveKit(source, release, fetchBytes, signal) {
38
+ let bytes;
39
+ try {
40
+ bytes = await fetchBytes(source.manifestUrl(release), signal);
41
+ }
42
+ catch (error) {
43
+ throw new SetupError(`The overcy-hive ${release} manifest cannot be fetched: ${error instanceof Error ? error.message : String(error)}`);
44
+ }
45
+ return parseKitManifest(new TextDecoder().decode(bytes), release);
46
+ }
47
+ export async function verifyKitFiles(files, read, release) {
48
+ for (const [path, expected] of Object.entries(files)) {
49
+ const data = await read(path);
50
+ if (data === null)
51
+ throw new SetupError(`overcy-hive ${release} is missing ${path} from its manifest. Nothing was installed.`);
52
+ const digest = sha256Hex(data);
53
+ if (digest !== expected)
54
+ throw new SetupError(`overcy-hive ${release} ${path} does not match its manifest sha256 (got ${digest.slice(0, 12)}, expected ${expected.slice(0, 12)}). Nothing was installed.`);
55
+ }
56
+ }
@@ -0,0 +1,73 @@
1
+ import type { StepId } from './registry.ts';
2
+ import { SetupError, type SetupRun } from './types.ts';
3
+ export declare const INSTALL_MANIFEST_FILE = "install-manifest.json";
4
+ export type EntryStatus = 'pending' | 'done';
5
+ export type ManifestEntry = {
6
+ path: string;
7
+ status: EntryStatus;
8
+ };
9
+ export type InstallService = {
10
+ kind: 'systemd' | 'launchd';
11
+ name: string;
12
+ file: string;
13
+ status: EntryStatus;
14
+ } | {
15
+ kind: 'none';
16
+ name: null;
17
+ file: null;
18
+ status: 'done';
19
+ };
20
+ export type InstallCrontab = {
21
+ marker: string;
22
+ user: string;
23
+ status: EntryStatus;
24
+ };
25
+ export type InstallManifest = {
26
+ version: 2;
27
+ node_id: string | null;
28
+ api_url: string;
29
+ created: {
30
+ paths: ManifestEntry[];
31
+ worktree_root: ManifestEntry | null;
32
+ service: InstallService;
33
+ key_path: ManifestEntry | null;
34
+ token_path: ManifestEntry | null;
35
+ crontab: InstallCrontab[];
36
+ };
37
+ kit_release: string | null;
38
+ written_at: string;
39
+ };
40
+ type EntrySlot = 'worktree_root' | 'key_path' | 'token_path';
41
+ export type Intent = {
42
+ slot: 'path';
43
+ path: string;
44
+ } | {
45
+ slot: EntrySlot;
46
+ path: string;
47
+ } | {
48
+ slot: 'service';
49
+ service: Exclude<InstallService, {
50
+ kind: 'none';
51
+ }>;
52
+ } | {
53
+ slot: 'crontab';
54
+ marker: string;
55
+ user: string;
56
+ };
57
+ export type CrontabProbe = () => Promise<string[] | null>;
58
+ export declare const journalSibling: (home: string) => string;
59
+ export declare function readInstallManifest(file: string): Promise<InstallManifest | null>;
60
+ export declare const exists: (path: string) => Promise<boolean>;
61
+ export declare function intentsFor(step: StepId | 'init', run: SetupRun): Intent[];
62
+ export declare function cronIntent(run: SetupRun): Intent[];
63
+ export declare class OwnershipRefusal extends SetupError {
64
+ }
65
+ export declare class CrontabBaselineError extends OwnershipRefusal {
66
+ constructor();
67
+ }
68
+ export declare class UnjournaledBlockError extends OwnershipRefusal {
69
+ constructor(markers: string[]);
70
+ }
71
+ export declare function journalAhead(run: SetupRun, intents: Intent[], probe?: CrontabProbe): Promise<void>;
72
+ export declare function journalSettle(run: SetupRun, probe?: CrontabProbe): Promise<void>;
73
+ export {};