@aibexhq/aibex-link 0.0.10 → 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.
- package/dist/index.js +568 -221
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync,
|
|
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")
|
|
@@ -1051,6 +1053,23 @@ async function collectReport(options) {
|
|
|
1051
1053
|
}
|
|
1052
1054
|
return report;
|
|
1053
1055
|
}
|
|
1056
|
+
function parseLinkHealth(value) {
|
|
1057
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
1058
|
+
const { failures, rolled_back: rolledBack } = value;
|
|
1059
|
+
if (typeof failures !== "number" || !Number.isInteger(failures) || failures < 0) {
|
|
1060
|
+
return void 0;
|
|
1061
|
+
}
|
|
1062
|
+
if (rolledBack === void 0) return { failures };
|
|
1063
|
+
if (typeof rolledBack !== "object" || rolledBack === null) return void 0;
|
|
1064
|
+
const { from, to, at, reason } = rolledBack;
|
|
1065
|
+
if (typeof from !== "string" || typeof to !== "string" || typeof at !== "string" || !Number.isFinite(Date.parse(at)) || typeof reason !== "string") {
|
|
1066
|
+
return void 0;
|
|
1067
|
+
}
|
|
1068
|
+
return {
|
|
1069
|
+
failures,
|
|
1070
|
+
rolled_back: { from, to, at, reason: reason.slice(0, 500) }
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1054
1073
|
function buildHeartbeat(input) {
|
|
1055
1074
|
const machine = describeMachine();
|
|
1056
1075
|
const heartbeat = {
|
|
@@ -1075,6 +1094,7 @@ function buildHeartbeat(input) {
|
|
|
1075
1094
|
if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
|
|
1076
1095
|
if (worktrees) heartbeat.worktrees = worktrees;
|
|
1077
1096
|
if (releases) heartbeat.releases = releases;
|
|
1097
|
+
if (input.linkHealth) heartbeat.link_health = input.linkHealth;
|
|
1078
1098
|
if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
|
|
1079
1099
|
return heartbeat;
|
|
1080
1100
|
}
|
|
@@ -1152,6 +1172,58 @@ class Repos {
|
|
|
1152
1172
|
return match(await this.list()) ?? match(await this.list({ fresh: true }));
|
|
1153
1173
|
}
|
|
1154
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
|
+
}
|
|
1155
1227
|
const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
|
|
1156
1228
|
function carryList(reposConfig) {
|
|
1157
1229
|
const value = readJson(reposConfig);
|
|
@@ -1327,9 +1399,9 @@ async function isDirty(worktree, carry) {
|
|
|
1327
1399
|
"--untracked-files=all"
|
|
1328
1400
|
]);
|
|
1329
1401
|
if (!status.ok) return false;
|
|
1330
|
-
const
|
|
1331
|
-
for (let index = 0; index <
|
|
1332
|
-
const entry =
|
|
1402
|
+
const entries2 = status.stdout.split("\0");
|
|
1403
|
+
for (let index = 0; index < entries2.length; index++) {
|
|
1404
|
+
const entry = entries2[index] ?? "";
|
|
1333
1405
|
if (entry === "") continue;
|
|
1334
1406
|
const code = entry.slice(0, 2);
|
|
1335
1407
|
const file = entry.slice(3);
|
|
@@ -1638,10 +1710,10 @@ class Reaper {
|
|
|
1638
1710
|
async report() {
|
|
1639
1711
|
const now = this.now();
|
|
1640
1712
|
if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
|
|
1641
|
-
this.listing =
|
|
1642
|
-
this.options.work,
|
|
1643
|
-
this.options.
|
|
1644
|
-
|
|
1713
|
+
this.listing = [
|
|
1714
|
+
...await scanWorktrees(this.options.work, this.options.reposConfig),
|
|
1715
|
+
...scanScratch(this.options.scratch)
|
|
1716
|
+
];
|
|
1645
1717
|
this.scannedAt = now;
|
|
1646
1718
|
}
|
|
1647
1719
|
this.inFlight = [...this.pending];
|
|
@@ -1654,9 +1726,20 @@ class Reaper {
|
|
|
1654
1726
|
);
|
|
1655
1727
|
this.inFlight = [];
|
|
1656
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
|
+
}
|
|
1657
1740
|
/** Handles one `work.release`. */
|
|
1658
1741
|
async release(command, sessionListed) {
|
|
1659
|
-
const outcome = await releaseWorktree({
|
|
1742
|
+
const outcome = hasScratch(this.options.scratch, command.thread_id) ? this.releaseScratch(command.thread_id, sessionListed) : await releaseWorktree({
|
|
1660
1743
|
work: this.options.work,
|
|
1661
1744
|
threadId: command.thread_id,
|
|
1662
1745
|
epoch: command.epoch,
|
|
@@ -1664,14 +1747,20 @@ class Reaper {
|
|
|
1664
1747
|
checkouts: await this.options.checkouts(),
|
|
1665
1748
|
sessionListed
|
|
1666
1749
|
});
|
|
1667
|
-
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
|
+
} : {
|
|
1668
1757
|
command_id: command.command_id,
|
|
1669
1758
|
thread_id: command.thread_id,
|
|
1670
1759
|
epoch: command.epoch,
|
|
1671
1760
|
...outcome
|
|
1672
1761
|
};
|
|
1673
1762
|
this.options.log(
|
|
1674
|
-
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}`
|
|
1675
1764
|
);
|
|
1676
1765
|
this.pending.push(result);
|
|
1677
1766
|
this.scannedAt = Number.NEGATIVE_INFINITY;
|
|
@@ -1844,6 +1933,7 @@ class Poller {
|
|
|
1844
1933
|
linkVersion: this.options.linkVersion,
|
|
1845
1934
|
aibexdVersion: status.aibexdVersion,
|
|
1846
1935
|
selfUpdate: status.selfUpdate,
|
|
1936
|
+
linkHealth: status.linkHealth,
|
|
1847
1937
|
harnesses: typeof this.options.harnesses === "function" ? this.options.harnesses() : this.options.harnesses,
|
|
1848
1938
|
acks,
|
|
1849
1939
|
diagnostics,
|
|
@@ -2437,10 +2527,11 @@ class Relay {
|
|
|
2437
2527
|
const HARNESSES = {
|
|
2438
2528
|
// The input box: a full-width rule, then `❯` and the placeholder. The
|
|
2439
2529
|
// folder trust dialog also starts a line with `❯`, but never under a rule.
|
|
2530
|
+
// Claude Code 2.1.3xx puts a no-break space after `❯`.
|
|
2440
2531
|
claude: {
|
|
2441
2532
|
command: "claude",
|
|
2442
2533
|
args: [],
|
|
2443
|
-
ready: /─{20,}\n❯(?: |$)/mu,
|
|
2534
|
+
ready: /─{20,}\n❯(?:[ \u00A0]|$)/mu,
|
|
2444
2535
|
multiline: "paste"
|
|
2445
2536
|
},
|
|
2446
2537
|
// The composer line `› Ask Codex to do anything`. The update notice, the
|
|
@@ -2512,6 +2603,142 @@ function reportedState(phase, hints) {
|
|
|
2512
2603
|
}
|
|
2513
2604
|
}
|
|
2514
2605
|
}
|
|
2606
|
+
const REPLY_MAX = 16 * 1024;
|
|
2607
|
+
const REPLY_TRUNCATED = "[… earlier output cut]\n";
|
|
2608
|
+
const REPLY_SCROLLBACK = 2e3;
|
|
2609
|
+
const ESCAPES = (
|
|
2610
|
+
// eslint-disable-next-line no-control-regex
|
|
2611
|
+
/\u001B\[[0-?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B[@-Z\\-_]|[\u0000-\u0008\u000B-\u001F\u007F]/gu
|
|
2612
|
+
);
|
|
2613
|
+
const DRAWING = "─━═│┃║╭╮╰╯┌┐└┘├┤┬┴┼╔╗╚╝╠╣╦╩╬┄┅┈┉╌╍▀▄█▌▐▔▁░▒▓■▪";
|
|
2614
|
+
const DRAWING_ONLY = new RegExp(
|
|
2615
|
+
String.raw`^[\s${DRAWING}\-_=~]*[${DRAWING}][\s${DRAWING}\-_=~]*$`,
|
|
2616
|
+
"u"
|
|
2617
|
+
);
|
|
2618
|
+
const LABELLED_RULE = /^\s*[─━═]{2,}.*[─━═]{3,}\s*$/u;
|
|
2619
|
+
const BOX_SIDES = /^\s*[│┃║]\s?(.*?)\s*[│┃║]\s*$/u;
|
|
2620
|
+
const GUTTER = /^(\s*)([⏺●⎿│┃›❯>→▶•])(?: |$)/u;
|
|
2621
|
+
const CHROME = [
|
|
2622
|
+
/\b(?:esc|ctrl\+c) to (?:interrupt|cancel|stop)\b/iu,
|
|
2623
|
+
/^\s*[⠀-⣿]/u,
|
|
2624
|
+
/^\s*[✻✶✳✢✽✺✹✸✷◐◓◑◒◴◷◶◵]\s/u,
|
|
2625
|
+
/^\s*[·∗*]\s+\S+(?:…|\.\.\.)/u,
|
|
2626
|
+
/\?\s+for shortcuts/iu,
|
|
2627
|
+
/\bshift\+tab to\b/iu,
|
|
2628
|
+
/^\s*⏵⏵/u,
|
|
2629
|
+
/^\s*\d{1,2}:\d{2}(?::\d{2})?\s?(?:[AP]M)?\s*$/iu
|
|
2630
|
+
];
|
|
2631
|
+
const INFORMATION_OPEN = "<aibexd-information>";
|
|
2632
|
+
const INFORMATION_CLOSE = "</aibexd-information>";
|
|
2633
|
+
function stripEscapes(text) {
|
|
2634
|
+
return text.replaceAll(ESCAPES, "").replaceAll(" ", " ");
|
|
2635
|
+
}
|
|
2636
|
+
function withoutGutter(line) {
|
|
2637
|
+
const match = GUTTER.exec(line);
|
|
2638
|
+
const indent = match?.[1] ?? "";
|
|
2639
|
+
if (!match || match[2] === "•" && indent !== "") return line;
|
|
2640
|
+
return indent + " ".repeat(match[0].length - indent.length) + line.slice(match[0].length);
|
|
2641
|
+
}
|
|
2642
|
+
function normalize(text) {
|
|
2643
|
+
return text.split("\n").map((line) => withoutGutter(stripEscapes(line))).join(" ").replaceAll(/\s+/gu, " ").trim();
|
|
2644
|
+
}
|
|
2645
|
+
function undecorate(text) {
|
|
2646
|
+
const kept = [];
|
|
2647
|
+
let inInformation = false;
|
|
2648
|
+
for (const raw of stripEscapes(text).split("\n")) {
|
|
2649
|
+
let line = raw.trimEnd();
|
|
2650
|
+
const sides = BOX_SIDES.exec(line);
|
|
2651
|
+
if (sides) line = sides[1] ?? "";
|
|
2652
|
+
line = withoutGutter(line).trimEnd();
|
|
2653
|
+
const bare = line.trim();
|
|
2654
|
+
if (inInformation) {
|
|
2655
|
+
if (bare.includes(INFORMATION_CLOSE)) inInformation = false;
|
|
2656
|
+
continue;
|
|
2657
|
+
}
|
|
2658
|
+
if (bare.startsWith(INFORMATION_OPEN)) {
|
|
2659
|
+
inInformation = !bare.includes(INFORMATION_CLOSE);
|
|
2660
|
+
continue;
|
|
2661
|
+
}
|
|
2662
|
+
if (bare === "") {
|
|
2663
|
+
kept.push("");
|
|
2664
|
+
continue;
|
|
2665
|
+
}
|
|
2666
|
+
if (DRAWING_ONLY.test(bare) || LABELLED_RULE.test(bare)) continue;
|
|
2667
|
+
if (CHROME.some((pattern) => pattern.test(bare))) continue;
|
|
2668
|
+
kept.push(line);
|
|
2669
|
+
}
|
|
2670
|
+
const lines = [];
|
|
2671
|
+
for (const line of kept) {
|
|
2672
|
+
if (line === "" && (lines.length === 0 || lines.at(-1) === "")) continue;
|
|
2673
|
+
lines.push(line);
|
|
2674
|
+
}
|
|
2675
|
+
while (lines.at(-1) === "") lines.pop();
|
|
2676
|
+
const indents = lines.filter((line) => line !== "").map((line) => /^ */u.exec(line)?.[0].length ?? 0);
|
|
2677
|
+
const indent = indents.length > 0 ? Math.min(...indents) : 0;
|
|
2678
|
+
return lines.map((line) => line.slice(indent)).join("\n");
|
|
2679
|
+
}
|
|
2680
|
+
function inputStart(text, ready) {
|
|
2681
|
+
const flags = ready.flags.includes("g") ? ready.flags : `${ready.flags}g`;
|
|
2682
|
+
let last = -1;
|
|
2683
|
+
for (const match of text.matchAll(new RegExp(ready.source, flags))) {
|
|
2684
|
+
last = match.index;
|
|
2685
|
+
}
|
|
2686
|
+
if (last === -1) return text.length;
|
|
2687
|
+
return text.lastIndexOf("\n", last - 1) + 1;
|
|
2688
|
+
}
|
|
2689
|
+
const PROMPT_PREFIX = /^\S{0,12}[>›❯$%#:→] ?/u;
|
|
2690
|
+
function echoed(line, typed) {
|
|
2691
|
+
const prefix = PROMPT_PREFIX.exec(line);
|
|
2692
|
+
if (!prefix) return line;
|
|
2693
|
+
const rest = line.slice(prefix[0].length);
|
|
2694
|
+
const length = Math.min(rest.length, typed.length);
|
|
2695
|
+
return length > 0 && rest.slice(0, length) === typed.slice(0, length) ? rest : line;
|
|
2696
|
+
}
|
|
2697
|
+
function afterEcho(lines, sent) {
|
|
2698
|
+
const typed = normalize(sent);
|
|
2699
|
+
if (typed === "") return void 0;
|
|
2700
|
+
const shortest = Math.min(typed.length, 8);
|
|
2701
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
2702
|
+
const line = echoed(normalize(lines[index] ?? ""), typed);
|
|
2703
|
+
if (line.length < shortest) continue;
|
|
2704
|
+
const length = Math.min(line.length, typed.length);
|
|
2705
|
+
if (line.slice(0, length) !== typed.slice(0, length)) continue;
|
|
2706
|
+
if (typed.length < 8 && line !== typed) continue;
|
|
2707
|
+
let echo = line;
|
|
2708
|
+
let next = index + 1;
|
|
2709
|
+
while (next < lines.length && echo.length < typed.length) {
|
|
2710
|
+
const more = normalize(lines[next] ?? "");
|
|
2711
|
+
if (more === "") {
|
|
2712
|
+
next += 1;
|
|
2713
|
+
continue;
|
|
2714
|
+
}
|
|
2715
|
+
if (typed.startsWith(`${echo} ${more}`)) echo = `${echo} ${more}`;
|
|
2716
|
+
else if (typed.startsWith(`${echo}${more}`)) echo += more;
|
|
2717
|
+
else break;
|
|
2718
|
+
next += 1;
|
|
2719
|
+
}
|
|
2720
|
+
return next;
|
|
2721
|
+
}
|
|
2722
|
+
return void 0;
|
|
2723
|
+
}
|
|
2724
|
+
const PASTE_PLACEHOLDER = /\[Pasted[^\]]*\]/u;
|
|
2725
|
+
function extractReply(screen, options) {
|
|
2726
|
+
const text = stripEscapes(screen);
|
|
2727
|
+
const above = text.slice(0, inputStart(text, options.ready));
|
|
2728
|
+
const lines = above.split("\n");
|
|
2729
|
+
let start = afterEcho(lines, options.sent);
|
|
2730
|
+
if (start === void 0) {
|
|
2731
|
+
const placeholder = lines.findLastIndex(
|
|
2732
|
+
(line) => PASTE_PLACEHOLDER.test(line)
|
|
2733
|
+
);
|
|
2734
|
+
start = placeholder === -1 ? 0 : placeholder + 1;
|
|
2735
|
+
}
|
|
2736
|
+
const reply = undecorate(lines.slice(start).join("\n"));
|
|
2737
|
+
if (reply.length <= REPLY_MAX) return reply;
|
|
2738
|
+
const tail = reply.slice(reply.length - (REPLY_MAX - REPLY_TRUNCATED.length));
|
|
2739
|
+
const newline = tail.indexOf("\n");
|
|
2740
|
+
return `${REPLY_TRUNCATED}${newline === -1 ? tail : tail.slice(newline + 1)}`;
|
|
2741
|
+
}
|
|
2515
2742
|
const MAX_CHUNK_BYTES = 1024 * 1024;
|
|
2516
2743
|
class Transcript {
|
|
2517
2744
|
constructor(spoolFile, state) {
|
|
@@ -2609,6 +2836,179 @@ class Transcript {
|
|
|
2609
2836
|
rmSync(this.spoolFile, { force: true });
|
|
2610
2837
|
}
|
|
2611
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
|
+
}
|
|
2612
3012
|
const DEFAULT_SESSION_TIMINGS = {
|
|
2613
3013
|
readyTimeoutMs: 6e4,
|
|
2614
3014
|
checkMs: 250,
|
|
@@ -2624,6 +3024,12 @@ const STATUS_MAX = 200;
|
|
|
2624
3024
|
function newEventId() {
|
|
2625
3025
|
return `e_${randomBytes(12).toString("base64url")}`;
|
|
2626
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
|
+
}
|
|
2627
3033
|
function errorText(error) {
|
|
2628
3034
|
return error instanceof Error ? error.message : String(error);
|
|
2629
3035
|
}
|
|
@@ -2839,7 +3245,11 @@ class Session {
|
|
|
2839
3245
|
}
|
|
2840
3246
|
case "idle": {
|
|
2841
3247
|
this.busy = false;
|
|
3248
|
+
const was = this.activity;
|
|
2842
3249
|
this.activity = "idle";
|
|
3250
|
+
if (was === "working" && this.phase === "running") {
|
|
3251
|
+
void this.captureReply();
|
|
3252
|
+
}
|
|
2843
3253
|
break;
|
|
2844
3254
|
}
|
|
2845
3255
|
case "title": {
|
|
@@ -2929,6 +3339,7 @@ class Session {
|
|
|
2929
3339
|
});
|
|
2930
3340
|
if (!pressed.ok || !this.live(client)) return;
|
|
2931
3341
|
this.record.queue.shift();
|
|
3342
|
+
this.record.last_sent = text;
|
|
2932
3343
|
const first = !this.record.prompted;
|
|
2933
3344
|
this.record.prompted = true;
|
|
2934
3345
|
this.lastSendAt = this.manager.now();
|
|
@@ -2940,6 +3351,38 @@ class Session {
|
|
|
2940
3351
|
`${this.record.thread_id}: ${first ? "typed the prompt" : "typed a follow-up"} into ${this.record.harness}`
|
|
2941
3352
|
);
|
|
2942
3353
|
}
|
|
3354
|
+
/**
|
|
3355
|
+
* On each move from working to idle: the screen below the last text typed
|
|
3356
|
+
* in, undecorated, as a `reply` event, unless it is empty or the same as
|
|
3357
|
+
* the last reply. A screen without the ready marker (a dialog) waits for
|
|
3358
|
+
* the next idle.
|
|
3359
|
+
*/
|
|
3360
|
+
async captureReply() {
|
|
3361
|
+
const client = this.client;
|
|
3362
|
+
const sent = this.record.last_sent;
|
|
3363
|
+
if (!client || sent === void 0 || this.fenced) return;
|
|
3364
|
+
const snapshot = await client.request({
|
|
3365
|
+
type: "snapshot",
|
|
3366
|
+
terminal: this.record.terminal,
|
|
3367
|
+
lines: REPLY_SCROLLBACK
|
|
3368
|
+
});
|
|
3369
|
+
if (!snapshot.ok || this.client !== client || this.phase !== "running" || this.record.last_sent !== sent || !this.harness.ready.test(String(snapshot.text))) {
|
|
3370
|
+
return;
|
|
3371
|
+
}
|
|
3372
|
+
const text = extractReply(String(snapshot.all ?? snapshot.text), {
|
|
3373
|
+
sent,
|
|
3374
|
+
ready: this.harness.ready
|
|
3375
|
+
});
|
|
3376
|
+
if (text === "") return;
|
|
3377
|
+
const hash = createHash("sha256").update(text).digest("base64url");
|
|
3378
|
+
if (hash === this.record.reply_hash) return;
|
|
3379
|
+
this.record.reply_hash = hash;
|
|
3380
|
+
this.manager.event(this, {
|
|
3381
|
+
type: "reply",
|
|
3382
|
+
text,
|
|
3383
|
+
...text.startsWith(REPLY_TRUNCATED) ? { truncated: true } : {}
|
|
3384
|
+
});
|
|
3385
|
+
}
|
|
2943
3386
|
/** A title becomes a `status` event, at most one per interval, the latest winning. */
|
|
2944
3387
|
setStatus(text) {
|
|
2945
3388
|
const status = text.trim().slice(0, STATUS_MAX);
|
|
@@ -3234,7 +3677,8 @@ class Sessions {
|
|
|
3234
3677
|
prompted: false,
|
|
3235
3678
|
messages: [],
|
|
3236
3679
|
transcript: { base: 0, uploaded: 0, seqOffset: 0 },
|
|
3237
|
-
outbox: []
|
|
3680
|
+
outbox: [],
|
|
3681
|
+
handoff_token: randomBytes(32).toString("base64url")
|
|
3238
3682
|
};
|
|
3239
3683
|
const session = new Session(record, this);
|
|
3240
3684
|
this.sessions.set(record.thread_id, session);
|
|
@@ -3256,39 +3700,55 @@ class Sessions {
|
|
|
3256
3700
|
}
|
|
3257
3701
|
const request = opened.payload;
|
|
3258
3702
|
const entry = harness ? this.harnesses[harness] : void 0;
|
|
3259
|
-
if (!entry || typeof request.prompt !== "string"
|
|
3703
|
+
if (!entry || typeof request.prompt !== "string") {
|
|
3260
3704
|
refuse("the request is not one this link can run");
|
|
3261
3705
|
return;
|
|
3262
3706
|
}
|
|
3263
|
-
record.repo = request.repo;
|
|
3264
3707
|
record.queue = [request.prompt];
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
)
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
return;
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
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
|
|
3290
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;
|
|
3291
3750
|
}
|
|
3751
|
+
this.save(session);
|
|
3292
3752
|
const socket = this.options.terminalSocket;
|
|
3293
3753
|
let client;
|
|
3294
3754
|
try {
|
|
@@ -3304,11 +3764,20 @@ class Sessions {
|
|
|
3304
3764
|
client.close();
|
|
3305
3765
|
return;
|
|
3306
3766
|
}
|
|
3767
|
+
const searchPath = setupSearchPath(
|
|
3768
|
+
this.options.paths.bin,
|
|
3769
|
+
this.options.path
|
|
3770
|
+
);
|
|
3307
3771
|
const created = await client.request({
|
|
3308
3772
|
type: "create",
|
|
3309
|
-
file: entry.command,
|
|
3773
|
+
file: resolveProgram(entry.command, searchPath),
|
|
3310
3774
|
args: entry.args,
|
|
3311
|
-
cwd:
|
|
3775
|
+
cwd: directory,
|
|
3776
|
+
env: {
|
|
3777
|
+
PATH: searchPath,
|
|
3778
|
+
AIBEX_THREAD_ID: record.thread_id,
|
|
3779
|
+
AIBEX_HANDOFF_TOKEN: record.handoff_token ?? ""
|
|
3780
|
+
},
|
|
3312
3781
|
label: `thread:${record.thread_id}`
|
|
3313
3782
|
});
|
|
3314
3783
|
if (!created.ok) {
|
|
@@ -3328,10 +3797,40 @@ class Sessions {
|
|
|
3328
3797
|
session.move({ type: "launched" });
|
|
3329
3798
|
this.save(session);
|
|
3330
3799
|
this.log.line(
|
|
3331
|
-
`${record.thread_id}: started ${entry.command} in ${
|
|
3800
|
+
`${record.thread_id}: started ${entry.command} in ${directory} as ${record.terminal}`
|
|
3332
3801
|
);
|
|
3333
3802
|
await session.drive(client);
|
|
3334
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
|
+
}
|
|
3335
3834
|
async message(command) {
|
|
3336
3835
|
const session = this.sessions.get(command.thread_id);
|
|
3337
3836
|
if (!session || session.record.ended) {
|
|
@@ -3555,179 +4054,6 @@ class Sessions {
|
|
|
3555
4054
|
for (const session of this.sessions.values()) session.dispose();
|
|
3556
4055
|
}
|
|
3557
4056
|
}
|
|
3558
|
-
const SETUP_LABEL = "setup:";
|
|
3559
|
-
function isProgram(value) {
|
|
3560
|
-
return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
|
|
3561
|
-
}
|
|
3562
|
-
const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
|
|
3563
|
-
function isAddRepo(value) {
|
|
3564
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3565
|
-
const { owner, name } = value;
|
|
3566
|
-
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;
|
|
3567
|
-
}
|
|
3568
|
-
class SetupTerminals {
|
|
3569
|
-
constructor(options) {
|
|
3570
|
-
this.options = options;
|
|
3571
|
-
this.home = options.home ?? homedir();
|
|
3572
|
-
}
|
|
3573
|
-
home;
|
|
3574
|
-
sockets() {
|
|
3575
|
-
return hostSockets(
|
|
3576
|
-
this.options.terminalsDirectory,
|
|
3577
|
-
this.options.terminalSocket
|
|
3578
|
-
);
|
|
3579
|
-
}
|
|
3580
|
-
/** `terminal.open`: checks the envelope and the program, then starts it. */
|
|
3581
|
-
async open(command) {
|
|
3582
|
-
const { log } = this.options;
|
|
3583
|
-
const opened = await this.options.access.open(
|
|
3584
|
-
command.request
|
|
3585
|
-
);
|
|
3586
|
-
if (!opened.ok) {
|
|
3587
|
-
log.line(`terminal.open refused: ${opened.reason}`);
|
|
3588
|
-
return;
|
|
3589
|
-
}
|
|
3590
|
-
const { open_id: openId, program, cwd, repo } = opened.payload;
|
|
3591
|
-
if (!isProgram(program)) {
|
|
3592
|
-
log.line(
|
|
3593
|
-
`terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
|
|
3594
|
-
);
|
|
3595
|
-
return;
|
|
3596
|
-
}
|
|
3597
|
-
if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
|
|
3598
|
-
log.line(
|
|
3599
|
-
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`
|
|
3600
|
-
);
|
|
3601
|
-
return;
|
|
3602
|
-
}
|
|
3603
|
-
if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
|
|
3604
|
-
log.line(`terminal.open ${openId} refused: unknown working directory`);
|
|
3605
|
-
return;
|
|
3606
|
-
}
|
|
3607
|
-
let directory = this.home;
|
|
3608
|
-
if (cwd.kind === "repo" && program !== "repo-add") {
|
|
3609
|
-
const checkout = await this.options.repos.find(cwd.repo);
|
|
3610
|
-
if (!checkout) {
|
|
3611
|
-
log.line(
|
|
3612
|
-
`terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
|
|
3613
|
-
);
|
|
3614
|
-
return;
|
|
3615
|
-
}
|
|
3616
|
-
directory = checkout.path;
|
|
3617
|
-
}
|
|
3618
|
-
const label = `${SETUP_LABEL}${openId}`;
|
|
3619
|
-
const existing = await listTerminals(this.sockets());
|
|
3620
|
-
if (existing.some((terminal) => terminal.label === label)) return;
|
|
3621
|
-
const searchPath = this.searchPath();
|
|
3622
|
-
const run = this.command(program, repo);
|
|
3623
|
-
const args = run.args;
|
|
3624
|
-
const file = resolveProgram(run.file, searchPath);
|
|
3625
|
-
const socket = this.options.terminalSocket;
|
|
3626
|
-
if (socket === void 0) {
|
|
3627
|
-
log.line(`terminal.open ${openId}: no terminal host is set`);
|
|
3628
|
-
return;
|
|
3629
|
-
}
|
|
3630
|
-
let client;
|
|
3631
|
-
try {
|
|
3632
|
-
client = await HostClient.connect(socket);
|
|
3633
|
-
} catch (error) {
|
|
3634
|
-
log.line(
|
|
3635
|
-
`terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
|
|
3636
|
-
);
|
|
3637
|
-
return;
|
|
3638
|
-
}
|
|
3639
|
-
try {
|
|
3640
|
-
const created = await client.request({
|
|
3641
|
-
type: "create",
|
|
3642
|
-
file,
|
|
3643
|
-
args,
|
|
3644
|
-
cwd: directory,
|
|
3645
|
-
env: { PATH: searchPath },
|
|
3646
|
-
label
|
|
3647
|
-
});
|
|
3648
|
-
log.line(
|
|
3649
|
-
created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
|
|
3650
|
-
);
|
|
3651
|
-
} finally {
|
|
3652
|
-
client.close();
|
|
3653
|
-
}
|
|
3654
|
-
}
|
|
3655
|
-
/** The file and arguments a program runs; `repo` is checked already. */
|
|
3656
|
-
command(program, repo) {
|
|
3657
|
-
if (program === "repo-add" && repo) {
|
|
3658
|
-
return {
|
|
3659
|
-
file: path.join(this.options.binDirectory, "aibexd"),
|
|
3660
|
-
args: ["repo", "add", `${repo.owner}/${repo.name}`]
|
|
3661
|
-
};
|
|
3662
|
-
}
|
|
3663
|
-
if (program === "shell") {
|
|
3664
|
-
return {
|
|
3665
|
-
file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
|
|
3666
|
-
args: ["-l"]
|
|
3667
|
-
};
|
|
3668
|
-
}
|
|
3669
|
-
return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
|
|
3670
|
-
}
|
|
3671
|
-
searchPath() {
|
|
3672
|
-
return setupSearchPath(this.options.binDirectory, this.options.path);
|
|
3673
|
-
}
|
|
3674
|
-
/** Every setup terminal a host still keeps, running or exited. */
|
|
3675
|
-
async list() {
|
|
3676
|
-
const terminals = await listTerminals(this.sockets());
|
|
3677
|
-
return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
|
|
3678
|
-
const program = this.program(terminal.file);
|
|
3679
|
-
const entry = {
|
|
3680
|
-
open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
|
|
3681
|
-
terminal: terminal.id,
|
|
3682
|
-
program,
|
|
3683
|
-
cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
|
|
3684
|
-
};
|
|
3685
|
-
if (program === "repo-add") {
|
|
3686
|
-
const [owner, name] = (terminal.args?.[2] ?? "").split("/");
|
|
3687
|
-
if (owner && name) entry.repo = { owner, name };
|
|
3688
|
-
}
|
|
3689
|
-
if (terminal.exited) entry.exit = terminal.exited;
|
|
3690
|
-
return entry;
|
|
3691
|
-
});
|
|
3692
|
-
}
|
|
3693
|
-
program(file) {
|
|
3694
|
-
const name = path.basename(file);
|
|
3695
|
-
const found = Object.entries(SETUP_PROGRAMS).find(
|
|
3696
|
-
([, command]) => command === name
|
|
3697
|
-
);
|
|
3698
|
-
return found?.[0] ?? "shell";
|
|
3699
|
-
}
|
|
3700
|
-
cwd(directory) {
|
|
3701
|
-
const relative = path.relative(
|
|
3702
|
-
path.join(this.options.reposDirectory, GITHUB_HOST),
|
|
3703
|
-
directory
|
|
3704
|
-
);
|
|
3705
|
-
const [owner, name, ...rest] = relative.split(path.sep);
|
|
3706
|
-
if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
|
|
3707
|
-
const repo = { owner, name };
|
|
3708
|
-
return { kind: "repo", repo };
|
|
3709
|
-
}
|
|
3710
|
-
return { kind: "home" };
|
|
3711
|
-
}
|
|
3712
|
-
}
|
|
3713
|
-
function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
|
|
3714
|
-
const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
|
|
3715
|
-
return [binDirectory, ...rest].join(path.delimiter);
|
|
3716
|
-
}
|
|
3717
|
-
function resolveProgram(file, searchPath) {
|
|
3718
|
-
if (file.includes("/")) return file;
|
|
3719
|
-
for (const directory of searchPath.split(path.delimiter)) {
|
|
3720
|
-
if (directory === "") continue;
|
|
3721
|
-
const candidate = path.join(directory, file);
|
|
3722
|
-
try {
|
|
3723
|
-
if (!statSync(candidate).isFile()) continue;
|
|
3724
|
-
accessSync(candidate, constants.X_OK);
|
|
3725
|
-
return candidate;
|
|
3726
|
-
} catch {
|
|
3727
|
-
}
|
|
3728
|
-
}
|
|
3729
|
-
return file;
|
|
3730
|
-
}
|
|
3731
4057
|
function send(message) {
|
|
3732
4058
|
return new Promise((resolve) => {
|
|
3733
4059
|
if (!process.send) {
|
|
@@ -3750,6 +4076,13 @@ function initialSelfUpdate() {
|
|
|
3750
4076
|
}
|
|
3751
4077
|
return { can: true, reason: null };
|
|
3752
4078
|
}
|
|
4079
|
+
function initialLinkHealth() {
|
|
4080
|
+
try {
|
|
4081
|
+
return parseLinkHealth(JSON.parse(process.env.AIBEX_LINK_HEALTH ?? ""));
|
|
4082
|
+
} catch {
|
|
4083
|
+
return void 0;
|
|
4084
|
+
}
|
|
4085
|
+
}
|
|
3753
4086
|
function main() {
|
|
3754
4087
|
const info = readPackageInfo();
|
|
3755
4088
|
if (process.argv.includes("--self-test")) {
|
|
@@ -3772,7 +4105,8 @@ function main() {
|
|
|
3772
4105
|
let status = {
|
|
3773
4106
|
type: "status",
|
|
3774
4107
|
aibexdVersion: process.env.AIBEX_AIBEXD_VERSION ?? "unknown",
|
|
3775
|
-
selfUpdate: initialSelfUpdate()
|
|
4108
|
+
selfUpdate: initialSelfUpdate(),
|
|
4109
|
+
linkHealth: initialLinkHealth()
|
|
3776
4110
|
};
|
|
3777
4111
|
const identity = readIdentity(hostDirectory);
|
|
3778
4112
|
const paths = linkPaths(hostDirectory);
|
|
@@ -3804,7 +4138,7 @@ function main() {
|
|
|
3804
4138
|
access,
|
|
3805
4139
|
repos,
|
|
3806
4140
|
reposDirectory: paths.repos,
|
|
3807
|
-
binDirectory:
|
|
4141
|
+
binDirectory: paths.bin,
|
|
3808
4142
|
terminalSocket,
|
|
3809
4143
|
terminalsDirectory,
|
|
3810
4144
|
log
|
|
@@ -3821,6 +4155,7 @@ function main() {
|
|
|
3821
4155
|
statuses = signIns;
|
|
3822
4156
|
reaper = new Reaper({
|
|
3823
4157
|
work: paths.work,
|
|
4158
|
+
scratch: paths.scratch,
|
|
3824
4159
|
reposConfig: paths.reposConfig,
|
|
3825
4160
|
checkouts: async () => {
|
|
3826
4161
|
const checkouts = await repos.list();
|
|
@@ -3862,7 +4197,7 @@ function main() {
|
|
|
3862
4197
|
paths,
|
|
3863
4198
|
repos,
|
|
3864
4199
|
access,
|
|
3865
|
-
features: ["sessions", "relay", "setup"],
|
|
4200
|
+
features: ["sessions", "relay", "setup", "scratch", "handoff"],
|
|
3866
4201
|
sessions: running.list(),
|
|
3867
4202
|
setupTerminals,
|
|
3868
4203
|
...await reaping.report()
|
|
@@ -3903,7 +4238,19 @@ function main() {
|
|
|
3903
4238
|
process.on("message", (message) => {
|
|
3904
4239
|
switch (message.type) {
|
|
3905
4240
|
case "status": {
|
|
3906
|
-
status =
|
|
4241
|
+
status = {
|
|
4242
|
+
...message,
|
|
4243
|
+
linkHealth: parseLinkHealth(message.linkHealth) ?? status.linkHealth
|
|
4244
|
+
};
|
|
4245
|
+
break;
|
|
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 });
|
|
3907
4254
|
break;
|
|
3908
4255
|
}
|
|
3909
4256
|
case "diagnostics": {
|