@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,127 @@
1
+ import type { Desired, ReportTransition, StepStatus } from '../nodeContract.ts';
2
+ import type { Layout } from './layout.ts';
3
+ import { type ToolchainMemory } from './toolchain.ts';
4
+ /** When a step last changed status, so a report that only repeats itself does not look new. */
5
+ export type StepMemory = {
6
+ status: StepStatus;
7
+ since: string;
8
+ detail: string;
9
+ };
10
+ /**
11
+ * What the supervisor keeps between ticks, in `node/supervisor.json` (0600). Only the supervisor writes it.
12
+ * `generations` are the one-shot action counters it echoes to Hive once the action is done. A counter moves only
13
+ * after the work ran, so a crash in between runs the action again.
14
+ */
15
+ export type SupervisorState = {
16
+ /** The connection id (`node.json`) this state was written for. A different enrollment starts from nothing. */
17
+ connection_id: number | null;
18
+ applied_revision: number;
19
+ generations: {
20
+ rerun_setup: number;
21
+ restart_engine: number;
22
+ };
23
+ /** `nodes.id`, the id Hive's tokens carry. Not the connection id in `node.json`. */
24
+ hive_node_id: number | null;
25
+ steps: Record<string, StepMemory>;
26
+ transitions: ReportTransition[];
27
+ /** The `sent_at` of the last heartbeat. Hive keeps one status post per node and second, so the next one is at least a second later. */
28
+ heartbeat_at: string | null;
29
+ posted: {
30
+ hash: string;
31
+ at: string;
32
+ } | null;
33
+ relay: {
34
+ hash: string;
35
+ at: string;
36
+ threads: number;
37
+ } | null;
38
+ engine: EngineMemory;
39
+ ingress: IngressMemory;
40
+ cli: CliMemory;
41
+ toolchain: ToolchainMemory;
42
+ };
43
+ /** A version this node tried and went back from. It is not tried again until Hive pins another or asks for a rerun of setup. */
44
+ export type Rejected = {
45
+ version: string;
46
+ at: string;
47
+ detail: string;
48
+ };
49
+ /**
50
+ * What the cli step last did. `swap` is written before `cli/current` moves and stays until the new release outlives
51
+ * the keeper's crash window, so a supervisor that starts on the old release again knows the keeper rolled it back.
52
+ */
53
+ export type CliMemory = {
54
+ swap: {
55
+ from: string | null;
56
+ to: string;
57
+ at: string;
58
+ } | null;
59
+ rejected: Rejected | null;
60
+ };
61
+ /** An engine upgrade between the restart on the new version and its first healthy answer. */
62
+ export type EngineUpgrade = {
63
+ from: string;
64
+ from_sha256: string | null;
65
+ to: string;
66
+ backup: string | null;
67
+ at: string;
68
+ };
69
+ /**
70
+ * What the engine step last did. A restart happens only when what is wanted differs from what is recorded here, so a
71
+ * new supervisor process (a CLI swap, a crash) never restarts a healthy engine.
72
+ */
73
+ export type EngineMemory = {
74
+ /** The OvercyCode version `bin/t3` points at. */
75
+ version: string | null;
76
+ sha256: string | null;
77
+ /** The sha256 of the `service.env` the engine was last restarted with. */
78
+ env_hash: string | null;
79
+ restarted_at: string | null;
80
+ /** True while the engine is stopped on purpose, because Hive paused the node. */
81
+ stopped: boolean;
82
+ /** The agent tool versions the engine last started with. OvercyCode looks for them only when it starts. */
83
+ tools: Record<string, string>;
84
+ /** Set while an upgrade waits for the new engine to answer. A rollback reads it. */
85
+ upgrade: EngineUpgrade | null;
86
+ rejected: Rejected | null;
87
+ };
88
+ export type IngressMemory = {
89
+ kind: string | null;
90
+ /** The Caddy version `bin/caddy` points at. */
91
+ caddy: string | null;
92
+ /** The cloudflared version `bin/cloudflared` points at. */
93
+ cloudflared: string | null;
94
+ /** The secret written to `ingress/config/`, as `<name>@<version>`: the dev_tls certificate or the tunnel token. */
95
+ secret: string | null;
96
+ /** The sha256 of the files the ingress was last restarted with. */
97
+ config_hash: string | null;
98
+ restarted_at: string | null;
99
+ /** The origin the node publishes, when it first did, and the origin Hive last showed back. */
100
+ origin: string | null;
101
+ published_at: string | null;
102
+ echoed: string | null;
103
+ };
104
+ export declare function initialEngine(): EngineMemory;
105
+ export declare function initialCli(): CliMemory;
106
+ export declare function initialIngress(): IngressMemory;
107
+ export declare const MAX_TRANSITIONS = 50;
108
+ export declare function initialState(): SupervisorState;
109
+ export declare function readState(layout: Layout): Promise<SupervisorState>;
110
+ /**
111
+ * The state for this enrollment. State written for another connection (the node was removed and enrolled again, so
112
+ * Hive's counters and node id start over) is dropped, and so is the cached desired document that came with it.
113
+ */
114
+ export declare function stateFor(layout: Layout, connectionId: number): Promise<SupervisorState>;
115
+ export declare function writeState(layout: Layout, state: SupervisorState): Promise<void>;
116
+ /** The last desired document Hive served and the supervisor processed. The step that needs a section of it reads it from here. */
117
+ export declare function readDesired(layout: Layout): Promise<Desired | null>;
118
+ export declare function writeDesired(layout: Layout, desired: Desired): Promise<void>;
119
+ export type Revoked = {
120
+ at: string;
121
+ reason: string;
122
+ };
123
+ export declare function readRevoked(layout: Layout): Promise<Revoked | null>;
124
+ /** Written before the supervisor exits 77. The unit's `ConditionPathExists=!` and the keeper both read it. */
125
+ export declare function writeRevoked(layout: Layout, reason: string, now: Date): Promise<void>;
126
+ /** A fresh enrollment lifts a revocation. Nothing else does. */
127
+ export declare function clearRevoked(layout: Layout): Promise<void>;
@@ -0,0 +1,95 @@
1
+ import { mkdir, readFile, rm } from 'node:fs/promises';
2
+ import { writeAtomic } from "../atomic.js";
3
+ import { initialToolchain } from "./toolchain.js";
4
+ export function initialEngine() {
5
+ return { version: null, sha256: null, env_hash: null, restarted_at: null, stopped: false, tools: {}, upgrade: null, rejected: null };
6
+ }
7
+ export function initialCli() {
8
+ return { swap: null, rejected: null };
9
+ }
10
+ export function initialIngress() {
11
+ return { kind: null, caddy: null, cloudflared: null, secret: null, config_hash: null, restarted_at: null, origin: null, published_at: null, echoed: null };
12
+ }
13
+ function merged(base, saved) {
14
+ if (saved === null || typeof saved !== 'object')
15
+ return base;
16
+ const out = { ...base };
17
+ for (const key of Object.keys(base)) {
18
+ const value = saved[key];
19
+ if (value !== undefined && (value === null || typeof value === typeof base[key] || base[key] === null))
20
+ out[key] = value;
21
+ }
22
+ return out;
23
+ }
24
+ export const MAX_TRANSITIONS = 50;
25
+ export function initialState() {
26
+ return { connection_id: null, applied_revision: 0, generations: { rerun_setup: 0, restart_engine: 0 }, hive_node_id: null, steps: {}, transitions: [], heartbeat_at: null, posted: null, relay: null, engine: initialEngine(), ingress: initialIngress(), cli: initialCli(), toolchain: initialToolchain() };
27
+ }
28
+ async function readJson(path) {
29
+ try {
30
+ return JSON.parse(await readFile(path, 'utf8'));
31
+ }
32
+ catch (error) {
33
+ if (error.code === 'ENOENT' || error instanceof SyntaxError)
34
+ return null;
35
+ throw error;
36
+ }
37
+ }
38
+ export async function readState(layout) {
39
+ const saved = await readJson(layout.supervisorState);
40
+ if (saved === null || typeof saved !== 'object')
41
+ return initialState();
42
+ const base = initialState();
43
+ return {
44
+ connection_id: Number.isInteger(saved.connection_id) ? saved.connection_id : null,
45
+ applied_revision: Number.isInteger(saved.applied_revision) ? saved.applied_revision : 0,
46
+ generations: { rerun_setup: Number(saved.generations?.rerun_setup) || 0, restart_engine: Number(saved.generations?.restart_engine) || 0 },
47
+ hive_node_id: Number.isInteger(saved.hive_node_id) ? saved.hive_node_id : null,
48
+ steps: saved.steps && typeof saved.steps === 'object' ? saved.steps : base.steps,
49
+ transitions: Array.isArray(saved.transitions) ? saved.transitions.slice(-MAX_TRANSITIONS) : [],
50
+ heartbeat_at: typeof saved.heartbeat_at === 'string' ? saved.heartbeat_at : null,
51
+ posted: saved.posted ?? null,
52
+ relay: saved.relay ?? null,
53
+ engine: merged(initialEngine(), saved.engine),
54
+ ingress: merged(initialIngress(), saved.ingress),
55
+ cli: merged(initialCli(), saved.cli),
56
+ toolchain: merged(initialToolchain(), saved.toolchain),
57
+ };
58
+ }
59
+ /**
60
+ * The state for this enrollment. State written for another connection (the node was removed and enrolled again, so
61
+ * Hive's counters and node id start over) is dropped, and so is the cached desired document that came with it.
62
+ */
63
+ export async function stateFor(layout, connectionId) {
64
+ const saved = await readState(layout);
65
+ if (saved.connection_id === connectionId)
66
+ return saved;
67
+ if (saved.connection_id === null && saved.applied_revision === 0 && saved.hive_node_id === null)
68
+ return { ...saved, connection_id: connectionId };
69
+ await rm(layout.desiredCache, { force: true });
70
+ return { ...initialState(), connection_id: connectionId };
71
+ }
72
+ export async function writeState(layout, state) {
73
+ await mkdir(layout.nodeDir, { recursive: true, mode: 0o700 });
74
+ await writeAtomic(layout.supervisorState, `${JSON.stringify(state, null, 2)}\n`, 0o600);
75
+ }
76
+ /** The last desired document Hive served and the supervisor processed. The step that needs a section of it reads it from here. */
77
+ export async function readDesired(layout) {
78
+ return readJson(layout.desiredCache);
79
+ }
80
+ export async function writeDesired(layout, desired) {
81
+ await mkdir(layout.nodeDir, { recursive: true, mode: 0o700 });
82
+ await writeAtomic(layout.desiredCache, `${JSON.stringify(desired, null, 2)}\n`, 0o600);
83
+ }
84
+ export async function readRevoked(layout) {
85
+ return readJson(layout.revokedMarker);
86
+ }
87
+ /** Written before the supervisor exits 77. The unit's `ConditionPathExists=!` and the keeper both read it. */
88
+ export async function writeRevoked(layout, reason, now) {
89
+ await mkdir(layout.nodeDir, { recursive: true, mode: 0o700 });
90
+ await writeAtomic(layout.revokedMarker, `${JSON.stringify({ at: now.toISOString(), reason })}\n`, 0o644);
91
+ }
92
+ /** A fresh enrollment lifts a revocation. Nothing else does. */
93
+ export async function clearRevoked(layout) {
94
+ await rm(layout.revokedMarker, { force: true });
95
+ }
@@ -0,0 +1,74 @@
1
+ import type { Exec } from '../bootstrap/types.ts';
2
+ import type { Health } from '../bootstrap/plan.ts';
3
+ import type { KeyFile, NodeFile } from '../config.ts';
4
+ import type { Context } from '../context.ts';
5
+ import type { Heartbeat } from '../commands/connect.ts';
6
+ import { type Desired, type Report, type ReportStep, type StepId } from '../nodeContract.ts';
7
+ import { type EngineHealth } from './engine.ts';
8
+ import type { Layout } from './layout.ts';
9
+ import { type SupervisorState } from './state.ts';
10
+ /** What one step found. `skipped` leaves the step out of the report. */
11
+ export type NodeObservation = {
12
+ status: Health;
13
+ detail: string;
14
+ fix?: NonNullable<ReportStep['fix']>;
15
+ };
16
+ export declare const TOOLS: readonly ["gh", "claude", "codex"];
17
+ export type Tool = (typeof TOOLS)[number];
18
+ /** The state of one tick. Steps read and fill it. */
19
+ export type TickRun = {
20
+ ctx: Context;
21
+ layout: Layout;
22
+ node: NodeFile;
23
+ key: KeyFile;
24
+ signal: AbortSignal;
25
+ exec: Exec;
26
+ state: SupervisorState;
27
+ heartbeat: Heartbeat;
28
+ /** The desired document in force: the last one fetched, or the cached one at the start of a tick. */
29
+ desired: Desired | null;
30
+ /** The lane slots the latest heartbeat carried, so a change in desired state can be posted again at once. */
31
+ slotsSent: number | null;
32
+ /** Set when Hive says the node is removed. The tick turns it into a revocation. */
33
+ removed: boolean;
34
+ /** Kept by the supervisor across ticks. */
35
+ probes: Map<Tool, {
36
+ at: number;
37
+ version: string | null;
38
+ }>;
39
+ versions: Partial<Record<Tool | 'engine', string>>;
40
+ relay: {
41
+ hash: string;
42
+ threads: number;
43
+ forced: boolean;
44
+ } | null;
45
+ /**
46
+ * Probes made once per tick. The tick observes every step again after each repair, so a probe that goes out over
47
+ * the network would otherwise repeat several times. A repair that changes what a probe sees clears its entry.
48
+ */
49
+ cache: {
50
+ engine?: Promise<EngineHealth> | undefined;
51
+ ingress?: Promise<string | null> | undefined;
52
+ edge?: Promise<string | null> | undefined;
53
+ echo?: Promise<string | null> | undefined;
54
+ };
55
+ };
56
+ export type NodeStep = {
57
+ id: StepId;
58
+ /** Ids of earlier steps that must work first. `planTick` blocks the step while one of them is failing. */
59
+ needs: readonly StepId[];
60
+ /** Reads the machine and says how the step stands. Never writes. */
61
+ observe: (run: TickRun) => Promise<NodeObservation>;
62
+ /** Fixes the step. A step without one is observed only: a person, `install.sh` or a later plan item fixes it. */
63
+ repair?: (run: TickRun) => Promise<void>;
64
+ };
65
+ export declare const RELAY_REFRESH_MS: number;
66
+ export declare function diskFreeGb(path: string): Promise<number | null>;
67
+ export declare function hostFacts(layout: Layout): Promise<NonNullable<Report['host']>>;
68
+ /**
69
+ * The node's steps in the order they run. Every id is one of `STEP_IDS` in nodeContract.ts, because the report
70
+ * schema rejects any other. These are not the steps of `hive setup` (`bootstrap/registry.ts`). docs/supervisor.md,
71
+ * "Steps", says why the two lists stay apart.
72
+ */
73
+ export declare const NODE_STEPS: readonly NodeStep[];
74
+ export declare function nodeStep(id: StepId): NodeStep;
@@ -0,0 +1,158 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { statfs } from 'node:fs/promises';
4
+ import { arch, cpus, platform, totalmem } from 'node:os';
5
+ import { parseDesired } from "../nodeContract.js";
6
+ import { collectThreads, relayThreads } from "../threads.js";
7
+ import { cliStep } from "./cli.js";
8
+ import { engineStep } from "./engine.js";
9
+ import { ingressStep, streamOriginFor } from "./ingress.js";
10
+ import { modelAccessStep } from "./modelAccess.js";
11
+ import { writeDesired } from "./state.js";
12
+ import { toolchainStep } from "./toolchain.js";
13
+ export const TOOLS = ['gh', 'claude', 'codex'];
14
+ const MIN_DISK_GB = 5;
15
+ export const RELAY_REFRESH_MS = 10 * 60_000;
16
+ export async function diskFreeGb(path) {
17
+ for (const candidate of [path, '/']) {
18
+ try {
19
+ const fs = await statfs(candidate);
20
+ return Math.floor((fs.bavail * fs.bsize) / 1024 ** 3);
21
+ }
22
+ catch {
23
+ // Try the next path.
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+ function osName() {
29
+ try {
30
+ const release = readFileSync('/etc/os-release', 'utf8');
31
+ const id = /^ID=("?)([^"\n]+)\1$/m.exec(release)?.[2];
32
+ const version = /^VERSION_ID=("?)([^"\n]+)\1$/m.exec(release)?.[2];
33
+ if (id)
34
+ return version ? `${id} ${version}` : id;
35
+ }
36
+ catch {
37
+ // Not a Linux with an os-release file.
38
+ }
39
+ return platform();
40
+ }
41
+ export async function hostFacts(layout) {
42
+ const facts = { os: osName(), init: existsSync('/run/systemd/system') ? 'systemd' : 'foreground', cpus: Math.max(1, cpus().length), ram_gb: Math.max(0, Math.round(totalmem() / 1024 ** 3)) };
43
+ if (arch() === 'x64' || arch() === 'arm64')
44
+ facts.arch = arch();
45
+ const free = await diskFreeGb(layout.root);
46
+ if (free !== null)
47
+ facts.disk_free_gb = free;
48
+ return facts;
49
+ }
50
+ const hostStep = {
51
+ id: 'host',
52
+ needs: [],
53
+ async observe(run) {
54
+ const facts = await hostFacts(run.layout);
55
+ if (facts.arch === undefined)
56
+ return { status: 'needs_action', detail: `${arch()} is not supported, use x64 or arm64`, fix: 'human' };
57
+ if (facts.disk_free_gb !== undefined && facts.disk_free_gb < MIN_DISK_GB)
58
+ return { status: 'failing', detail: `${facts.disk_free_gb} GB of disk is free, ${MIN_DISK_GB} GB is needed`, fix: 'human' };
59
+ return { status: 'ok', detail: `${facts.os}, ${facts.arch}, ${facts.init}${facts.disk_free_gb === undefined ? '' : `, ${facts.disk_free_gb} GB free`}` };
60
+ },
61
+ };
62
+ const identityStep = {
63
+ id: 'identity',
64
+ needs: [],
65
+ async observe(run) {
66
+ const { heartbeat } = run;
67
+ if (heartbeat.state === 'paused')
68
+ return { status: 'needs_action', detail: `Hive paused this node${heartbeat.error ? `: ${heartbeat.error}` : ''}`, fix: 'hive_button' };
69
+ if (heartbeat.state !== 'connected')
70
+ return { status: 'failing', detail: heartbeat.error ?? `the connection is ${heartbeat.state}`, fix: 'rerun_install' };
71
+ if (run.state.hive_node_id === null)
72
+ return { status: 'stale', detail: 'the Hive node id is not stored yet' };
73
+ return { status: 'ok', detail: `node ${run.state.hive_node_id} in team ${run.node.team.name} (connection ${run.node.node_id})` };
74
+ },
75
+ async repair(run) {
76
+ const me = await run.ctx.api.json('GET', '/api/v0/nodes/me', { token: run.node.token, key: run.key, signal: run.signal });
77
+ const id = me.node?.node_id;
78
+ if (typeof id !== 'number' || !Number.isInteger(id))
79
+ throw new Error('Hive did not say which node this is.');
80
+ run.state.hive_node_id = id;
81
+ },
82
+ };
83
+ const desiredStep = {
84
+ id: 'desired',
85
+ needs: ['identity'],
86
+ async observe(run) {
87
+ const held = run.desired;
88
+ if (held === null)
89
+ return { status: 'stale', detail: 'no desired state fetched yet' };
90
+ const hive = run.heartbeat.desiredRevision;
91
+ if (hive !== null && hive !== held.revision)
92
+ return { status: 'stale', detail: `revision ${held.revision} held, Hive is at ${hive}` };
93
+ return { status: 'ok', detail: `revision ${held.revision}, applied ${run.state.applied_revision}` };
94
+ },
95
+ async repair(run) {
96
+ const raw = await run.ctx.api.json('GET', '/api/v0/nodes/me/desired', { token: run.node.token, key: run.key, signal: run.signal });
97
+ const desired = parseDesired(raw);
98
+ await writeDesired(run.layout, desired);
99
+ run.desired = desired;
100
+ if (desired.removed === true)
101
+ run.removed = true;
102
+ // This supervisor applies what it owns: slots (reported with the heartbeat), the pause and removal flags, and the
103
+ // action counters. The engine, ingress and model-access sections stay in the cached document for their steps.
104
+ run.state.applied_revision = desired.revision;
105
+ },
106
+ };
107
+ function batchHash(threads, streamOrigin) {
108
+ return createHash('sha256').update(JSON.stringify({ threads, streamOrigin: streamOrigin ?? null })).digest('hex');
109
+ }
110
+ /**
111
+ * The relay posts the thread batch when it changes and at least every ten minutes. Observing reads the local T3 Code
112
+ * database and compares the batch with what was last sent. It does not post.
113
+ */
114
+ const relayStep = {
115
+ id: 'relay',
116
+ needs: ['identity'],
117
+ async observe(run) {
118
+ run.relay = null;
119
+ let collected;
120
+ try {
121
+ collected = await collectThreads(run.ctx, streamOriginFor(run));
122
+ }
123
+ catch (error) {
124
+ return { status: 'failing', detail: `cannot read the T3 Code database: ${error instanceof Error ? error.message : String(error)}`, fix: 'rerun_install' };
125
+ }
126
+ if (collected === null)
127
+ return { status: 'ok', detail: 'no T3 Code database yet, nothing to relay' };
128
+ const { batch } = collected;
129
+ const hash = batchHash(batch.threads, batch.stream_origin);
130
+ const last = run.state.relay;
131
+ const forced = batch.removed.length > 0;
132
+ run.relay = { hash, threads: batch.threads.length, forced };
133
+ const current = last !== null && last.hash === hash && !forced && run.ctx.now().getTime() - Date.parse(last.at) < RELAY_REFRESH_MS;
134
+ if (current)
135
+ return { status: 'ok', detail: `${batch.threads.length} threads relayed` };
136
+ return { status: 'stale', detail: `${batch.threads.length} threads to relay` };
137
+ },
138
+ async repair(run) {
139
+ const pending = run.relay;
140
+ const result = await relayThreads(run.ctx, run.node, run.key, run.signal, streamOriginFor(run));
141
+ if (result.kind === 'absent')
142
+ return;
143
+ if (pending !== null)
144
+ run.state.relay = { hash: pending.hash, at: run.ctx.now().toISOString(), threads: result.threads };
145
+ },
146
+ };
147
+ /**
148
+ * The node's steps in the order they run. Every id is one of `STEP_IDS` in nodeContract.ts, because the report
149
+ * schema rejects any other. These are not the steps of `hive setup` (`bootstrap/registry.ts`). docs/supervisor.md,
150
+ * "Steps", says why the two lists stay apart.
151
+ */
152
+ export const NODE_STEPS = [hostStep, identityStep, desiredStep, cliStep, toolchainStep, engineStep, ingressStep, modelAccessStep, relayStep];
153
+ export function nodeStep(id) {
154
+ const found = NODE_STEPS.find((step) => step.id === id);
155
+ if (!found)
156
+ throw new Error(`${id} is not a node step.`);
157
+ return found;
158
+ }
@@ -0,0 +1,22 @@
1
+ import type { KeyFile, NodeFile } from '../config.ts';
2
+ import type { Context } from '../context.ts';
3
+ import { type Layout } from './layout.ts';
4
+ import { type TickResult } from './tick.ts';
5
+ /** A repair request is noticed within this long, even in the middle of the 60 second wait between ticks. */
6
+ export declare const REQUEST_POLL_MS = 2000;
7
+ export declare function prepareDirs(layout: Layout): Promise<void>;
8
+ export type Identity = {
9
+ node: NodeFile;
10
+ key: KeyFile;
11
+ };
12
+ export declare function loadIdentity(ctx: Context): Promise<Identity | null>;
13
+ /**
14
+ * `hive node run`: the node's only writer. Returns the process exit code:
15
+ * 0 after a stop signal, 1 when it cannot start, 75 when `cli/current` was swapped, 77 when Hive revoked or removed
16
+ * the node (the `revoked` marker is already written then).
17
+ */
18
+ export declare function runSupervisor(ctx: Context, signal: AbortSignal): Promise<number>;
19
+ /** One tick in this process, for `hive doctor --repair` and `hive setup` when no supervisor runs. The caller holds the lock. */
20
+ export declare function runOneTick(ctx: Context, signal: AbortSignal): Promise<TickResult | {
21
+ error: string;
22
+ }>;
@@ -0,0 +1,95 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readlink } from 'node:fs/promises';
3
+ import { makeExec } from "../bootstrap/system.js";
4
+ import { nextDelaySeconds } from "../machine.js";
5
+ import { EXIT, layoutOf } from "./layout.js";
6
+ import { tryLock } from "./lock.js";
7
+ import { readRevoked } from "./state.js";
8
+ import { tracedTick } from "./tick.js";
9
+ /** A repair request is noticed within this long, even in the middle of the 60 second wait between ticks. */
10
+ export const REQUEST_POLL_MS = 2_000;
11
+ async function currentLink(layout) {
12
+ try {
13
+ return await readlink(layout.cliCurrent);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ export async function prepareDirs(layout) {
20
+ await mkdir(layout.nodeDir, { recursive: true, mode: 0o700 });
21
+ await mkdir(layout.reportDir, { recursive: true, mode: 0o750 });
22
+ }
23
+ export async function loadIdentity(ctx) {
24
+ const node = await ctx.store.read('node.json');
25
+ const key = await ctx.store.read('key.json');
26
+ return node !== null && key !== null ? { node, key } : null;
27
+ }
28
+ /** Waits up to `ms`, and returns early when a repair request shows up or the signal aborts. */
29
+ async function waitForWork(ctx, layout, ms, signal) {
30
+ for (let waited = 0; waited < ms; waited += REQUEST_POLL_MS) {
31
+ await ctx.sleep(Math.min(REQUEST_POLL_MS, ms - waited), signal);
32
+ if (signal.aborted || existsSync(layout.repairRequest))
33
+ return;
34
+ }
35
+ }
36
+ /**
37
+ * `hive node run`: the node's only writer. Returns the process exit code:
38
+ * 0 after a stop signal, 1 when it cannot start, 75 when `cli/current` was swapped, 77 when Hive revoked or removed
39
+ * the node (the `revoked` marker is already written then).
40
+ */
41
+ export async function runSupervisor(ctx, signal) {
42
+ const layout = layoutOf(ctx.env);
43
+ // The marker means the file exists, as systemd's ConditionPathExists and the keeper read it. Its content is only a note.
44
+ if (existsSync(layout.revokedMarker)) {
45
+ const note = await readRevoked(layout);
46
+ ctx.io.err(`This node was revoked${note ? ` (${note.reason})` : ''}. It stays stopped until it is enrolled again.`);
47
+ return EXIT.REVOKED;
48
+ }
49
+ await prepareDirs(layout);
50
+ const lock = tryLock(layout.lockFile);
51
+ if (lock === null) {
52
+ ctx.io.err(`Another \`hive node run\` holds ${layout.lockFile}. Only one supervisor runs on a node.`);
53
+ return 1;
54
+ }
55
+ try {
56
+ const identity = await loadIdentity(ctx);
57
+ if (identity === null) {
58
+ ctx.io.err(`This machine is not enrolled: no node identity in ${ctx.store.dir}. Enroll with \`hive node bootstrap --token <hvr_...>\` or \`hive setup --token <hvr_...>\`.`);
59
+ return 1;
60
+ }
61
+ const deps = { ctx, layout, ...identity, exec: makeExec(ctx.env), signal, probes: new Map() };
62
+ const startedOn = await currentLink(layout);
63
+ let failures = 0;
64
+ ctx.io.out(`Supervising ${identity.node.name} in ${identity.node.team.name}, state in ${layout.root}.`);
65
+ for (;;) {
66
+ const result = await tracedTick(deps);
67
+ if (result.revoked !== null)
68
+ return EXIT.REVOKED;
69
+ if ((await currentLink(layout)) !== startedOn) {
70
+ ctx.io.out('The CLI was swapped. Exiting so the keeper starts the new one.');
71
+ return EXIT.RESTART;
72
+ }
73
+ failures = result.heartbeat.state === 'degraded' ? failures + 1 : 0;
74
+ if (signal.aborted)
75
+ break;
76
+ await waitForWork(ctx, layout, nextDelaySeconds(result.heartbeat.state, failures - 1, ctx.random) * 1000, signal);
77
+ if (signal.aborted)
78
+ break;
79
+ }
80
+ ctx.io.out('Stopped.');
81
+ return 0;
82
+ }
83
+ finally {
84
+ lock.release();
85
+ }
86
+ }
87
+ /** One tick in this process, for `hive doctor --repair` and `hive setup` when no supervisor runs. The caller holds the lock. */
88
+ export async function runOneTick(ctx, signal) {
89
+ const layout = layoutOf(ctx.env);
90
+ const identity = await loadIdentity(ctx);
91
+ if (identity === null)
92
+ return { error: `This machine is not enrolled: no node identity in ${ctx.store.dir}.` };
93
+ await prepareDirs(layout);
94
+ return tracedTick({ ctx, layout, ...identity, exec: makeExec(ctx.env), signal, probes: new Map() });
95
+ }
@@ -0,0 +1,47 @@
1
+ import type { Exec } from '../bootstrap/types.ts';
2
+ import { postOnce } from '../commands/connect.ts';
3
+ import type { KeyFile, NodeFile } from '../config.ts';
4
+ import type { Context } from '../context.ts';
5
+ import { type Report } from '../nodeContract.ts';
6
+ import type { Layout } from './layout.ts';
7
+ import { type TickRun } from './steps.ts';
8
+ /** A report is posted when it changed, and at least this often. */
9
+ export declare const REPORT_REFRESH_MS: number;
10
+ export type TickDeps = {
11
+ ctx: Context;
12
+ layout: Layout;
13
+ node: NodeFile;
14
+ key: KeyFile;
15
+ exec: Exec;
16
+ signal: AbortSignal;
17
+ /** Kept by the caller across ticks. */
18
+ probes: TickRun['probes'];
19
+ };
20
+ export type TickResult = {
21
+ heartbeat: Awaited<ReturnType<typeof postOnce>>;
22
+ /** Why the node is revoked. The marker is already written. */
23
+ revoked: string | null;
24
+ report: Report | null;
25
+ posted: boolean;
26
+ };
27
+ export type RepairRequest = {
28
+ id: string;
29
+ at: string;
30
+ by: string;
31
+ };
32
+ export declare function readRequest(layout: Layout): Promise<RepairRequest | null>;
33
+ /**
34
+ * One tick of the supervisor. The caller holds the state lock. Order:
35
+ *
36
+ * 1. heartbeat. A revoking answer ends the tick.
37
+ * 2. observe every step, then repair in order what `planTick` queues.
38
+ * 3. if the repairs changed the slots Hive asked for, heartbeat again, so the change shows within this tick.
39
+ * 4. run a full pass when Hive raised the `rerun_setup` counter, then save the counter.
40
+ * 5. write `report/report.json`, post it when it changed or is ten minutes old, and settle the repair request.
41
+ */
42
+ export declare function runTick(deps: TickDeps): Promise<TickResult>;
43
+ /**
44
+ * Test hook. When `HIVE_NODE_TRACE` names a file, each tick appends `start <pid>` and `end <pid>`, so a test can
45
+ * prove that two processes never tick at the same time.
46
+ */
47
+ export declare function tracedTick(deps: TickDeps): Promise<TickResult>;