@aibexhq/aibex-link 0.0.2 → 0.0.3

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 (2) hide show
  1. package/dist/index.js +922 -13
  2. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1,15 +1,686 @@
1
- import { readFileSync } from "node:fs";
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync } from "node:fs";
2
3
  import path from "node:path";
4
+ import { platform, arch, release } from "node:os";
3
5
  import { fileURLToPath } from "node:url";
4
6
  const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
5
- function aliveIntervalMs(env = process.env) {
7
+ const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
8
+ const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
9
+ function timing(key, fallback, env = process.env) {
6
10
  const raw = env.AIBEX_TIMINGS;
7
- if (!raw) return DEFAULT_ALIVE_INTERVAL_MS;
11
+ if (!raw) return fallback;
8
12
  try {
9
- const value = JSON.parse(raw).aliveIntervalMs;
10
- return typeof value === "number" && value > 0 ? value : DEFAULT_ALIVE_INTERVAL_MS;
13
+ const value = JSON.parse(raw)[key];
14
+ return typeof value === "number" && value > 0 ? value : fallback;
11
15
  } catch {
12
- return DEFAULT_ALIVE_INTERVAL_MS;
16
+ return fallback;
17
+ }
18
+ }
19
+ function aliveIntervalMs(env = process.env) {
20
+ return timing("aliveIntervalMs", DEFAULT_ALIVE_INTERVAL_MS, env);
21
+ }
22
+ const encoder = new TextEncoder();
23
+ function utf8(text) {
24
+ return new Uint8Array(encoder.encode(text));
25
+ }
26
+ function toBase64(bytes) {
27
+ let binary = "";
28
+ for (const byte of bytes) binary += String.fromCodePoint(byte);
29
+ return btoa(binary);
30
+ }
31
+ function fromBase64(text) {
32
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text)) {
33
+ throw new TypeError("not base64");
34
+ }
35
+ const binary = atob(text);
36
+ const bytes = new Uint8Array(binary.length);
37
+ for (let index = 0; index < binary.length; index++) {
38
+ bytes[index] = binary.codePointAt(index) ?? 0;
39
+ }
40
+ return bytes;
41
+ }
42
+ function toBase64Url(bytes) {
43
+ return toBase64(bytes).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
44
+ }
45
+ function fromBase64Url(text) {
46
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new TypeError("not base64url");
47
+ const padded = text.replaceAll("-", "+").replaceAll("_", "/");
48
+ return fromBase64(padded + "=".repeat((4 - padded.length % 4) % 4));
49
+ }
50
+ async function sha256(data) {
51
+ const bytes = typeof data === "string" ? utf8(data) : new Uint8Array(data);
52
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
53
+ }
54
+ function equalBytes(a, b) {
55
+ if (a.length !== b.length) return false;
56
+ let difference = 0;
57
+ for (const [index, element] of a.entries()) {
58
+ difference |= (element ?? 0) ^ (b[index] ?? 0);
59
+ }
60
+ return difference === 0;
61
+ }
62
+ class Parser {
63
+ constructor(input) {
64
+ this.input = input;
65
+ }
66
+ index = 0;
67
+ fail(why) {
68
+ throw new SyntaxError(`structured field: ${why} at ${this.index}`);
69
+ }
70
+ peek() {
71
+ return this.input.charAt(this.index);
72
+ }
73
+ done() {
74
+ return this.index >= this.input.length;
75
+ }
76
+ skip(characters) {
77
+ while (!this.done() && characters.includes(this.peek())) this.index++;
78
+ }
79
+ key() {
80
+ const match = /^[a-z*][a-z0-9_.*-]*/.exec(this.input.slice(this.index));
81
+ if (!match) this.fail("expected a key");
82
+ this.index += match[0].length;
83
+ return match[0];
84
+ }
85
+ parameters() {
86
+ const parameters = [];
87
+ while (this.peek() === ";") {
88
+ this.index++;
89
+ this.skip(" ");
90
+ const key = this.key();
91
+ let value = { kind: "boolean", value: true };
92
+ if (this.peek() === "=") {
93
+ this.index++;
94
+ value = this.bareItem();
95
+ }
96
+ const existing = parameters.findIndex(([name]) => name === key);
97
+ if (existing === -1) parameters.push([key, value]);
98
+ else parameters[existing] = [key, value];
99
+ }
100
+ return parameters;
101
+ }
102
+ bareItem() {
103
+ const rest = this.input.slice(this.index);
104
+ const first = this.peek();
105
+ if (first === "-" || /\d/.test(first)) {
106
+ const match = /^-?\d{1,15}/.exec(rest);
107
+ if (!match) this.fail("expected an integer");
108
+ this.index += match[0].length;
109
+ if (this.peek() === ".") this.fail("decimals are not supported");
110
+ return { kind: "integer", value: Number(match[0]) };
111
+ }
112
+ if (first === '"') {
113
+ this.index++;
114
+ let value = "";
115
+ for (; ; ) {
116
+ if (this.done()) this.fail("unterminated string");
117
+ const character = this.peek();
118
+ this.index++;
119
+ if (character === "\\") {
120
+ const escaped = this.peek();
121
+ if (escaped !== '"' && escaped !== "\\") this.fail("bad escape");
122
+ value += escaped;
123
+ this.index++;
124
+ } else if (character === '"') {
125
+ return { kind: "string", value };
126
+ } else {
127
+ const code = character.codePointAt(0) ?? 0;
128
+ if (code < 32 || code > 126) this.fail("bad string character");
129
+ value += character;
130
+ }
131
+ }
132
+ }
133
+ if (first === ":") {
134
+ const match = /^:([A-Za-z0-9+/=]*):/.exec(rest);
135
+ if (!match) this.fail("bad byte sequence");
136
+ this.index += match[0].length;
137
+ return { kind: "bytes", value: match[1] ?? "" };
138
+ }
139
+ if (first === "?") {
140
+ const match = /^\?[01]/.exec(rest);
141
+ if (!match) this.fail("bad boolean");
142
+ this.index += 2;
143
+ return { kind: "boolean", value: match[0] === "?1" };
144
+ }
145
+ const token = /^[A-Za-z*][\w!#$%&'*+.^`|~:/-]*/.exec(rest);
146
+ if (!token) this.fail("expected an item");
147
+ this.index += token[0].length;
148
+ return { kind: "token", value: token[0] };
149
+ }
150
+ member() {
151
+ if (this.peek() !== "(") {
152
+ return { value: this.bareItem(), parameters: this.parameters() };
153
+ }
154
+ this.index++;
155
+ const items = [];
156
+ for (; ; ) {
157
+ this.skip(" ");
158
+ if (this.peek() === ")") {
159
+ this.index++;
160
+ return { value: { kind: "inner-list", items }, parameters: this.parameters() };
161
+ }
162
+ items.push({ value: this.bareItem(), parameters: this.parameters() });
163
+ const next = this.peek();
164
+ if (next !== " " && next !== ")") this.fail("expected a space or )");
165
+ }
166
+ }
167
+ }
168
+ function parseDictionary(input) {
169
+ const parser = new Parser(input.trim());
170
+ const result = /* @__PURE__ */ new Map();
171
+ while (!parser.done()) {
172
+ const key = parser.key();
173
+ let member;
174
+ if (parser.peek() === "=") {
175
+ parser.index++;
176
+ member = parser.member();
177
+ } else {
178
+ member = { value: { kind: "boolean", value: true }, parameters: parser.parameters() };
179
+ }
180
+ result.set(key, member);
181
+ parser.skip(" ");
182
+ if (parser.done()) break;
183
+ if (parser.peek() !== ",") parser.fail("expected a comma");
184
+ parser.index++;
185
+ parser.skip(" ");
186
+ if (parser.done()) parser.fail("trailing comma");
187
+ }
188
+ return result;
189
+ }
190
+ function serializeBareItem(item) {
191
+ switch (item.kind) {
192
+ case "integer": {
193
+ if (!Number.isInteger(item.value) || Math.abs(item.value) >= 1e15) {
194
+ throw new TypeError("integer out of range");
195
+ }
196
+ return String(item.value);
197
+ }
198
+ case "string": {
199
+ if (!/^[ -~]*$/.test(item.value)) {
200
+ throw new TypeError("string has characters outside ASCII");
201
+ }
202
+ return `"${item.value.replaceAll("\\", "\\\\").replaceAll('"', String.raw`\"`)}"`;
203
+ }
204
+ case "token": {
205
+ return item.value;
206
+ }
207
+ case "bytes": {
208
+ return `:${item.value}:`;
209
+ }
210
+ case "boolean": {
211
+ return item.value ? "?1" : "?0";
212
+ }
213
+ }
214
+ }
215
+ function serializeParameters(parameters) {
216
+ return parameters.map(
217
+ ([key, value]) => value.kind === "boolean" && value.value ? `;${key}` : `;${key}=${serializeBareItem(value)}`
218
+ ).join("");
219
+ }
220
+ function serializeItem(item) {
221
+ return serializeBareItem(item.value) + serializeParameters(item.parameters);
222
+ }
223
+ function serializeMember(member) {
224
+ if (member.value.kind === "inner-list") {
225
+ return `(${member.value.items.map((item) => serializeItem(item)).join(" ")})${serializeParameters(member.parameters)}`;
226
+ }
227
+ return serializeItem(member);
228
+ }
229
+ async function contentDigest(body) {
230
+ return `sha-256=:${toBase64(await sha256(body))}:`;
231
+ }
232
+ async function verifyContentDigest(header, body) {
233
+ if (header === null) return false;
234
+ let digest;
235
+ try {
236
+ const member = parseDictionary(header).get("sha-256");
237
+ if (member?.value.kind !== "bytes") return false;
238
+ digest = fromBase64(member.value.value);
239
+ } catch {
240
+ return false;
241
+ }
242
+ return equalBytes(digest, await sha256(body));
243
+ }
244
+ const ED25519 = { name: "Ed25519" };
245
+ function importSignPrivateKey(pkcs8) {
246
+ return crypto.subtle.importKey("pkcs8", fromBase64Url(pkcs8), ED25519, false, [
247
+ "sign"
248
+ ]);
249
+ }
250
+ function importSignPublicKey(raw) {
251
+ const bytes = fromBase64Url(raw);
252
+ if (bytes.length !== 32) {
253
+ throw new TypeError("an Ed25519 public key is 32 bytes");
254
+ }
255
+ return crypto.subtle.importKey("raw", bytes, ED25519, false, ["verify"]);
256
+ }
257
+ async function signBytes(privateKey, data) {
258
+ return new Uint8Array(
259
+ await crypto.subtle.sign(ED25519, privateKey, new Uint8Array(data))
260
+ );
261
+ }
262
+ function verifyBytes(publicKey, signature, data) {
263
+ return crypto.subtle.verify(
264
+ ED25519,
265
+ publicKey,
266
+ new Uint8Array(signature),
267
+ new Uint8Array(data)
268
+ );
269
+ }
270
+ function component(name, options = {}) {
271
+ const parameters = [];
272
+ if (options.req) parameters.push(["req", { kind: "boolean", value: true }]);
273
+ if (options.key !== void 0) {
274
+ parameters.push(["key", { kind: "string", value: options.key }]);
275
+ }
276
+ return { name, parameters };
277
+ }
278
+ function signatureParameters(values) {
279
+ const parameters = [];
280
+ for (const [key, value] of Object.entries(values)) {
281
+ if (value === void 0) continue;
282
+ parameters.push([
283
+ key,
284
+ typeof value === "number" ? { kind: "integer", value } : { kind: "string", value }
285
+ ]);
286
+ }
287
+ return parameters;
288
+ }
289
+ function parameterValue(parameters, key) {
290
+ return parameters.find(([name]) => name === key)?.[1];
291
+ }
292
+ function stringParameter(parameters, key) {
293
+ const value = parameterValue(parameters, key);
294
+ return value?.kind === "string" ? value.value : void 0;
295
+ }
296
+ function hasParameter(id, key) {
297
+ return id.parameters.some(([name]) => name === key);
298
+ }
299
+ function asInnerList(input) {
300
+ return {
301
+ value: {
302
+ kind: "inner-list",
303
+ items: input.components.map((id) => ({
304
+ value: { kind: "string", value: id.name },
305
+ parameters: id.parameters
306
+ }))
307
+ },
308
+ parameters: input.parameters
309
+ };
310
+ }
311
+ function serializeSignatureInput(input) {
312
+ return serializeMember(asInnerList(input));
313
+ }
314
+ function componentValue(id, message, request) {
315
+ let source = message;
316
+ if (hasParameter(id, "req")) {
317
+ if (!request) throw new Error(`${id.name};req needs the request`);
318
+ source = request;
319
+ }
320
+ const { name } = id;
321
+ if (name.startsWith("@")) {
322
+ if (name === "@status") {
323
+ if (source.status === void 0) throw new Error("@status needs a response");
324
+ return String(source.status);
325
+ }
326
+ if (name === "@method") {
327
+ if (!source.method) throw new Error("@method needs a request");
328
+ return source.method.toUpperCase();
329
+ }
330
+ if (!source.url) throw new Error(`${name} needs a request URL`);
331
+ const url = new URL(source.url);
332
+ switch (name) {
333
+ case "@target-uri": {
334
+ return source.url;
335
+ }
336
+ case "@authority": {
337
+ return url.host.toLowerCase();
338
+ }
339
+ case "@scheme": {
340
+ return url.protocol.slice(0, -1).toLowerCase();
341
+ }
342
+ case "@request-target": {
343
+ return `${url.pathname}${url.search}`;
344
+ }
345
+ case "@path": {
346
+ return url.pathname || "/";
347
+ }
348
+ case "@query": {
349
+ return url.search || "?";
350
+ }
351
+ default: {
352
+ throw new Error(`unsupported derived component ${name}`);
353
+ }
354
+ }
355
+ }
356
+ if (name !== name.toLowerCase()) {
357
+ throw new Error(`field name ${name} is not lowercase`);
358
+ }
359
+ const value = source.headers.get(name);
360
+ if (value === null) throw new Error(`missing field ${name}`);
361
+ const key = stringParameter(id.parameters, "key");
362
+ if (key === void 0) return value.trim();
363
+ const member = parseDictionary(value).get(key);
364
+ if (!member) throw new Error(`field ${name} has no member ${key}`);
365
+ return serializeMember(member);
366
+ }
367
+ function signatureBase(message, input, request) {
368
+ const lines = [];
369
+ const seen = /* @__PURE__ */ new Set();
370
+ for (const id of input.components) {
371
+ const identifier = serializeMember({
372
+ value: { kind: "string", value: id.name },
373
+ parameters: id.parameters
374
+ });
375
+ if (seen.has(identifier)) throw new Error(`${identifier} is covered twice`);
376
+ seen.add(identifier);
377
+ lines.push(`${identifier}: ${componentValue(id, message, request)}`);
378
+ }
379
+ lines.push(`"@signature-params": ${serializeSignatureInput(input)}`);
380
+ return lines.join("\n");
381
+ }
382
+ async function createSignature(options) {
383
+ const base = signatureBase(options.message, options.input, options.request);
384
+ const signature = await options.sign(utf8(base));
385
+ return {
386
+ signatureInput: `${options.label}=${serializeSignatureInput(options.input)}`,
387
+ signature: `${options.label}=:${toBase64(signature)}:`
388
+ };
389
+ }
390
+ function readSignature(headers, label) {
391
+ const inputField = headers.get("signature-input");
392
+ const signatureField = headers.get("signature");
393
+ if (inputField === null || signatureField === null) return void 0;
394
+ try {
395
+ const input = parseDictionary(inputField).get(label);
396
+ const signature = parseDictionary(signatureField).get(label);
397
+ if (input?.value.kind !== "inner-list") return void 0;
398
+ if (signature?.value.kind !== "bytes") return void 0;
399
+ const components = [];
400
+ for (const item of input.value.items) {
401
+ if (item.value.kind !== "string") return void 0;
402
+ components.push({ name: item.value.value, parameters: item.parameters });
403
+ }
404
+ return {
405
+ label,
406
+ input: { components, parameters: input.parameters },
407
+ signature: fromBase64(signature.value.value)
408
+ };
409
+ } catch {
410
+ return void 0;
411
+ }
412
+ }
413
+ function coversComponents(received, expected) {
414
+ const key = (id) => serializeMember({ value: { kind: "string", value: id.name }, parameters: id.parameters });
415
+ const have = new Set(received.input.components.map((id) => key(id)));
416
+ return have.size === expected.length && expected.every((id) => have.has(key(id)));
417
+ }
418
+ function receivedSignatureBase(received, message, request) {
419
+ try {
420
+ return signatureBase(message, received.input, request);
421
+ } catch {
422
+ return void 0;
423
+ }
424
+ }
425
+ const SIGNATURE_LABEL = "aibex";
426
+ const SIGNATURE_ALGORITHM = "ed25519";
427
+ const HERD_HEADER = "aibex-herd";
428
+ const REQUEST_COMPONENTS = [
429
+ component("@method"),
430
+ component("@target-uri"),
431
+ component("content-digest"),
432
+ component(HERD_HEADER)
433
+ ];
434
+ function responseComponents(requestSigned) {
435
+ const components = [component("@status"), component("content-digest")];
436
+ if (requestSigned) {
437
+ components.push(component("signature", { req: true, key: SIGNATURE_LABEL }));
438
+ }
439
+ return components;
440
+ }
441
+ function randomNonce() {
442
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(16)));
443
+ }
444
+ async function signRequest(options) {
445
+ const headers = new Headers({
446
+ "content-type": "application/json",
447
+ "content-digest": await contentDigest(options.body),
448
+ [HERD_HEADER]: options.herdId
449
+ });
450
+ const fields = await createSignature({
451
+ message: { method: options.method, url: options.url, headers },
452
+ label: SIGNATURE_LABEL,
453
+ input: {
454
+ components: [...REQUEST_COMPONENTS],
455
+ parameters: signatureParameters({
456
+ created: Math.floor((options.now ?? Date.now()) / 1e3),
457
+ nonce: options.nonce ?? randomNonce(),
458
+ keyid: options.machineId,
459
+ alg: SIGNATURE_ALGORITHM
460
+ })
461
+ },
462
+ sign: (base) => signBytes(options.privateKey, base)
463
+ });
464
+ headers.set("signature-input", fields.signatureInput);
465
+ headers.set("signature", fields.signature);
466
+ return headers;
467
+ }
468
+ async function verifyResponse(options) {
469
+ const received = readSignature(options.response.headers, SIGNATURE_LABEL);
470
+ if (!received) return false;
471
+ const requestSigned = options.request !== void 0 && readSignature(options.request.headers, SIGNATURE_LABEL) !== void 0;
472
+ if (!coversComponents(received, responseComponents(requestSigned))) {
473
+ return false;
474
+ }
475
+ const alg = stringParameter(received.input.parameters, "alg");
476
+ if (alg !== void 0 && alg !== SIGNATURE_ALGORITHM) return false;
477
+ if (!await verifyContentDigest(
478
+ options.response.headers.get("content-digest"),
479
+ options.body
480
+ )) {
481
+ return false;
482
+ }
483
+ const base = receivedSignatureBase(received, options.response, options.request);
484
+ if (base === void 0) return false;
485
+ try {
486
+ return await verifyBytes(
487
+ await importSignPublicKey(options.publicKey),
488
+ received.signature,
489
+ utf8(base)
490
+ );
491
+ } catch {
492
+ return false;
493
+ }
494
+ }
495
+ function isRecord(value) {
496
+ return typeof value === "object" && value !== null;
497
+ }
498
+ function isKeyPair(value) {
499
+ return isRecord(value) && typeof value.public === "string" && typeof value.private === "string";
500
+ }
501
+ function parseIdentity(value) {
502
+ if (!isRecord(value) || value.version !== 1) return void 0;
503
+ const strings = [
504
+ "host",
505
+ "machine_id",
506
+ "herd_id",
507
+ "machine_name",
508
+ "ca_public_key",
509
+ "server_public_key",
510
+ "next_join_key",
511
+ "joined_at"
512
+ ];
513
+ if (strings.some((key) => typeof value[key] !== "string")) return void 0;
514
+ if (!isRecord(value.certificate) || !isRecord(value.keys)) return void 0;
515
+ if (!isKeyPair(value.keys.sign) || !isKeyPair(value.keys.encrypt)) {
516
+ return void 0;
517
+ }
518
+ return value;
519
+ }
520
+ function controlRequest(command) {
521
+ switch (command.type) {
522
+ case "control.restart": {
523
+ return { kind: "restart" };
524
+ }
525
+ case "control.update": {
526
+ return "version" in command && typeof command.version === "string" ? { kind: "update", version: command.version } : void 0;
527
+ }
528
+ case "control.rollback": {
529
+ return { kind: "rollback" };
530
+ }
531
+ case "control.diagnostics": {
532
+ return { kind: "diagnostics" };
533
+ }
534
+ default: {
535
+ return void 0;
536
+ }
537
+ }
538
+ }
539
+ const IDENTITY_FILE = "identity.json";
540
+ const COMMANDS_FILE = "link-commands.json";
541
+ const POLL_FILE = "link-poll.json";
542
+ function readJson(file) {
543
+ try {
544
+ return JSON.parse(readFileSync(file, "utf8"));
545
+ } catch {
546
+ return void 0;
547
+ }
548
+ }
549
+ function writeJsonAtomic(file, value, mode = 384) {
550
+ mkdirSync(path.dirname(file), { recursive: true });
551
+ const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
552
+ try {
553
+ writeFileSync(temporary, `${JSON.stringify(value, void 0, 2)}
554
+ `);
555
+ chmodSync(temporary, mode);
556
+ renameSync(temporary, file);
557
+ } catch (error) {
558
+ rmSync(temporary, { force: true });
559
+ throw error;
560
+ }
561
+ }
562
+ function readIdentity(hostDirectory) {
563
+ return parseIdentity(readJson(path.join(hostDirectory, IDENTITY_FILE)));
564
+ }
565
+ const REMEMBER_MS = 60 * 6e4;
566
+ class HandledCommands {
567
+ constructor(hostDirectory, now = Date.now) {
568
+ this.now = now;
569
+ this.file = path.join(hostDirectory, COMMANDS_FILE);
570
+ const value = readJson(this.file);
571
+ this.stored = {
572
+ handled: value && typeof value.handled === "object" && value.handled !== null ? { ...value.handled } : {},
573
+ unacked: Array.isArray(value?.unacked) ? value.unacked.filter((id) => typeof id === "string") : []
574
+ };
575
+ }
576
+ stored;
577
+ file;
578
+ has(commandId) {
579
+ return commandId in this.stored.handled;
580
+ }
581
+ /** Records a command as handled and due an ack, before anything acts on it. */
582
+ record(commandId) {
583
+ this.stored.handled[commandId] = this.now();
584
+ this.ackAgain(commandId);
585
+ }
586
+ /** A handled command came again: ack it again without handling it. */
587
+ ackAgain(commandId) {
588
+ if (!this.stored.unacked.includes(commandId)) {
589
+ this.stored.unacked.push(commandId);
590
+ }
591
+ this.save();
592
+ }
593
+ /** Undoes `record` when the command could not be handed on. */
594
+ forget(commandId) {
595
+ delete this.stored.handled[commandId];
596
+ this.stored.unacked = this.stored.unacked.filter((id) => id !== commandId);
597
+ this.save();
598
+ }
599
+ unacked() {
600
+ return [...this.stored.unacked];
601
+ }
602
+ /** A poll carrying these acks succeeded. */
603
+ acked(commandIds) {
604
+ this.stored.unacked = this.stored.unacked.filter(
605
+ (id) => !commandIds.includes(id)
606
+ );
607
+ const cutoff = this.now() - REMEMBER_MS;
608
+ for (const [id, at] of Object.entries(this.stored.handled)) {
609
+ if (at < cutoff && !this.stored.unacked.includes(id)) {
610
+ delete this.stored.handled[id];
611
+ }
612
+ }
613
+ this.save();
614
+ }
615
+ save() {
616
+ writeJsonAtomic(this.file, this.stored);
617
+ }
618
+ }
619
+ const HARNESS_COMMANDS = {
620
+ claude: "claude",
621
+ codex: "codex",
622
+ cursor: "cursor-agent"
623
+ };
624
+ function onPath(command, pathVariable = process.env.PATH ?? "") {
625
+ return pathVariable.split(path.delimiter).some(
626
+ (directory) => directory && existsSync(path.join(directory, command))
627
+ );
628
+ }
629
+ function detectHarnesses() {
630
+ const harnesses = {};
631
+ for (const [harness, command] of Object.entries(HARNESS_COMMANDS)) {
632
+ harnesses[harness] = {
633
+ installed: onPath(command),
634
+ auth: "unknown"
635
+ };
636
+ }
637
+ return harnesses;
638
+ }
639
+ function describeMachine() {
640
+ const darwin = platform() === "darwin";
641
+ return {
642
+ runner: darwin ? "macos" : "linux",
643
+ os: {
644
+ name: darwin ? "darwin" : "linux",
645
+ version: release(),
646
+ arch: arch() === "arm64" ? "arm64" : "amd64"
647
+ }
648
+ };
649
+ }
650
+ function buildHeartbeat(input) {
651
+ const machine = describeMachine();
652
+ const heartbeat = {
653
+ machine_id: input.machineId,
654
+ sent_at: new Date(input.now).toISOString(),
655
+ protocol_version: 1,
656
+ daemon_version: input.linkVersion,
657
+ link_version: input.linkVersion,
658
+ aibexd_version: input.aibexdVersion,
659
+ self_update: input.selfUpdate.can ? { can: true } : { can: false, reason: input.selfUpdate.reason ?? "unknown" },
660
+ runner: machine.runner,
661
+ os: machine.os,
662
+ harnesses: input.harnesses,
663
+ capacity: { slots_total: 0, slots_free: 0 },
664
+ sessions: [],
665
+ acks: input.acks
666
+ };
667
+ if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
668
+ return heartbeat;
669
+ }
670
+ const LOG_TAIL_LINES = 50;
671
+ class LinkLog {
672
+ constructor(write = (line) => process.stdout.write(`${line}
673
+ `)) {
674
+ this.write = write;
675
+ }
676
+ lines = [];
677
+ line(message) {
678
+ this.write(message);
679
+ this.lines.push(message);
680
+ if (this.lines.length > LOG_TAIL_LINES) this.lines.shift();
681
+ }
682
+ tail() {
683
+ return [...this.lines];
13
684
  }
14
685
  }
15
686
  const PACKAGE_ROOT = path.resolve(
@@ -25,8 +696,205 @@ function readPackageInfo() {
25
696
  }
26
697
  return { name: manifest.name, version: manifest.version };
27
698
  }
699
+ const DEFAULT_INTERVAL_MS = 1e4;
700
+ const MIN_INTERVAL_MS = 1e3;
701
+ const EXACT_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
702
+ class Poller {
703
+ constructor(options) {
704
+ this.options = options;
705
+ this.backoffMs = options.backoffInitialMs;
706
+ this.url = new URL("/v1/poll", options.identity.host).href;
707
+ }
708
+ intervalMs = DEFAULT_INTERVAL_MS;
709
+ backoffMs;
710
+ timer;
711
+ stopped = false;
712
+ diagnostics;
713
+ /** What link-poll.json last said, so a failure keeps the last success. */
714
+ lastRecord = {};
715
+ url;
716
+ start() {
717
+ this.schedule(0);
718
+ }
719
+ stop() {
720
+ this.stopped = true;
721
+ clearTimeout(this.timer);
722
+ }
723
+ /** A diagnostics report to carry in the next heartbeat. */
724
+ attachDiagnostics(diagnostics) {
725
+ this.diagnostics = diagnostics;
726
+ }
727
+ schedule(ms) {
728
+ if (this.stopped) return;
729
+ this.timer = setTimeout(() => {
730
+ void (async () => {
731
+ const outcome = await this.pollOnce();
732
+ this.schedule(outcome.waitMs);
733
+ })();
734
+ }, ms);
735
+ }
736
+ fail(reason) {
737
+ const waitMs = this.backoffMs;
738
+ this.backoffMs = Math.min(this.backoffMs * 2, this.options.backoffMaxMs);
739
+ this.options.log.line(
740
+ `poll failed: ${reason}; retrying in ${Math.round(waitMs / 1e3)}s`
741
+ );
742
+ this.recordPoll({ lastError: reason });
743
+ return { kind: "failed", waitMs, reason };
744
+ }
745
+ recordPoll(fields) {
746
+ try {
747
+ writeJsonAtomic(path.join(this.options.hostDirectory, POLL_FILE), {
748
+ machine_id: this.options.identity.machine_id,
749
+ herd_id: this.options.identity.herd_id,
750
+ ...this.lastRecord,
751
+ ...fields,
752
+ updatedAt: new Date(this.now()).toISOString()
753
+ });
754
+ this.lastRecord = { ...this.lastRecord, ...fields };
755
+ } catch {
756
+ }
757
+ }
758
+ now() {
759
+ return (this.options.now ?? Date.now)();
760
+ }
761
+ async pollOnce() {
762
+ const { identity, handled } = this.options;
763
+ const acks = handled.unacked();
764
+ const diagnostics = this.diagnostics;
765
+ const status = this.options.status();
766
+ const body = JSON.stringify(
767
+ buildHeartbeat({
768
+ machineId: identity.machine_id,
769
+ linkVersion: this.options.linkVersion,
770
+ aibexdVersion: status.aibexdVersion,
771
+ selfUpdate: status.selfUpdate,
772
+ harnesses: this.options.harnesses,
773
+ acks,
774
+ diagnostics,
775
+ now: this.now()
776
+ })
777
+ );
778
+ let response;
779
+ let headers;
780
+ let text;
781
+ try {
782
+ headers = await signRequest({
783
+ method: "POST",
784
+ url: this.url,
785
+ body,
786
+ herdId: identity.herd_id,
787
+ machineId: identity.machine_id,
788
+ privateKey: await importSignPrivateKey(identity.keys.sign.private),
789
+ now: this.now()
790
+ });
791
+ response = await (this.options.fetch ?? fetch)(this.url, {
792
+ method: "POST",
793
+ headers,
794
+ body,
795
+ signal: AbortSignal.timeout(3e4)
796
+ });
797
+ text = await response.text();
798
+ } catch (error) {
799
+ return this.fail(error instanceof Error ? error.message : String(error));
800
+ }
801
+ const verified = await verifyResponse({
802
+ response: { status: response.status, headers: response.headers },
803
+ body: text,
804
+ request: { method: "POST", url: this.url, headers },
805
+ publicKey: identity.server_public_key
806
+ });
807
+ if (!verified) {
808
+ if (response.status >= 500) return this.fail(`HTTP ${response.status}`);
809
+ this.options.log.line(
810
+ `discarded a poll answer (HTTP ${response.status}) that is not signed by the herd's server key`
811
+ );
812
+ return { kind: "discarded", waitMs: this.intervalMs };
813
+ }
814
+ if (response.status !== 200) {
815
+ let title = `HTTP ${response.status}`;
816
+ try {
817
+ title = `${JSON.parse(text).title} (HTTP ${response.status})`;
818
+ } catch {
819
+ }
820
+ return this.fail(title);
821
+ }
822
+ let answer;
823
+ try {
824
+ answer = JSON.parse(text);
825
+ } catch {
826
+ return this.fail("the answer is not JSON");
827
+ }
828
+ handled.acked(acks);
829
+ if (diagnostics && this.diagnostics === diagnostics) {
830
+ this.diagnostics = void 0;
831
+ }
832
+ this.backoffMs = this.options.backoffInitialMs;
833
+ this.intervalMs = Math.max(
834
+ MIN_INTERVAL_MS,
835
+ answer.next_poll_after_ms || DEFAULT_INTERVAL_MS
836
+ );
837
+ this.recordPoll({
838
+ lastPollAt: new Date(this.now()).toISOString(),
839
+ machineState: answer.machine_state,
840
+ lastError: null
841
+ });
842
+ for (const command of answer.commands) await this.handle(command);
843
+ return { kind: "ok", waitMs: this.intervalMs, response: answer };
844
+ }
845
+ async handle(command) {
846
+ const { handled, log } = this.options;
847
+ const id = command.command_id;
848
+ if (handled.has(id)) {
849
+ handled.ackAgain(id);
850
+ return;
851
+ }
852
+ const request = controlRequest(command);
853
+ if (request === void 0) {
854
+ handled.record(id);
855
+ log.line(
856
+ command.type === "control.drop_session" ? `${command.type} ${id}: there are no sessions yet; acked` : `unknown command type ${command.type} (${id}); acked and ignored`
857
+ );
858
+ return;
859
+ }
860
+ if (request.kind === "update" && !EXACT_VERSION.test(request.version)) {
861
+ handled.record(id);
862
+ log.line(
863
+ `control.update ${id} names ${JSON.stringify(request.version)}, which is not a version; acked and ignored`
864
+ );
865
+ return;
866
+ }
867
+ handled.record(id);
868
+ log.line(
869
+ `${command.type}${request.kind === "update" ? ` ${request.version}` : ""} (${id}): handing it to aibexd`
870
+ );
871
+ if (!await this.options.forward(id, request)) {
872
+ handled.forget(id);
873
+ log.line(`could not hand ${id} to aibexd; it will come again`);
874
+ }
875
+ }
876
+ }
28
877
  function send(message) {
29
- process.send?.(message);
878
+ return new Promise((resolve) => {
879
+ if (!process.send) {
880
+ resolve(false);
881
+ return;
882
+ }
883
+ process.send(message, void 0, {}, (error) => resolve(error === null));
884
+ });
885
+ }
886
+ function initialSelfUpdate() {
887
+ try {
888
+ const value = JSON.parse(process.env.AIBEX_SELF_UPDATE ?? "");
889
+ if (typeof value.can === "boolean") {
890
+ return {
891
+ can: value.can,
892
+ reason: typeof value.reason === "string" ? value.reason : null
893
+ };
894
+ }
895
+ } catch {
896
+ }
897
+ return { can: true, reason: null };
30
898
  }
