@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
package/dist/run.js ADDED
@@ -0,0 +1,487 @@
1
+ import { connect } from "./commands/connect.js";
2
+ import { login } from "./commands/login.js";
3
+ import { logout } from "./commands/logout.js";
4
+ import { failedReport } from "./bootstrap/index.js";
5
+ import { nodeBootstrap } from "./commands/node.js";
6
+ import { nodeAdd } from "./commands/node-add.js";
7
+ import { doctor } from "./commands/doctor.js";
8
+ import { nodeMode } from "./node/layout.js";
9
+ import { renderNodeReport, repairNow } from "./node/repair.js";
10
+ import { leaveHive } from "./node/leave.js";
11
+ import { runSupervisor } from "./node/supervisor.js";
12
+ import { setup } from "./commands/setup.js";
13
+ import { configDir, serverUrl, Store, UnreadableFileError } from "./config.js";
14
+ import { ENROLLED } from "./bootstrap/steps/auth.js";
15
+ import { normalizeRole } from "./bootstrap/types.js";
16
+ import { status } from "./commands/status.js";
17
+ import { threads } from "./commands/threads.js";
18
+ import { prEvents } from "./commands/prEvents.js";
19
+ import { makeContext } from "./context.js";
20
+ import { readFile } from 'node:fs/promises';
21
+ import { VERSION } from "./version.js";
22
+ import { PACKAGE_NAME } from "./package.js";
23
+ export { VERSION };
24
+ const HELP = `hive ${VERSION} (${PACKAGE_NAME})
25
+
26
+ Usage:
27
+ hive [setup] [options] Sign in, enroll this machine and install proxy, lanes, env, cron and drift-check
28
+ hive doctor [--json] Check every setup step and print one row each: status, detail and fix.
29
+ Read-only. Exits 0 only when every step is ok or skipped
30
+ hive login Sign in with a code you approve in the browser
31
+ hive node run Supervise this node: heartbeat, apply Hive's desired state, repair and report
32
+ every 60 seconds. One per node. Exit 75 asks the keeper for a restart, 77 means
33
+ Hive revoked the node
34
+ hive node leave Tell Hive this node is leaving, signed with the node key. Hive removes it and
35
+ revokes its token and key. install.sh --uninstall runs it
36
+ hive doctor --repair [--json] Ask the supervisor for a repair pass and print the report it wrote. With no
37
+ supervisor running it takes the lock and runs one pass itself
38
+ hive connect [options] Deprecated, use \`hive node run\`. Registers this machine and reports its status
39
+ hive status Show your team, plan usage and nodes
40
+ hive threads --once Relay this machine's T3 Code threads to Hive one time
41
+ hive threads --dry-run Print the thread batch without sending it
42
+ hive pr-events --once Deliver new PR events from Hive to this machine's T3 Code threads one time
43
+ hive pr-events --dry-run Print the PR event messages without sending them
44
+ hive logout Revoke this machine's sign-in
45
+ hive node bootstrap [options] Set up a node with no prompts, for cloud-init and EC2 user data
46
+ hive node add <name> --team <slug> --token-file <path>
47
+ Add a bring your own node with your sign-in (owner or admin) and write
48
+ its one-time registration token to a new 0600 file, never to the screen
49
+
50
+ setup options:
51
+ --role <role> primary, worker, lite or proxy-only
52
+ --yes Never prompt; use flags, saved answers and defaults
53
+ --install-proxy Also run hive-proxy install here, to host your own proxy (Overcy hosts none)
54
+ --server <url> Hive server (default https://hive.overcy.ai)
55
+ --token <token> Enroll with a registration token and skip the sign-in
56
+ --dry-run Print the plan and change nothing
57
+ --json Print one machine-readable result on stdout
58
+
59
+ node bootstrap options:
60
+ --role <role> primary, worker, lite or proxy-only (required)
61
+ --token <token> Registration token. HIVE_REGISTRATION_TOKEN works too and keeps it out of the process list
62
+ --token-from-imds On EC2, exchange the signed instance identity for a one-time token (no secret in user data)
63
+ --node-id <id> The node Hive launched this instance for. Required with --token-from-imds, not a secret
64
+ --toolchain <name> Toolchain profile, written to hive.env as HIVE_TOOLCHAIN and shown in the report
65
+ --slots <n> Lane slots to install
66
+ --kit-release <v> overcy-hive release whose manifest to install (default: the pinned release)
67
+ --api-url <url> Hive server (default https://hive.overcy.ai)
68
+ --install-proxy Also run hive-proxy install here
69
+ --dry-run Print the plan and change nothing
70
+ --json Print one machine-readable report on stdout
71
+ It never prompts and exits non-zero when a step fails.
72
+
73
+ connect options:
74
+ --once Report one time and exit
75
+ --name <name> Node name (default: the hostname)
76
+ --team <slug> Team to add the node to (default: your current team)
77
+ --rebind Not built yet
78
+ --reconnect <code> Not built yet
79
+ --rotate Not built yet
80
+ --token <token> Register with a registration token from the app, with no sign-in
81
+ (a bare token also works: hive connect hvr_...)
82
+ --token-file <path> Read the registration token from a file, and delete the file once it is exchanged
83
+
84
+ Environment:
85
+ HIVE_URL Server (default https://hive.overcy.ai)
86
+ HIVE_CONFIG_DIR Config directory (default ~/.config/hive, or <HIVE_STATE_DIR>/node on a node)
87
+ HIVE_STATE_DIR A node's state root (default /var/lib/hive). Setting it puts this machine in node mode
88
+ HIVE_LANES_DIR Directory whose subdirectories are lanes to report
89
+ HIVE_REGISTRATION_TOKEN Registration token, for machines set up by a script
90
+ HIVE_T3_HOME T3 Code home whose threads connect relays (default ~/.t3, used only if it holds userdata/statev2.sqlite)
91
+ HIVE_THREADS Set to off to stop relaying threads
92
+ HIVE_PR_EVENTS Set to on to deliver PR events to T3 Code threads (default off)
93
+ HIVE_T3_BIN The t3 command that delivers them (default t3 on PATH)
94
+ HIVE_LIB_DIR Where install.sh put servicectl, on a node (default /usr/local/lib/hive)
95
+ HIVE_ENGINE_PORT The engine's loopback port, on a node (default 3773)
96
+ `;
97
+ export function parseFlags(args) {
98
+ const flags = new Map();
99
+ const positional = [];
100
+ for (let i = 0; i < args.length; i++) {
101
+ const arg = args[i];
102
+ if (!arg.startsWith('--')) {
103
+ positional.push(arg);
104
+ continue;
105
+ }
106
+ const [name = '', inline] = arg.slice(2).split(/=(.*)/s, 2);
107
+ if (inline !== undefined)
108
+ flags.set(name, inline);
109
+ else if (['name', 'team', 'reconnect', 'token', 'token-file', 'interval'].includes(name))
110
+ flags.set(name, args[++i] ?? '');
111
+ else
112
+ flags.set(name, true);
113
+ }
114
+ return { flags, positional };
115
+ }
116
+ const INVALID_TOKEN_MESSAGE = 'Give `--token` a registration token that starts with hvr_. Create one in the app under team settings, Connect a node.';
117
+ function registrationTokenFrom(flag, positional, fromEnv) {
118
+ if (flag !== undefined)
119
+ return typeof flag === 'string' && flag.startsWith('hvr_') ? flag : 'invalid';
120
+ const bare = positional[0];
121
+ if (bare !== undefined)
122
+ return bare.startsWith('hvr_') ? bare : 'invalid';
123
+ if (fromEnv === undefined || fromEnv === '')
124
+ return undefined;
125
+ return fromEnv.startsWith('hvr_') ? fromEnv : 'invalid';
126
+ }
127
+ async function readTokenFile(path, enrolled) {
128
+ let text;
129
+ try {
130
+ text = await readFile(path, 'utf8');
131
+ }
132
+ catch (error) {
133
+ if (enrolled && error.code === 'ENOENT')
134
+ return null;
135
+ return { error: `Cannot read ${path}: ${error.code ?? String(error)}` };
136
+ }
137
+ const token = text.trim();
138
+ return token.startsWith('hvr_') && !/\s/.test(token) ? { token } : { error: `${path} does not hold a registration token that starts with hvr_.` };
139
+ }
140
+ export async function run(argv, env, io, signal, overrides = {}) {
141
+ const [command, ...rest] = argv;
142
+ if (command === 'node')
143
+ return runNodeCommand(rest, env, io, signal, overrides);
144
+ if (command === 'doctor')
145
+ return runDoctorCommand(rest, env, io, signal, overrides);
146
+ const isSetup = command === undefined || command === 'setup' || (command.startsWith('--') && !['--version', '--help'].includes(command));
147
+ if (isSetup)
148
+ return runSetupCommand(command === 'setup' ? rest : argv, env, io, signal, overrides);
149
+ const { flags, positional } = parseFlags(rest);
150
+ const ctx = makeContext(env, io, overrides);
151
+ switch (command) {
152
+ case 'login':
153
+ return login(ctx, signal);
154
+ case 'connect': {
155
+ const name = flags.get('name');
156
+ const team = flags.get('team');
157
+ const reconnect = flags.get('reconnect');
158
+ const interval = flags.get('interval');
159
+ const hasIdentity = (await ctx.store.read('node.json')) !== null || (await ctx.store.read('user.json')) !== null;
160
+ const tokenFile = flags.get('token-file');
161
+ if (tokenFile !== undefined && (flags.has('token') || positional.length > 0)) {
162
+ io.err('Pass either --token or --token-file, not both.');
163
+ return 1;
164
+ }
165
+ if (tokenFile === true || tokenFile === '') {
166
+ io.err('--token-file needs a path.');
167
+ return 1;
168
+ }
169
+ const fromFile = typeof tokenFile === 'string' ? await readTokenFile(tokenFile, (await ctx.store.read('node.json')) !== null) : undefined;
170
+ if (fromFile && 'error' in fromFile) {
171
+ io.err(fromFile.error);
172
+ return 1;
173
+ }
174
+ const token = fromFile?.token ?? registrationTokenFrom(flags.get('token'), positional, hasIdentity ? undefined : env.HIVE_REGISTRATION_TOKEN);
175
+ if (token === 'invalid') {
176
+ io.err(INVALID_TOKEN_MESSAGE);
177
+ return 1;
178
+ }
179
+ return connect(ctx, {
180
+ once: flags.get('once') === true,
181
+ rebind: flags.get('rebind') === true,
182
+ rotate: flags.get('rotate') === true,
183
+ ...(typeof name === 'string' ? { name } : {}),
184
+ ...(typeof team === 'string' ? { team } : {}),
185
+ ...(typeof reconnect === 'string' ? { reconnect } : {}),
186
+ ...(token !== undefined ? { token } : {}),
187
+ ...(typeof tokenFile === 'string' ? { tokenFile } : {}),
188
+ ...(typeof interval === 'string' ? { intervalSeconds: Number(interval) } : {}),
189
+ }, signal);
190
+ }
191
+ case 'status': {
192
+ const team = flags.get('team');
193
+ return status(ctx, typeof team === 'string' ? team : undefined);
194
+ }
195
+ case 'threads':
196
+ return threads(ctx, { once: flags.get('once') === true, dryRun: flags.get('dry-run') === true }, signal);
197
+ case 'pr-events':
198
+ return prEvents(ctx, { once: flags.get('once') === true, dryRun: flags.get('dry-run') === true }, signal);
199
+ case 'logout':
200
+ return logout(ctx);
201
+ case '--version':
202
+ case '-v':
203
+ case 'version':
204
+ io.out(VERSION);
205
+ return 0;
206
+ case 'help':
207
+ case '--help':
208
+ case '-h':
209
+ io.out(HELP.trimEnd());
210
+ return 0;
211
+ default:
212
+ io.err(`Unknown command: ${command}\n\n${HELP.trimEnd()}`);
213
+ return 1;
214
+ }
215
+ }
216
+ async function runDoctorCommand(args, env, io, signal, overrides) {
217
+ const parsed = parseFlagList(args, ['json', 'repair'], []);
218
+ if ('help' in parsed) {
219
+ io.out(HELP.trimEnd());
220
+ return 0;
221
+ }
222
+ if ('error' in parsed) {
223
+ io.err(`${parsed.error}\n\n${HELP.trimEnd()}`);
224
+ return 1;
225
+ }
226
+ const json = parsed.flags.get('json') === true;
227
+ const quiet = json ? { out: io.err, err: io.err } : io;
228
+ if (parsed.flags.get('repair') === true) {
229
+ if (!nodeMode(env)) {
230
+ io.err('`hive doctor --repair` repairs a node. This machine has no node state: set HIVE_STATE_DIR, or install the node first.');
231
+ return 1;
232
+ }
233
+ const outcome = await repairNow(makeContext(env, quiet, overrides), 'doctor', signal);
234
+ if (!outcome.ok) {
235
+ io.err(outcome.error);
236
+ return outcome.code;
237
+ }
238
+ if (json)
239
+ io.out(JSON.stringify(outcome.report));
240
+ else
241
+ for (const line of renderNodeReport(outcome.report))
242
+ io.out(line);
243
+ return outcome.report.steps.every((step) => step.status === 'ok' || step.status === 'repaired') ? 0 : 1;
244
+ }
245
+ return doctor(makeContext(env, quiet, overrides), { json }, signal, io, overrides.setup);
246
+ }
247
+ const SETUP_BOOLEAN_FLAGS = ['yes', 'install-proxy', 'configure-agents', 'dry-run', 'json'];
248
+ const SETUP_VALUE_FLAGS = ['role', 'server', 'name', 'team', 'token'];
249
+ function parseSetupArgs(args) {
250
+ const flags = new Map();
251
+ for (let i = 0; i < args.length; i++) {
252
+ const arg = args[i];
253
+ if (arg === '--help' || arg === '-h')
254
+ return { help: true };
255
+ if (!arg.startsWith('--'))
256
+ return { error: `Unexpected argument: ${arg}` };
257
+ const [name = '', inline] = arg.slice(2).split(/=(.*)/s, 2);
258
+ if (SETUP_BOOLEAN_FLAGS.includes(name) && inline === undefined)
259
+ flags.set(name, true);
260
+ else if (SETUP_VALUE_FLAGS.includes(name)) {
261
+ const value = inline ?? args[++i];
262
+ if (value === undefined || value === '' || value.startsWith('--'))
263
+ return { error: `--${name} needs a value` };
264
+ flags.set(name, value);
265
+ }
266
+ else
267
+ return { error: `Unknown option: ${arg}` };
268
+ }
269
+ return { flags };
270
+ }
271
+ async function runSetupCommand(args, env, io, signal, overrides) {
272
+ const parsed = parseSetupArgs(args);
273
+ if ('help' in parsed) {
274
+ io.out(HELP.trimEnd());
275
+ return 0;
276
+ }
277
+ if ('error' in parsed) {
278
+ io.err(`${parsed.error}\n\n${HELP.trimEnd()}`);
279
+ return 1;
280
+ }
281
+ const { flags } = parsed;
282
+ const text = (name) => (typeof flags.get(name) === 'string' ? flags.get(name) : undefined);
283
+ const rawRole = text('role');
284
+ const role = rawRole === undefined ? undefined : normalizeRole(rawRole);
285
+ if (rawRole !== undefined && role === null) {
286
+ io.err(`--role must be primary, worker, lite or proxy-only, not ${rawRole}.`);
287
+ return 1;
288
+ }
289
+ const flagServer = text('server')?.replace(/\/+$/, '');
290
+ const resolved = await resolveServer(env, flagServer);
291
+ if ('error' in resolved) {
292
+ io.err(resolved.error);
293
+ return 1;
294
+ }
295
+ const json = flags.get('json') === true;
296
+ const quiet = json ? { out: io.err, err: io.err } : io;
297
+ const ctx = makeContext({ ...env, HIVE_URL: resolved.server }, quiet, overrides);
298
+ const name = text('name');
299
+ const team = text('team');
300
+ const store = new Store(configDir(env));
301
+ const hasIdentity = (await store.read('node.json')) !== null || (await store.read('user.json')) !== null;
302
+ const token = registrationTokenFrom(text('token'), [], hasIdentity ? undefined : env.HIVE_REGISTRATION_TOKEN);
303
+ if (token === 'invalid') {
304
+ io.err(INVALID_TOKEN_MESSAGE);
305
+ return 1;
306
+ }
307
+ return setup(ctx, {
308
+ yes: flags.get('yes') === true,
309
+ installProxy: flags.get('install-proxy') === true,
310
+ configureAgents: flags.get('configure-agents') === true,
311
+ dryRun: flags.get('dry-run') === true,
312
+ json,
313
+ ...(role ? { role } : {}),
314
+ ...(flagServer ? { server: flagServer } : {}),
315
+ ...(name ? { name } : {}),
316
+ ...(team ? { team } : {}),
317
+ ...(token !== undefined ? { token } : {}),
318
+ }, signal, io, overrides.setup);
319
+ }
320
+ async function resolveServer(env, flag) {
321
+ const store = new Store(configDir(env));
322
+ const node = await store.read('node.json');
323
+ if (flag && node && node.url !== flag)
324
+ return { error: `This machine is enrolled at ${node.url}, not ${flag}. Run hive logout and delete ${store.dir} to move it.` };
325
+ return { server: flag ?? serverUrl(env) };
326
+ }
327
+ const NODE_BOOLEAN_FLAGS = ['token-from-imds', 'install-proxy', 'dry-run', 'json'];
328
+ const NODE_VALUE_FLAGS = ['role', 'token', 'toolchain', 'slots', 'kit-release', 'node-id', 'api-url', 'name', 'team'];
329
+ const PROFILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
330
+ function parseFlagList(args, booleans, values) {
331
+ const flags = new Map();
332
+ for (let i = 0; i < args.length; i++) {
333
+ const arg = args[i];
334
+ if (arg === '--help' || arg === '-h')
335
+ return { help: true };
336
+ if (!arg.startsWith('--'))
337
+ return { error: `Unexpected argument: ${arg}` };
338
+ const [name = '', inline] = arg.slice(2).split(/=(.*)/s, 2);
339
+ if (booleans.includes(name) && inline === undefined)
340
+ flags.set(name, true);
341
+ else if (values.includes(name)) {
342
+ const value = inline ?? args[++i];
343
+ if (value === undefined || value === '' || value.startsWith('--'))
344
+ return { error: `--${name} needs a value` };
345
+ flags.set(name, value);
346
+ }
347
+ else
348
+ return { error: `Unknown option: ${arg}` };
349
+ }
350
+ return { flags };
351
+ }
352
+ async function runNodeCommand(args, env, io, signal, overrides) {
353
+ const [sub, ...rest] = args;
354
+ if (sub === 'add')
355
+ return runNodeAddCommand(rest, env, io, overrides);
356
+ if (sub === 'run') {
357
+ if (rest.length > 0) {
358
+ io.err(rest[0] === '--help' || rest[0] === '-h' ? HELP.trimEnd() : `\`hive node run\` takes no options. Got ${rest[0]}.`);
359
+ return rest[0] === '--help' || rest[0] === '-h' ? 0 : 1;
360
+ }
361
+ return runSupervisor(makeContext(env, io, overrides), signal);
362
+ }
363
+ if (sub === 'leave') {
364
+ if (rest.length > 0) {
365
+ io.err(rest[0] === '--help' || rest[0] === '-h' ? HELP.trimEnd() : `\`hive node leave\` takes no options. Got ${rest[0]}.`);
366
+ return rest[0] === '--help' || rest[0] === '-h' ? 0 : 1;
367
+ }
368
+ return leaveHive(makeContext(env, io, overrides), signal);
369
+ }
370
+ if (sub !== 'bootstrap') {
371
+ io.err(`Use \`hive node run\`, \`hive node leave\`, \`hive node bootstrap\` or \`hive node add\`.\n\n${HELP.trimEnd()}`);
372
+ return 1;
373
+ }
374
+ const parsed = parseFlagList(rest, NODE_BOOLEAN_FLAGS, NODE_VALUE_FLAGS);
375
+ if ('help' in parsed) {
376
+ io.out(HELP.trimEnd());
377
+ return 0;
378
+ }
379
+ if ('error' in parsed) {
380
+ io.err(`${parsed.error}\n\n${HELP.trimEnd()}`);
381
+ return 1;
382
+ }
383
+ const { flags } = parsed;
384
+ const json = flags.get('json') === true;
385
+ const refuse = (message, server = '') => {
386
+ if (json)
387
+ io.out(JSON.stringify(failedReport({ role: null, dryRun: flags.get('dry-run') === true }, server, 'preflight', message)));
388
+ else
389
+ io.err(message);
390
+ return 1;
391
+ };
392
+ const text = (name) => (typeof flags.get(name) === 'string' ? flags.get(name) : undefined);
393
+ const role = normalizeRole(text('role') ?? '');
394
+ if (role === null) {
395
+ return refuse('--role is required and must be primary, worker, lite or proxy-only.');
396
+ }
397
+ const rawSlots = text('slots');
398
+ if (rawSlots !== undefined && !/^\d{1,4}$/.test(rawSlots)) {
399
+ return refuse('--slots must be a whole number.');
400
+ }
401
+ const toolchain = text('toolchain');
402
+ if (toolchain !== undefined && !PROFILE.test(toolchain)) {
403
+ return refuse('--toolchain must be a profile name of letters, digits, dots, dashes and underscores.');
404
+ }
405
+ const kitRelease = text('kit-release');
406
+ if (kitRelease !== undefined && !PROFILE.test(kitRelease)) {
407
+ return refuse('--kit-release must be a release tag of letters, digits, dots, dashes and underscores.');
408
+ }
409
+ const flagServer = text('api-url')?.replace(/\/+$/, '');
410
+ let resolved;
411
+ let enrolled;
412
+ try {
413
+ resolved = await resolveServer(env, flagServer);
414
+ const store = new Store(configDir(env));
415
+ enrolled = (await store.read('node.json')) !== null && ENROLLED.includes((await store.state()).state);
416
+ }
417
+ catch (error) {
418
+ if (error instanceof UnreadableFileError)
419
+ return refuse(error.message, flagServer ?? '');
420
+ throw error;
421
+ }
422
+ if ('error' in resolved) {
423
+ return refuse(resolved.error, flagServer ?? '');
424
+ }
425
+ const tokenFromImds = flags.get('token-from-imds') === true;
426
+ const token = registrationTokenFrom(text('token'), [], enrolled ? undefined : env.HIVE_REGISTRATION_TOKEN);
427
+ if (token === 'invalid') {
428
+ return refuse(INVALID_TOKEN_MESSAGE);
429
+ }
430
+ const nodeId = text('node-id');
431
+ if (tokenFromImds && (nodeId === undefined || !PROFILE.test(nodeId))) {
432
+ return refuse('--token-from-imds needs --node-id <id>, the node Hive launched this instance for.');
433
+ }
434
+ if (token !== undefined && tokenFromImds) {
435
+ return refuse('Pass either --token or --token-from-imds, not both.');
436
+ }
437
+ if (token === undefined && !tokenFromImds && !enrolled && flags.get('dry-run') !== true) {
438
+ return refuse('This machine is not enrolled. Pass --token <hvr_...> (or set HIVE_REGISTRATION_TOKEN), or --token-from-imds on EC2.');
439
+ }
440
+ const quiet = json ? { out: io.err, err: io.err } : io;
441
+ const ctx = makeContext({ ...env, HIVE_URL: resolved.server }, quiet, overrides);
442
+ const name = text('name');
443
+ const team = text('team');
444
+ return nodeBootstrap(ctx, {
445
+ role,
446
+ tokenFromImds,
447
+ ...(nodeId !== undefined ? { nodeId } : {}),
448
+ saveApiUrl: flagServer !== undefined,
449
+ dryRun: flags.get('dry-run') === true,
450
+ json,
451
+ installProxy: flags.get('install-proxy') === true,
452
+ ...(token !== undefined ? { token } : {}),
453
+ ...(rawSlots !== undefined ? { slots: Number(rawSlots) } : {}),
454
+ ...(toolchain ? { toolchain } : {}),
455
+ ...(kitRelease ? { kitRelease } : {}),
456
+ ...(name ? { name } : {}),
457
+ ...(team ? { team } : {}),
458
+ }, signal, io, overrides.setup, overrides.imdsFetch);
459
+ }
460
+ const NODE_NAME = /^[A-Za-z0-9._-]{1,128}$/;
461
+ async function runNodeAddCommand(args, env, io, overrides) {
462
+ const [name, ...rest] = args;
463
+ if (name === '--help' || name === '-h') {
464
+ io.out(HELP.trimEnd());
465
+ return 0;
466
+ }
467
+ if (name === undefined || !NODE_NAME.test(name)) {
468
+ io.err('Usage: hive node add <name> --team <slug> --token-file <path>. The name is letters, digits, dots, dashes and underscores.');
469
+ return 1;
470
+ }
471
+ const parsed = parseFlagList(rest, [], ['team', 'token-file']);
472
+ if ('help' in parsed) {
473
+ io.out(HELP.trimEnd());
474
+ return 0;
475
+ }
476
+ if ('error' in parsed) {
477
+ io.err(`${parsed.error}\n\n${HELP.trimEnd()}`);
478
+ return 1;
479
+ }
480
+ const team = parsed.flags.get('team');
481
+ const tokenFile = parsed.flags.get('token-file');
482
+ if (typeof team !== 'string' || typeof tokenFile !== 'string') {
483
+ io.err('hive node add needs --team <slug> and --token-file <path>. The token is only ever written to that file.');
484
+ return 1;
485
+ }
486
+ return nodeAdd(makeContext(env, io, overrides), { name, team, tokenFile });
487
+ }