@aibexhq/aibex-link 0.0.5 → 0.0.6

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.
package/dist/index.js CHANGED
@@ -1,24 +1,10 @@
1
- import { randomBytes } from "node:crypto";
2
- import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync } from "node:fs";
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
3
  import path from "node:path";
4
- import { platform, arch, release } from "node:os";
4
+ import { platform, arch, release, homedir } from "node:os";
5
5
  import { fileURLToPath } from "node:url";
6
- const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
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) {
10
- const raw = env.AIBEX_TIMINGS;
11
- if (!raw) return fallback;
12
- try {
13
- const value = JSON.parse(raw)[key];
14
- return typeof value === "number" && value > 0 ? value : fallback;
15
- } catch {
16
- return fallback;
17
- }
18
- }
19
- function aliveIntervalMs(env = process.env) {
20
- return timing("aliveIntervalMs", DEFAULT_ALIVE_INTERVAL_MS, env);
21
- }
6
+ import { createConnection } from "node:net";
7
+ import { execFile } from "node:child_process";
22
8
  const encoder = new TextEncoder();
23
9
  function utf8(text) {
24
10
  return new Uint8Array(encoder.encode(text));
@@ -438,6 +424,24 @@ function responseComponents(requestSigned) {
438
424
  }
439
425
  return components;
440
426
  }
427
+ const PROBLEMS = {
428
+ "invalid-request": { status: 400, title: "The request does not match the protocol" },
429
+ "join-key-invalid": { status: 401, title: "The join key is unknown, spent or expired" },
430
+ "machine-present": { status: 409, title: "That machine is still present; it can only be resumed once it is offline" },
431
+ "signature-invalid": { status: 401, title: "The request signature does not verify" },
432
+ "signature-expired": { status: 401, title: "The request signature was created too long ago or in the future" },
433
+ "nonce-reused": { status: 401, title: "The request nonce was already used" },
434
+ "lease-fenced": { status: 409, title: "The lease is from an older epoch; stop the session and write nothing more for it" },
435
+ "transcript-offset": { status: 409, title: "The append does not start where the transcript ends; next_offset says where it does" }
436
+ };
437
+ const PROBLEM_BASE = "https://aibex.com/problems/";
438
+ function problemName(value) {
439
+ if (typeof value.type !== "string" || !value.type.startsWith(PROBLEM_BASE)) {
440
+ return void 0;
441
+ }
442
+ const name = value.type.slice(PROBLEM_BASE.length);
443
+ return name in PROBLEMS ? name : void 0;
444
+ }
441
445
  function randomNonce() {
442
446
  return toBase64Url(crypto.getRandomValues(new Uint8Array(16)));
443
447
  }
@@ -492,6 +496,49 @@ async function verifyResponse(options) {
492
496
  return false;
493
497
  }
494
498
  }
499
+ function isRecord$1(value) {
500
+ return typeof value === "object" && value !== null && !Array.isArray(value);
501
+ }
502
+ async function openEnvelope(envelope, trust) {
503
+ if (!isRecord$1(envelope) || typeof envelope.signer !== "string" || typeof envelope.key_id !== "string" || typeof envelope.payload !== "string" || typeof envelope.signature !== "string") {
504
+ return { ok: false, reason: "malformed" };
505
+ }
506
+ const { signer, key_id: keyId } = envelope;
507
+ const key = trust.keys.find(
508
+ (candidate) => candidate.principal === signer && candidate.keyId === keyId
509
+ );
510
+ if (!key) return { ok: false, reason: "unknown-key" };
511
+ let bytes;
512
+ let verified = false;
513
+ try {
514
+ bytes = fromBase64Url(envelope.payload);
515
+ verified = await verifyBytes(
516
+ await importSignPublicKey(key.publicKey),
517
+ fromBase64Url(envelope.signature),
518
+ bytes
519
+ );
520
+ } catch {
521
+ return { ok: false, reason: "bad-signature" };
522
+ }
523
+ if (!verified) return { ok: false, reason: "bad-signature" };
524
+ let payload;
525
+ try {
526
+ payload = JSON.parse(
527
+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes)
528
+ );
529
+ } catch {
530
+ return { ok: false, reason: "malformed" };
531
+ }
532
+ if (!isRecord$1(payload)) return { ok: false, reason: "malformed" };
533
+ if (trust.accept.includes(signer)) {
534
+ return { ok: true, payload, signer, requester: signer };
535
+ }
536
+ const requester = typeof payload.requester === "string" ? payload.requester : payload.from;
537
+ if (trust.integrations.includes(signer) && typeof requester === "string" && trust.accept.includes(requester)) {
538
+ return { ok: true, payload, signer, requester };
539
+ }
540
+ return { ok: false, reason: "not-accepted" };
541
+ }
495
542
  function isRecord(value) {
496
543
  return typeof value === "object" && value !== null;
497
544
  }
@@ -500,7 +547,7 @@ function isKeyPair(value) {
500
547
  }