31
899
  function main() {
32
900
  const info = readPackageInfo();
@@ -46,12 +914,53 @@ function main() {
46
914
  process.exitCode = 1;
47
915
  return;
48
916
  }
49
- process.stdout.write(
50
- `aibex-link ${info.version} linked to ${host} (not polling yet)
51
- `
52
- );
53
- send({ type: "ready" });
54
- setInterval(() => send({ type: "alive" }), aliveIntervalMs());
917
+ const log = new LinkLog();
918
+ let status = {
919
+ type: "status",
920
+ aibexdVersion: process.env.AIBEX_AIBEXD_VERSION ?? "unknown",
921
+ selfUpdate: initialSelfUpdate()
922
+ };
923
+ const identity = readIdentity(hostDirectory);
924
+ let poller;
925
+ if (identity) {
926
+ log.line(
927
+ `aibex-link ${info.version} linked to ${host} as ${identity.machine_id} (${identity.machine_name}) in herd ${identity.herd_id}`
928
+ );
929
+ poller = new Poller({
930
+ identity,
931
+ hostDirectory,
932
+ linkVersion: info.version,
933
+ log,
934
+ handled: new HandledCommands(hostDirectory),
935
+ status: () => status,
936
+ harnesses: detectHarnesses(),
937
+ forward: (commandId, request) => send({ type: "control", commandId, request }),
938
+ backoffInitialMs: timing(
939
+ "pollBackoffInitialMs",
940
+ DEFAULT_POLL_BACKOFF_INITIAL_MS
941
+ ),
942
+ backoffMaxMs: timing("pollBackoffMaxMs", DEFAULT_POLL_BACKOFF_MAX_MS)
943
+ });
944
+ } else {
945
+ log.line(
946
+ `aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
947
+ );
948
+ }
949
+ process.on("message", (message) => {
950
+ if (message.type === "status") {
951
+ status = message;
952
+ } else if (message.type === "diagnostics") {
953
+ poller?.attachDiagnostics({
954
+ ...message.diagnostics,
955
+ collected_at: (/* @__PURE__ */ new Date()).toISOString(),
956
+ command_id: message.commandId,
957
+ log_tail: log.tail()
958
+ });
959
+ }
960
+ });
961
+ void send({ type: "ready" });
962
+ setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
963
+ poller?.start();
55
964
  process.on("disconnect", () => process.exit(0));
56
965
  process.on("SIGTERM", () => process.exit(0));
57
966
  process.on("SIGINT", () => process.exit(0));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "The process aibexd runs to link a machine to an Aibex herd",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,6 +33,7 @@
33
33
  "typecheck": "turbo run turbo:typecheck --filter=@aibexhq/aibex-link"
34
34
  },
35
35
  "devDependencies": {
36
+ "@aibex/protocol": "workspace:*",
36
37
  "@types/node": "^22.15.29",
37
38
  "typescript": "^5.9.3",
38
39
  "vite": "^6.4.1",