@overcy/hive 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +209 -4
  2. package/dist/api.d.ts +31 -0
  3. package/dist/api.js +83 -0
  4. package/dist/atomic.d.ts +1 -0
  5. package/dist/atomic.js +24 -0
  6. package/dist/binding.d.ts +5 -0
  7. package/dist/binding.js +16 -0
  8. package/dist/bootstrap/deps.d.ts +3 -0
  9. package/dist/bootstrap/deps.js +35 -0
  10. package/dist/bootstrap/doctor.d.ts +29 -0
  11. package/dist/bootstrap/doctor.js +80 -0
  12. package/dist/bootstrap/engine.d.ts +29 -0
  13. package/dist/bootstrap/engine.js +160 -0
  14. package/dist/bootstrap/forwarder.d.ts +11 -0
  15. package/dist/bootstrap/forwarder.js +30 -0
  16. package/dist/bootstrap/identity.d.ts +7 -0
  17. package/dist/bootstrap/identity.js +52 -0
  18. package/dist/bootstrap/index.d.ts +36 -0
  19. package/dist/bootstrap/index.js +40 -0
  20. package/dist/bootstrap/kit.d.ts +9 -0
  21. package/dist/bootstrap/kit.js +56 -0
  22. package/dist/bootstrap/manifest.d.ts +73 -0
  23. package/dist/bootstrap/manifest.js +309 -0
  24. package/dist/bootstrap/model-access.d.ts +43 -0
  25. package/dist/bootstrap/model-access.js +74 -0
  26. package/dist/bootstrap/pin.d.ts +2 -0
  27. package/dist/bootstrap/pin.js +16 -0
  28. package/dist/bootstrap/plan.d.ts +49 -0
  29. package/dist/bootstrap/plan.js +69 -0
  30. package/dist/bootstrap/prompt.d.ts +3 -0
  31. package/dist/bootstrap/prompt.js +35 -0
  32. package/dist/bootstrap/registry.d.ts +85 -0
  33. package/dist/bootstrap/registry.js +38 -0
  34. package/dist/bootstrap/secrets.d.ts +11 -0
  35. package/dist/bootstrap/secrets.js +105 -0
  36. package/dist/bootstrap/steps/agents.d.ts +9 -0
  37. package/dist/bootstrap/steps/agents.js +75 -0
  38. package/dist/bootstrap/steps/auth.d.ts +8 -0
  39. package/dist/bootstrap/steps/auth.js +138 -0
  40. package/dist/bootstrap/steps/cron.d.ts +7 -0
  41. package/dist/bootstrap/steps/cron.js +74 -0
  42. package/dist/bootstrap/steps/drift.d.ts +5 -0
  43. package/dist/bootstrap/steps/drift.js +67 -0
  44. package/dist/bootstrap/steps/env.d.ts +6 -0
  45. package/dist/bootstrap/steps/env.js +108 -0
  46. package/dist/bootstrap/steps/files.d.ts +7 -0
  47. package/dist/bootstrap/steps/files.js +28 -0
  48. package/dist/bootstrap/steps/lanes.d.ts +14 -0
  49. package/dist/bootstrap/steps/lanes.js +153 -0
  50. package/dist/bootstrap/steps/model-access.d.ts +10 -0
  51. package/dist/bootstrap/steps/model-access.js +122 -0
  52. package/dist/bootstrap/steps/preflight.d.ts +3 -0
  53. package/dist/bootstrap/steps/preflight.js +49 -0
  54. package/dist/bootstrap/steps/reporter.d.ts +12 -0
  55. package/dist/bootstrap/steps/reporter.js +155 -0
  56. package/dist/bootstrap/system.d.ts +5 -0
  57. package/dist/bootstrap/system.js +69 -0
  58. package/dist/bootstrap/types.d.ts +157 -0
  59. package/dist/bootstrap/types.js +14 -0
  60. package/dist/cli.d.ts +2 -0
  61. package/dist/cli.js +23 -0
  62. package/dist/collect.d.ts +28 -0
  63. package/dist/collect.js +63 -0
  64. package/dist/commands/connect.d.ts +33 -0
  65. package/dist/commands/connect.js +306 -0
  66. package/dist/commands/doctor.d.ts +7 -0
  67. package/dist/commands/doctor.js +13 -0
  68. package/dist/commands/login.d.ts +3 -0
  69. package/dist/commands/login.js +118 -0
  70. package/dist/commands/logout.d.ts +2 -0
  71. package/dist/commands/logout.js +37 -0
  72. package/dist/commands/node-add.d.ts +7 -0
  73. package/dist/commands/node-add.js +56 -0
  74. package/dist/commands/node.d.ts +19 -0
  75. package/dist/commands/node.js +43 -0
  76. package/dist/commands/prEvents.d.ts +7 -0
  77. package/dist/commands/prEvents.js +32 -0
  78. package/dist/commands/setup.d.ts +15 -0
  79. package/dist/commands/setup.js +35 -0
  80. package/dist/commands/status.d.ts +18 -0
  81. package/dist/commands/status.js +71 -0
  82. package/dist/commands/threads.d.ts +6 -0
  83. package/dist/commands/threads.js +36 -0
  84. package/dist/config.d.ts +71 -0
  85. package/dist/config.js +121 -0
  86. package/dist/context.d.ts +26 -0
  87. package/dist/context.js +31 -0
  88. package/dist/crypto.d.ts +7 -0
  89. package/dist/crypto.js +50 -0
  90. package/dist/machine.d.ts +66 -0
  91. package/dist/machine.js +103 -0
  92. package/dist/node/cli.d.ts +25 -0
  93. package/dist/node/cli.js +130 -0
  94. package/dist/node/engine.d.ts +47 -0
  95. package/dist/node/engine.js +463 -0
  96. package/dist/node/ingress.d.ts +102 -0
  97. package/dist/node/ingress.js +473 -0
  98. package/dist/node/layout.d.ts +56 -0
  99. package/dist/node/layout.js +55 -0
  100. package/dist/node/leave.d.ts +8 -0
  101. package/dist/node/leave.js +32 -0
  102. package/dist/node/lock.d.ts +19 -0
  103. package/dist/node/lock.js +99 -0
  104. package/dist/node/modelAccess.d.ts +2 -0
  105. package/dist/node/modelAccess.js +44 -0
  106. package/dist/node/repair.d.ts +28 -0
  107. package/dist/node/repair.js +78 -0
  108. package/dist/node/services.d.ts +58 -0
  109. package/dist/node/services.js +171 -0
  110. package/dist/node/state.d.ts +127 -0
  111. package/dist/node/state.js +95 -0
  112. package/dist/node/steps.d.ts +74 -0
  113. package/dist/node/steps.js +158 -0
  114. package/dist/node/supervisor.d.ts +22 -0
  115. package/dist/node/supervisor.js +95 -0
  116. package/dist/node/tick.d.ts +47 -0
  117. package/dist/node/tick.js +278 -0
  118. package/dist/node/toolchain.d.ts +50 -0
  119. package/dist/node/toolchain.js +230 -0
  120. package/dist/nodeContract.d.ts +101 -0
  121. package/dist/nodeContract.js +192 -0
  122. package/dist/package.d.ts +3 -0
  123. package/dist/package.js +5 -0
  124. package/dist/prEvents.d.ts +109 -0
  125. package/dist/prEvents.js +374 -0
  126. package/dist/run.d.ts +19 -0
  127. package/dist/run.js +487 -0
  128. package/dist/specs/device-client.json +920 -0
  129. package/dist/threads.d.ts +88 -0
  130. package/dist/threads.js +268 -0
  131. package/dist/version.d.ts +1 -0
  132. package/dist/version.js +1 -0
  133. package/package.json +33 -7
  134. package/bin/hive.js +0 -2
