@aibexhq/aibex-link 0.0.9 → 0.0.11

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 +458 -117
  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,15 +1045,29 @@ 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;
894
1051
  }
895
1052
  return report;
896
1053
  }
1054
+ function parseLinkHealth(value) {
1055
+ if (typeof value !== "object" || value === null) return void 0;
1056
+ const { failures, rolled_back: rolledBack } = value;
1057
+ if (typeof failures !== "number" || !Number.isInteger(failures) || failures < 0) {
1058
+ return void 0;
1059
+ }
1060
+ if (rolledBack === void 0) return { failures };
1061
+ if (typeof rolledBack !== "object" || rolledBack === null) return void 0;
1062
+ const { from, to, at, reason } = rolledBack;
1063
+ if (typeof from !== "string" || typeof to !== "string" || typeof at !== "string" || !Number.isFinite(Date.parse(at)) || typeof reason !== "string") {
1064
+ return void 0;
1065
+ }
1066
+ return {
1067
+ failures,
1068
+ rolled_back: { from, to, at, reason: reason.slice(0, 500) }
1069
+ };
1070
+ }
897
1071
  function buildHeartbeat(input) {
898
1072
  const machine = describeMachine();
899
1073
  const heartbeat = {
@@ -911,22 +1085,14 @@ function buildHeartbeat(input) {
911
1085
  sessions: input.report.sessions,
912
1086
  acks: input.acks
913
1087
  };
914
- const {
915
- repos,
916
- access,
917
- features,
918
- setup_terminals,
919
- activations,
920
- worktrees,
921
- releases
922
- } = input.report;
1088
+ const { repos, access, features, setup_terminals, worktrees, releases } = input.report;
923
1089
  if (repos) heartbeat.repos = repos;
924
1090
  if (access) heartbeat.access = access;
925
1091
  if (features) heartbeat.features = features;
926
1092
  if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
927
- if (activations) heartbeat.activations = activations;
928
1093
  if (worktrees) heartbeat.worktrees = worktrees;
929
1094
  if (releases) heartbeat.releases = releases;
1095
+ if (input.linkHealth) heartbeat.link_health = input.linkHealth;
930
1096
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
931
1097
  return heartbeat;
932
1098
  }
@@ -1696,7 +1862,8 @@ class Poller {
1696
1862
  linkVersion: this.options.linkVersion,
1697
1863
  aibexdVersion: status.aibexdVersion,
1698
1864
  selfUpdate: status.selfUpdate,
1699
- harnesses: this.options.harnesses,
1865
+ linkHealth: status.linkHealth,
1866
+ harnesses: typeof this.options.harnesses === "function" ? this.options.harnesses() : this.options.harnesses,
1700
1867
  acks,
1701
1868
  diagnostics,
1702
1869
  report,
@@ -2289,10 +2456,11 @@ class Relay {
2289
2456
  const HARNESSES = {
2290
2457
  // The input box: a full-width rule, then `❯` and the placeholder. The
2291
2458
  // folder trust dialog also starts a line with `❯`, but never under a rule.
2459
+ // Claude Code 2.1.3xx puts a no-break space after `❯`.
2292
2460
  claude: {
2293
2461
  command: "claude",
2294
2462
  args: [],
2295
- ready: /─{20,}\n❯(?: |$)/mu,
2463
+ ready: /─{20,}\n❯(?:[ \u00A0]|$)/mu,
2296
2464
  multiline: "paste"
2297
2465
  },
2298
2466
  // The composer line `› Ask Codex to do anything`. The update notice, the
@@ -2364,6 +2532,142 @@ function reportedState(phase, hints) {
2364
2532
  }
2365
2533
  }
2366
2534
  }
2535
+ const REPLY_MAX = 16 * 1024;
2536
+ const REPLY_TRUNCATED = "[… earlier output cut]\n";
2537
+ const REPLY_SCROLLBACK = 2e3;
2538
+ const ESCAPES = (
2539
+ // eslint-disable-next-line no-control-regex
2540
+ /\u001B\[[0-?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B[@-Z\\-_]|[\u0000-\u0008\u000B-\u001F\u007F]/gu
2541
+ );
2542
+ const DRAWING = "─━═│┃║╭╮╰╯┌┐└┘├┤┬┴┼╔╗╚╝╠╣╦╩╬┄┅┈┉╌╍▀▄█▌▐▔▁░▒▓■▪";
2543
+ const DRAWING_ONLY = new RegExp(
2544
+ String.raw`^[\s${DRAWING}\-_=~]*[${DRAWING}][\s${DRAWING}\-_=~]*$`,
2545
+ "u"
2546
+ );
2547
+ const LABELLED_RULE = /^\s*[─━═]{2,}.*[─━═]{3,}\s*$/u;
2548
+ const BOX_SIDES = /^\s*[│┃║]\s?(.*?)\s*[│┃║]\s*$/u;
2549
+ const GUTTER = /^(\s*)([⏺●⎿│┃›❯>→▶•])(?: |$)/u;
2550
+ const CHROME = [
2551
+ /\b(?:esc|ctrl\+c) to (?:interrupt|cancel|stop)\b/iu,
2552
+ /^\s*[⠀-⣿]/u,
2553
+ /^\s*[✻✶✳✢✽✺✹✸✷◐◓◑◒◴◷◶◵]\s/u,
2554
+ /^\s*[·∗*]\s+\S+(?:…|\.\.\.)/u,
2555
+ /\?\s+for shortcuts/iu,
2556
+ /\bshift\+tab to\b/iu,
2557
+ /^\s*⏵⏵/u,
2558
+ /^\s*\d{1,2}:\d{2}(?::\d{2})?\s?(?:[AP]M)?\s*$/iu
2559
+ ];
2560
+ const INFORMATION_OPEN = "<aibexd-information>";
2561
+ const INFORMATION_CLOSE = "</aibexd-information>";
2562
+ function stripEscapes(text) {
2563
+ return text.replaceAll(ESCAPES, "").replaceAll(" ", " ");
2564
+ }
2565
+ function withoutGutter(line) {
2566
+ const match = GUTTER.exec(line);
2567
+ const indent = match?.[1] ?? "";
2568
+ if (!match || match[2] === "•" && indent !== "") return line;
2569
+ return indent + " ".repeat(match[0].length - indent.length) + line.slice(match[0].length);
2570
+ }
2571
+ function normalize(text) {
2572
+ return text.split("\n").map((line) => withoutGutter(stripEscapes(line))).join(" ").replaceAll(/\s+/gu, " ").trim();
2573
+ }
2574
+ function undecorate(text) {
2575
+ const kept = [];
2576
+ let inInformation = false;
2577
+ for (const raw of stripEscapes(text).split("\n")) {
2578
+ let line = raw.trimEnd();
2579
+ const sides = BOX_SIDES.exec(line);
2580
+ if (sides) line = sides[1] ?? "";
2581
+ line = withoutGutter(line).trimEnd();
2582
+ const bare = line.trim();
2583
+ if (inInformation) {
2584
+ if (bare.includes(INFORMATION_CLOSE)) inInformation = false;
2585
+ continue;
2586
+ }
2587
+ if (bare.startsWith(INFORMATION_OPEN)) {
2588
+ inInformation = !bare.includes(INFORMATION_CLOSE);
2589
+ continue;
2590
+ }
2591
+ if (bare === "") {
2592
+ kept.push("");
2593
+ continue;
2594
+ }
2595
+ if (DRAWING_ONLY.test(bare) || LABELLED_RULE.test(bare)) continue;
2596
+ if (CHROME.some((pattern) => pattern.test(bare))) continue;
2597
+ kept.push(line);
2598
+ }
2599
+ const lines = [];
2600
+ for (const line of kept) {
2601
+ if (line === "" && (lines.length === 0 || lines.at(-1) === "")) continue;
2602
+ lines.push(line);
2603
+ }
2604
+ while (lines.at(-1) === "") lines.pop();
2605
+ const indents = lines.filter((line) => line !== "").map((line) => /^ */u.exec(line)?.[0].length ?? 0);
2606
+ const indent = indents.length > 0 ? Math.min(...indents) : 0;
2607
+ return lines.map((line) => line.slice(indent)).join("\n");
2608
+ }
2609
+ function inputStart(text, ready) {
2610
+ const flags = ready.flags.includes("g") ? ready.flags : `${ready.flags}g`;
2611
+ let last = -1;
2612
+ for (const match of text.matchAll(new RegExp(ready.source, flags))) {
2613
+ last = match.index;
2614
+ }
2615
+ if (last === -1) return text.length;
2616
+ return text.lastIndexOf("\n", last - 1) + 1;
2617
+ }
2618
+ const PROMPT_PREFIX = /^\S{0,12}[>›❯$%#:→] ?/u;
2619
+ function echoed(line, typed) {
2620
+ const prefix = PROMPT_PREFIX.exec(line);
2621
+ if (!prefix) return line;
2622
+ const rest = line.slice(prefix[0].length);
2623
+ const length = Math.min(rest.length, typed.length);
2624
+ return length > 0 && rest.slice(0, length) === typed.slice(0, length) ? rest : line;
2625
+ }
2626
+ function afterEcho(lines, sent) {
2627
+ const typed = normalize(sent);
2628
+ if (typed === "") return void 0;
2629
+ const shortest = Math.min(typed.length, 8);
2630
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
2631
+ const line = echoed(normalize(lines[index] ?? ""), typed);
2632
+ if (line.length < shortest) continue;
2633
+ const length = Math.min(line.length, typed.length);
2634
+ if (line.slice(0, length) !== typed.slice(0, length)) continue;
2635
+ if (typed.length < 8 && line !== typed) continue;
2636
+ let echo = line;
2637
+ let next = index + 1;
2638
+ while (next < lines.length && echo.length < typed.length) {
2639
+ const more = normalize(lines[next] ?? "");
2640
+ if (more === "") {
2641
+ next += 1;
2642
+ continue;
2643
+ }
2644
+ if (typed.startsWith(`${echo} ${more}`)) echo = `${echo} ${more}`;
2645
+ else if (typed.startsWith(`${echo}${more}`)) echo += more;
2646
+ else break;
2647
+ next += 1;
2648
+ }
2649
+ return next;
2650
+ }
2651
+ return void 0;
2652
+ }
2653
+ const PASTE_PLACEHOLDER = /\[Pasted[^\]]*\]/u;
2654
+ function extractReply(screen, options) {
2655
+ const text = stripEscapes(screen);
2656
+ const above = text.slice(0, inputStart(text, options.ready));
2657
+ const lines = above.split("\n");
2658
+ let start = afterEcho(lines, options.sent);
2659
+ if (start === void 0) {
2660
+ const placeholder = lines.findLastIndex(
2661
+ (line) => PASTE_PLACEHOLDER.test(line)
2662
+ );
2663
+ start = placeholder === -1 ? 0 : placeholder + 1;
2664
+ }
2665
+ const reply = undecorate(lines.slice(start).join("\n"));
2666
+ if (reply.length <= REPLY_MAX) return reply;
2667
+ const tail = reply.slice(reply.length - (REPLY_MAX - REPLY_TRUNCATED.length));
2668
+ const newline = tail.indexOf("\n");
2669
+ return `${REPLY_TRUNCATED}${newline === -1 ? tail : tail.slice(newline + 1)}`;
2670
+ }
2367
2671
  const MAX_CHUNK_BYTES = 1024 * 1024;
2368
2672
  class Transcript {
2369
2673
  constructor(spoolFile, state) {
@@ -2691,7 +2995,11 @@ class Session {
2691
2995
  }
2692
2996
  case "idle": {
2693
2997
  this.busy = false;
2998
+ const was = this.activity;
2694
2999
  this.activity = "idle";
3000
+ if (was === "working" && this.phase === "running") {
3001
+ void this.captureReply();
3002
+ }
2695
3003
  break;
2696
3004
  }
2697
3005
  case "title": {
@@ -2781,6 +3089,7 @@ class Session {
2781
3089
  });
2782
3090
  if (!pressed.ok || !this.live(client)) return;
2783
3091
  this.record.queue.shift();
3092
+ this.record.last_sent = text;
2784
3093
  const first = !this.record.prompted;
2785
3094
  this.record.prompted = true;
2786
3095
  this.lastSendAt = this.manager.now();
@@ -2792,6 +3101,38 @@ class Session {
2792
3101
  `${this.record.thread_id}: ${first ? "typed the prompt" : "typed a follow-up"} into ${this.record.harness}`
2793
3102
  );
2794
3103
  }
3104
+ /**
3105
+ * On each move from working to idle: the screen below the last text typed
3106
+ * in, undecorated, as a `reply` event, unless it is empty or the same as
3107
+ * the last reply. A screen without the ready marker (a dialog) waits for
3108
+ * the next idle.
3109
+ */
3110
+ async captureReply() {
3111
+ const client = this.client;
3112
+ const sent = this.record.last_sent;
3113
+ if (!client || sent === void 0 || this.fenced) return;
3114
+ const snapshot = await client.request({
3115
+ type: "snapshot",
3116
+ terminal: this.record.terminal,
3117
+ lines: REPLY_SCROLLBACK
3118
+ });
3119
+ if (!snapshot.ok || this.client !== client || this.phase !== "running" || this.record.last_sent !== sent || !this.harness.ready.test(String(snapshot.text))) {
3120
+ return;
3121
+ }
3122
+ const text = extractReply(String(snapshot.all ?? snapshot.text), {
3123
+ sent,
3124
+ ready: this.harness.ready
3125
+ });
3126
+ if (text === "") return;
3127
+ const hash = createHash("sha256").update(text).digest("base64url");
3128
+ if (hash === this.record.reply_hash) return;
3129
+ this.record.reply_hash = hash;
3130
+ this.manager.event(this, {
3131
+ type: "reply",
3132
+ text,
3133
+ ...text.startsWith(REPLY_TRUNCATED) ? { truncated: true } : {}
3134
+ });
3135
+ }
2795
3136
  /** A title becomes a `status` event, at most one per interval, the latest winning. */
2796
3137
  setStatus(text) {
2797
3138
  const status = text.trim().slice(0, STATUS_MAX);
@@ -3520,12 +3861,8 @@ class SetupTerminals {
3520
3861
  }
3521
3862
  return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
3522
3863
  }
3523
- /** `<state>/bin` first, so `aibexd activate` resolves in a harness started here. */
3524
3864
  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);
3865
+ return setupSearchPath(this.options.binDirectory, this.options.path);
3529
3866
  }
3530
3867
  /** Every setup terminal a host still keeps, running or exited. */
3531
3868
  async list() {
@@ -3566,6 +3903,10 @@ class SetupTerminals {
3566
3903
  return { kind: "home" };
3567
3904
  }
3568
3905
  }
3906
+ function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
3907
+ const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
3908
+ return [binDirectory, ...rest].join(path.delimiter);
3909
+ }
3569
3910
  function resolveProgram(file, searchPath) {
3570
3911
  if (file.includes("/")) return file;
3571
3912
  for (const directory of searchPath.split(path.delimiter)) {
@@ -3602,6 +3943,13 @@ function initialSelfUpdate() {
3602
3943
  }
3603
3944
  return { can: true, reason: null };
3604
3945
  }
3946
+ function initialLinkHealth() {
3947
+ try {
3948
+ return parseLinkHealth(JSON.parse(process.env.AIBEX_LINK_HEALTH ?? ""));
3949
+ } catch {
3950
+ return void 0;
3951
+ }
3952
+ }
3605
3953
  function main() {
3606
3954
  const info = readPackageInfo();
3607
3955
  if (process.argv.includes("--self-test")) {
@@ -3624,18 +3972,20 @@ function main() {
3624
3972
  let status = {
3625
3973
  type: "status",
3626
3974
  aibexdVersion: process.env.AIBEX_AIBEXD_VERSION ?? "unknown",
3627
- selfUpdate: initialSelfUpdate()
3975
+ selfUpdate: initialSelfUpdate(),
3976
+ linkHealth: initialLinkHealth()
3628
3977
  };
3629
3978
  const identity = readIdentity(hostDirectory);
3630
3979
  const paths = linkPaths(hostDirectory);
3631
3980
  const access = new Access(paths.access);
3632
3981
  const repos = new Repos(paths.repos);
3633
- const activations = new Activations(hostDirectory);
3982
+ rmSync(path.join(hostDirectory, "activations.json"), { force: true });
3634
3983
  const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
3635
3984
  const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
3636
3985
  let poller;
3637
3986
  let sessions;
3638
3987
  let reaper;
3988
+ let statuses;
3639
3989
  if (identity) {
3640
3990
  sessions = new Sessions({
3641
3991
  paths,
@@ -3661,6 +4011,15 @@ function main() {
3661
4011
  log
3662
4012
  });
3663
4013
  const running = sessions;
4014
+ const probePath = setupSearchPath(path.join(paths.state, "bin"));
4015
+ const signIns = new HarnessStatuses({
4016
+ installed: () => installedHarnesses(),
4017
+ run: (probe) => runProbe(probe, { path: probePath }),
4018
+ changed: (harness, signIn) => log.line(
4019
+ `${harness}: ${signIn.auth}${signIn.plan ? ` (${signIn.plan})` : ""}`
4020
+ )
4021
+ });
4022
+ statuses = signIns;
3664
4023
  reaper = new Reaper({
3665
4024
  work: paths.work,
3666
4025
  reposConfig: paths.reposConfig,
@@ -3695,18 +4054,21 @@ function main() {
3695
4054
  log,
3696
4055
  handled: new HandledCommands(hostDirectory),
3697
4056
  status: () => status,
3698
- harnesses: detectHarnesses(),
4057
+ harnesses: () => signIns.current(),
3699
4058
  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
- }),
4059
+ report: async () => {
4060
+ const setupTerminals = await setup.list();
4061
+ signIns.observe(setupTerminals);
4062
+ return collectReport({
4063
+ paths,
4064
+ repos,
4065
+ access,
4066
+ features: ["sessions", "relay", "setup"],
4067
+ sessions: running.list(),
4068
+ setupTerminals,
4069
+ ...await reaping.report()
4070
+ });
4071
+ },
3710
4072
  handleCommand: async (command) => {
3711
4073
  if (command.type === "relay.open") {
3712
4074
  await relay.open();
@@ -3725,7 +4087,6 @@ function main() {
3725
4087
  },
3726
4088
  afterPoll: async (answer) => {
3727
4089
  reaping.delivered();
3728
- activations.confirm(answer.activations_confirmed);
3729
4090
  await running.afterPoll(answer);
3730
4091
  },
3731
4092
  forward: (commandId, request) => send({ type: "control", commandId, request }),
@@ -3740,34 +4101,13 @@ function main() {
3740
4101
  `aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
3741
4102
  );
3742
4103
  }
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
4104
  process.on("message", (message) => {
3764
4105
  switch (message.type) {
3765
4106
  case "status": {
3766
- status = message;
3767
- break;
3768
- }
3769
- case "activate": {
3770
- void send(activate(message.code));
4107
+ status = {
4108
+ ...message,
4109
+ linkHealth: parseLinkHealth(message.linkHealth) ?? status.linkHealth
4110
+ };
3771
4111
  break;
3772
4112
  }
3773
4113
  case "diagnostics": {
@@ -3788,8 +4128,8 @@ function main() {
3788
4128
  });
3789
4129
  void send({ type: "ready" });
3790
4130
  setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
3791
- if (poller && sessions) {
3792
- const [started, recorded] = [poller, sessions];
4131
+ if (poller && sessions && statuses) {
4132
+ const [started, recorded, probed] = [poller, sessions, statuses];
3793
4133
  void (async () => {
3794
4134
  try {
3795
4135
  const checkouts = await repos.list();
@@ -3808,6 +4148,7 @@ function main() {
3808
4148
  } catch (error) {
3809
4149
  log.line(`could not pick up recorded sessions: ${String(error)}`);
3810
4150
  }
4151
+ await probed.start();
3811
4152
  started.start();
3812
4153
  })();
3813
4154
  }
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.11",
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": {