@aibexhq/aibex-link 0.0.11 → 0.0.12

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 +361 -218
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
1
+ import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, cpSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
2
2
  import path from "node:path";
3
- import { randomBytes, createHash } from "node:crypto";
3
+ import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
4
4
  import { execFile } from "node:child_process";
5
5
  import { homedir, platform, arch, release, tmpdir } from "node:os";
6
6
  import { fileURLToPath } from "node:url";
@@ -986,6 +986,8 @@ function linkPaths(hostDirectory) {
986
986
  state,
987
987
  repos: path.join(state, "repos"),
988
988
  work: path.join(state, "work"),
989
+ scratch: path.join(state, "scratch"),
990
+ bin: path.join(state, "bin"),
989
991
  reposConfig: path.join(state, "repos.json"),
990
992
  config: path.join(state, "config.json"),
991
993
  access: path.join(hostDirectory, "access.json")
@@ -1170,6 +1172,58 @@ class Repos {
1170
1172
  return match(await this.list()) ?? match(await this.list({ fresh: true }));
1171
1173
  }
1172
1174
  }
1175
+ const THREAD_ID$1 = /^t_[A-Za-z0-9]{8,64}$/u;
1176
+ function prepareScratch(scratch, threadId) {
1177
+ if (!THREAD_ID$1.test(threadId))
1178
+ return { ok: false, reason: "not a thread id" };
1179
+ const directory = path.join(scratch, threadId);
1180
+ try {
1181
+ mkdirSync(directory, { recursive: true, mode: 448 });
1182
+ return { ok: true, directory };
1183
+ } catch (error) {
1184
+ return { ok: false, reason: error.message };
1185
+ }
1186
+ }
1187
+ function entries(directory) {
1188
+ try {
1189
+ return readdirSync(directory, { withFileTypes: true });
1190
+ } catch {
1191
+ return [];
1192
+ }
1193
+ }
1194
+ function scanScratch(scratch) {
1195
+ const listings = [];
1196
+ for (const entry of entries(scratch)) {
1197
+ if (!entry.isDirectory() || !THREAD_ID$1.test(entry.name)) continue;
1198
+ const directory = path.join(scratch, entry.name);
1199
+ let createdAt;
1200
+ try {
1201
+ createdAt = statSync(directory).mtime.toISOString();
1202
+ } catch {
1203
+ continue;
1204
+ }
1205
+ listings.push({
1206
+ thread_id: entry.name,
1207
+ scratch: true,
1208
+ dirty: entries(directory).length > 0,
1209
+ unpushed: false,
1210
+ created_at: createdAt
1211
+ });
1212
+ }
1213
+ return listings.toSorted((a, b) => a.thread_id.localeCompare(b.thread_id));
1214
+ }
1215
+ function hasScratch(scratch, threadId) {
1216
+ if (!THREAD_ID$1.test(threadId)) return false;
1217
+ try {
1218
+ return statSync(path.join(scratch, threadId)).isDirectory();
1219
+ } catch {
1220
+ return false;
1221
+ }
1222
+ }
1223
+ function removeScratch(scratch, threadId) {
1224
+ if (!THREAD_ID$1.test(threadId)) return;
1225
+ rmSync(path.join(scratch, threadId), { recursive: true, force: true });
1226
+ }
1173
1227
  const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
1174
1228
  function carryList(reposConfig) {
1175
1229
  const value = readJson(reposConfig);
@@ -1345,9 +1399,9 @@ async function isDirty(worktree, carry) {
1345
1399
  "--untracked-files=all"
1346
1400
  ]);
1347
1401
  if (!status.ok) return false;
