@aibexhq/aibex-link 0.0.6 → 0.0.7

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 +216 -35
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, appendFileSync, openSync, readSync, closeSync, cpSync } from "node:fs";
2
- import { randomBytes, createHash } from "node:crypto";
3
1
  import path from "node:path";
2
+ import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, appendFileSync, openSync, readSync, closeSync, cpSync, accessSync, constants } from "node:fs";
3
+ import { randomBytes, createHash } from "node:crypto";
4
4
  import { platform, arch, release, homedir } from "node:os";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { createConnection } from "node:net";
@@ -700,6 +700,51 @@ class Access {
700
700
  return { accept: file.accept, integrations: file.integrations };
701
701
  }
702
702
  }
703
+ const ACTIVATIONS_FILE = "activations.json";
704
+ const ACTIVATION_TTL_MS = 10 * 60 * 1e3;
705
+ const ACTIVATION_CODE = /^[0-9A-HJKMNP-TV-Z]{8}$/u;
706
+ function isActivation(value) {
707
+ if (typeof value !== "object" || value === null) return false;
708
+ const { code, at } = value;
709
+ return typeof code === "string" && ACTIVATION_CODE.test(code) && typeof at === "string" && !Number.isNaN(Date.parse(at));
710
+ }
711
+ class Activations {
712
+ constructor(hostDirectory, now = Date.now) {
713
+ this.now = now;
714
+ this.file = path.join(hostDirectory, ACTIVATIONS_FILE);
715
+ }
716
+ file;
717
+ /** Keeps a code to report; false when it is not one. */
718
+ add(code) {
719
+ if (!ACTIVATION_CODE.test(code)) return false;
720
+ const kept = this.read().filter((entry) => entry.code !== code);
721
+ this.write([...kept, { code, at: new Date(this.now()).toISOString() }]);
722
+ return true;
723
+ }
724
+ /** The codes to report now, forgetting those 10 minutes old. */
725
+ list() {
726
+ const all = this.read();
727
+ const fresh = all.filter(
728
+ (entry) => this.now() - Date.parse(entry.at) < ACTIVATION_TTL_MS
729
+ );
730
+ if (fresh.length !== all.length) this.write(fresh);
731
+ return fresh;
732
+ }
733
+ /** Forgets the codes a poll answer confirmed. */
734
+ confirm(codes) {
735
+ if (!codes || codes.length === 0) return;
736
+ const all = this.read();
737
+ const left = all.filter((entry) => !codes.includes(entry.code));
738
+ if (left.length !== all.length) this.write(left);
739
+ }
740
+ read() {
741
+ const value = readJson(this.file);
742
+ return Array.isArray(value) ? value.filter((entry) => isActivation(entry)) : [];
743
+ }
744
+ write(entries) {
745
+ writeJsonAtomic(this.file, entries);
746
+ }
747
+ }
703
748
  const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
704
749
  const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
705
750
  const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
@@ -840,6 +885,9 @@ async function collectReport(options) {
840
885
  const access = options.access.heartbeat();
841
886
  if (access) report.access = access;
842
887
  if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
888
+ if (options.activations && options.activations.length > 0) {
889
+ report.activations = options.activations;
890
+ }
843
891
  return report;
844
892
  }
845
893
  function buildHeartbeat(input) {
@@ -859,11 +907,12 @@ function buildHeartbeat(input) {
859
907
  sessions: input.report.sessions,
860
908
  acks: input.acks
861
909
  };
862
- const { repos, access, features, setup_terminals } = input.report;
910
+ const { repos, access, features, setup_terminals, activations } = input.report;
863
911
  if (repos) heartbeat.repos = repos;
864
912
  if (access) heartbeat.access = access;
865
913
  if (features) heartbeat.features = features;
866
914
  if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
915
+ if (activations) heartbeat.activations = activations;
867
916
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
868
917
  return heartbeat;
869
918
  }
