@aibexhq/aibex-link 0.0.9 → 0.0.10

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 +251 -114
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import path from "node:path";
2
1
  import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
2
+ import path from "node:path";
3
3
  import { randomBytes, createHash } from "node:crypto";
4
- import { platform, arch, release, tmpdir, homedir } from "node:os";
5
4
  import { execFile } from "node:child_process";
5
+ import { homedir, platform, arch, release, tmpdir } from "node:os";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createConnection } from "node:net";
8
8
  const encoder = new TextEncoder();
@@ -700,51 +700,6 @@ 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
- }
748
703
  const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
749
704
  const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
750
705
  const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
@@ -815,6 +770,214 @@ class HandledCommands {
815
770
  writeJsonAtomic(this.file, this.stored);
816
771
  }
817
772
  }
773
+ const UNKNOWN = { auth: "unknown" };
774
+ function parseObject(text) {
775
+ try {
776
+ const value = JSON.parse(text);
777
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
778
+ } catch {
779
+ return void 0;
780
+ }
781
+ }
782
+ const CLAUDE_PLANS = {
783
+ "claude.ai": "subscription",
784
+ api_key: "api_key",
785
+ console: "api_key"
786
+ };
787
+ const PROBES = {
788
+ // exit 0 `{"loggedIn": true, "authMethod": "claude.ai", "loginExpiresAt": …}`
789
+ // signed in; exit 1 `{"loggedIn": false, "authMethod": "none"}` signed out.
790
+ claude: {
791
+ command: "claude",
792
+ args: ["auth", "status", "--json"],
793
+ read: ({ exitCode, stdout }, now) => {
794
+ const status = parseObject(stdout);
795
+ if (!status) return UNKNOWN;
796
+ if (status.loggedIn === false && (exitCode === 0 || exitCode === 1)) {
797
+ return { auth: "signed_out" };
798
+ }
799
+ if (status.loggedIn !== true || exitCode !== 0) return UNKNOWN;
800
+ const expires = typeof status.loginExpiresAt === "string" ? Date.parse(status.loginExpiresAt) : Number.NaN;
801
+ const plan = typeof status.authMethod === "string" ? CLAUDE_PLANS[status.authMethod] : void 0;
802
+ return {
803
+ auth: expires < now ? "expired" : "signed_in",
804
+ ...plan ? { plan } : {}
805
+ };
806
+ }
807
+ },
808
+ // Prints to stderr: exit 0 `Logged in using ChatGPT` or `Logged in using an
809
+ // API key`, exit 1 `Not logged in`.
810
+ codex: {
811
+ command: "codex",
812
+ args: ["login", "status"],
813
+ read: ({ exitCode, stdout, stderr }) => {
814
+ const text = `${stdout}
815
+ ${stderr}`;
816
+ if (exitCode === 0 && /^Logged in using ChatGPT/mu.test(text)) {
817
+ return { auth: "signed_in", plan: "subscription" };
818
+ }
819
+ if (exitCode === 0 && /^Logged in using an? API key/imu.test(text)) {
820
+ return { auth: "signed_in", plan: "api_key" };
821
+ }
822
+ if (exitCode !== 0 && /^Not logged in/mu.test(text)) {
823
+ return { auth: "signed_out" };
824
+ }
825
+ return UNKNOWN;
826
+ }
827
+ },
828
+ // exit 0 with `{"isAuthenticated": true, "status": "authenticated"}` or
829
+ // `{"isAuthenticated": false, "status": "unauthenticated"}`. No plan.
830
+ cursor: {
831
+ command: "cursor-agent",
832
+ args: ["status", "--format", "json"],
833
+ read: ({ exitCode, stdout }) => {
834
+ const status = parseObject(stdout);
835
+ if (!status || exitCode !== 0) return UNKNOWN;
836
+ if (status.isAuthenticated === true) return { auth: "signed_in" };
837
+ if (status.isAuthenticated === false) return { auth: "signed_out" };
838
+ return UNKNOWN;
839
+ }
840
+ }
841
+ };
842
+ const PROBE_TIMEOUT_MS = 1e4;
843
+ const PROBE_MAX_OUTPUT = 64 * 1024;
844
+ function runProbe(probe, options = {}) {
845
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
846
+ return new Promise((resolve) => {
847
+ const backstop = setTimeout(() => {
848
+ child.stdout?.destroy();
849
+ child.stderr?.destroy();
850
+ resolve({ exitCode: null, stdout: "", stderr: "" });
851
+ }, timeoutMs + 1e3);
852
+ const child = execFile(
853
+ probe.command,
854
+ probe.args,
855
+ {
856
+ cwd: options.cwd ?? homedir(),
857
+ env: { ...process.env, PATH: options.path ?? process.env.PATH ?? "" },
858
+ timeout: timeoutMs,
859
+ maxBuffer: PROBE_MAX_OUTPUT,
860
+ encoding: "utf8",
861
+ windowsHide: true
862
+ },
863
+ (error, stdout, stderr) => {
864
+ clearTimeout(backstop);
865
+ if (!error) {
866
+ resolve({ exitCode: 0, stdout, stderr });
867
+ return;
868
+ }
869
+ const code = error.code;
870
+ resolve({
871
+ exitCode: typeof code === "number" && !error.killed ? code : null,
872
+ stdout,
873
+ stderr
874
+ });
875
+ }
876
+ );
877
+ child.stdin?.end();
878
+ });
879
+ }
880
+ function readProbe(probe, output, now) {
881
+ if (output.exitCode === null) return UNKNOWN;
882
+ return probe.read(output, now);
883
+ }
884
+ const PROBE_EVERY_MS = 5 * 6e4;
885
+ const PROBE_SETUP_EVERY_MS = 15e3;
886
+ class HarnessStatuses {
887
+ constructor(options) {
888
+ this.options = options;
889
+ this.probes = options.probes ?? PROBES;
890
+ this.now = options.now ?? Date.now;
891
+ }
892
+ last = /* @__PURE__ */ new Map();
893
+ running = /* @__PURE__ */ new Map();
894
+ lastStarted = Number.NEGATIVE_INFINITY;
895
+ /** Setup terminals running at the last look, by terminal id. */
896
+ runningSetup = /* @__PURE__ */ new Set();
897
+ timer;
898
+ probes;
899
+ now;
900
+ /** Probes every installed harness, then every 5 minutes; resolves after the first round. */
901
+ async start() {
902
+ await this.refresh();
903
+ this.timer = setInterval(() => void this.refresh(), PROBE_EVERY_MS);
904
+ }
905
+ stop() {
906
+ clearInterval(this.timer);
907
+ }
908
+ /**
909
+ * Probes every installed harness that has no probe in flight, in
910
+ * parallel; resolves when they are done.
911
+ */
912
+ async refresh() {
913
+ this.lastStarted = this.now();
914
+ const installed = this.options.installed();
915
+ const rounds = [];
916
+ for (const harness of Object.keys(this.probes)) {
917
+ if (!installed[harness]) {
918
+ this.last.delete(harness);
919
+ continue;
920
+ }
921
+ const inFlight = this.running.get(harness);
922
+ if (inFlight) {
923
+ rounds.push(inFlight);
924
+ continue;
925
+ }
926
+ const round = (async () => {
927
+ try {
928
+ await this.probe(harness);
929
+ } finally {
930
+ this.running.delete(harness);
931
+ }
932
+ })();
933
+ this.running.set(harness, round);
934
+ rounds.push(round);
935
+ }
936
+ await Promise.all(rounds);
937
+ }
938
+ async probe(harness) {
939
+ const probe = this.probes[harness];
940
+ const run = this.options.run ?? ((entry) => runProbe(entry));
941
+ let signIn;
942
+ try {
943
+ signIn = readProbe(probe, await run(probe), this.now());
944
+ } catch {
945
+ signIn = UNKNOWN;
946
+ }
947
+ const before = this.last.get(harness);
948
+ this.last.set(harness, signIn);
949
+ if (before?.auth !== signIn.auth || before.plan !== signIn.plan) {
950
+ this.options.changed?.(harness, signIn);
951
+ }
952
+ }
953
+ /**
954
+ * Looks at the setup terminals each heartbeat lists: probes again when
955
+ * one runs and 15 s have passed, or when one that ran has exited or gone.
956
+ */
957
+ observe(terminals) {
958
+ const running = new Set(
959
+ (terminals ?? []).filter((terminal) => !terminal.exit).map((terminal) => terminal.terminal)
960
+ );
961
+ const ended = [...this.runningSetup].some((id) => !running.has(id));
962
+ this.runningSetup = running;
963
+ if (ended || running.size > 0 && this.now() - this.lastStarted >= PROBE_SETUP_EVERY_MS) {
964
+ void this.refresh();
965
+ }
966
+ }
967
+ /** What the heartbeat reports: installed from PATH, auth and plan from the last probe. */
968
+ current() {
969
+ const installed = this.options.installed();
970
+ const harnesses = {};
971
+ for (const harness of Object.keys(this.probes)) {
972
+ const signIn = installed[harness] ? this.last.get(harness) : void 0;
973
+ harnesses[harness] = {
974
+ installed: installed[harness],
975
+ ...signIn ?? UNKNOWN
976
+ };
977
+ }
978
+ return harnesses;
979
+ }
980
+ }
818
981
  const DEFAULT_SLOTS = 2;