1348
- const entries = status.stdout.split("\0");
1349
- for (let index = 0; index < entries.length; index++) {
1350
- const entry = entries[index] ?? "";
1402
+ const entries2 = status.stdout.split("\0");
1403
+ for (let index = 0; index < entries2.length; index++) {
1404
+ const entry = entries2[index] ?? "";
1351
1405
  if (entry === "") continue;
1352
1406
  const code = entry.slice(0, 2);
1353
1407
  const file = entry.slice(3);
@@ -1656,10 +1710,10 @@ class Reaper {
1656
1710
  async report() {
1657
1711
  const now = this.now();
1658
1712
  if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
1659
- this.listing = await scanWorktrees(
1660
- this.options.work,
1661
- this.options.reposConfig
1662
- );
1713
+ this.listing = [
1714
+ ...await scanWorktrees(this.options.work, this.options.reposConfig),
1715
+ ...scanScratch(this.options.scratch)
1716
+ ];
1663
1717
  this.scannedAt = now;
1664
1718
  }
1665
1719
  this.inFlight = [...this.pending];
@@ -1672,9 +1726,20 @@ class Reaper {
1672
1726
  );
1673
1727
  this.inFlight = [];
1674
1728
  }
1729
+ /** A scratch directory: refused while its session is listed, else removed. */
1730
+ releaseScratch(threadId, sessionListed) {
1731
+ if (sessionListed) {
1732
+ return {
1733
+ outcome: "refused",
1734
+ reason: "a session for this thread is listed"
1735
+ };
1736
+ }
1737
+ removeScratch(this.options.scratch, threadId);
1738
+ return { outcome: "released", scratch: true };
1739
+ }
1675
1740
  /** Handles one `work.release`. */
1676
1741
  async release(command, sessionListed) {
1677
- const outcome = await releaseWorktree({
1742
+ const outcome = hasScratch(this.options.scratch, command.thread_id) ? this.releaseScratch(command.thread_id, sessionListed) : await releaseWorktree({
1678
1743
  work: this.options.work,
1679
1744
  threadId: command.thread_id,
1680
1745
  epoch: command.epoch,
@@ -1682,14 +1747,20 @@ class Reaper {
1682
1747
  checkouts: await this.options.checkouts(),
1683
1748
  sessionListed
1684
1749
  });
1685
- const result = {
1750
+ const result = outcome.outcome === "released" ? {
1751
+ command_id: command.command_id,
1752
+ thread_id: command.thread_id,
1753
+ epoch: command.epoch,
1754
+ outcome: "released",
1755
+ ...outcome.salvage === void 0 ? {} : { salvage: outcome.salvage }
1756
+ } : {
1686
1757
  command_id: command.command_id,
1687
1758
  thread_id: command.thread_id,
1688
1759
  epoch: command.epoch,
1689
1760
  ...outcome
1690
1761
  };
1691
1762
  this.options.log(
1692
- outcome.outcome === "released" ? `${command.thread_id}: worktree released${outcome.salvage ? `; its work is saved at ${salvageReference(command.thread_id)} (${outcome.salvage})` : ""}` : `${command.thread_id}: release refused: ${outcome.reason}`
1763
+ outcome.outcome === "released" ? `${command.thread_id}: ${outcome.scratch ? "scratch directory" : "worktree"} released${outcome.salvage ? `; its work is saved at ${salvageReference(command.thread_id)} (${outcome.salvage})` : ""}` : `${command.thread_id}: release refused: ${outcome.reason}`
1693
1764
  );
1694
1765
  this.pending.push(result);
1695
1766
  this.scannedAt = Number.NEGATIVE_INFINITY;
@@ -2765,6 +2836,179 @@ class Transcript {
2765
2836
  rmSync(this.spoolFile, { force: true });
2766
2837
  }
2767
2838
  }
2839
+ const SETUP_LABEL = "setup:";
2840
+ function isProgram(value) {
2841
+ return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
2842
+ }
2843
+ const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
2844
+ function isAddRepo(value) {
2845
+ if (typeof value !== "object" || value === null) return false;
2846
+ const { owner, name } = value;
2847
+ return Object.keys(value).length === 2 && typeof owner === "string" && typeof name === "string" && REPO_PART.test(owner) && REPO_PART.test(name) && owner.length <= 100 && name.length <= 100;
2848
+ }
2849
+ class SetupTerminals {
2850
+ constructor(options) {
2851
+ this.options = options;
2852
+ this.home = options.home ?? homedir();
2853
+ }
2854
+ home;
2855
+ sockets() {
2856
+ return hostSockets(
2857
+ this.options.terminalsDirectory,
2858
+ this.options.terminalSocket
2859
+ );
2860
+ }
2861
+ /** `terminal.open`: checks the envelope and the program, then starts it. */
2862
+ async open(command) {
2863
+ const { log } = this.options;
2864
+ const opened = await this.options.access.open(
2865
+ command.request
2866
+ );
2867
+ if (!opened.ok) {
2868
+ log.line(`terminal.open refused: ${opened.reason}`);
2869
+ return;
2870
+ }
2871
+ const { open_id: openId, program, cwd, repo } = opened.payload;
2872
+ if (!isProgram(program)) {
2873
+ log.line(
2874
+ `terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
2875
+ );
2876
+ return;
2877
+ }
2878
+ if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
2879
+ log.line(
2880
+ program === "repo-add" ? `terminal.open ${openId} refused: repo-add needs a repository whose owner and name are letters, digits, _, . and -, starting with neither - nor .` : `terminal.open ${openId} refused: only repo-add takes a repository`
2881
+ );
2882
+ return;
2883
+ }
2884
+ if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
2885
+ log.line(`terminal.open ${openId} refused: unknown working directory`);
2886
+ return;
2887
+ }
2888
+ let directory = this.home;
2889
+ if (cwd.kind === "repo" && program !== "repo-add") {
2890
+ const checkout = await this.options.repos.find(cwd.repo);
2891
+ if (!checkout) {
2892
+ log.line(
2893
+ `terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
2894
+ );
2895
+ return;
2896
+ }
2897
+ directory = checkout.path;
2898
+ }
2899
+ const label = `${SETUP_LABEL}${openId}`;
2900
+ const existing = await listTerminals(this.sockets());
2901
+ if (existing.some((terminal) => terminal.label === label)) return;
2902
+ const searchPath = this.searchPath();
2903
+ const run = this.command(program, repo);
2904
+ const args = run.args;
2905
+ const file = resolveProgram(run.file, searchPath);
2906
+ const socket = this.options.terminalSocket;
2907
+ if (socket === void 0) {
2908
+ log.line(`terminal.open ${openId}: no terminal host is set`);
2909
+ return;
2910
+ }
2911
+ let client;
2912
+ try {
2913
+ client = await HostClient.connect(socket);
2914
+ } catch (error) {
2915
+ log.line(
2916
+ `terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
2917
+ );
2918
+ return;
2919
+ }
2920
+ try {
2921
+ const created = await client.request({
2922
+ type: "create",
2923
+ file,
2924
+ args,
2925
+ cwd: directory,
2926
+ env: { PATH: searchPath },
2927
+ label
2928
+ });
2929
+ log.line(
2930
+ created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
2931
+ );
2932
+ } finally {
2933
+ client.close();
2934
+ }
2935
+ }
2936
+ /** The file and arguments a program runs; `repo` is checked already. */
2937
+ command(program, repo) {
2938
+ if (program === "repo-add" && repo) {
2939
+ return {
2940
+ file: path.join(this.options.binDirectory, "aibexd"),
2941
+ args: ["repo", "add", `${repo.owner}/${repo.name}`]
2942
+ };
2943
+ }
2944
+ if (program === "shell") {
2945
+ return {
2946
+ file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
2947
+ args: ["-l"]
2948
+ };
2949
+ }
2950
+ return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
2951
+ }
2952
+ searchPath() {
2953
+ return setupSearchPath(this.options.binDirectory, this.options.path);
2954
+ }
2955
+ /** Every setup terminal a host still keeps, running or exited. */
2956
+ async list() {
2957
+ const terminals = await listTerminals(this.sockets());
2958
+ return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
2959
+ const program = this.program(terminal.file);
2960
+ const entry = {
2961
+ open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
2962
+ terminal: terminal.id,
2963
+ program,
2964
+ cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
2965
+ };
2966
+ if (program === "repo-add") {
2967
+ const [owner, name] = (terminal.args?.[2] ?? "").split("/");
2968
+ if (owner && name) entry.repo = { owner, name };
2969
+ }
2970
+ if (terminal.exited) entry.exit = terminal.exited;
2971
+ return entry;
2972
+ });
2973
+ }
2974
+ program(file) {
2975
+ const name = path.basename(file);
2976
+ const found = Object.entries(SETUP_PROGRAMS).find(
2977
+ ([, command]) => command === name
2978
+ );
2979
+ return found?.[0] ?? "shell";
2980
+ }
2981
+ cwd(directory) {
2982
+ const relative = path.relative(
2983
+ path.join(this.options.reposDirectory, GITHUB_HOST),
2984
+ directory
2985
+ );
2986
+ const [owner, name, ...rest] = relative.split(path.sep);
2987
+ if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
2988
+ const repo = { owner, name };
2989
+ return { kind: "repo", repo };
2990
+ }
2991
+ return { kind: "home" };
2992
+ }
2993
+ }
2994
+ function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
2995
+ const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
2996
+ return [binDirectory, ...rest].join(path.delimiter);
2997
+ }
2998
+ function resolveProgram(file, searchPath) {
2999
+ if (file.includes("/")) return file;
3000
+ for (const directory of searchPath.split(path.delimiter)) {
3001
+ if (directory === "") continue;
3002
+ const candidate = path.join(directory, file);
3003
+ try {
3004
+ if (!statSync(candidate).isFile()) continue;
3005
+ accessSync(candidate, constants.X_OK);
3006
+ return candidate;
3007
+ } catch {
3008
+ }
3009
+ }
3010
+ return file;
3011
+ }
2768
3012
  const DEFAULT_SESSION_TIMINGS = {
2769
3013
  readyTimeoutMs: 6e4,
2770
3014
  checkMs: 250,
@@ -2780,6 +3024,12 @@ const STATUS_MAX = 200;
2780
3024
  function newEventId() {
2781
3025
  return `e_${randomBytes(12).toString("base64url")}`;
2782
3026
  }
3027
+ function sameToken(expected, given) {
3028
+ if (!expected) return false;
3029
+ const a = Buffer.from(expected);
3030
+ const b = Buffer.from(given);
3031
+ return a.length === b.length && timingSafeEqual(a, b);
3032
+ }
2783
3033
  function errorText(error) {
2784
3034
  return error instanceof Error ? error.message : String(error);
2785
3035
  }
@@ -3427,7 +3677,8 @@ class Sessions {
3427
3677
  prompted: false,
3428
3678
  messages: [],
3429
3679
  transcript: { base: 0, uploaded: 0, seqOffset: 0 },
3430
- outbox: []
3680
+ outbox: [],
3681
+ handoff_token: randomBytes(32).toString("base64url")
3431
3682
  };
3432
3683
  const session = new Session(record, this);
3433
3684
  this.sessions.set(record.thread_id, session);
@@ -3449,39 +3700,55 @@ class Sessions {
3449
3700
  }
3450
3701
  const request = opened.payload;
3451
3702
  const entry = harness ? this.harnesses[harness] : void 0;
3452
- if (!entry || typeof request.prompt !== "string" || !request.repo) {
3703
+ if (!entry || typeof request.prompt !== "string") {
3453
3704
  refuse("the request is not one this link can run");
3454
3705
  return;
3455
3706
  }
3456
- record.repo = request.repo;
3457
3707
  record.queue = [request.prompt];
3458
- this.save(session);
3459
- const checkout = await this.options.repos.find(request.repo);
3460
- if (stale()) return;
3461
- if (!checkout) {
3462
- refuse(
3463
- `no checkout of ${request.repo.owner}/${request.repo.name} under ${this.options.paths.repos}`
3464
- );
3465
- return;
3466
- }
3467
- const prepared = await prepareWorktree({
3468
- checkout: checkout.path,
3469
- workDirectory: this.options.paths.work,
3470
- threadId: record.thread_id,
3471
- baseRef: request.base_ref,
3472
- reposConfig: this.options.paths.reposConfig
3473
- });
3474
- if (stale()) return;
3475
- if (!prepared.ok) {
3476
- refuse(`the worktree could not be made: ${prepared.reason}`);
3477
- return;
3478
- }
3479
- record.worktree = prepared.worktree;
3480
- if (prepared.restored !== void 0) {
3481
- this.options.log.line(
3482
- `${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
3708
+ let directory;
3709
+ if (request.repo) {
3710
+ record.repo = request.repo;
3711
+ this.save(session);
3712
+ const checkout = await this.options.repos.find(request.repo);
3713
+ if (stale()) return;
3714
+ if (!checkout) {
3715
+ refuse(
3716
+ `no checkout of ${request.repo.owner}/${request.repo.name} under ${this.options.paths.repos}`
3717
+ );
3718
+ return;
3719
+ }
3720
+ const prepared = await prepareWorktree({
3721
+ checkout: checkout.path,
3722
+ workDirectory: this.options.paths.work,
3723
+ threadId: record.thread_id,
3724
+ baseRef: request.base_ref,
3725
+ reposConfig: this.options.paths.reposConfig
3726
+ });
3727
+ if (stale()) return;
3728
+ if (!prepared.ok) {
3729
+ refuse(`the worktree could not be made: ${prepared.reason}`);
3730
+ return;
3731
+ }
3732
+ record.worktree = prepared.worktree;
3733
+ directory = prepared.worktree.path;
3734
+ if (prepared.restored !== void 0) {
3735
+ this.options.log.line(
3736
+ `${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
3737
+ );
3738
+ }
3739
+ } else {
3740
+ const prepared = prepareScratch(
3741
+ this.options.paths.scratch,
3742
+ record.thread_id
3483
3743
  );
3744
+ if (!prepared.ok) {
3745
+ refuse(`the scratch directory could not be made: ${prepared.reason}`);
3746
+ return;
3747
+ }
3748
+ record.scratch = prepared.directory;
3749
+ directory = prepared.directory;
3484
3750
  }
3751
+ this.save(session);
3485
3752
  const socket = this.options.terminalSocket;
3486
3753
  let client;
3487
3754
  try {
@@ -3497,11 +3764,20 @@ class Sessions {
3497
3764
  client.close();
3498
3765
  return;
3499
3766
  }
3767
+ const searchPath = setupSearchPath(
3768
+ this.options.paths.bin,
3769
+ this.options.path
3770
+ );
3500
3771
  const created = await client.request({
3501
3772
  type: "create",
3502
- file: entry.command,
3773
+ file: resolveProgram(entry.command, searchPath),
3503
3774
  args: entry.args,
3504
- cwd: prepared.worktree.path,
3775
+ cwd: directory,
3776
+ env: {
3777
+ PATH: searchPath,
3778
+ AIBEX_THREAD_ID: record.thread_id,
3779
+ AIBEX_HANDOFF_TOKEN: record.handoff_token ?? ""
3780
+ },
3505
3781
  label: `thread:${record.thread_id}`
3506
3782
  });
3507
3783
  if (!created.ok) {
@@ -3521,10 +3797,40 @@ class Sessions {
3521
3797
  session.move({ type: "launched" });
3522
3798
  this.save(session);
3523
3799
  this.log.line(
3524
- `${record.thread_id}: started ${entry.command} in ${prepared.worktree.path} as ${record.terminal}`
3800
+ `${record.thread_id}: started ${entry.command} in ${directory} as ${record.terminal}`
3525
3801
  );
3526
3802
  await session.drive(client);
3527
3803
  }
3804
+ /**
3805
+ * `aibexd handoff` from inside a session: queues a `reroute` event under
3806
+ * the session's lease when the thread runs here with no repository, its
3807
+ * session is running or detached, and the token is the session's.
3808
+ */
3809
+ handoff(request) {
3810
+ const session = this.sessions.get(request.threadId);
3811
+ if (!session || session.phase !== "running" && session.phase !== "detached") {
3812
+ return { ok: false, reason: "no running session of that thread here" };
3813
+ }
3814
+ const { record } = session;
3815
+ if (!sameToken(record.handoff_token, request.token)) {
3816
+ return { ok: false, reason: "the handoff token is not this thread's" };
3817
+ }
3818
+ if (record.repo || record.scratch === void 0) {
3819
+ return {
3820
+ ok: false,
3821
+ reason: "this thread already has a repository; only a thread without one hands off"
3822
+ };
3823
+ }
3824
+ this.event(session, {
3825
+ type: "reroute",
3826
+ repo: { owner: request.repo.owner, name: request.repo.name },
3827
+ ...request.note ? { note: request.note } : {}
3828
+ });
3829
+ this.log.line(
3830
+ `${record.thread_id}: handing off to ${request.repo.owner}/${request.repo.name}`
3831
+ );
3832
+ return { ok: true };
3833
+ }
3528
3834
  async message(command) {
3529
3835
  const session = this.sessions.get(command.thread_id);
3530
3836
  if (!session || session.record.ended) {
@@ -3748,179 +4054,6 @@ class Sessions {
3748
4054
  for (const session of this.sessions.values()) session.dispose();
3749
4055
  }
3750
4056
  }
3751
- const SETUP_LABEL = "setup:";
3752
- function isProgram(value) {
3753
- return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
3754
- }
3755
- const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
3756
- function isAddRepo(value) {
3757
- if (typeof value !== "object" || value === null) return false;
3758
- const { owner, name } = value;
3759
- return Object.keys(value).length === 2 && typeof owner === "string" && typeof name === "string" && REPO_PART.test(owner) && REPO_PART.test(name) && owner.length <= 100 && name.length <= 100;
3760
- }
3761
- class SetupTerminals {
3762
- constructor(options) {
3763
- this.options = options;
3764
- this.home = options.home ?? homedir();
3765
- }
3766
- home;
3767
- sockets() {
3768
- return hostSockets(
3769
- this.options.terminalsDirectory,
3770
- this.options.terminalSocket
3771
- );
3772
- }
3773
- /** `terminal.open`: checks the envelope and the program, then starts it. */
3774
- async open(command) {
3775
- const { log } = this.options;
3776
- const opened = await this.options.access.open(
3777
- command.request
3778
- );
3779
- if (!opened.ok) {
3780
- log.line(`terminal.open refused: ${opened.reason}`);
3781
- return;
3782
- }
3783
- const { open_id: openId, program, cwd, repo } = opened.payload;
3784
- if (!isProgram(program)) {
3785
- log.line(
3786
- `terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
3787
- );
3788
- return;
3789
- }
3790
- if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
3791
- log.line(
3792
- program === "repo-add" ? `terminal.open ${openId} refused: repo-add needs a repository whose owner and name are letters, digits, _, . and -, starting with neither - nor .` : `terminal.open ${openId} refused: only repo-add takes a repository`
3793
- );
3794
- return;
3795
- }
3796
- if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
3797
- log.line(`terminal.open ${openId} refused: unknown working directory`);
3798
- return;
3799
- }
3800
- let directory = this.home;
3801
- if (cwd.kind === "repo" && program !== "repo-add") {
3802
- const checkout = await this.options.repos.find(cwd.repo);
3803
- if (!checkout) {
3804
- log.line(
3805
- `terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
3806
- );
3807
- return;
3808
- }
3809
- directory = checkout.path;
3810
- }
3811
- const label = `${SETUP_LABEL}${openId}`;
3812
- const existing = await listTerminals(this.sockets());
3813
- if (existing.some((terminal) => terminal.label === label)) return;
3814
- const searchPath = this.searchPath();
3815
- const run = this.command(program, repo);
3816
- const args = run.args;
3817
- const file = resolveProgram(run.file, searchPath);
3818
- const socket = this.options.terminalSocket;
3819
- if (socket === void 0) {
3820
- log.line(`terminal.open ${openId}: no terminal host is set`);
3821
- return;
3822
- }
3823
- let client;
3824
- try {
3825
- client = await HostClient.connect(socket);
3826
- } catch (error) {
3827
- log.line(
3828
- `terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
3829
- );
3830
- return;
3831
- }
3832
- try {
3833
- const created = await client.request({
3834
- type: "create",
3835
- file,
3836
- args,
3837
- cwd: directory,
3838
- env: { PATH: searchPath },
3839
- label
3840
- });
3841
- log.line(
3842
- created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
3843
- );
3844
- } finally {
3845
- client.close();
3846
- }
3847
- }
3848
- /** The file and arguments a program runs; `repo` is checked already. */
3849
- command(program, repo) {
3850
- if (program === "repo-add" && repo) {
3851
- return {
3852
- file: path.join(this.options.binDirectory, "aibexd"),
3853
- args: ["repo", "add", `${repo.owner}/${repo.name}`]
3854
- };
3855
- }
3856
- if (program === "shell") {
3857
- return {
3858
- file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
3859
- args: ["-l"]
3860
- };
3861
- }
3862
- return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
3863
- }
3864
- searchPath() {
3865
- return setupSearchPath(this.options.binDirectory, this.options.path);
3866
- }
3867
- /** Every setup terminal a host still keeps, running or exited. */
3868
- async list() {
3869
- const terminals = await listTerminals(this.sockets());
3870
- return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
3871
- const program = this.program(terminal.file);
3872
- const entry = {
3873
- open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
3874
- terminal: terminal.id,
3875
- program,
3876
- cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
3877
- };
3878
- if (program === "repo-add") {
3879
- const [owner, name] = (terminal.args?.[2] ?? "").split("/");
3880
- if (owner && name) entry.repo = { owner, name };
3881
- }
3882
- if (terminal.exited) entry.exit = terminal.exited;
3883
- return entry;
3884
- });
3885
- }
3886
- program(file) {
3887
- const name = path.basename(file);
3888
- const found = Object.entries(SETUP_PROGRAMS).find(
3889
- ([, command]) => command === name
3890
- );
3891
- return found?.[0] ?? "shell";
3892
- }
3893
- cwd(directory) {
3894
- const relative = path.relative(
3895
- path.join(this.options.reposDirectory, GITHUB_HOST),
3896
- directory
3897
- );
3898
- const [owner, name, ...rest] = relative.split(path.sep);
3899
- if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
3900
- const repo = { owner, name };
3901
- return { kind: "repo", repo };
3902
- }
3903
- return { kind: "home" };
3904
- }
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
- }
3910
- function resolveProgram(file, searchPath) {
3911
- if (file.includes("/")) return file;
3912
- for (const directory of searchPath.split(path.delimiter)) {
3913
- if (directory === "") continue;
3914
- const candidate = path.join(directory, file);
3915
- try {
3916
- if (!statSync(candidate).isFile()) continue;
3917
- accessSync(candidate, constants.X_OK);
3918
- return candidate;
3919
- } catch {
3920
- }
3921
- }
3922
- return file;
3923
- }
3924
4057
  function send(message) {
3925
4058
  return new Promise((resolve) => {
3926
4059
  if (!process.send) {
@@ -4005,7 +4138,7 @@ function main() {
4005
4138
  access,
4006
4139
  repos,
4007
4140
  reposDirectory: paths.repos,
4008
- binDirectory: path.join(paths.state, "bin"),
4141
+ binDirectory: paths.bin,
4009
4142
  terminalSocket,
4010
4143
  terminalsDirectory,
4011
4144
  log
@@ -4022,6 +4155,7 @@ function main() {
4022
4155
  statuses = signIns;
4023
4156
  reaper = new Reaper({
4024
4157
  work: paths.work,
4158
+ scratch: paths.scratch,
4025
4159
  reposConfig: paths.reposConfig,
4026
4160
  checkouts: async () => {
4027
4161
  const checkouts = await repos.list();
@@ -4063,7 +4197,7 @@ function main() {
4063
4197
  paths,
4064
4198
  repos,
4065
4199
  access,
4066
- features: ["sessions", "relay", "setup"],
4200
+ features: ["sessions", "relay", "setup", "scratch", "handoff"],
4067
4201
  sessions: running.list(),
4068
4202
  setupTerminals,
4069
4203
  ...await reaping.report()
@@ -4110,6 +4244,15 @@ function main() {
4110
4244
  };
4111
4245
  break;
4112
4246
  }
4247
+ case "handoff": {
4248
+ const { requestId, ...request } = message;
4249
+ const answer = sessions ? sessions.handoff(request) : {
4250
+ ok: false,
4251
+ reason: "this machine has not joined a herd"
4252
+ };
4253
+ void send({ type: "handed-off", requestId, ...answer });
4254
+ break;
4255
+ }
4113
4256
  case "diagnostics": {
4114
4257
  const mismatch = access.mismatch;
4115
4258
  poller?.attachDiagnostics({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.11",
3
+ "version": "0.0.12",
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": {