501
548
  function parseIdentity(value) {
502
549
  if (!isRecord(value) || value.version !== 1) return void 0;
503
- const strings = [
550
+ const strings2 = [
504
551
  "host",
505
552
  "machine_id",
506
553
  "herd_id",
@@ -510,7 +557,7 @@ function parseIdentity(value) {
510
557
  "next_join_key",
511
558
  "joined_at"
512
559
  ];
513
- if (strings.some((key) => typeof value[key] !== "string")) return void 0;
560
+ if (strings2.some((key) => typeof value[key] !== "string")) return void 0;
514
561
  if (!isRecord(value.certificate) || !isRecord(value.keys)) return void 0;
515
562
  if (!isKeyPair(value.keys.sign) || !isKeyPair(value.keys.encrypt)) {
516
563
  return void 0;
@@ -562,6 +609,113 @@ function writeJsonAtomic(file, value, mode = 384) {
562
609
  function readIdentity(hostDirectory) {
563
610
  return parseIdentity(readJson(path.join(hostDirectory, IDENTITY_FILE)));
564
611
  }
612
+ const DASHBOARD = "app:dashboard";
613
+ const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
614
+ function parseAccess(value) {
615
+ if (typeof value !== "object" || value === null) return void 0;
616
+ const record = value;
617
+ const accept = strings(record.accept);
618
+ const integrations = strings(record.integrations ?? []);
619
+ const keys = Array.isArray(record.keys) ? record.keys : void 0;
620
+ if (!accept || !integrations || !keys) return void 0;
621
+ const parsed = [];
622
+ for (const key of keys) {
623
+ const entry = key;
624
+ if (typeof entry?.principal !== "string" || typeof entry.key_id !== "string" || typeof entry.public_key !== "string") {
625
+ return void 0;
626
+ }
627
+ parsed.push({
628
+ principal: entry.principal,
629
+ key_id: entry.key_id,
630
+ public_key: entry.public_key
631
+ });
632
+ }
633
+ return { accept, integrations, keys: parsed };
634
+ }
635
+ function compare(file, trust) {
636
+ const problems = [];
637
+ if (!file.accept.includes(trust.owner)) {
638
+ problems.push(`the herd owner ${trust.owner} is not accepted`);
639
+ }
640
+ const pinned = file.keys.some(
641
+ (key) => key.principal === DASHBOARD && key.key_id === trust.dashboard.key_id && key.public_key === trust.dashboard.public_key
642
+ );
643
+ if (!pinned) {
644
+ problems.push(
645
+ `the dashboard key ${trust.dashboard.key_id} is not the pinned one`
646
+ );
647
+ }
648
+ return problems.length > 0 ? problems.join(", and ") : void 0;
649
+ }
650
+ class Access {
651
+ constructor(file, now = Date.now) {
652
+ this.file = file;
653
+ this.now = now;
654
+ }
655
+ /** Why the herd's latest `trust` is not what the file trusts, if it is not. */
656
+ mismatch;
657
+ read() {
658
+ return parseAccess(readJson(this.file));
659
+ }
660
+ /** Pins `trust` when there is no file yet, else compares it with the file. */
661
+ observe(trust) {
662
+ if (trust === void 0) return;
663
+ if (!existsSync(this.file)) {
664
+ writeJsonAtomic(this.file, {
665
+ accept: [trust.owner],
666
+ integrations: [DASHBOARD],
667
+ keys: [
668
+ {
669
+ principal: DASHBOARD,
670
+ key_id: trust.dashboard.key_id,
671
+ public_key: trust.dashboard.public_key
672
+ }
673
+ ],
674
+ pinned_at: new Date(this.now()).toISOString()
675
+ });
676
+ this.mismatch = void 0;
677
+ return;
678
+ }
679
+ const file = this.read();
680
+ this.mismatch = file ? compare(file, trust) : "access.json cannot be read, so no work is accepted";
681
+ }
682
+ /** Verifies an envelope against the file; nothing opens without one. */
683
+ open(envelope) {
684
+ const file = this.read();
685
+ const trust = file ? {
686
+ accept: file.accept,
687
+ integrations: file.integrations,
688
+ keys: file.keys.map((key) => ({
689
+ principal: key.principal,
690
+ keyId: key.key_id,
691
+ publicKey: key.public_key
692
+ }))
693
+ } : { accept: [], integrations: [], keys: [] };
694
+ return openEnvelope(envelope, trust);
695
+ }
696
+ /** The heartbeat's FYI copy of the file. */
697
+ heartbeat() {
698
+ const file = this.read();
699
+ if (!file) return void 0;
700
+ return { accept: file.accept, integrations: file.integrations };
701
+ }
702
+ }
703
+ const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
704
+ const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
705
+ const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
706
+ function timing(key, fallback, env = process.env) {
707
+ const raw = env.AIBEX_TIMINGS;
708
+ if (!raw) return fallback;
709
+ try {
710
+ const value = JSON.parse(raw)[key];
711
+ return typeof value === "number" && value > 0 ? value : fallback;
712
+ } catch {
713
+ return fallback;
714
+ }
715
+ }
716
+ function aliveIntervalMs(env = process.env) {
717
+ return timing("aliveIntervalMs", DEFAULT_ALIVE_INTERVAL_MS, env);
718
+ }
565
719
  const REMEMBER_MS = 60 * 6e4;
566
720
  class HandledCommands {
567
721
  constructor(hostDirectory, now = Date.now) {
@@ -616,6 +770,24 @@ class HandledCommands {
616
770
  writeJsonAtomic(this.file, this.stored);
617
771
  }
618
772
  }
773
+ const DEFAULT_SLOTS = 2;
774
+ function linkPaths(hostDirectory) {
775
+ const state = path.resolve(hostDirectory, "..", "..");
776
+ return {
777
+ hostDirectory,
778
+ state,
779
+ repos: path.join(state, "repos"),
780
+ work: path.join(state, "work"),
781
+ reposConfig: path.join(state, "repos.json"),
782
+ config: path.join(state, "config.json"),
783
+ access: path.join(hostDirectory, "access.json")
784
+ };
785
+ }
786
+ function configuredSlots(paths) {
787
+ const value = readJson(paths.config);
788
+ const slots = value?.slots;
789
+ return typeof slots === "number" && Number.isInteger(slots) && slots >= 0 && slots <= 64 ? slots : DEFAULT_SLOTS;
790
+ }
619
791
  const HARNESS_COMMANDS = {
620
792
  claude: "claude",
621
793
  codex: "codex",
@@ -647,6 +819,29 @@ function describeMachine() {
647
819
  }
648
820
  };
649
821
  }
822
+ const EMPTY_REPORT = {
823
+ capacity: { slots_total: 0, slots_free: 0 },
824
+ sessions: []
825
+ };
826
+ async function collectReport(options) {
827
+ const sessions = options.sessions ?? [];
828
+ const slots = configuredSlots(options.paths);
829
+ const running = sessions.filter((session) => session.state !== "ended");
830
+ const checkouts = await options.repos.list();
831
+ const report = {
832
+ repos: checkouts.map((checkout) => checkout.repo),
833
+ capacity: {
834
+ slots_total: slots,
835
+ slots_free: Math.max(0, slots - running.length)
836
+ },
837
+ sessions,
838
+ features: options.features
839
+ };
840
+ const access = options.access.heartbeat();
841
+ if (access) report.access = access;
842
+ if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
843
+ return report;
844
+ }
650
845
  function buildHeartbeat(input) {
651
846
  const machine = describeMachine();
652
847
  const heartbeat = {
@@ -660,10 +855,15 @@ function buildHeartbeat(input) {
660
855
  runner: machine.runner,
661
856
  os: machine.os,
662
857
  harnesses: input.harnesses,
663
- capacity: { slots_total: 0, slots_free: 0 },
664
- sessions: [],
858
+ capacity: input.report.capacity,
859
+ sessions: input.report.sessions,
665
860
  acks: input.acks
666
861
  };
862
+ const { repos, access, features, setup_terminals } = input.report;
863
+ if (repos) heartbeat.repos = repos;
864
+ if (access) heartbeat.access = access;
865
+ if (features) heartbeat.features = features;
866
+ if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
667
867
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
668
868
  return heartbeat;
669
869
  }
@@ -696,6 +896,62 @@ function readPackageInfo() {
696
896
  }
697
897
  return { name: manifest.name, version: manifest.version };
698
898
  }
899
+ class HerdClient {
900
+ constructor(identity, fetchImpl = fetch) {
901
+ this.identity = identity;
902
+ this.fetchImpl = fetchImpl;
903
+ }
904
+ /** The headers that sign a request, as a poll is signed. */
905
+ async sign(method, url, body) {
906
+ return signRequest({
907
+ method,
908
+ url,
909
+ body,
910
+ herdId: this.identity.herd_id,
911
+ machineId: this.identity.machine_id,
912
+ privateKey: await importSignPrivateKey(this.identity.keys.sign.private)
913
+ });
914
+ }
915
+ async post(pathname, value) {
916
+ const url = new URL(pathname, this.identity.host).href;
917
+ const body = JSON.stringify(value);
918
+ let headers;
919
+ let response;
920
+ let text;
921
+ try {
922
+ headers = await this.sign("POST", url, body);
923
+ response = await this.fetchImpl(url, {
924
+ method: "POST",
925
+ headers,
926
+ body,
927
+ signal: AbortSignal.timeout(3e4)
928
+ });
929
+ text = await response.text();
930
+ } catch (error) {
931
+ return {
932
+ ok: false,
933
+ reason: error instanceof Error ? error.message : String(error)
934
+ };
935
+ }
936
+ const verified = await verifyResponse({
937
+ response: { status: response.status, headers: response.headers },
938
+ body: text,
939
+ request: { method: "POST", url, headers },
940
+ publicKey: this.identity.server_public_key
941
+ });
942
+ if (!verified) {
943
+ return {
944
+ ok: false,
945
+ reason: `HTTP ${response.status}, not signed by the herd's server key`
946
+ };
947
+ }
948
+ try {
949
+ return { ok: true, status: response.status, body: JSON.parse(text) };
950
+ } catch {
951
+ return { ok: false, reason: "the answer is not JSON" };
952
+ }
953
+ }
954
+ }
699
955
  const DEFAULT_INTERVAL_MS = 1e4;
700
956
  const MIN_INTERVAL_MS = 1e3;
701
957
  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-]+)*)?$/;
@@ -763,6 +1019,14 @@ class Poller {
763
1019
  const acks = handled.unacked();
764
1020
  const diagnostics = this.diagnostics;
765
1021
  const status = this.options.status();
1022
+ let report = EMPTY_REPORT;
1023
+ try {
1024
+ report = await this.options.report?.() ?? EMPTY_REPORT;
1025
+ } catch (error) {
1026
+ this.options.log.line(
1027
+ `could not collect the heartbeat report: ${error instanceof Error ? error.message : String(error)}`
1028
+ );
1029
+ }
766
1030
  const body = JSON.stringify(
767
1031
  buildHeartbeat({
768
1032
  machineId: identity.machine_id,
@@ -772,6 +1036,7 @@ class Poller {
772
1036
  harnesses: this.options.harnesses,
773
1037
  acks,
774
1038
  diagnostics,
1039
+ report,
775
1040
  now: this.now()
776
1041
  })
777
1042
  );
@@ -834,12 +1099,34 @@ class Poller {
834
1099
  MIN_INTERVAL_MS,
835
1100
  answer.next_poll_after_ms || DEFAULT_INTERVAL_MS
836
1101
  );
1102
+ const access = this.options.access;
1103
+ if (access) {
1104
+ const before = access.mismatch;
1105
+ try {
1106
+ access.observe(answer.trust);
1107
+ } catch (error) {
1108
+ access.mismatch = `access.json could not be written: ${error instanceof Error ? error.message : String(error)}`;
1109
+ }
1110
+ if (access.mismatch !== void 0 && access.mismatch !== before) {
1111
+ this.options.log.line(
1112
+ `the herd's trust does not match access.json: ${access.mismatch}; work it signs is refused`
1113
+ );
1114
+ }
1115
+ }
837
1116
  this.recordPoll({
838
1117
  lastPollAt: new Date(this.now()).toISOString(),
839
1118
  machineState: answer.machine_state,
840
- lastError: null
1119
+ lastError: null,
1120
+ trustMismatch: access?.mismatch ?? null
841
1121
  });
842
1122
  for (const command of answer.commands) await this.handle(command);
1123
+ try {
1124
+ await this.options.afterPoll?.(answer);
1125
+ } catch (error) {
1126
+ this.options.log.line(
1127
+ `after the poll: ${error instanceof Error ? error.message : String(error)}`
1128
+ );
1129
+ }
843
1130
  return { kind: "ok", waitMs: this.intervalMs, response: answer };
844
1131
  }
845
1132
  async handle(command) {
@@ -850,6 +1137,21 @@ class Poller {
850
1137
  return;
851
1138
  }
852
1139
  const request = controlRequest(command);
1140
+ if (request === void 0 && this.options.handleCommand) {
1141
+ handled.record(id);
1142
+ try {
1143
+ if (await this.options.handleCommand(command)) return;
1144
+ } catch (error) {
1145
+ log.line(
1146
+ `${command.type} (${id}) failed: ${error instanceof Error ? error.message : String(error)}`
1147
+ );
1148
+ return;
1149
+ }
1150
+ log.line(
1151
+ `unknown command type ${command.type} (${id}); acked and ignored`
1152
+ );
1153
+ return;
1154
+ }
853
1155
  if (request === void 0) {
854
1156
  handled.record(id);
855
1157
  log.line(
@@ -874,93 +1176,1638 @@ class Poller {
874
1176
  }
875
1177
  }
876
1178
  }
877
- function send(message) {
878
- return new Promise((resolve) => {
879
- if (!process.send) {
880
- resolve(false);
881
- return;
1179
+ const MAX_SOCKET_PATH_BYTES = 100;
1180
+ function socketAddress(socketFile) {
1181
+ if (Buffer.byteLength(socketFile) <= MAX_SOCKET_PATH_BYTES) return socketFile;
1182
+ process.chdir(path.dirname(socketFile));
1183
+ return path.basename(socketFile);
1184
+ }
1185
+ const ENDING = /* @__PURE__ */ new Set(["exit", "removed", "dropped"]);
1186
+ class HostClient {
1187
+ constructor(socketFile, socket) {
1188
+ this.socketFile = socketFile;
1189
+ this.socket = socket;
1190
+ socket.setEncoding("utf8");
1191
+ socket.on("data", (chunk) => this.read(chunk));
1192
+ socket.on("close", () => this.end());
1193
+ socket.on("error", () => this.end());
1194
+ }
1195
+ buffer = "";
1196
+ nextId = 1;
1197
+ replies = /* @__PURE__ */ new Map();
1198
+ listeners = /* @__PURE__ */ new Map();
1199
+ closeListeners = [];
1200
+ closed = false;
1201
+ static connect(socketFile, timeoutMs = 2e3) {
1202
+ return new Promise((resolve, reject) => {
1203
+ let socket;
1204
+ try {
1205
+ socket = createConnection(socketAddress(socketFile));
1206
+ } catch (error) {
1207
+ reject(error instanceof Error ? error : new Error(String(error)));
1208
+ return;
1209
+ }
1210
+ const timer = setTimeout(() => {
1211
+ socket.destroy();
1212
+ reject(new Error(`${socketFile} did not answer`));
1213
+ }, timeoutMs);
1214
+ socket.once("connect", () => {
1215
+ clearTimeout(timer);
1216
+ resolve(new HostClient(socketFile, socket));
1217
+ });
1218
+ socket.once("error", (error) => {
1219
+ clearTimeout(timer);
1220
+ reject(error);
1221
+ });
1222
+ });
1223
+ }
1224
+ read(chunk) {
1225
+ this.buffer += chunk;
1226
+ let newline;
1227
+ while ((newline = this.buffer.indexOf("\n")) !== -1) {
1228
+ const line = this.buffer.slice(0, newline);
1229
+ this.buffer = this.buffer.slice(newline + 1);
1230
+ let message;
1231
+ try {
1232
+ message = JSON.parse(line);
1233
+ } catch {
1234
+ continue;
1235
+ }
1236
+ const id = message.id;
1237
+ if ("ok" in message) {
1238
+ const resolve = this.replies.get(id);
1239
+ this.replies.delete(id);
1240
+ if (message.ok !== true) this.listeners.delete(id);
1241
+ resolve?.(message);
1242
+ } else if (typeof message.event === "string") {
1243
+ this.listeners.get(id)?.(message);
1244
+ if (ENDING.has(message.event) && message.event !== "exit") {
1245
+ this.listeners.delete(id);
1246
+ }
1247
+ }
882
1248
  }
883
- process.send(message, void 0, {}, (error) => resolve(error === null));
884
- });
1249
+ }
1250
+ end() {
1251
+ if (this.closed) return;
1252
+ this.closed = true;
1253
+ const failed = {
1254
+ ok: false,
1255
+ error: { code: "closed", message: "the terminal host connection closed" }
1256
+ };
1257
+ for (const resolve of this.replies.values()) resolve(failed);
1258
+ this.replies.clear();
1259
+ this.listeners.clear();
1260
+ for (const listener of this.closeListeners.splice(0)) listener();
1261
+ }
1262
+ /** Sends one request (without an id) and resolves with its reply. */
1263
+ request(body) {
1264
+ return this.subscribe(body);
1265
+ }
1266
+ /** Sends an `attach` or `watch` and hands its events to `onEvent`. */
1267
+ subscribe(body, onEvent) {
1268
+ if (this.closed) {
1269
+ return Promise.resolve({
1270
+ ok: false,
1271
+ error: {
1272
+ code: "closed",
1273
+ message: "the terminal host connection closed"
1274
+ }
1275
+ });
1276
+ }
1277
+ const id = this.nextId++;
1278
+ if (onEvent) this.listeners.set(id, onEvent);
1279
+ return new Promise((resolve) => {
1280
+ this.replies.set(id, resolve);
1281
+ this.socket.write(`${JSON.stringify({ ...body, id })}
1282
+ `);
1283
+ });
1284
+ }
1285
+ onClose(listener) {
1286
+ if (this.closed) listener();
1287
+ else this.closeListeners.push(listener);
1288
+ }
1289
+ close() {
1290
+ this.socket.destroy();
1291
+ this.end();
1292
+ }
885
1293
  }
886
- function initialSelfUpdate() {
1294
+ async function requestOnce(socketFile, body) {
1295
+ let client;
887
1296
  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
- };
1297
+ client = await HostClient.connect(socketFile);
1298
+ } catch (error) {
1299
+ return {
1300
+ ok: false,
1301
+ error: { code: "closed", message: error.message }
1302
+ };
1303
+ }
1304
+ try {
1305
+ return await client.request(body);
1306
+ } finally {
1307
+ client.close();
1308
+ }
1309
+ }
1310
+ function hostSockets(terminalsDirectory, first) {
1311
+ let names = [];
1312
+ if (terminalsDirectory !== void 0) {
1313
+ try {
1314
+ names = readdirSync(terminalsDirectory).filter(
1315
+ (name) => name.endsWith(".sock")
1316
+ );
1317
+ } catch {
1318
+ names = [];
894
1319
  }
895
- } catch {
896
1320
  }
897
- return { can: true, reason: null };
1321
+ const sockets = names.toSorted().map((name) => path.join(terminalsDirectory ?? "", name));
1322
+ return first === void 0 ? sockets : [first, ...sockets.filter((socket) => socket !== first)];
898
1323
  }
899
- function main() {
900
- const info = readPackageInfo();
901
- if (process.argv.includes("--self-test")) {
902
- process.stdout.write(
903
- `${JSON.stringify({ name: info.name, version: info.version })}
904
- `
905
- );
906
- return;
1324
+ async function listTerminals(sockets) {
1325
+ const replies = await Promise.all(
1326
+ sockets.map(async (socket) => ({
1327
+ socket,
1328
+ reply: await requestOnce(socket, { type: "list" })
1329
+ }))
1330
+ );
1331
+ return replies.flatMap(
1332
+ ({ socket, reply }) => reply.ok && Array.isArray(reply.terminals) ? reply.terminals.map(
1333
+ (terminal) => ({ ...terminal, socket })
1334
+ ) : []
1335
+ );
1336
+ }
1337
+ const RELAYED = /* @__PURE__ */ new Set([
1338
+ "list",
1339
+ "screen",
1340
+ "snapshot",
1341
+ "attach",
1342
+ "write",
1343
+ "type",
1344
+ "press",
1345
+ "resize",
1346
+ "kill"
1347
+ ]);
1348
+ const LABELS = ["thread:", "setup:"];
1349
+ const DEFAULT_RELAY_TIMINGS = {
1350
+ idleCloseMs: 6e4,
1351
+ freshnessMs: 6e4
1352
+ };
1353
+ function isAibexTerminal(terminal) {
1354
+ return LABELS.some((label) => terminal?.label?.startsWith(label) ?? false);
1355
+ }
1356
+ class Relay {
1357
+ constructor(options) {
1358
+ this.options = options;
1359
+ this.timings = { ...DEFAULT_RELAY_TIMINGS, ...options.timings };
907
1360
  }
908
- const host = process.env.AIBEX_HOST;
909
- const hostDirectory = process.env.AIBEX_HOST_DIR;
910
- if (!host || !hostDirectory || !process.send) {
911
- process.stderr.write(
912
- "aibex-link is started by aibexd: it needs AIBEX_HOST, AIBEX_HOST_DIR and an IPC channel\n"
913
- );
914
- process.exitCode = 1;
915
- return;
1361
+ socket;
1362
+ idleTimer;
1363
+ /** Connections to terminal hosts made for this relay, by socket path. */
1364
+ hosts = /* @__PURE__ */ new Map();
1365
+ /** Nonces seen, with when they may be forgotten. */
1366
+ nonces = /* @__PURE__ */ new Map();
1367
+ timings;
1368
+ now() {
1369
+ return (this.options.now ?? Date.now)();
916
1370
  }
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
- );
1371
+ isOpen() {
1372
+ return this.socket?.readyState === WebSocket.OPEN;
948
1373
  }
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
- });
1374
+ /** How many terminal host connections the relay holds; each carries its subscriptions. */
1375
+ hostConnections() {
1376
+ return this.hosts.size;
1377
+ }
1378
+ /**
1379
+ * Opens a signed WebSocket to `/v1/relay`, replacing any open relay. The
1380
+ * upgrade is signed like a poll, over the URL's `https` (or local `http`)
1381
+ * form, and sent to its `wss` (`ws`) form.
1382
+ */
1383
+ async open() {
1384
+ this.close();
1385
+ const url = new URL("/v1/relay", this.options.host);
1386
+ const headers = await this.options.herd.sign("GET", url.href, "");
1387
+ const target = url.href.replace(/^http/u, "ws");
1388
+ const socket = new WebSocket(target, {
1389
+ headers: Object.fromEntries(headers)
1390
+ });
1391
+ this.socket = socket;
1392
+ const opened = await new Promise((resolve) => {
1393
+ const timer = setTimeout(() => {
1394
+ socket.close();
1395
+ resolve(false);
1396
+ }, 3e4);
1397
+ socket.addEventListener(
1398
+ "open",
1399
+ () => {
1400
+ clearTimeout(timer);
1401
+ resolve(true);
1402
+ },
1403
+ { once: true }
1404
+ );
1405
+ socket.addEventListener("error", () => resolve(false), { once: true });
1406
+ socket.addEventListener("close", () => resolve(false), { once: true });
1407
+ });
1408
+ if (!opened || this.socket !== socket) {
1409
+ if (this.socket === socket) this.socket = void 0;
1410
+ this.options.log.line("the herd refused the relay upgrade");
1411
+ return false;
959
1412
  }
960
- });
961
- void send({ type: "ready" });
962
- setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
963
- poller?.start();
1413
+ this.options.log.line("relay open");
1414
+ socket.addEventListener("message", (message) => {
1415
+ void this.receive(message.data);
1416
+ });
1417
+ socket.addEventListener("close", () => {
1418
+ if (this.socket !== socket) return;
1419
+ this.socket = void 0;
1420
+ this.end();
1421
+ this.options.log.line("relay closed");
1422
+ });
1423
+ return true;
1424
+ }
1425
+ /** Closes the relay and ends every relayed subscription. */
1426
+ close() {
1427
+ const socket = this.socket;
1428
+ this.socket = void 0;
1429
+ socket?.close(1e3);
1430
+ this.end();
1431
+ }
1432
+ end() {
1433
+ clearTimeout(this.idleTimer);
1434
+ this.idleTimer = void 0;
1435
+ for (const pending of this.hosts.values()) {
1436
+ void (async () => {
1437
+ try {
1438
+ const client = await pending;
1439
+ client.close();
1440
+ } catch {
1441
+ }
1442
+ })();
1443
+ }
1444
+ this.hosts.clear();
1445
+ }
1446
+ send(frame) {
1447
+ if (this.socket?.readyState === WebSocket.OPEN) {
1448
+ this.socket.send(JSON.stringify(frame));
1449
+ }
1450
+ }
1451
+ refuse(conn, id, message) {
1452
+ this.send({
1453
+ type: "reply",
1454
+ conn,
1455
+ message: {
1456
+ id: typeof id === "string" || typeof id === "number" ? id : null,
1457
+ ok: false,
1458
+ error: { code: "bad-request", message }
1459
+ }
1460
+ });
1461
+ }
1462
+ async receive(data) {
1463
+ let frame;
1464
+ try {
1465
+ frame = JSON.parse(String(data));
1466
+ } catch {
1467
+ return;
1468
+ }
1469
+ if (frame.type === "viewers") {
1470
+ this.viewers(frame.count);
1471
+ } else if (frame.type === "request" && typeof frame.conn === "string") {
1472
+ await this.request(frame.conn, frame.envelope);
1473
+ }
1474
+ }
1475
+ viewers(count) {
1476
+ clearTimeout(this.idleTimer);
1477
+ this.idleTimer = void 0;
1478
+ if (count > 0) return;
1479
+ this.idleTimer = setTimeout(() => {
1480
+ this.options.log.line("no viewers for a while; closing the relay");
1481
+ this.close();
1482
+ }, this.timings.idleCloseMs);
1483
+ }
1484
+ /** Checks a viewer's request and forwards it to the host that holds the terminal. */
1485
+ async request(conn, envelope) {
1486
+ const opened = await this.options.access.open(envelope);
1487
+ if (!opened.ok) {
1488
+ this.refuse(conn, null, `refused: ${opened.reason}`);
1489
+ return;
1490
+ }
1491
+ const { created_at: createdAt, nonce, request } = opened.payload;
1492
+ const id = request?.id;
1493
+ const age = this.now() - Date.parse(createdAt);
1494
+ if (!(Math.abs(age) <= this.timings.freshnessMs)) {
1495
+ this.refuse(conn, id, "refused: the request is not fresh");
1496
+ return;
1497
+ }
1498
+ const now = this.now();
1499
+ for (const [seen, until] of this.nonces) {
1500
+ if (until < now) this.nonces.delete(seen);
1501
+ }
1502
+ if (typeof nonce !== "string" || this.nonces.has(nonce)) {
1503
+ this.refuse(conn, id, "refused: the nonce was used before");
1504
+ return;
1505
+ }
1506
+ this.nonces.set(nonce, now + 2 * this.timings.freshnessMs);
1507
+ const type = request?.type;
1508
+ if (typeof type !== "string" || !RELAYED.has(type)) {
1509
+ this.refuse(conn, id, `refused: ${String(type)} is never relayed`);
1510
+ return;
1511
+ }
1512
+ const sockets = hostSockets(
1513
+ this.options.terminalsDirectory,
1514
+ this.options.terminalSocket
1515
+ );
1516
+ const terminals = await listTerminals(sockets);
1517
+ if (type === "list") {
1518
+ this.send({
1519
+ type: "reply",
1520
+ conn,
1521
+ message: {
1522
+ id,
1523
+ ok: true,
1524
+ terminals: terminals.filter((terminal2) => isAibexTerminal(terminal2)).map(({ socket: _socket, ...terminal2 }) => terminal2)
1525
+ }
1526
+ });
1527
+ return;
1528
+ }
1529
+ const terminalId = request.terminal;
1530
+ const terminal = terminals.find((found) => found.id === terminalId);
1531
+ if (!terminal || !isAibexTerminal(terminal)) {
1532
+ this.refuse(conn, id, "refused: not a terminal Aibex started");
1533
+ return;
1534
+ }
1535
+ if (type === "kill" && !terminal.label?.startsWith("setup:")) {
1536
+ this.refuse(conn, id, "refused: only a setup terminal can be killed");
1537
+ return;
1538
+ }
1539
+ await this.forward(conn, terminal.socket, request);
1540
+ }
1541
+ connection(socket) {
1542
+ let pending = this.hosts.get(socket);
1543
+ if (!pending) {
1544
+ pending = HostClient.connect(socket);
1545
+ this.hosts.set(socket, pending);
1546
+ void (async () => {
1547
+ try {
1548
+ const client = await pending;
1549
+ client.onClose(() => {
1550
+ if (this.hosts.get(socket) === pending) this.hosts.delete(socket);
1551
+ });
1552
+ } catch {
1553
+ if (this.hosts.get(socket) === pending) this.hosts.delete(socket);
1554
+ }
1555
+ })();
1556
+ }
1557
+ return pending;
1558
+ }
1559
+ /** Sends the request under the link's own id, and everything back under the viewer's. */
1560
+ async forward(conn, socket, request) {
1561
+ const viewerId = request.id;
1562
+ let client;
1563
+ try {
1564
+ client = await this.connection(socket);
1565
+ } catch {
1566
+ this.refuse(conn, viewerId, "the terminal host cannot be reached");
1567
+ return;
1568
+ }
1569
+ const { id: _id, ...body } = request;
1570
+ let held = [];
1571
+ const event = (message) => this.send({
1572
+ type: "event",
1573
+ conn,
1574
+ message: { ...message, id: viewerId }
1575
+ });
1576
+ const reply = await client.subscribe(
1577
+ body,
1578
+ request.type === "attach" ? (message) => {
1579
+ if (held) held.push(message);
1580
+ else event(message);
1581
+ } : void 0
1582
+ );
1583
+ this.send({
1584
+ type: "reply",
1585
+ conn,
1586
+ message: { ...reply, id: viewerId }
1587
+ });
1588
+ const queued = held;
1589
+ held = void 0;
1590
+ for (const message of queued) event(message);
1591
+ }
1592
+ }
1593
+ const REPO_SCAN_MS = 6e4;
1594
+ const GITHUB_REMOTE = [
1595
+ /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
1596
+ /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
1597
+ ];
1598
+ function parseGitHubRemote(url) {
1599
+ for (const pattern of GITHUB_REMOTE) {
1600
+ const match = pattern.exec(url.trim());
1601
+ if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
1602
+ }
1603
+ return void 0;
1604
+ }
1605
+ function git(cwd, args) {
1606
+ return new Promise((resolve) => {
1607
+ execFile(
1608
+ "git",
1609
+ ["-C", cwd, ...args],
1610
+ (failure, stdout, stderr) => resolve({
1611
+ ok: failure === null,
1612
+ stdout: stdout.trim(),
1613
+ stderr: stderr.trim()
1614
+ })
1615
+ );
1616
+ });
1617
+ }
1618
+ function directories(parent) {
1619
+ try {
1620
+ return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
1621
+ } catch {
1622
+ return [];
1623
+ }
1624
+ }
1625
+ 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")))
1628
+ );
1629
+ const found = await Promise.all(
1630
+ candidates.map(async (directory) => {
1631
+ const origin = await git(directory, [
1632
+ "config",
1633
+ "--get",
1634
+ "remote.origin.url"
1635
+ ]);
1636
+ const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
1637
+ return repo ? { repo, path: directory } : void 0;
1638
+ })
1639
+ );
1640
+ return found.filter((checkout) => checkout !== void 0);
1641
+ }
1642
+ class Repos {
1643
+ constructor(reposDirectory, now = Date.now) {
1644
+ this.reposDirectory = reposDirectory;
1645
+ this.now = now;
1646
+ }
1647
+ scanned = [];
1648
+ scannedAt = Number.NEGATIVE_INFINITY;
1649
+ async list(options = {}) {
1650
+ if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
1651
+ this.scanned = await scanRepos(this.reposDirectory);
1652
+ this.scannedAt = this.now();
1653
+ }
1654
+ return this.scanned;
1655
+ }
1656
+ /** The checkout for a repository, rescanning once when it is not known. */
1657
+ async find(repo) {
1658
+ const match = (checkouts) => checkouts.find(
1659
+ (checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
1660
+ );
1661
+ return match(await this.list()) ?? match(await this.list({ fresh: true }));
1662
+ }
1663
+ }
1664
+ const HARNESSES = {
1665
+ // The input box: a full-width rule, then `❯` and the placeholder. The
1666
+ // folder trust dialog also starts a line with `❯`, but never under a rule.
1667
+ claude: {
1668
+ command: "claude",
1669
+ args: [],
1670
+ ready: /─{20,}\n❯(?: |$)/mu,
1671
+ multiline: "paste"
1672
+ },
1673
+ // The composer line `› Ask Codex to do anything`. The update notice, the
1674
+ // folder trust dialog and sign-in all list numbered choices after `›`.
1675
+ codex: {
1676
+ command: "codex",
1677
+ // The update notice waits for a key, so a driven session skips it.
1678
+ args: ["-c", "check_for_update_on_startup=false"],
1679
+ ready: /^›(?: (?!\d+\. )|$)/mu,
1680
+ multiline: "paste"
1681
+ },
1682
+ // The input box under a row of `▄`, with `→` and the placeholder.
1683
+ cursor: {
1684
+ command: "cursor-agent",
1685
+ args: [],
1686
+ ready: /▄{20,}\n\s*→/u,
1687
+ multiline: "paste"
1688
+ }
1689
+ };
1690
+ const SETUP_PROGRAMS = {
1691
+ shell: void 0,
1692
+ claude: "claude",
1693
+ codex: "codex",
1694
+ cursor: "cursor-agent"
1695
+ };
1696
+ function bracketedPaste(text) {
1697
+ return `\x1B[200~${text}\x1B[201~`;
1698
+ }
1699
+ const MAX_CHUNK_BYTES = 1024 * 1024;
1700
+ class Transcript {
1701
+ constructor(spoolFile, state) {
1702
+ this.spoolFile = spoolFile;
1703
+ this.state = state;
1704
+ }
1705
+ size() {
1706
+ try {
1707
+ return statSync(this.spoolFile).size;
1708
+ } catch {
1709
+ return 0;
1710
+ }
1711
+ }
1712
+ /** The terminal `seq` the spool ends at. */
1713
+ seq() {
1714
+ return this.size() + this.state.seqOffset;
1715
+ }
1716
+ /** The bytes not yet stored on the server. */
1717
+ pending() {
1718
+ return this.size() - this.state.uploaded;
1719
+ }
1720
+ /** Appends output that ends at terminal `seq`, dropping what the spool already holds. */
1721
+ appendOutput(data, seq) {
1722
+ let bytes = Buffer.from(data, "utf8");
1723
+ const have = this.seq();
1724
+ if (seq <= have) return;
1725
+ const start = seq - bytes.length;
1726
+ if (start < have) bytes = bytes.subarray(have - start);
1727
+ appendFileSync(this.spoolFile, bytes, { mode: 384 });
1728
+ if (start > have) this.state.seqOffset += start - have;
1729
+ }
1730
+ /** Appends a screen redraw taken at terminal `seq`. */
1731
+ appendRedraw(serialized, seq) {
1732
+ appendFileSync(this.spoolFile, serialized, { mode: 384 });
1733
+ this.state.seqOffset = seq - this.size();
1734
+ }
1735
+ /** Empties the spool so it starts at server offset `base` with a redraw. */
1736
+ newSegment(base, serialized, seq) {
1737
+ writeFileSync(this.spoolFile, "", { mode: 384 });
1738
+ this.state.base = base;
1739
+ this.state.uploaded = 0;
1740
+ this.appendRedraw(serialized, seq);
1741
+ }
1742
+ read(from, length) {
1743
+ const buffer = Buffer.alloc(length);
1744
+ const fd = openSync(this.spoolFile, "r");
1745
+ try {
1746
+ const read = readSync(fd, buffer, 0, length, from);
1747
+ return buffer.subarray(0, read);
1748
+ } finally {
1749
+ closeSync(fd);
1750
+ }
1751
+ }
1752
+ /** Sends everything not yet stored, one chunk at a time. */
1753
+ async upload(options) {
1754
+ while (this.pending() > 0) {
1755
+ const chunk = this.read(
1756
+ this.state.uploaded,
1757
+ Math.min(this.pending(), MAX_CHUNK_BYTES)
1758
+ );
1759
+ const answer = await options.herd.post(
1760
+ `/v1/threads/${options.threadId}/transcript`,
1761
+ {
1762
+ lease_id: options.leaseId,
1763
+ epoch: options.epoch,
1764
+ harness: options.harness,
1765
+ format: "terminal",
1766
+ offset: this.state.base + this.state.uploaded,
1767
+ chunk: chunk.toString("base64url"),
1768
+ sha256: createHash("sha256").update(chunk).digest("hex")
1769
+ }
1770
+ );
1771
+ if (!answer.ok) return "failed";
1772
+ const body = answer.body ?? {};
1773
+ if (answer.status === 200 && typeof body.next_offset === "number") {
1774
+ this.state.uploaded = body.next_offset - this.state.base;
1775
+ continue;
1776
+ }
1777
+ const problem = problemName(body);
1778
+ if (problem === "lease-fenced") return "fenced";
1779
+ if (problem === "transcript-offset" && typeof body.next_offset === "number") {
1780
+ const next = body.next_offset - this.state.base;
1781
+ if (next >= 0 && next <= this.size()) {
1782
+ this.state.uploaded = next;
1783
+ continue;
1784
+ }
1785
+ return { newSegment: body.next_offset };
1786
+ }
1787
+ if (answer.status >= 500 || answer.status === 429) return "failed";
1788
+ return "refused";
1789
+ }
1790
+ return "done";
1791
+ }
1792
+ remove() {
1793
+ rmSync(this.spoolFile, { force: true });
1794
+ }
1795
+ }
1796
+ const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
1797
+ function carryList(reposConfig) {
1798
+ const value = readJson(reposConfig);
1799
+ const carry = value?.carry;
1800
+ if (!Array.isArray(carry)) return DEFAULT_CARRY;
1801
+ return carry.filter(
1802
+ (entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
1803
+ );
1804
+ }
1805
+ async function defaultBranch(checkout) {
1806
+ const head = await git(checkout, [
1807
+ "symbolic-ref",
1808
+ "--short",
1809
+ "refs/remotes/origin/HEAD"
1810
+ ]);
1811
+ return head.ok && head.stdout.startsWith("origin/") ? head.stdout.slice("origin/".length) : "main";
1812
+ }
1813
+ async function prepareWorktree(options) {
1814
+ const { checkout, threadId } = options;
1815
+ const worktreePath = path.join(options.workDirectory, threadId);
1816
+ const branch = `aibex/${threadId}`;
1817
+ const fetched = await git(checkout, ["fetch", "--quiet", "origin"]);
1818
+ const base = options.baseRef ?? await defaultBranch(checkout);
1819
+ if (!existsSync(path.join(worktreePath, ".git"))) {
1820
+ mkdirSync(options.workDirectory, { recursive: true });
1821
+ const known = await git(checkout, [
1822
+ "rev-parse",
1823
+ "--verify",
1824
+ "--quiet",
1825
+ `refs/heads/${branch}`
1826
+ ]);
1827
+ const added = await git(
1828
+ checkout,
1829
+ known.ok ? ["worktree", "add", "--quiet", worktreePath, branch] : [
1830
+ "worktree",
1831
+ "add",
1832
+ "--quiet",
1833
+ "-b",
1834
+ branch,
1835
+ worktreePath,
1836
+ `origin/${base}`
1837
+ ]
1838
+ );
1839
+ if (!added.ok) {
1840
+ const why = added.stderr || `git worktree add failed`;
1841
+ return {
1842
+ ok: false,
1843
+ reason: fetched.ok ? why : `${why} (git fetch failed too: ${fetched.stderr})`
1844
+ };
1845
+ }
1846
+ }
1847
+ const carried = [];
1848
+ for (const file of carryList(options.reposConfig)) {
1849
+ const from = path.join(checkout, file);
1850
+ const to = path.join(worktreePath, file);
1851
+ if (!existsSync(from) || existsSync(to)) continue;
1852
+ const tracked = await git(checkout, [
1853
+ "ls-files",
1854
+ "--error-unmatch",
1855
+ "--",
1856
+ file
1857
+ ]);
1858
+ if (tracked.ok) continue;
1859
+ mkdirSync(path.dirname(to), { recursive: true });
1860
+ cpSync(from, to, { recursive: true });
1861
+ carried.push(file);
1862
+ }
1863
+ return {
1864
+ ok: true,
1865
+ worktree: { path: worktreePath, branch, base },
1866
+ carried
1867
+ };
1868
+ }
1869
+ const DEFAULT_SESSION_TIMINGS = {
1870
+ readyTimeoutMs: 6e4,
1871
+ checkMs: 250,
1872
+ quietMs: 750,
1873
+ statusIntervalMs: 5e3,
1874
+ uploadIntervalMs: 5e3,
1875
+ uploadThresholdBytes: 256 * 1024,
1876
+ settleMs: 150
1877
+ };
1878
+ const STATUS_MAX = 200;
1879
+ function newEventId() {
1880
+ return `e_${randomBytes(12).toString("base64url")}`;
1881
+ }
1882
+ function errorText(error) {
1883
+ return error instanceof Error ? error.message : String(error);
1884
+ }
1885
+ class Session {
1886
+ constructor(record, manager) {
1887
+ this.record = record;
1888
+ this.manager = manager;
1889
+ const now = manager.now();
1890
+ this.lastProgressAt = now;
1891
+ this.quietSince = now;
1892
+ this.readySince = now;
1893
+ this.transcript = new Transcript(
1894
+ manager.spoolFile(record.thread_id),
1895
+ record.transcript
1896
+ );
1897
+ if (record.ended) this.state = "ended";
1898
+ else if (record.prompted) this.state = "idle";
1899
+ }
1900
+ client;
1901
+ state = "starting";
1902
+ waitingOn;
1903
+ lastProgressAt;
1904
+ busy = false;
1905
+ lastScreenSeq = -1;
1906
+ quietSince;
1907
+ lastSendAt = 0;
1908
+ sending = false;
1909
+ readySince;
1910
+ timer;
1911
+ uploadTimer;
1912
+ uploading;
1913
+ statusAt = Number.NEGATIVE_INFINITY;
1914
+ statusSent;
1915
+ statusPending;
1916
+ statusTimer;
1917
+ /** Set when the server fenced the lease: nothing more is sent. */
1918
+ fenced = false;
1919
+ disposed = false;
1920
+ transcript;
1921
+ get harness() {
1922
+ return this.manager.harnesses[this.record.harness];
1923
+ }
1924
+ get timings() {
1925
+ return this.manager.timings;
1926
+ }
1927
+ save() {
1928
+ this.manager.save(this);
1929
+ }
1930
+ /** Attaches for the transcript and watches for state, then starts checking. */
1931
+ async drive(client) {
1932
+ this.client = client;
1933
+ const terminal = this.record.terminal;
1934
+ client.onClose(() => {
1935
+ if (!this.disposed && !this.record.ended) {
1936
+ this.manager.log.line(
1937
+ `lost the terminal host for ${this.record.thread_id}; it is picked up again when the link restarts`
1938
+ );
1939
+ }
1940
+ });
1941
+ const watched = await client.subscribe(
1942
+ { type: "watch", terminal },
1943
+ (event) => this.onWatch(event)
1944
+ );
1945
+ if (!watched.ok) {
1946
+ this.end("the terminal is gone");
1947
+ return;
1948
+ }
1949
+ const since = this.transcript.seq();
1950
+ let attached = await client.subscribe(
1951
+ { type: "attach", terminal, since },
1952
+ (event) => this.onOutput(event)
1953
+ );
1954
+ if (!attached.ok && attached.error?.code === "gap") {
1955
+ attached = await client.subscribe(
1956
+ { type: "attach", terminal },
1957
+ (event) => this.onOutput(event)
1958
+ );
1959
+ if (attached.ok && typeof attached.serialized === "string") {
1960
+ this.transcript.appendRedraw(
1961
+ attached.serialized,
1962
+ attached.seq
1963
+ );
1964
+ this.save();
1965
+ }
1966
+ }
1967
+ const screen = await client.request({ type: "screen", terminal });
1968
+ if (screen.ok && screen.exited) {
1969
+ this.end("exited");
1970
+ return;
1971
+ }
1972
+ this.timer = setInterval(() => void this.check(), this.timings.checkMs);
1973
+ this.uploadTimer = setInterval(
1974
+ () => void this.upload(),
1975
+ this.timings.uploadIntervalMs
1976
+ );
1977
+ }
1978
+ onOutput(event) {
1979
+ if (event.event === "output" && !this.fenced) {
1980
+ this.transcript.appendOutput(event.data, event.seq);
1981
+ if (this.transcript.pending() >= this.timings.uploadThresholdBytes) {
1982
+ void this.upload();
1983
+ }
1984
+ } else if (event.event === "exit") {
1985
+ this.end("exited");
1986
+ }
1987
+ }
1988
+ onWatch(event) {
1989
+ const now = this.manager.now();
1990
+ switch (event.event) {
1991
+ case "screen": {
1992
+ this.lastProgressAt = now;
1993
+ this.quietSince = now;
1994
+ break;
1995
+ }
1996
+ case "active": {
1997
+ this.busy = true;
1998
+ if (this.record.prompted && !this.record.ended) this.state = "working";
1999
+ break;
2000
+ }
2001
+ case "idle": {
2002
+ this.busy = false;
2003
+ if (this.record.prompted && !this.record.ended) this.state = "idle";
2004
+ break;
2005
+ }
2006
+ case "title": {
2007
+ this.setStatus(typeof event.title === "string" ? event.title : "");
2008
+ break;
2009
+ }
2010
+ case "exit":
2011
+ case "removed": {
2012
+ this.end("exited");
2013
+ break;
2014
+ }
2015
+ }
2016
+ }
2017
+ /** Whether output has been quiet long enough to type. */
2018
+ quiet(screenSeq) {
2019
+ const now = this.manager.now();
2020
+ if (screenSeq !== this.lastScreenSeq) {
2021
+ this.lastScreenSeq = screenSeq;
2022
+ this.quietSince = now;
2023
+ }
2024
+ return !this.busy && now - this.quietSince >= this.timings.quietMs;
2025
+ }
2026
+ /** Types the prompt once the harness is ready, then one follow-up per idle. */
2027
+ async check() {
2028
+ if (this.sending || this.record.ended || this.fenced || !this.client) {
2029
+ return;
2030
+ }
2031
+ const next = this.record.queue[0];
2032
+ if (next === void 0) return;
2033
+ if (this.record.prompted && this.manager.now() - this.lastSendAt < this.timings.quietMs * 2) {
2034
+ return;
2035
+ }
2036
+ this.sending = true;
2037
+ try {
2038
+ const screen = await this.client.request({
2039
+ type: "screen",
2040
+ terminal: this.record.terminal
2041
+ });
2042
+ if (!screen.ok) return;
2043
+ const quiet = this.quiet(screen.seq);
2044
+ const ready = this.record.prompted || this.harness.ready.test(String(screen.text));
2045
+ if (!quiet || !ready) {
2046
+ if (!this.record.prompted && this.state !== "waiting" && this.manager.now() - this.readySince >= this.timings.readyTimeoutMs) {
2047
+ this.state = "waiting";
2048
+ this.waitingOn = "login";
2049
+ this.setStatus("harness not ready");
2050
+ this.manager.log.line(
2051
+ `${this.record.thread_id}: ${this.record.harness} showed no ready marker in ${Math.round(this.timings.readyTimeoutMs / 1e3)}s; nothing typed`
2052
+ );
2053
+ }
2054
+ return;
2055
+ }
2056
+ await this.send(next);
2057
+ } finally {
2058
+ this.sending = false;
2059
+ }
2060
+ }
2061
+ async send(text) {
2062
+ const client = this.client;
2063
+ if (!client) return;
2064
+ const terminal = this.record.terminal;
2065
+ const multiline = text.includes("\n");
2066
+ const sent = multiline && this.harness.multiline === "paste" ? await client.request({
2067
+ type: "write",
2068
+ terminal,
2069
+ data: bracketedPaste(text)
2070
+ }) : await client.request({ type: "type", terminal, text });
2071
+ if (!sent.ok) return;
2072
+ await new Promise((resolve) => setTimeout(resolve, this.timings.settleMs));
2073
+ await client.request({ type: "press", terminal, keys: ["Enter"] });
2074
+ this.record.queue.shift();
2075
+ const first = !this.record.prompted;
2076
+ this.record.prompted = true;
2077
+ this.lastSendAt = this.manager.now();
2078
+ this.state = "working";
2079
+ this.waitingOn = void 0;
2080
+ this.save();
2081
+ this.manager.log.line(
2082
+ `${this.record.thread_id}: ${first ? "typed the prompt" : "typed a follow-up"} into ${this.record.harness}`
2083
+ );
2084
+ }
2085
+ /** A title becomes a `status` event, at most one per interval, the latest winning. */
2086
+ setStatus(text) {
2087
+ const status = text.trim().slice(0, STATUS_MAX);
2088
+ if (status === "") return;
2089
+ this.statusPending = status;
2090
+ const wait = this.statusAt + this.timings.statusIntervalMs - this.manager.now();
2091
+ if (wait <= 0) {
2092
+ this.flushStatus();
2093
+ } else {
2094
+ this.statusTimer ??= setTimeout(() => {
2095
+ this.statusTimer = void 0;
2096
+ this.flushStatus();
2097
+ }, wait);
2098
+ }
2099
+ }
2100
+ flushStatus() {
2101
+ const status = this.statusPending;
2102
+ this.statusPending = void 0;
2103
+ if (status === void 0 || status === this.statusSent || this.fenced) {
2104
+ return;
2105
+ }
2106
+ this.statusAt = this.manager.now();
2107
+ this.statusSent = status;
2108
+ this.manager.event(this, { type: "status", text: status });
2109
+ }
2110
+ queueText(text) {
2111
+ this.record.queue.push(text);
2112
+ this.save();
2113
+ }
2114
+ /** The program exited, or the session never started: report it once. */
2115
+ end(reason) {
2116
+ if (this.record.ended || this.fenced) return;
2117
+ this.record.ended = reason;
2118
+ this.state = "ended";
2119
+ this.stopTimers();
2120
+ this.manager.event(this, { type: "session.ended", without_done: true });
2121
+ this.manager.log.line(
2122
+ `${this.record.thread_id}: session ended (${reason})`
2123
+ );
2124
+ void this.upload();
2125
+ }
2126
+ async kill() {
2127
+ if (!this.client || this.record.terminal === void 0) return;
2128
+ await this.client.request({ type: "kill", terminal: this.record.terminal });
2129
+ }
2130
+ /** Sends the spool from the server's offset. */
2131
+ upload() {
2132
+ this.uploading ??= (async () => {
2133
+ try {
2134
+ await this.uploadOnce();
2135
+ } finally {
2136
+ this.uploading = void 0;
2137
+ this.manager.settle(this);
2138
+ }
2139
+ })();
2140
+ return this.uploading;
2141
+ }
2142
+ async uploadOnce() {
2143
+ if (this.fenced || this.transcript.pending() <= 0) return;
2144
+ const outcome = await this.transcript.upload({
2145
+ herd: this.manager.herd,
2146
+ threadId: this.record.thread_id,
2147
+ leaseId: this.record.lease_id,
2148
+ epoch: this.record.epoch,
2149
+ harness: this.record.harness
2150
+ });
2151
+ if (outcome === "fenced") {
2152
+ await this.manager.fence(this);
2153
+ return;
2154
+ }
2155
+ if (outcome === "refused") {
2156
+ this.manager.log.line(
2157
+ `${this.record.thread_id}: the herd refused the transcript; it stays in the spool`
2158
+ );
2159
+ this.transcript.state.uploaded = this.transcript.size();
2160
+ } else if (typeof outcome === "object") {
2161
+ const snapshot = this.client ? await this.client.request({
2162
+ type: "snapshot",
2163
+ terminal: this.record.terminal,
2164
+ lines: 0
2165
+ }) : void 0;
2166
+ this.transcript.newSegment(
2167
+ outcome.newSegment,
2168
+ snapshot?.ok && typeof snapshot.serialized === "string" ? snapshot.serialized : "",
2169
+ snapshot?.ok ? snapshot.seq : this.transcript.seq()
2170
+ );
2171
+ }
2172
+ this.save();
2173
+ }
2174
+ /** Whether everything about it reached the herd, so its record can go. */
2175
+ settled() {
2176
+ return this.record.ended !== void 0 && this.record.outbox.length === 0 && this.transcript.pending() <= 0 && this.uploading === void 0;
2177
+ }
2178
+ stopTimers() {
2179
+ clearInterval(this.timer);
2180
+ clearInterval(this.uploadTimer);
2181
+ }
2182
+ dispose() {
2183
+ this.disposed = true;
2184
+ this.stopTimers();
2185
+ clearTimeout(this.statusTimer);
2186
+ this.client?.close();
2187
+ }
2188
+ heartbeat() {
2189
+ const { record } = this;
2190
+ const session = {
2191
+ thread_id: record.thread_id,
2192
+ lease_id: record.lease_id,
2193
+ epoch: record.epoch,
2194
+ harness: record.harness,
2195
+ state: this.state,
2196
+ last_progress_at: new Date(this.lastProgressAt).toISOString(),
2197
+ transcript_offset: record.transcript.base + record.transcript.uploaded,
2198
+ started_at: record.started_at
2199
+ };
2200
+ if (this.waitingOn) session.waiting_on = this.waitingOn;
2201
+ if (record.repo) session.repo = record.repo;
2202
+ if (record.worktree) session.worktree = record.worktree;
2203
+ return session;
2204
+ }
2205
+ }
2206
+ class Sessions {
2207
+ constructor(options) {
2208
+ this.options = options;
2209
+ this.harnesses = options.harnesses ?? HARNESSES;
2210
+ this.timings = { ...DEFAULT_SESSION_TIMINGS, ...options.timings };
2211
+ this.herd = options.herd;
2212
+ this.log = options.log;
2213
+ this.directory = path.join(options.paths.hostDirectory, "sessions");
2214
+ }
2215
+ sessions = /* @__PURE__ */ new Map();
2216
+ harnesses;
2217
+ timings;
2218
+ herd;
2219
+ log;
2220
+ directory;
2221
+ flushing;
2222
+ flushTimer;
2223
+ now() {
2224
+ return (this.options.now ?? Date.now)();
2225
+ }
2226
+ spoolFile(threadId) {
2227
+ return path.join(this.directory, `${threadId}.spool`);
2228
+ }
2229
+ recordFile(threadId) {
2230
+ return path.join(this.directory, `${threadId}.json`);
2231
+ }
2232
+ save(session) {
2233
+ if (session.fenced || session.disposed) return;
2234
+ writeJsonAtomic(this.recordFile(session.record.thread_id), session.record);
2235
+ }
2236
+ /** The heartbeat's sessions. */
2237
+ list() {
2238
+ return [...this.sessions.values()].filter((session) => !session.fenced).map((session) => session.heartbeat());
2239
+ }
2240
+ /** Picks up every recorded session from whichever terminal host runs it. */
2241
+ async resume() {
2242
+ mkdirSync(this.directory, { recursive: true, mode: 448 });
2243
+ const files = readdirSync(this.directory).filter(
2244
+ (name) => name.endsWith(".json")
2245
+ );
2246
+ const terminals = await listTerminals(
2247
+ hostSockets(this.options.terminalsDirectory, this.options.terminalSocket)
2248
+ );
2249
+ for (const file of files) {
2250
+ const record = readJson(path.join(this.directory, file));
2251
+ if (!record?.thread_id || this.sessions.has(record.thread_id)) continue;
2252
+ const session = new Session(record, this);
2253
+ this.sessions.set(record.thread_id, session);
2254
+ const found = terminals.find(
2255
+ (terminal) => terminal.id === record.terminal
2256
+ );
2257
+ if (record.ended || !found || found.exited) {
2258
+ session.end(record.ended ?? "its terminal is gone");
2259
+ this.settle(session);
2260
+ continue;
2261
+ }
2262
+ record.socket = found.socket;
2263
+ try {
2264
+ await session.drive(await HostClient.connect(found.socket));
2265
+ this.log.line(
2266
+ `${record.thread_id}: picked up ${record.terminal} on ${path.basename(found.socket)}`
2267
+ );
2268
+ } catch (error) {
2269
+ session.end(`its terminal host cannot be reached: ${errorText(error)}`);
2270
+ }
2271
+ }
2272
+ }
2273
+ /** Handles a command the poller recorded; anything else is ignored. */
2274
+ async handle(command) {
2275
+ switch (command.type) {
2276
+ case "work.assign": {
2277
+ await this.assign(command);
2278
+ return true;
2279
+ }
2280
+ case "thread.message": {
2281
+ await this.message(command);
2282
+ return true;
2283
+ }
2284
+ case "thread.stop":
2285
+ case "control.drop_session": {
2286
+ await this.stop(
2287
+ command.thread_id,
2288
+ command.type
2289
+ );
2290
+ return true;
2291
+ }
2292
+ default: {
2293
+ return false;
2294
+ }
2295
+ }
2296
+ }
2297
+ async assign(command) {
2298
+ const { lease } = command;
2299
+ const existing = this.sessions.get(lease.thread_id);
2300
+ if (existing && existing.record.lease_id === lease.lease_id) return;
2301
+ if (existing) await this.fence(existing);
2302
+ const opened = await this.options.access.open(command.request);
2303
+ const harness = opened.ok ? opened.payload.needs?.harness : void 0;
2304
+ const record = {
2305
+ thread_id: lease.thread_id,
2306
+ lease_id: lease.lease_id,
2307
+ epoch: lease.epoch,
2308
+ harness: harness ?? "claude",
2309
+ started_at: new Date(this.now()).toISOString(),
2310
+ queue: [],
2311
+ prompted: false,
2312
+ messages: [],
2313
+ transcript: { base: 0, uploaded: 0, seqOffset: 0 },
2314
+ outbox: []
2315
+ };
2316
+ const session = new Session(record, this);
2317
+ this.sessions.set(record.thread_id, session);
2318
+ const refuse = (reason) => {
2319
+ this.log.line(`work.assign for ${record.thread_id} refused: ${reason}`);
2320
+ this.event(session, { type: "status", text: `refused: ${reason}` });
2321
+ session.end(reason);
2322
+ this.settle(session);
2323
+ };
2324
+ if (!opened.ok) {
2325
+ refuse(`the request did not pass the accept check (${opened.reason})`);
2326
+ return;
2327
+ }
2328
+ const request = opened.payload;
2329
+ const entry = harness ? this.harnesses[harness] : void 0;
2330
+ if (!entry || typeof request.prompt !== "string" || !request.repo) {
2331
+ refuse("the request is not one this link can run");
2332
+ return;
2333
+ }
2334
+ record.repo = request.repo;
2335
+ record.queue = [request.prompt];
2336
+ const checkout = await this.options.repos.find(request.repo);
2337
+ if (!checkout) {
2338
+ refuse(
2339
+ `no checkout of ${request.repo.owner}/${request.repo.name} under ${this.options.paths.repos}`
2340
+ );
2341
+ return;
2342
+ }
2343
+ const prepared = await prepareWorktree({
2344
+ checkout: checkout.path,
2345
+ workDirectory: this.options.paths.work,
2346
+ threadId: record.thread_id,
2347
+ baseRef: request.base_ref,
2348
+ reposConfig: this.options.paths.reposConfig
2349
+ });
2350
+ if (!prepared.ok) {
2351
+ refuse(`the worktree could not be made: ${prepared.reason}`);
2352
+ return;
2353
+ }
2354
+ record.worktree = prepared.worktree;
2355
+ const socket = this.options.terminalSocket;
2356
+ let client;
2357
+ try {
2358
+ if (socket === void 0) throw new Error("no terminal host is set");
2359
+ client = await HostClient.connect(socket);
2360
+ } catch (error) {
2361
+ refuse(`the terminal host cannot be reached: ${errorText(error)}`);
2362
+ return;
2363
+ }
2364
+ const created = await client.request({
2365
+ type: "create",
2366
+ file: entry.command,
2367
+ args: entry.args,
2368
+ cwd: prepared.worktree.path,
2369
+ label: `thread:${record.thread_id}`
2370
+ });
2371
+ if (!created.ok) {
2372
+ client.close();
2373
+ refuse(`${entry.command} could not start: ${created.error?.message}`);
2374
+ return;
2375
+ }
2376
+ record.socket = socket;
2377
+ record.terminal = created.terminal;
2378
+ this.save(session);
2379
+ this.log.line(
2380
+ `${record.thread_id}: started ${entry.command} in ${prepared.worktree.path} as ${record.terminal}`
2381
+ );
2382
+ await session.drive(client);
2383
+ }
2384
+ async message(command) {
2385
+ const session = this.sessions.get(command.thread_id);
2386
+ if (!session || session.record.ended) {
2387
+ this.log.line(
2388
+ `thread.message for ${command.thread_id}, which runs no session here; acked`
2389
+ );
2390
+ return;
2391
+ }
2392
+ const opened = await this.options.access.open(command.message);
2393
+ if (!opened.ok || typeof opened.payload.text !== "string") {
2394
+ const reason = opened.ok ? "malformed" : opened.reason;
2395
+ this.log.line(
2396
+ `thread.message for ${command.thread_id} refused: ${reason}`
2397
+ );
2398
+ this.event(session, {
2399
+ type: "status",
2400
+ text: `refused a follow-up: ${reason}`
2401
+ });
2402
+ return;
2403
+ }
2404
+ const { message_id: messageId, text } = opened.payload;
2405
+ if (session.record.messages.includes(messageId)) return;
2406
+ session.record.messages.push(messageId);
2407
+ session.queueText(text);
2408
+ }
2409
+ async stop(threadId, why) {
2410
+ const session = this.sessions.get(threadId);
2411
+ if (!session || session.record.ended) {
2412
+ this.log.line(
2413
+ `${why} for ${threadId}, which runs no session here; acked`
2414
+ );
2415
+ return;
2416
+ }
2417
+ this.log.line(`${threadId}: ${why}; ending the session`);
2418
+ await session.kill();
2419
+ session.end(why);
2420
+ }
2421
+ /** After each poll: fences, then everything still owed to the herd. */
2422
+ async afterPoll(answer) {
2423
+ await this.leases(answer.leases);
2424
+ await this.flush();
2425
+ await Promise.all(
2426
+ [...this.sessions.values()].filter((session) => session.record.ended !== void 0).map((session) => session.upload())
2427
+ );
2428
+ }
2429
+ /** Applies the lease statuses of a poll answer: a fenced lease ends its session silently. */
2430
+ async leases(leases) {
2431
+ for (const lease of leases) {
2432
+ const session = this.sessions.get(lease.thread_id);
2433
+ if (lease.status === "fenced" && session && session.record.lease_id === lease.lease_id) {
2434
+ await this.fence(session);
2435
+ }
2436
+ }
2437
+ }
2438
+ /** Kills the terminal and forgets the session, sending nothing more for it. */
2439
+ async fence(session) {
2440
+ if (session.fenced) return;
2441
+ session.fenced = true;
2442
+ this.log.line(
2443
+ `${session.record.thread_id}: lease ${session.record.lease_id} is fenced; ending the session and sending nothing more`
2444
+ );
2445
+ if (!session.record.ended) await session.kill();
2446
+ this.forget(session);
2447
+ }
2448
+ forget(session) {
2449
+ session.dispose();
2450
+ if (this.sessions.get(session.record.thread_id) === session) {
2451
+ this.sessions.delete(session.record.thread_id);
2452
+ }
2453
+ rmSync(this.recordFile(session.record.thread_id), { force: true });
2454
+ session.transcript.remove();
2455
+ }
2456
+ /** Forgets a session once everything about it reached the herd. */
2457
+ settle(session) {
2458
+ if (session.fenced) return;
2459
+ if (session.settled()) this.forget(session);
2460
+ }
2461
+ /** Queues an event for the herd and sends it soon. */
2462
+ event(session, event) {
2463
+ if (session.fenced) return;
2464
+ session.record.outbox.push({
2465
+ event_id: newEventId(),
2466
+ thread_id: session.record.thread_id,
2467
+ lease_id: session.record.lease_id,
2468
+ epoch: session.record.epoch,
2469
+ at: new Date(this.now()).toISOString(),
2470
+ ...event
2471
+ });
2472
+ this.save(session);
2473
+ clearTimeout(this.flushTimer);
2474
+ this.flushTimer = setTimeout(() => void this.flush(), 50);
2475
+ }
2476
+ /** Sends every queued event, at most 100 per request. */
2477
+ flush() {
2478
+ this.flushing ??= (async () => {
2479
+ try {
2480
+ await this.flushOnce();
2481
+ } finally {
2482
+ this.flushing = void 0;
2483
+ }
2484
+ })();
2485
+ return this.flushing;
2486
+ }
2487
+ async flushOnce() {
2488
+ const owners = /* @__PURE__ */ new Map();
2489
+ const events = [];
2490
+ for (const session of this.sessions.values()) {
2491
+ for (const event of session.record.outbox) {
2492
+ if (events.length >= 100) break;
2493
+ owners.set(event.event_id, session);
2494
+ events.push(event);
2495
+ }
2496
+ }
2497
+ if (events.length === 0) return;
2498
+ const answer = await this.herd.post("/v1/events", { events });
2499
+ const results = answer.ok ? answer.body.results : void 0;
2500
+ if (!Array.isArray(results)) {
2501
+ this.log.line(
2502
+ `could not send ${events.length} thread events: ${answer.ok ? `HTTP ${answer.status}` : answer.reason}; they go again`
2503
+ );
2504
+ return;
2505
+ }
2506
+ const fenced = /* @__PURE__ */ new Set();
2507
+ for (const result of results) {
2508
+ const session = owners.get(result.event_id);
2509
+ if (!session) continue;
2510
+ session.record.outbox = session.record.outbox.filter(
2511
+ (event) => event.event_id !== result.event_id
2512
+ );
2513
+ if (result.status === "fenced") fenced.add(session);
2514
+ if (result.status === "invalid") {
2515
+ this.log.line(
2516
+ `the herd called event ${result.event_id} of ${session.record.thread_id} invalid`
2517
+ );
2518
+ }
2519
+ }
2520
+ for (const session of new Set(owners.values())) {
2521
+ if (fenced.has(session)) {
2522
+ await this.fence(session);
2523
+ } else {
2524
+ this.save(session);
2525
+ this.settle(session);
2526
+ }
2527
+ }
2528
+ }
2529
+ /** Ends every timer and connection, leaving the terminals running. */
2530
+ dispose() {
2531
+ clearTimeout(this.flushTimer);
2532
+ for (const session of this.sessions.values()) session.dispose();
2533
+ }
2534
+ }
2535
+ const SETUP_LABEL = "setup:";
2536
+ function isProgram(value) {
2537
+ return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
2538
+ }
2539
+ class SetupTerminals {
2540
+ constructor(options) {
2541
+ this.options = options;
2542
+ this.home = options.home ?? homedir();
2543
+ }
2544
+ home;
2545
+ sockets() {
2546
+ return hostSockets(
2547
+ this.options.terminalsDirectory,
2548
+ this.options.terminalSocket
2549
+ );
2550
+ }
2551
+ /** `terminal.open`: checks the envelope and the program, then starts it. */
2552
+ async open(command) {
2553
+ const { log } = this.options;
2554
+ const opened = await this.options.access.open(
2555
+ command.request
2556
+ );
2557
+ if (!opened.ok) {
2558
+ log.line(`terminal.open refused: ${opened.reason}`);
2559
+ return;
2560
+ }
2561
+ const { open_id: openId, program, cwd } = opened.payload;
2562
+ if (!isProgram(program)) {
2563
+ log.line(
2564
+ `terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
2565
+ );
2566
+ return;
2567
+ }
2568
+ let directory = this.home;
2569
+ if (cwd?.kind === "repo") {
2570
+ const checkout = await this.options.repos.find(cwd.repo);
2571
+ if (!checkout) {
2572
+ log.line(
2573
+ `terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
2574
+ );
2575
+ return;
2576
+ }
2577
+ directory = checkout.path;
2578
+ } else if (cwd?.kind !== "home") {
2579
+ log.line(`terminal.open ${openId} refused: unknown working directory`);
2580
+ return;
2581
+ }
2582
+ const label = `${SETUP_LABEL}${openId}`;
2583
+ const existing = await listTerminals(this.sockets());
2584
+ 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;
2587
+ const socket = this.options.terminalSocket;
2588
+ if (socket === void 0) {
2589
+ log.line(`terminal.open ${openId}: no terminal host is set`);
2590
+ return;
2591
+ }
2592
+ let client;
2593
+ try {
2594
+ client = await HostClient.connect(socket);
2595
+ } catch (error) {
2596
+ log.line(
2597
+ `terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
2598
+ );
2599
+ return;
2600
+ }
2601
+ try {
2602
+ const created = await client.request({
2603
+ type: "create",
2604
+ file,
2605
+ args: program === "shell" ? ["-l"] : [],
2606
+ cwd: directory,
2607
+ label
2608
+ });
2609
+ log.line(
2610
+ created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
2611
+ );
2612
+ } finally {
2613
+ client.close();
2614
+ }
2615
+ }
2616
+ /** Every setup terminal a host still keeps, running or exited. */
2617
+ async list() {
2618
+ const terminals = await listTerminals(this.sockets());
2619
+ return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
2620
+ const entry = {
2621
+ open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
2622
+ terminal: terminal.id,
2623
+ program: this.program(terminal.file),
2624
+ cwd: this.cwd(terminal.cwd)
2625
+ };
2626
+ if (terminal.exited) entry.exit = terminal.exited;
2627
+ return entry;
2628
+ });
2629
+ }
2630
+ program(file) {
2631
+ const name = path.basename(file);
2632
+ const found = Object.entries(SETUP_PROGRAMS).find(
2633
+ ([, command]) => command === name
2634
+ );
2635
+ return found?.[0] ?? "shell";
2636
+ }
2637
+ cwd(directory) {
2638
+ const relative = path.relative(this.options.reposDirectory, directory);
2639
+ const [owner, name, ...rest] = relative.split(path.sep);
2640
+ if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
2641
+ const repo = { owner, name };
2642
+ return { kind: "repo", repo };
2643
+ }
2644
+ return { kind: "home" };
2645
+ }
2646
+ }
2647
+ function send(message) {
2648
+ return new Promise((resolve) => {
2649
+ if (!process.send) {
2650
+ resolve(false);
2651
+ return;
2652
+ }
2653
+ process.send(message, void 0, {}, (error) => resolve(error === null));
2654
+ });
2655
+ }
2656
+ function initialSelfUpdate() {
2657
+ try {
2658
+ const value = JSON.parse(process.env.AIBEX_SELF_UPDATE ?? "");
2659
+ if (typeof value.can === "boolean") {
2660
+ return {
2661
+ can: value.can,
2662
+ reason: typeof value.reason === "string" ? value.reason : null
2663
+ };
2664
+ }
2665
+ } catch {
2666
+ }
2667
+ return { can: true, reason: null };
2668
+ }
2669
+ function main() {
2670
+ const info = readPackageInfo();
2671
+ if (process.argv.includes("--self-test")) {
2672
+ process.stdout.write(
2673
+ `${JSON.stringify({ name: info.name, version: info.version })}
2674
+ `
2675
+ );
2676
+ return;
2677
+ }
2678
+ const host = process.env.AIBEX_HOST;
2679
+ const hostDirectory = process.env.AIBEX_HOST_DIR;
2680
+ if (!host || !hostDirectory || !process.send) {
2681
+ process.stderr.write(
2682
+ "aibex-link is started by aibexd: it needs AIBEX_HOST, AIBEX_HOST_DIR and an IPC channel\n"
2683
+ );
2684
+ process.exitCode = 1;
2685
+ return;
2686
+ }
2687
+ const log = new LinkLog();
2688
+ let status = {
2689
+ type: "status",
2690
+ aibexdVersion: process.env.AIBEX_AIBEXD_VERSION ?? "unknown",
2691
+ selfUpdate: initialSelfUpdate()
2692
+ };
2693
+ const identity = readIdentity(hostDirectory);
2694
+ const paths = linkPaths(hostDirectory);
2695
+ const access = new Access(paths.access);
2696
+ const repos = new Repos(paths.repos);
2697
+ const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
2698
+ const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
2699
+ let poller;
2700
+ let sessions;
2701
+ if (identity) {
2702
+ sessions = new Sessions({
2703
+ paths,
2704
+ access,
2705
+ repos,
2706
+ herd: new HerdClient(identity),
2707
+ log,
2708
+ terminalSocket,
2709
+ terminalsDirectory,
2710
+ timings: Object.fromEntries(
2711
+ Object.entries(DEFAULT_SESSION_TIMINGS).map(
2712
+ ([key, fallback]) => [key, timing(key, fallback)]
2713
+ )
2714
+ )
2715
+ });
2716
+ const setup = new SetupTerminals({
2717
+ access,
2718
+ repos,
2719
+ reposDirectory: paths.repos,
2720
+ terminalSocket,
2721
+ terminalsDirectory,
2722
+ log
2723
+ });
2724
+ const running = sessions;
2725
+ const relay = new Relay({
2726
+ host: identity.host,
2727
+ herd: new HerdClient(identity),
2728
+ access,
2729
+ log,
2730
+ terminalSocket,
2731
+ terminalsDirectory,
2732
+ timings: {
2733
+ idleCloseMs: timing(
2734
+ "relayIdleCloseMs",
2735
+ DEFAULT_RELAY_TIMINGS.idleCloseMs
2736
+ )
2737
+ }
2738
+ });
2739
+ log.line(
2740
+ `aibex-link ${info.version} linked to ${host} as ${identity.machine_id} (${identity.machine_name}) in herd ${identity.herd_id}`
2741
+ );
2742
+ poller = new Poller({
2743
+ identity,
2744
+ hostDirectory,
2745
+ linkVersion: info.version,
2746
+ log,
2747
+ handled: new HandledCommands(hostDirectory),
2748
+ status: () => status,
2749
+ harnesses: detectHarnesses(),
2750
+ access,
2751
+ report: async () => collectReport({
2752
+ paths,
2753
+ repos,
2754
+ access,
2755
+ features: ["sessions", "relay"],
2756
+ sessions: running.list(),
2757
+ setupTerminals: await setup.list()
2758
+ }),
2759
+ handleCommand: async (command) => {
2760
+ if (command.type === "relay.open") {
2761
+ await relay.open();
2762
+ return true;
2763
+ }
2764
+ if (command.type !== "terminal.open") return running.handle(command);
2765
+ await setup.open(command);
2766
+ return true;
2767
+ },
2768
+ afterPoll: (answer) => running.afterPoll(answer),
2769
+ forward: (commandId, request) => send({ type: "control", commandId, request }),
2770
+ backoffInitialMs: timing(
2771
+ "pollBackoffInitialMs",
2772
+ DEFAULT_POLL_BACKOFF_INITIAL_MS
2773
+ ),
2774
+ backoffMaxMs: timing("pollBackoffMaxMs", DEFAULT_POLL_BACKOFF_MAX_MS)
2775
+ });
2776
+ } else {
2777
+ log.line(
2778
+ `aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
2779
+ );
2780
+ }
2781
+ 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
+ });
2796
+ }
2797
+ });
2798
+ void send({ type: "ready" });
2799
+ setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
2800
+ if (poller && sessions) {
2801
+ const [started, recorded] = [poller, sessions];
2802
+ void (async () => {
2803
+ try {
2804
+ await recorded.resume();
2805
+ } catch (error) {
2806
+ log.line(`could not pick up recorded sessions: ${String(error)}`);
2807
+ }
2808
+ started.start();
2809
+ })();
2810
+ }
964
2811
  process.on("disconnect", () => process.exit(0));
965
2812
  process.on("SIGTERM", () => process.exit(0));
966
2813
  process.on("SIGINT", () => process.exit(0));