@@ -0,0 +1,306 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { rm } from 'node:fs/promises';
3
+ import { hostname, platform, arch } from 'node:os';
4
+ import { ApiError, NetworkError } from "../api.js";
5
+ import { collectStatus, defaultNodeName, nodeNameFrom } from "../collect.js";
6
+ import { PENDING_KEY } from "../config.js";
7
+ import { boundToServer, sameServer } from "../binding.js";
8
+ import { generateKey, machineIdHash } from "../crypto.js";
9
+ import { classifyFailure, nextDelaySeconds } from "../machine.js";
10
+ import { prEventsEnabled, pullPrEvents } from "../prEvents.js";
11
+ import { relayThreads } from "../threads.js";
12
+ import { relayFailure } from "./threads.js";
13
+ import { layoutOf } from "../node/layout.js";
14
+ import { lockHeld } from "../node/lock.js";
15
+ import { clearRevoked } from "../node/state.js";
16
+ export async function connect(ctx, options, signal) {
17
+ const notBuilt = options.rebind ? 'rebind' : options.rotate ? 'rotate' : options.reconnect !== undefined ? 'reconnect' : null;
18
+ if (notBuilt !== null) {
19
+ ctx.io.err(`--${notBuilt} is not built yet. Remove the node in the app and run \`hive connect\` again.`);
20
+ return 1;
21
+ }
22
+ let saved = await ctx.store.state();
23
+ if (saved.state === 'rotating' || saved.state === 'recovering') {
24
+ await ctx.store.applyAndRun('REGISTRATION_FAILED', { guards: await ctx.store.heldGuards(), lastError: 'The previous attempt did not finish.' });
25
+ saved = await ctx.store.state();
26
+ }
27
+ if (saved.state === 'authorizing' && options.token !== undefined) {
28
+ await ctx.store.apply('LOGIN_FAILED');
29
+ saved = await ctx.store.state();
30
+ }
31
+ const state = saved.state;
32
+ const unregistered = state === 'unconfigured' || state === 'authorizing' || state === 'revoked';
33
+ const viaToken = options.token !== undefined && (unregistered || state === 'connecting');
34
+ if (options.token !== undefined && state === 'logged_in') {
35
+ ctx.io.err('This machine is signed in. Run `hive connect` without a token, or `hive logout` first.');
36
+ return 1;
37
+ }
38
+ if (!viaToken && (state === 'unconfigured' || state === 'authorizing')) {
39
+ ctx.io.err('Not signed in. Run `hive login` first, or pass a registration token with `hive connect --token <token>`.');
40
+ return 1;
41
+ }
42
+ if (!viaToken && state === 'revoked') {
43
+ ctx.io.err(`This machine's access was revoked${saved.last_error ? ` (${saved.last_error})` : ''}. Run \`hive logout\`, then \`hive login\` and \`hive connect\`.`);
44
+ return 1;
45
+ }
46
+ let node = await ctx.store.read('node.json');
47
+ let key = await ctx.store.read('key.json');
48
+ if (node && key && !sameServer(node.url, ctx.url)) {
49
+ ctx.io.err(`This machine is connected to ${node.url}. Set HIVE_URL back to it, or delete ${ctx.store.dir} to start over.`);
50
+ return 1;
51
+ }
52
+ if (state === 'logged_in' || state === 'connecting' || viaToken) {
53
+ const registered = await register(ctx, options, state === 'logged_in' || state === 'connecting' ? state : 'token', node, key);
54
+ if (typeof registered === 'number')
55
+ return registered;
56
+ [node, key] = registered;
57
+ }
58
+ if (!node || !key) {
59
+ ctx.io.err('The saved node identity is missing. Run `hive logout`, delete the config directory and connect again.');
60
+ return 1;
61
+ }
62
+ ctx.io.out(`Connected as ${node.name} in ${node.team.name}.`);
63
+ if (!options.once) {
64
+ // The supervisor replaces this loop. Two writers would race on the state and post twice, so a held lock stops it.
65
+ if (lockHeld(layoutOf(ctx.env).lockFile)) {
66
+ ctx.io.err('`hive node run` is already supervising this node, so `hive connect` has nothing to do. Stop using `hive connect`.');
67
+ return 1;
68
+ }
69
+ ctx.io.err('`hive connect` is deprecated. `hive node run` replaces it and does more: it applies desired state from Hive, repairs the node and reports it. This loop keeps working for now.');
70
+ }
71
+ return report(ctx, node, key, options, signal);
72
+ }
73
+ async function register(ctx, options, state, node, current) {
74
+ const pending = await ctx.store.read(PENDING_KEY);
75
+ if (state === 'connecting' && node && current && !pending) {
76
+ await ctx.store.apply('REGISTERED');
77
+ return [node, current];
78
+ }
79
+ const registrationToken = options.token;
80
+ let bearer = registrationToken;
81
+ if (bearer === undefined) {
82
+ const saved = await ctx.store.read('user.json');
83
+ const user = boundToServer(ctx, saved, 'sign-in');
84
+ if (saved && !user)
85
+ return 1;
86
+ bearer = user?.token;
87
+ }
88
+ if (bearer === undefined) {
89
+ if (state === 'connecting')
90
+ await ctx.store.applyAndRun('REGISTRATION_FAILED', { guards: await ctx.store.heldGuards(), lastError: 'The saved sign-in is missing.' });
91
+ ctx.io.err('The saved sign-in is missing. Run `hive logout`, then `hive login`.');
92
+ return 1;
93
+ }
94
+ const step = await ctx.store.applyAndRun(state === 'token' ? 'CONNECT_WITH_TOKEN' : 'CONNECT', { guards: await ctx.store.heldGuards() });
95
+ const stored = pending ? await ctx.store.read('registration.json') : null;
96
+ const repeats = stored !== null && (!options.name || nodeNameFrom(options.name) === stored.name) && (!options.team || options.team === stored.team);
97
+ const reuseKey = pending !== null && !step.actions.includes('generate_keypair');
98
+ const key = reuseKey ? pending : generateKey();
99
+ let registration;
100
+ if (reuseKey && repeats && stored) {
101
+ registration = stored;
102
+ ctx.io.out(`Resuming the registration of ${registration.name}.`);
103
+ }
104
+ else {
105
+ registration = { registration_id: randomBytes(16).toString('hex'), name: options.name ? nodeNameFrom(options.name) : (stored?.name ?? defaultNodeName()), ...(options.team ? { team: options.team } : {}) };
106
+ if (!reuseKey)
107
+ await ctx.store.savePendingKey(key);
108
+ await ctx.store.write('registration.json', registration);
109
+ }
110
+ try {
111
+ const body = {
112
+ name: registration.name,
113
+ kind: 'machine',
114
+ hostname: hostname(),
115
+ platform: `${platform()}-${arch()}`,
116
+ machine_id_hash: await machineIdHash(),
117
+ public_key: key.public_key,
118
+ registration_id: registration.registration_id,
119
+ mode: 'register',
120
+ };
121
+ if (registration.team)
122
+ body.team = registration.team;
123
+ if (options.enrollment)
124
+ body.enrollment = options.enrollment;
125
+ const response = await ctx.api.json('POST', '/api/v0/nodes', { token: bearer, body, timeoutMs: ctx.registrationTimeoutMs });
126
+ const registered = { url: ctx.url, node_id: response.node.id, name: response.node.name, kind: response.node.kind, token: response.node_token, team: response.team };
127
+ await ctx.store.write('node.json', registered);
128
+ await ctx.store.promotePendingKey();
129
+ await ctx.store.remove('registration.json');
130
+ await ctx.store.apply('REGISTERED');
131
+ // A new enrollment is the one thing that lifts a revocation.
132
+ if (registrationToken !== undefined)
133
+ await clearRevoked(layoutOf(ctx.env)).catch(() => undefined);
134
+ if (registrationToken !== undefined && options.tokenFile !== undefined)
135
+ await removeTokenFile(ctx, options.tokenFile);
136
+ return [registered, key];
137
+ }
138
+ catch (error) {
139
+ return failRegistration(ctx, error, registrationToken !== undefined);
140
+ }
141
+ }
142
+ async function removeTokenFile(ctx, path) {
143
+ try {
144
+ await rm(path, { force: true });
145
+ }
146
+ catch (error) {
147
+ ctx.io.err(`Registered, but could not delete ${path}: ${error.code ?? String(error)}. The token is used up; delete the file yourself.`);
148
+ }
149
+ }
150
+ function isDefinitiveRefusal(status) {
151
+ return status >= 400 && status < 500 && status !== 408 && status !== 429;
152
+ }
153
+ async function failRegistration(ctx, error, viaToken) {
154
+ const detail = error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof Error ? error.message : String(error);
155
+ const refused = error instanceof ApiError && isDefinitiveRefusal(error.status);
156
+ await ctx.store.applyAndRun(refused ? 'REGISTRATION_REFUSED' : 'REGISTRATION_FAILED', { guards: await ctx.store.heldGuards(), lastError: detail });
157
+ if (!viaToken && error instanceof ApiError && error.status === 401) {
158
+ ctx.io.err(`${error.message} Run \`hive logout\`, then \`hive login\` and \`hive connect\`.`);
159
+ return 1;
160
+ }
161
+ ctx.io.err(detail);
162
+ return 1;
163
+ }
164
+ async function report(ctx, node, key, options, signal) {
165
+ const lanesDir = ctx.env.HIVE_LANES_DIR && ctx.env.HIVE_LANES_DIR !== '' ? ctx.env.HIVE_LANES_DIR : null;
166
+ let failures = 0;
167
+ let relayed = null;
168
+ const stopEvents = new AbortController();
169
+ let events = null;
170
+ const finish = async (code) => {
171
+ if (!options.once)
172
+ stopEvents.abort();
173
+ await events;
174
+ return code;
175
+ };
176
+ for (;;) {
177
+ const { state } = await postOnce(ctx, node, key, lanesDir, signal);
178
+ failures = state === 'degraded' ? failures + 1 : 0;
179
+ if (state === 'connected' && !signal.aborted)
180
+ relayed = await relayQuietly(ctx, node, key, signal, relayed);
181
+ if (state === 'connected' && events === null && prEventsEnabled(ctx.env))
182
+ events = prEventsLoop(ctx, node, key, AbortSignal.any([signal, stopEvents.signal]), options);
183
+ if (state === 'revoked' || state === 'unconfigured')
184
+ return finish(1);
185
+ if (options.once)
186
+ return finish(state === 'connected' ? 0 : 1);
187
+ if (signal.aborted)
188
+ break;
189
+ const delay = options.intervalSeconds !== undefined && state !== 'degraded' ? options.intervalSeconds : nextDelaySeconds(state, failures - 1, ctx.random);
190
+ await ctx.sleep(delay * 1000, signal);
191
+ if (signal.aborted)
192
+ break;
193
+ }
194
+ await finish(0);
195
+ ctx.io.out('Stopped.');
196
+ return 0;
197
+ }
198
+ /**
199
+ * PR events run beside the status loop, never inside it, so a slow or hung T3 Code never delays a status post or
200
+ * the thread relay. Each pass has its own deadline. The task only reads the connection state, and a send in flight
201
+ * at shutdown is allowed to finish.
202
+ */
203
+ async function prEventsLoop(ctx, node, key, signal, options) {
204
+ let last = null;
205
+ for (;;) {
206
+ try {
207
+ if ((await ctx.store.state()).state === 'connected')
208
+ last = await deliverQuietly(ctx, node, key, signal, last);
209
+ }
210
+ catch (error) {
211
+ ctx.io.err(`PR events failed: ${relayFailure(error)}`);
212
+ }
213
+ if (options.once || signal.aborted)
214
+ return;
215
+ await ctx.sleep((options.intervalSeconds ?? 60) * 1000, signal);
216
+ if (signal.aborted)
217
+ return;
218
+ }
219
+ }
220
+ async function relayQuietly(ctx, node, key, signal, last) {
221
+ let line;
222
+ try {
223
+ const result = await relayThreads(ctx, node, key, signal);
224
+ if (result.kind === 'absent')
225
+ return last;
226
+ line = `Relaying ${result.threads} T3 Code threads.`;
227
+ if (line !== last)
228
+ ctx.io.out(line);
229
+ }
230
+ catch (error) {
231
+ if (signal.aborted)
232
+ return last;
233
+ line = `Thread relay failed: ${relayFailure(error)}`;
234
+ if (line !== last)
235
+ ctx.io.err(line);
236
+ }
237
+ return line;
238
+ }
239
+ async function deliverQuietly(ctx, node, key, signal, last) {
240
+ try {
241
+ const result = await pullPrEvents(ctx, node, key, { signal });
242
+ if (result.sent > 0)
243
+ ctx.io.out(`Delivered ${result.sent} PR event messages.`);
244
+ return null;
245
+ }
246
+ catch (error) {
247
+ if (signal.aborted)
248
+ return last;
249
+ const line = `PR events failed: ${relayFailure(error)}`;
250
+ if (line !== last)
251
+ ctx.io.err(line);
252
+ return line;
253
+ }
254
+ }
255
+ /**
256
+ * One status post. `laneMax` overrides `HIVE_BOX_SLOTS`, so the supervisor can report the slots Hive asked for.
257
+ * `stamp` is the post's `sent_at`. Hive keeps one post per second and node, so two posts in one second need distinct stamps.
258
+ * The answer's `desired_revision` is how a node learns that Hive changed something.
259
+ */
260
+ export async function postOnce(ctx, node, key, lanesDir, signal, laneMax, stamp = ctx.now()) {
261
+ const rawSlots = ctx.env.HIVE_BOX_SLOTS;
262
+ const slots = rawSlots === undefined || rawSlots.trim() === '' ? NaN : Number(rawSlots);
263
+ const max = laneMax !== undefined ? laneMax : Number.isInteger(slots) && slots >= 0 ? slots : null;
264
+ const body = await collectStatus(node.name, node.kind, lanesDir, stamp, max);
265
+ const saved = await ctx.store.state();
266
+ const before = saved.state;
267
+ if (before === 'degraded')
268
+ await ctx.store.applyIfLegal('BACKOFF_ELAPSED', { lastError: saved.last_error });
269
+ if (before === 'paused')
270
+ await ctx.store.applyIfLegal('RETRY_DUE', { lastError: saved.last_error });
271
+ try {
272
+ const corrected = (skewMs) => ({ ...body, sent_at: new Date(stamp.getTime() + skewMs).toISOString().replace(/\.\d{3}Z$/, 'Z') });
273
+ const response = await ctx.api.json('POST', '/api/v0/nodes/me/status', { token: node.token, key, body: corrected, signal });
274
+ const after = await ctx.store.applyIfLegal('POST_OK');
275
+ if (before !== after)
276
+ ctx.io.out(`Reporting again (${after}).`);
277
+ else
278
+ ctx.io.out(`Reported at ${body.sent_at}.`);
279
+ const revision = typeof response.desired_revision === 'number' && Number.isInteger(response.desired_revision) && response.desired_revision >= 0 ? response.desired_revision : null;
280
+ return { state: after, desiredRevision: revision, error: null };
281
+ }
282
+ catch (error) {
283
+ if (signal.aborted)
284
+ return { state: before, desiredRevision: null, error: null };
285
+ const event = error instanceof ApiError ? classifyFailure(error.status, error.code) : 'POST_FAILED';
286
+ if (error instanceof ApiError && (event === 'HTTP_402' || event === 'HTTP_403_FLAGGED')) {
287
+ const after = await ctx.store.applyIfLegal(event, { lastError: error.message });
288
+ ctx.io.err(`Paused: ${error.message}`);
289
+ return { state: after, desiredRevision: null, error: error.message };
290
+ }
291
+ if (error instanceof ApiError && event === 'HTTP_401') {
292
+ const after = await ctx.store.applyIfLegal(event, { lastError: error.message });
293
+ ctx.io.err(`Revoked: ${error.message} Run \`hive logout\`, then \`hive login\` and \`hive connect\`.`);
294
+ return { state: after, desiredRevision: null, error: error.message };
295
+ }
296
+ const hint = error instanceof ApiError && error.code === 'timestamp_skew' ? ' Check this machine\'s clock.' : '';
297
+ const message = error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof NetworkError ? error.message : String(error);
298
+ if (before === 'paused') {
299
+ ctx.io.err(`Still paused, could not report: ${message}`);
300
+ return { state: before, desiredRevision: null, error: message };
301
+ }
302
+ const after = await ctx.store.applyIfLegal('POST_FAILED', { lastError: message });
303
+ ctx.io.err(`Report failed, will retry with backoff: ${message}${hint}`);
304
+ return { state: after, desiredRevision: null, error: message };
305
+ }
306
+ }
@@ -0,0 +1,7 @@
1
+ import type { Context, Io } from '../context.ts';
2
+ import type { SetupDeps } from '../bootstrap/types.ts';
3
+ export type DoctorOptions = {
4
+ json: boolean;
5
+ };
6
+ /** `hive doctor`: read-only. Exits 0 only when every step is ok or skipped. */
7
+ export declare function doctor(ctx: Context, opts: DoctorOptions, signal: AbortSignal, io: Io, overrides?: Partial<SetupDeps>): Promise<number>;
@@ -0,0 +1,13 @@
1
+ import { renderDoctor, runDoctor } from "../bootstrap/doctor.js";
2
+ import { makeSetupDeps } from "../bootstrap/deps.js";
3
+ /** `hive doctor`: read-only. Exits 0 only when every step is ok or skipped. */
4
+ export async function doctor(ctx, opts, signal, io, overrides = {}) {
5
+ const deps = await makeSetupDeps(ctx, false, overrides);
6
+ const report = await runDoctor(ctx, deps, signal);
7
+ if (opts.json)
8
+ io.out(JSON.stringify(report));
9
+ else
10
+ for (const line of renderDoctor(report))
11
+ io.out(line);
12
+ return report.ok ? 0 : 1;
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { Context } from '../context.ts';
2
+ export declare function login(ctx: Context, signal?: AbortSignal): Promise<number>;
3
+ export declare function expiryTime(at: Date): string;
@@ -0,0 +1,118 @@
1
+ import { hostname, platform, arch } from 'node:os';
2
+ import { ApiError, NetworkError } from "../api.js";
3
+ import { boundToServer } from "../binding.js";
4
+ import { classifyFailure } from "../machine.js";
5
+ export async function login(ctx, signal) {
6
+ let current = await ctx.store.state();
7
+ if (current.state === 'authorizing') {
8
+ await ctx.store.apply('LOGIN_FAILED', { lastError: 'The previous sign-in did not finish.' });
9
+ current = await ctx.store.state();
10
+ }
11
+ const keepError = current.state === 'unconfigured' ? null : current.last_error;
12
+ const user = boundToServer(ctx, await ctx.store.read('user.json'), 'sign-in');
13
+ if (user && current.state !== 'unconfigured') {
14
+ if (!(await signInExpired(ctx, user))) {
15
+ ctx.io.out(`Already signed in as ${user.user.email}. Run \`hive logout\` first to sign in as someone else.`);
16
+ return 0;
17
+ }
18
+ ctx.io.out('Your sign-in expired. Signing in again. A running `hive connect` keeps reporting.');
19
+ }
20
+ await ctx.store.apply('LOGIN_STARTED', { lastError: keepError });
21
+ const abandon = async (reason) => {
22
+ await ctx.store.apply('LOGIN_FAILED', { lastError: current.state === 'unconfigured' ? reason : keepError });
23
+ };
24
+ for (let attempt = 1; attempt <= MAX_CODES; attempt++) {
25
+ let started;
26
+ try {
27
+ started = await ctx.api.json('POST', '/api/v0/device/code', { body: { hostname: hostname(), platform: `${platform()}-${arch()}` } });
28
+ }
29
+ catch (error) {
30
+ await abandon(describe(error));
31
+ return fail(ctx, error);
32
+ }
33
+ if (attempt === 1)
34
+ ctx.io.out(`Open ${started.verification_uri} and enter the code ${started.user_code}`);
35
+ else
36
+ ctx.io.out(`The code expired before anyone approved it. New code (${attempt} of ${MAX_CODES}): ${started.user_code}`);
37
+ ctx.io.out(`Or open ${started.verification_uri_complete}`);
38
+ const deadline = ctx.now().getTime() + started.expires_in * 1000;
39
+ ctx.io.out(`Code expires at ${expiryTime(new Date(deadline))}.`);
40
+ if (attempt === 1)
41
+ ctx.io.out('Waiting for approval. Approve only if you started this sign-in.');
42
+ const outcome = await poll(ctx, started, deadline, signal);
43
+ if (outcome === 'expired')
44
+ continue;
45
+ if ('access_token' in outcome) {
46
+ await ctx.store.applyAndRun('LOGIN_APPROVED', { lastError: keepError });
47
+ ctx.io.out(`Signed in as ${outcome.user.email}.`);
48
+ return 0;
49
+ }
50
+ await abandon(outcome.reason);
51
+ return outcome.exit;
52
+ }
53
+ await abandon('The code expired.');
54
+ ctx.io.err(`No code was approved after ${MAX_CODES} codes. Run \`hive login\` again.`);
55
+ return 1;
56
+ }
57
+ const MAX_CODES = 5;
58
+ export function expiryTime(at) {
59
+ return at.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
60
+ }
61
+ async function poll(ctx, started, deadline, signal) {
62
+ let interval = started.interval;
63
+ while (ctx.now().getTime() < deadline) {
64
+ await ctx.sleep(interval * 1000, signal);
65
+ if (signal?.aborted)
66
+ return { reason: 'The sign-in was interrupted.', exit: 130 };
67
+ try {
68
+ const granted = await ctx.api.json('POST', '/api/v0/device/token', { body: { device_code: started.device_code }, ...(signal ? { signal } : {}) });
69
+ await ctx.store.write('user.json', { url: ctx.url, token: granted.access_token, expires_at: granted.expires_at, user: granted.user });
70
+ return granted;
71
+ }
72
+ catch (error) {
73
+ if (error instanceof ApiError) {
74
+ if (error.code === 'authorization_pending')
75
+ continue;
76
+ if (error.code === 'slow_down') {
77
+ interval = typeof error.body.interval === 'number' ? error.body.interval : interval + 5;
78
+ continue;
79
+ }
80
+ if (error.status === 429) {
81
+ interval = Math.min(interval + 5, 60);
82
+ continue;
83
+ }
84
+ if (error.code === 'expired_token')
85
+ return 'expired';
86
+ if (error.code === 'access_denied') {
87
+ ctx.io.err('The sign-in was denied.');
88
+ return { reason: 'The sign-in was denied.', exit: 1 };
89
+ }
90
+ if (error.code === 'invalid_grant') {
91
+ ctx.io.err('This sign-in code was already used. Run `hive login` again.');
92
+ return { reason: 'The code was already used.', exit: 1 };
93
+ }
94
+ return { reason: describe(error), exit: fail(ctx, error) };
95
+ }
96
+ if (error instanceof NetworkError) {
97
+ ctx.io.err(`Network problem, retrying: ${error.message}`);
98
+ continue;
99
+ }
100
+ throw error;
101
+ }
102
+ }
103
+ return 'expired';
104
+ }
105
+ const describe = (error) => (error instanceof Error ? error.message : String(error));
106
+ async function signInExpired(ctx, user) {
107
+ try {
108
+ await ctx.api.json('GET', '/api/v0/nodes', { token: user.token });
109
+ return false;
110
+ }
111
+ catch (error) {
112
+ return error instanceof ApiError && classifyFailure(error.status, error.code) === 'HTTP_401';
113
+ }
114
+ }
115
+ function fail(ctx, error) {
116
+ ctx.io.err(error instanceof ApiError || error instanceof NetworkError ? error.message : String(error));
117
+ return 1;
118
+ }
@@ -0,0 +1,2 @@
1
+ import type { Context } from '../context.ts';
2
+ export declare function logout(ctx: Context): Promise<number>;
@@ -0,0 +1,37 @@
1
+ import { ApiError, NetworkError } from "../api.js";
2
+ import { sameServer } from "../binding.js";
3
+ import { allows } from "../machine.js";
4
+ export async function logout(ctx) {
5
+ const current = (await ctx.store.state()).state;
6
+ const saved = await ctx.store.read('user.json');
7
+ const user = saved !== null && sameServer(saved.url, ctx.url) ? saved : null;
8
+ if (!saved && current !== 'revoked' && current !== 'logged_in' && current !== 'authorizing') {
9
+ if (current === 'unconfigured')
10
+ await ctx.store.applyAndRun('LOGOUT');
11
+ ctx.io.out('Not signed in.');
12
+ return 0;
13
+ }
14
+ if (saved) {
15
+ const owner = user ? ctx.api : ctx.apiFor(saved.url);
16
+ try {
17
+ await owner.json('DELETE', '/api/v0/user-token', { token: saved.token });
18
+ }
19
+ catch (error) {
20
+ if (!(error instanceof ApiError) && !(error instanceof NetworkError))
21
+ throw error;
22
+ if (!user && error instanceof NetworkError) {
23
+ ctx.io.err(`Could not reach ${saved.url} to revoke the token (${error.message}). The sign-in stays on this machine. Run \`hive logout\` again when that server is reachable.`);
24
+ return 1;
25
+ }
26
+ ctx.io.err(`Could not revoke the token on ${saved.url} (${error.message}). It is removed from this machine.`);
27
+ }
28
+ }
29
+ await ctx.store.remove('user.json');
30
+ if (allows(current, 'LOGOUT'))
31
+ await ctx.store.applyAndRun('LOGOUT');
32
+ if (current === 'revoked')
33
+ ctx.io.out('Signed out. This machine forgot its revoked node, so `hive login` then `hive connect` registers it as a new node.');
34
+ else
35
+ ctx.io.out('Signed out. This machine keeps its node identity, so `hive login` then `hive connect` reuses its slot.');
36
+ return 0;
37
+ }
@@ -0,0 +1,7 @@
1
+ import type { Context } from '../context.ts';
2
+ export type NodeAddOptions = {
3
+ name: string;
4
+ team: string;
5
+ tokenFile: string;
6
+ };
7
+ export declare function nodeAdd(ctx: Context, options: NodeAddOptions): Promise<number>;
@@ -0,0 +1,56 @@
1
+ import { open, rm } from 'node:fs/promises';
2
+ import { ApiError, NetworkError } from "../api.js";
3
+ import { boundToServer } from "../binding.js";
4
+ export async function nodeAdd(ctx, options) {
5
+ const saved = await ctx.store.read('user.json');
6
+ const user = boundToServer(ctx, saved, 'sign-in');
7
+ if (!user) {
8
+ if (!saved)
9
+ ctx.io.err('Not signed in. Run `hive login` first.');
10
+ return 1;
11
+ }
12
+ let file;
13
+ try {
14
+ file = await open(options.tokenFile, 'wx', 0o600);
15
+ }
16
+ catch (error) {
17
+ const code = error.code;
18
+ ctx.io.err(code === 'EEXIST' ? `${options.tokenFile} already exists. Pick a new path; it is never overwritten.` : `Cannot create ${options.tokenFile}: ${code ?? String(error)}`);
19
+ return 1;
20
+ }
21
+ let written = false;
22
+ let sent = false;
23
+ try {
24
+ await file.chmod(0o600);
25
+ sent = true;
26
+ const minted = await ctx.api.json('POST', '/api/v0/registration-tokens', { token: user.token, body: { team: options.team, name: options.name } });
27
+ if (typeof minted.registration_token !== 'string' || !minted.registration_token.startsWith('hvr_'))
28
+ throw new Error('The server did not return a registration token.');
29
+ await file.writeFile(`${minted.registration_token}\n`, 'utf8');
30
+ await file.sync();
31
+ written = true;
32
+ ctx.io.out(`Added node ${minted.node.name} (id ${minted.node.id}) to ${options.team}.`);
33
+ ctx.io.out(`Its registration token is in ${options.tokenFile} and works once until ${minted.expires_at}.`);
34
+ ctx.io.out(`On the box: hive connect --token-file ${options.tokenFile}`);
35
+ return 0;
36
+ }
37
+ catch (error) {
38
+ if (error instanceof ApiError && error.status === 401)
39
+ ctx.io.err(`${error.message} Run \`hive login\` again.`);
40
+ else
41
+ ctx.io.err(error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof NetworkError ? error.message : error instanceof Error ? error.message : String(error));
42
+ const unknown = sent && !(error instanceof ApiError);
43
+ if (unknown || (error instanceof ApiError && error.code === 'node_exists'))
44
+ ctx.io.err(stuckHint(options, unknown));
45
+ return 1;
46
+ }
47
+ finally {
48
+ await file.close();
49
+ if (!written)
50
+ await rm(options.tokenFile, { force: true });
51
+ }
52
+ }
53
+ function stuckHint(options, unknown) {
54
+ const lead = unknown ? `Hive may have added ${options.name} before the reply was lost, and its token cannot be shown again.` : `If an earlier \`hive node add ${options.name}\` lost its reply, the node is waiting with a token nobody has.`;
55
+ return `${lead} Remove ${options.name} in the app under team settings, then run \`hive node add\` again.`;
56
+ }
@@ -0,0 +1,19 @@
1
+ import type { Context, Io } from '../context.ts';
2
+ import type { Role, SetupDeps } from '../bootstrap/types.ts';
3
+ import type { Fetch } from '../api.ts';
4
+ export type NodeBootstrapOptions = {
5
+ role: Role;
6
+ token?: string;
7
+ tokenFromImds: boolean;
8
+ nodeId?: string;
9
+ slots?: number;
10
+ toolchain?: string;
11
+ kitRelease?: string;
12
+ name?: string;
13
+ team?: string;
14
+ saveApiUrl: boolean;
15
+ dryRun: boolean;
16
+ json: boolean;
17
+ installProxy: boolean;
18
+ };
19
+ export declare function nodeBootstrap(ctx: Context, opts: NodeBootstrapOptions, signal: AbortSignal, io: Io, overrides?: Partial<SetupDeps>, imdsFetch?: Fetch): Promise<number>;
@@ -0,0 +1,43 @@
1
+ import { exchangeIdentityForToken, readInstanceIdentity } from "../bootstrap/identity.js";
2
+ import { bootstrapNode, failedReport, renderReport } from "../bootstrap/index.js";
3
+ import { makeSetupDeps } from "../bootstrap/deps.js";
4
+ import { ENROLLED } from "../bootstrap/steps/auth.js";
5
+ import { SetupError } from "../bootstrap/types.js";
6
+ export async function nodeBootstrap(ctx, opts, signal, io, overrides = {}, imdsFetch = fetch) {
7
+ const deps = await makeSetupDeps(ctx, false, overrides);
8
+ let token = opts.token;
9
+ const enrolled = (await ctx.store.read('node.json')) !== null && ENROLLED.includes((await ctx.store.state()).state);
10
+ if (token === undefined && opts.tokenFromImds && !enrolled && !opts.dryRun) {
11
+ try {
12
+ token = await exchangeIdentityForToken(ctx.api, opts.nodeId ?? '', await readInstanceIdentity(imdsFetch, signal), signal, ctx.sleep);
13
+ }
14
+ catch (error) {
15
+ if (!(error instanceof SetupError))
16
+ throw error;
17
+ if (opts.json)
18
+ io.out(JSON.stringify(failedReport({ role: opts.role, toolchain: opts.toolchain ?? null, dryRun: opts.dryRun }, ctx.url, 'enroll', error.message)));
19
+ else
20
+ io.err(error.message);
21
+ return 1;
22
+ }
23
+ }
24
+ const report = await bootstrapNode({
25
+ apiUrl: ctx.url,
26
+ role: opts.role,
27
+ hiveProxy: opts.installProxy ? 'install' : 'skip',
28
+ dryRun: opts.dryRun,
29
+ saveApiUrl: opts.saveApiUrl,
30
+ ...(opts.slots !== undefined ? { slots: opts.slots } : {}),
31
+ ...(opts.toolchain ? { toolchain: opts.toolchain } : {}),
32
+ ...(opts.kitRelease ? { kitRelease: opts.kitRelease } : {}),
33
+ ...(opts.name ? { name: opts.name } : {}),
34
+ ...(opts.team ? { team: opts.team } : {}),
35
+ ...(token ? { registrationToken: token } : {}),
36
+ }, { ...deps, ctx, signal });
37
+ if (opts.json)
38
+ io.out(JSON.stringify(report));
39
+ else
40
+ for (const line of renderReport(report, ctx.url))
41
+ (line.startsWith('failed:') ? io.err : io.out)(line);
42
+ return report.ok ? 0 : 1;
43
+ }
@@ -0,0 +1,7 @@
1
+ import type { Context } from '../context.ts';
2
+ import { type Transport } from '../prEvents.ts';
3
+ export declare function prEvents(ctx: Context, options: {
4
+ once: boolean;
5
+ dryRun: boolean;
6
+ transport?: Transport;
7
+ }, signal: AbortSignal): Promise<number>;
@@ -0,0 +1,32 @@
1
+ import { prEventsEnabled, pullPrEvents } from "../prEvents.js";
2
+ import { relayFailure } from "./threads.js";
3
+ export async function prEvents(ctx, options, signal) {
4
+ if (!options.once && !options.dryRun) {
5
+ ctx.io.err('Use `hive pr-events --once` to deliver one time, or `hive pr-events --dry-run` to print what would be sent. With HIVE_PR_EVENTS=on, `hive connect` delivers every minute beside its status posts.');
6
+ return 1;
7
+ }
8
+ if (!options.dryRun && !prEventsEnabled(ctx.env)) {
9
+ ctx.io.err('PR event delivery is off. Set HIVE_PR_EVENTS=on to turn it on.');
10
+ return 1;
11
+ }
12
+ const node = await ctx.store.read('node.json');
13
+ const key = await ctx.store.read('key.json');
14
+ if (node === null || key === null) {
15
+ ctx.io.err('This machine is not connected. Run `hive connect` first.');
16
+ return 1;
17
+ }
18
+ try {
19
+ const result = await pullPrEvents({ ...ctx, ...(options.transport ? { transport: options.transport } : {}) }, node, key, { dryRun: options.dryRun, signal });
20
+ if (result.skipped)
21
+ return 0;
22
+ if (options.dryRun)
23
+ ctx.io.out(`Dry run: ${result.events} PR events after ${result.cursor}. Nothing was sent.`);
24
+ else
25
+ ctx.io.out(`Delivered ${result.sent} PR event messages, ${result.failed} failed, ${result.retries} waiting to retry. Cursor ${result.cursor}.`);
26
+ return result.failed > 0 ? 1 : 0;
27
+ }
28
+ catch (error) {
29
+ ctx.io.err(`PR events failed: ${relayFailure(error)}`);
30
+ return 1;
31
+ }
32
+ }