@@ -1362,6 +1411,11 @@ class Relay {
1362
1411
  idleTimer;
1363
1412
  /** Connections to terminal hosts made for this relay, by socket path. */
1364
1413
  hosts = /* @__PURE__ */ new Map();
1414
+ /**
1415
+ * Each viewer's requests still being handled, by `conn`: the tail of a
1416
+ * chain that runs them one at a time in the order they arrived.
1417
+ */
1418
+ queues = /* @__PURE__ */ new Map();
1365
1419
  /** Nonces seen, with when they may be forgotten. */
1366
1420
  nonces = /* @__PURE__ */ new Map();
1367
1421
  timings;
@@ -1432,6 +1486,7 @@ class Relay {
1432
1486
  end() {
1433
1487
  clearTimeout(this.idleTimer);
1434
1488
  this.idleTimer = void 0;
1489
+ this.queues.clear();
1435
1490
  for (const pending of this.hosts.values()) {
1436
1491
  void (async () => {
1437
1492
  try {
@@ -1469,9 +1524,36 @@ class Relay {
1469
1524
  if (frame.type === "viewers") {
1470
1525
  this.viewers(frame.count);
1471
1526
  } else if (frame.type === "request" && typeof frame.conn === "string") {
1472
- await this.request(frame.conn, frame.envelope);
1527
+ await this.enqueue(frame.conn, frame.envelope);
1473
1528
  }
1474
1529
  }
1530
+ /**
1531
+ * Runs a viewer's request after every earlier request from the same
1532
+ * `conn` has reached its terminal host and been answered, so two
1533
+ * keystrokes are never swapped. Different viewers stay concurrent.
1534
+ */
1535
+ enqueue(conn, envelope) {
1536
+ const socket = this.socket;
1537
+ const previous = this.queues.get(conn);
1538
+ const run = (async () => {
1539
+ await previous;
1540
+ if (this.socket === socket) {
1541
+ try {
1542
+ await this.request(conn, envelope);
1543
+ } catch (error) {
1544
+ this.options.log.line(
1545
+ `a relayed request failed: ${error instanceof Error ? error.message : String(error)}`
1546
+ );
1547
+ }
1548
+ }
1549
+ })();
1550
+ this.queues.set(conn, run);
1551
+ void (async () => {
1552
+ await run;
1553
+ if (this.queues.get(conn) === run) this.queues.delete(conn);
1554
+ })();
1555
+ return run;
1556
+ }
1475
1557
  viewers(count) {
1476
1558
  clearTimeout(this.idleTimer);
1477
1559
  this.idleTimer = void 0;
@@ -1590,6 +1672,7 @@ class Relay {
1590
1672
  for (const message of queued) event(message);
1591
1673
  }
1592
1674
  }
1675
+ const GITHUB_HOST = "github.com";
1593
1676
  const REPO_SCAN_MS = 6e4;
1594
1677
  const GITHUB_REMOTE = [
1595
1678
  /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
@@ -1623,8 +1706,9 @@ function directories(parent) {
1623
1706
  }
1624
1707
  }
1625
1708
  async function scanRepos(reposDirectory) {
1626
- const candidates = directories(reposDirectory).flatMap(
1627
- (owner) => directories(path.join(reposDirectory, owner)).map((name) => path.join(reposDirectory, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
1709
+ const github = path.join(reposDirectory, GITHUB_HOST);
1710
+ const candidates = directories(github).flatMap(
1711
+ (owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
1628
1712
  );
1629
1713
  const found = await Promise.all(
1630
1714
  candidates.map(async (directory) => {
@@ -1691,7 +1775,8 @@ const SETUP_PROGRAMS = {
1691
1775
  shell: void 0,
1692
1776
  claude: "claude",
1693
1777
  codex: "codex",
1694
- cursor: "cursor-agent"
1778
+ cursor: "cursor-agent",
1779
+ "repo-add": "aibexd"
1695
1780
  };
1696
1781
  function bracketedPaste(text) {
1697
1782
  return `\x1B[200~${text}\x1B[201~`;
@@ -2536,6 +2621,12 @@ const SETUP_LABEL = "setup:";
2536
2621
  function isProgram(value) {
2537
2622
  return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
2538
2623
  }
2624
+ const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
2625
+ function isAddRepo(value) {
2626
+ if (typeof value !== "object" || value === null) return false;
2627
+ const { owner, name } = value;
2628
+ return Object.keys(value).length === 2 && typeof owner === "string" && typeof name === "string" && REPO_PART.test(owner) && REPO_PART.test(name) && owner.length <= 100 && name.length <= 100;
2629
+ }
2539
2630
  class SetupTerminals {
2540
2631
  constructor(options) {
2541
2632
  this.options = options;
@@ -2558,15 +2649,25 @@ class SetupTerminals {
2558
2649
  log.line(`terminal.open refused: ${opened.reason}`);
2559
2650
  return;
2560
2651
  }
2561
- const { open_id: openId, program, cwd } = opened.payload;
2652
+ const { open_id: openId, program, cwd, repo } = opened.payload;
2562
2653
  if (!isProgram(program)) {
2563
2654
  log.line(
2564
2655
  `terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
2565
2656
  );
2566
2657
  return;
2567
2658
  }
2659
+ if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
2660
+ log.line(
2661
+ program === "repo-add" ? `terminal.open ${openId} refused: repo-add needs a repository whose owner and name are letters, digits, _, . and -, starting with neither - nor .` : `terminal.open ${openId} refused: only repo-add takes a repository`
2662
+ );
2663
+ return;
2664
+ }
2665
+ if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
2666
+ log.line(`terminal.open ${openId} refused: unknown working directory`);
2667
+ return;
2668
+ }
2568
2669
  let directory = this.home;
2569
- if (cwd?.kind === "repo") {
2670
+ if (cwd.kind === "repo" && program !== "repo-add") {
2570
2671
  const checkout = await this.options.repos.find(cwd.repo);
2571
2672
  if (!checkout) {
2572
2673
  log.line(
@@ -2575,15 +2676,14 @@ class SetupTerminals {
2575
2676
  return;
2576
2677
  }
2577
2678
  directory = checkout.path;
2578
- } else if (cwd?.kind !== "home") {
2579
- log.line(`terminal.open ${openId} refused: unknown working directory`);
2580
- return;
2581
2679
  }
2582
2680
  const label = `${SETUP_LABEL}${openId}`;
2583
2681
  const existing = await listTerminals(this.sockets());
2584
2682
  if (existing.some((terminal) => terminal.label === label)) return;
2585
- const shell = this.options.shell ?? process.env.SHELL ?? "/bin/sh";
2586
- const file = SETUP_PROGRAMS[program] ?? shell;
2683
+ const searchPath = this.searchPath();
2684
+ const run = this.command(program, repo);
2685
+ const args = run.args;
2686
+ const file = resolveProgram(run.file, searchPath);
2587
2687
  const socket = this.options.terminalSocket;
2588
2688
  if (socket === void 0) {
2589
2689
  log.line(`terminal.open ${openId}: no terminal host is set`);
@@ -2602,8 +2702,9 @@ class SetupTerminals {
2602
2702
  const created = await client.request({
2603
2703
  type: "create",
2604
2704
  file,
2605
- args: program === "shell" ? ["-l"] : [],
2705
+ args,
2606
2706
  cwd: directory,
2707
+ env: { PATH: searchPath },
2607
2708
  label
2608
2709
  });
2609
2710
  log.line(
@@ -2613,16 +2714,44 @@ class SetupTerminals {
2613
2714
  client.close();
2614
2715
  }
2615
2716
  }
2717
+ /** The file and arguments a program runs; `repo` is checked already. */
2718
+ command(program, repo) {
2719
+ if (program === "repo-add" && repo) {
2720
+ return {
2721
+ file: path.join(this.options.binDirectory, "aibexd"),
2722
+ args: ["repo", "add", `${repo.owner}/${repo.name}`]
2723
+ };
2724
+ }
2725
+ if (program === "shell") {
2726
+ return {
2727
+ file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
2728
+ args: ["-l"]
2729
+ };
2730
+ }
2731
+ return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
2732
+ }
2733
+ /** `<state>/bin` first, so `aibexd activate` resolves in a harness started here. */
2734
+ searchPath() {
2735
+ const rest = (this.options.path ?? process.env.PATH ?? "").split(path.delimiter).filter(
2736
+ (directory) => directory !== "" && directory !== this.options.binDirectory
2737
+ );
2738
+ return [this.options.binDirectory, ...rest].join(path.delimiter);
2739
+ }
2616
2740
  /** Every setup terminal a host still keeps, running or exited. */
2617
2741
  async list() {
2618
2742
  const terminals = await listTerminals(this.sockets());
2619
2743
  return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
2744
+ const program = this.program(terminal.file);
2620
2745
  const entry = {
2621
2746
  open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
2622
2747
  terminal: terminal.id,
2623
- program: this.program(terminal.file),
2624
- cwd: this.cwd(terminal.cwd)
2748
+ program,
2749
+ cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
2625
2750
  };
2751
+ if (program === "repo-add") {
2752
+ const [owner, name] = (terminal.args?.[2] ?? "").split("/");
2753
+ if (owner && name) entry.repo = { owner, name };
2754
+ }
2626
2755
  if (terminal.exited) entry.exit = terminal.exited;
2627
2756
  return entry;
2628
2757
  });
@@ -2635,7 +2764,10 @@ class SetupTerminals {
2635
2764
  return found?.[0] ?? "shell";
2636
2765
  }
2637
2766
  cwd(directory) {
2638
- const relative = path.relative(this.options.reposDirectory, directory);
2767
+ const relative = path.relative(
2768
+ path.join(this.options.reposDirectory, GITHUB_HOST),
2769
+ directory
2770
+ );
2639
2771
  const [owner, name, ...rest] = relative.split(path.sep);
2640
2772
  if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
2641
2773
  const repo = { owner, name };
@@ -2644,6 +2776,20 @@ class SetupTerminals {
2644
2776
  return { kind: "home" };
2645
2777
  }
2646
2778
  }
2779
+ function resolveProgram(file, searchPath) {
2780
+ if (file.includes("/")) return file;
2781
+ for (const directory of searchPath.split(path.delimiter)) {
2782
+ if (directory === "") continue;
2783
+ const candidate = path.join(directory, file);
2784
+ try {
2785
+ if (!statSync(candidate).isFile()) continue;
2786
+ accessSync(candidate, constants.X_OK);
2787
+ return candidate;
2788
+ } catch {
2789
+ }
2790
+ }
2791
+ return file;
2792
+ }
2647
2793
  function send(message) {
2648
2794
  return new Promise((resolve) => {
2649
2795
  if (!process.send) {
@@ -2694,6 +2840,7 @@ function main() {
2694
2840
  const paths = linkPaths(hostDirectory);
2695
2841
  const access = new Access(paths.access);
2696
2842
  const repos = new Repos(paths.repos);
2843
+ const activations = new Activations(hostDirectory);
2697
2844
  const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
2698
2845
  const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
2699
2846
  let poller;
@@ -2717,6 +2864,7 @@ function main() {
2717
2864
  access,
2718
2865
  repos,
2719
2866
  reposDirectory: paths.repos,
2867
+ binDirectory: path.join(paths.state, "bin"),
2720
2868
  terminalSocket,
2721
2869
  terminalsDirectory,
2722
2870
  log
@@ -2752,9 +2900,10 @@ function main() {
2752
2900
  paths,
2753
2901
  repos,
2754
2902
  access,
2755
- features: ["sessions", "relay"],
2903
+ features: ["sessions", "relay", "setup"],
2756
2904
  sessions: running.list(),
2757
- setupTerminals: await setup.list()
2905
+ setupTerminals: await setup.list(),
2906
+ activations: activations.list()
2758
2907
  }),
2759
2908
  handleCommand: async (command) => {
2760
2909
  if (command.type === "relay.open") {
@@ -2765,7 +2914,10 @@ function main() {
2765
2914
  await setup.open(command);
2766
2915
  return true;
2767
2916
  },
2768
- afterPoll: (answer) => running.afterPoll(answer),
2917
+ afterPoll: async (answer) => {
2918
+ activations.confirm(answer.activations_confirmed);
2919
+ await running.afterPoll(answer);
2920
+ },
2769
2921
  forward: (commandId, request) => send({ type: "control", commandId, request }),
2770
2922
  backoffInitialMs: timing(
2771
2923
  "pollBackoffInitialMs",
@@ -2778,21 +2930,50 @@ function main() {
2778
2930
  `aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
2779
2931
  );
2780
2932
  }
2933
+ const activate = (code) => {
2934
+ if (!poller) {
2935
+ return {
2936
+ type: "activated",
2937
+ code,
2938
+ ok: false,
2939
+ reason: "this machine has not joined a herd: run `aibexd join <key>` first"
2940
+ };
2941
+ }
2942
+ if (!activations.add(code)) {
2943
+ return {
2944
+ type: "activated",
2945
+ code,
2946
+ ok: false,
2947
+ reason: "not an activation code"
2948
+ };
2949
+ }
2950
+ log.line(`activation ${code} taken; reporting it until the herd confirms`);
2951
+ return { type: "activated", code, ok: true };
2952
+ };
2781
2953
  process.on("message", (message) => {
2782
- if (message.type === "status") {
2783
- status = message;
2784
- } else if (message.type === "diagnostics") {
2785
- const mismatch = access.mismatch;
2786
- poller?.attachDiagnostics({
2787
- ...message.diagnostics,
2788
- warnings: [
2789
- ...message.diagnostics.warnings,
2790
- ...mismatch === void 0 ? [] : [`access.json does not match the herd's trust: ${mismatch}`]
2791
- ],
2792
- collected_at: (/* @__PURE__ */ new Date()).toISOString(),
2793
- command_id: message.commandId,
2794
- log_tail: log.tail()
2795
- });
2954
+ switch (message.type) {
2955
+ case "status": {
2956
+ status = message;
2957
+ break;
2958
+ }
2959
+ case "activate": {
2960
+ void send(activate(message.code));
2961
+ break;
2962
+ }
2963
+ case "diagnostics": {
2964
+ const mismatch = access.mismatch;
2965
+ poller?.attachDiagnostics({
2966
+ ...message.diagnostics,
2967
+ warnings: [
2968
+ ...message.diagnostics.warnings,
2969
+ ...mismatch === void 0 ? [] : [`access.json does not match the herd's trust: ${mismatch}`]
2970
+ ],
2971
+ collected_at: (/* @__PURE__ */ new Date()).toISOString(),
2972
+ command_id: message.commandId,
2973
+ log_tail: log.tail()
2974
+ });
2975
+ break;
2976
+ }
2796
2977
  }
2797
2978
  });
2798
2979
  void send({ type: "ready" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "The process aibexd runs to link a machine to an Aibex herd",
5
5
  "homepage": "https://github.com/aibexhq",
6
6
  "bugs": {