819
982
  function linkPaths(hostDirectory) {
820
983
  const state = path.resolve(hostDirectory, "..", "..");
@@ -843,15 +1006,12 @@ function onPath(command, pathVariable = process.env.PATH ?? "") {
843
1006
  (directory) => directory && existsSync(path.join(directory, command))
844
1007
  );
845
1008
  }
846
- function detectHarnesses() {
847
- const harnesses = {};
848
- for (const [harness, command] of Object.entries(HARNESS_COMMANDS)) {
849
- harnesses[harness] = {
850
- installed: onPath(command),
851
- auth: "unknown"
852
- };
853
- }
854
- return harnesses;
1009
+ function installedHarnesses(pathVariable = process.env.PATH ?? "") {
1010
+ return {
1011
+ claude: onPath(HARNESS_COMMANDS.claude, pathVariable),
1012
+ codex: onPath(HARNESS_COMMANDS.codex, pathVariable),
1013
+ cursor: onPath(HARNESS_COMMANDS.cursor, pathVariable)
1014
+ };
855
1015
  }
856
1016
  function describeMachine() {
857
1017
  const darwin = platform() === "darwin";
@@ -885,9 +1045,6 @@ async function collectReport(options) {
885
1045
  const access = options.access.heartbeat();
886
1046
  if (access) report.access = access;
887
1047
  if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
888
- if (options.activations && options.activations.length > 0) {
889
- report.activations = options.activations;
890
- }
891
1048
  if (options.worktrees) report.worktrees = options.worktrees;
892
1049
  if (options.releases && options.releases.length > 0) {
893
1050
  report.releases = options.releases;
@@ -911,20 +1068,11 @@ function buildHeartbeat(input) {
911
1068
  sessions: input.report.sessions,
912
1069
  acks: input.acks
913
1070
  };
914
- const {
915
- repos,
916
- access,
917
- features,
918
- setup_terminals,
919
- activations,
920
- worktrees,
921
- releases
922
- } = input.report;
1071
+ const { repos, access, features, setup_terminals, worktrees, releases } = input.report;
923
1072
  if (repos) heartbeat.repos = repos;
924
1073
  if (access) heartbeat.access = access;
925
1074
  if (features) heartbeat.features = features;
926
1075
  if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
927
- if (activations) heartbeat.activations = activations;
928
1076
  if (worktrees) heartbeat.worktrees = worktrees;
929
1077
  if (releases) heartbeat.releases = releases;
930
1078
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
@@ -1696,7 +1844,7 @@ class Poller {
1696
1844
  linkVersion: this.options.linkVersion,
1697
1845
  aibexdVersion: status.aibexdVersion,
1698
1846
  selfUpdate: status.selfUpdate,
1699
- harnesses: this.options.harnesses,
1847
+ harnesses: typeof this.options.harnesses === "function" ? this.options.harnesses() : this.options.harnesses,
1700
1848
  acks,
1701
1849
  diagnostics,
1702
1850
  report,
@@ -3520,12 +3668,8 @@ class SetupTerminals {
3520
3668
  }
3521
3669
  return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
3522
3670
  }
3523
- /** `<state>/bin` first, so `aibexd activate` resolves in a harness started here. */
3524
3671
  searchPath() {
3525
- const rest = (this.options.path ?? process.env.PATH ?? "").split(path.delimiter).filter(
3526
- (directory) => directory !== "" && directory !== this.options.binDirectory
3527
- );
3528
- return [this.options.binDirectory, ...rest].join(path.delimiter);
3672
+ return setupSearchPath(this.options.binDirectory, this.options.path);
3529
3673
  }
3530
3674
  /** Every setup terminal a host still keeps, running or exited. */
3531
3675
  async list() {
@@ -3566,6 +3710,10 @@ class SetupTerminals {
3566
3710
  return { kind: "home" };
3567
3711
  }
3568
3712
  }
3713
+ function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
3714
+ const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
3715
+ return [binDirectory, ...rest].join(path.delimiter);
3716
+ }
3569
3717
  function resolveProgram(file, searchPath) {
3570
3718
  if (file.includes("/")) return file;
3571
3719
  for (const directory of searchPath.split(path.delimiter)) {
@@ -3630,12 +3778,13 @@ function main() {
3630
3778
  const paths = linkPaths(hostDirectory);
3631
3779
  const access = new Access(paths.access);
3632
3780
  const repos = new Repos(paths.repos);
3633
- const activations = new Activations(hostDirectory);
3781
+ rmSync(path.join(hostDirectory, "activations.json"), { force: true });
3634
3782
  const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
3635
3783
  const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
3636
3784
  let poller;
3637
3785
  let sessions;
3638
3786
  let reaper;
3787
+ let statuses;
3639
3788
  if (identity) {
3640
3789
  sessions = new Sessions({
3641
3790
  paths,
@@ -3661,6 +3810,15 @@ function main() {
3661
3810
  log
3662
3811
  });
3663
3812
  const running = sessions;
3813
+ const probePath = setupSearchPath(path.join(paths.state, "bin"));
3814
+ const signIns = new HarnessStatuses({
3815
+ installed: () => installedHarnesses(),
3816
+ run: (probe) => runProbe(probe, { path: probePath }),
3817
+ changed: (harness, signIn) => log.line(
3818
+ `${harness}: ${signIn.auth}${signIn.plan ? ` (${signIn.plan})` : ""}`
3819
+ )
3820
+ });
3821
+ statuses = signIns;
3664
3822
  reaper = new Reaper({
3665
3823
  work: paths.work,
3666
3824
  reposConfig: paths.reposConfig,
@@ -3695,18 +3853,21 @@ function main() {
3695
3853
  log,
3696
3854
  handled: new HandledCommands(hostDirectory),
3697
3855
  status: () => status,
3698
- harnesses: detectHarnesses(),
3856
+ harnesses: () => signIns.current(),
3699
3857
  access,
3700
- report: async () => collectReport({
3701
- paths,
3702
- repos,
3703
- access,
3704
- features: ["sessions", "relay", "setup"],
3705
- sessions: running.list(),
3706
- setupTerminals: await setup.list(),
3707
- activations: activations.list(),
3708
- ...await reaping.report()
3709
- }),
3858
+ report: async () => {
3859
+ const setupTerminals = await setup.list();
3860
+ signIns.observe(setupTerminals);
3861
+ return collectReport({
3862
+ paths,
3863
+ repos,
3864
+ access,
3865
+ features: ["sessions", "relay", "setup"],
3866
+ sessions: running.list(),
3867
+ setupTerminals,
3868
+ ...await reaping.report()
3869
+ });
3870
+ },
3710
3871
  handleCommand: async (command) => {
3711
3872
  if (command.type === "relay.open") {
3712
3873
  await relay.open();
@@ -3725,7 +3886,6 @@ function main() {
3725
3886
  },
3726
3887
  afterPoll: async (answer) => {
3727
3888
  reaping.delivered();
3728
- activations.confirm(answer.activations_confirmed);
3729
3889
  await running.afterPoll(answer);
3730
3890
  },
3731
3891
  forward: (commandId, request) => send({ type: "control", commandId, request }),
@@ -3740,36 +3900,12 @@ function main() {
3740
3900
  `aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
3741
3901
  );
3742
3902
  }
3743
- const activate = (code) => {
3744
- if (!poller) {
3745
- return {
3746
- type: "activated",
3747
- code,
3748
- ok: false,
3749
- reason: "this machine has not joined a herd: run `aibexd join <key>` first"
3750
- };
3751
- }
3752
- if (!activations.add(code)) {
3753
- return {
3754
- type: "activated",
3755
- code,
3756
- ok: false,
3757
- reason: "not an activation code"
3758
- };
3759
- }
3760
- log.line(`activation ${code} taken; reporting it until the herd confirms`);
3761
- return { type: "activated", code, ok: true };
3762
- };
3763
3903
  process.on("message", (message) => {
3764
3904
  switch (message.type) {
3765
3905
  case "status": {
3766
3906
  status = message;
3767
3907
  break;
3768
3908
  }
3769
- case "activate": {
3770
- void send(activate(message.code));
3771
- break;
3772
- }
3773
3909
  case "diagnostics": {
3774
3910
  const mismatch = access.mismatch;
3775
3911
  poller?.attachDiagnostics({
@@ -3788,8 +3924,8 @@ function main() {
3788
3924
  });
3789
3925
  void send({ type: "ready" });
3790
3926
  setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
3791
- if (poller && sessions) {
3792
- const [started, recorded] = [poller, sessions];
3927
+ if (poller && sessions && statuses) {
3928
+ const [started, recorded, probed] = [poller, sessions, statuses];
3793
3929
  void (async () => {
3794
3930
  try {
3795
3931
  const checkouts = await repos.list();
@@ -3808,6 +3944,7 @@ function main() {
3808
3944
  } catch (error) {
3809
3945
  log.line(`could not pick up recorded sessions: ${String(error)}`);
3810
3946
  }
3947
+ await probed.start();
3811
3948
  started.start();
3812
3949
  })();
3813
3950
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
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": {