@aibexhq/aibex-link 0.0.8 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +946 -304
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
|
|
1
2
|
import path from "node:path";
|
|
2
|
-
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, appendFileSync, openSync, readSync, closeSync, cpSync, accessSync, constants } from "node:fs";
|
|
3
3
|
import { randomBytes, createHash } from "node:crypto";
|
|
4
|
-
import {
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { homedir, platform, arch, release, tmpdir } from "node:os";
|
|
5
6
|
import { fileURLToPath } from "node:url";
|
|
6
7
|
import { createConnection } from "node:net";
|
|
7
|
-
import { execFile } from "node:child_process";
|
|
8
8
|
const encoder = new TextEncoder();
|
|
9
9
|
function utf8(text) {
|
|
10
10
|
return new Uint8Array(encoder.encode(text));
|
|
@@ -700,51 +700,6 @@ class Access {
|
|
|
700
700
|
return { accept: file.accept, integrations: file.integrations };
|
|
701
701
|
}
|
|
702
702
|
}
|
|
703
|
-
const ACTIVATIONS_FILE = "activations.json";
|
|
704
|
-
const ACTIVATION_TTL_MS = 10 * 60 * 1e3;
|
|
705
|
-
const ACTIVATION_CODE = /^[0-9A-HJKMNP-TV-Z]{8}$/u;
|
|
706
|
-
function isActivation(value) {
|
|
707
|
-
if (typeof value !== "object" || value === null) return false;
|
|
708
|
-
const { code, at } = value;
|
|
709
|
-
return typeof code === "string" && ACTIVATION_CODE.test(code) && typeof at === "string" && !Number.isNaN(Date.parse(at));
|
|
710
|
-
}
|
|
711
|
-
class Activations {
|
|
712
|
-
constructor(hostDirectory, now = Date.now) {
|
|
713
|
-
this.now = now;
|
|
714
|
-
this.file = path.join(hostDirectory, ACTIVATIONS_FILE);
|
|
715
|
-
}
|
|
716
|
-
file;
|
|
717
|
-
/** Keeps a code to report; false when it is not one. */
|
|
718
|
-
add(code) {
|
|
719
|
-
if (!ACTIVATION_CODE.test(code)) return false;
|
|
720
|
-
const kept = this.read().filter((entry) => entry.code !== code);
|
|
721
|
-
this.write([...kept, { code, at: new Date(this.now()).toISOString() }]);
|
|
722
|
-
return true;
|
|
723
|
-
}
|
|
724
|
-
/** The codes to report now, forgetting those 10 minutes old. */
|
|
725
|
-
list() {
|
|
726
|
-
const all = this.read();
|
|
727
|
-
const fresh = all.filter(
|
|
728
|
-
(entry) => this.now() - Date.parse(entry.at) < ACTIVATION_TTL_MS
|
|
729
|
-
);
|
|
730
|
-
if (fresh.length !== all.length) this.write(fresh);
|
|
731
|
-
return fresh;
|
|
732
|
-
}
|
|
733
|
-
/** Forgets the codes a poll answer confirmed. */
|
|
734
|
-
confirm(codes) {
|
|
735
|
-
if (!codes || codes.length === 0) return;
|
|
736
|
-
const all = this.read();
|
|
737
|
-
const left = all.filter((entry) => !codes.includes(entry.code));
|
|
738
|
-
if (left.length !== all.length) this.write(left);
|
|
739
|
-
}
|
|
740
|
-
read() {
|
|
741
|
-
const value = readJson(this.file);
|
|
742
|
-
return Array.isArray(value) ? value.filter((entry) => isActivation(entry)) : [];
|
|
743
|
-
}
|
|
744
|
-
write(entries) {
|
|
745
|
-
writeJsonAtomic(this.file, entries);
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
703
|
const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
|
|
749
704
|
const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
|
|
750
705
|
const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
|
|
@@ -815,6 +770,214 @@ class HandledCommands {
|
|
|
815
770
|
writeJsonAtomic(this.file, this.stored);
|
|
816
771
|
}
|
|
817
772
|
}
|
|
773
|
+
const UNKNOWN = { auth: "unknown" };
|
|
774
|
+
function parseObject(text) {
|
|
775
|
+
try {
|
|
776
|
+
const value = JSON.parse(text);
|
|
777
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
778
|
+
} catch {
|
|
779
|
+
return void 0;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
const CLAUDE_PLANS = {
|
|
783
|
+
"claude.ai": "subscription",
|
|
784
|
+
api_key: "api_key",
|
|
785
|
+
console: "api_key"
|
|
786
|
+
};
|
|
787
|
+
const PROBES = {
|
|
788
|
+
// exit 0 `{"loggedIn": true, "authMethod": "claude.ai", "loginExpiresAt": …}`
|
|
789
|
+
// signed in; exit 1 `{"loggedIn": false, "authMethod": "none"}` signed out.
|
|
790
|
+
claude: {
|
|
791
|
+
command: "claude",
|
|
792
|
+
args: ["auth", "status", "--json"],
|
|
793
|
+
read: ({ exitCode, stdout }, now) => {
|
|
794
|
+
const status = parseObject(stdout);
|
|
795
|
+
if (!status) return UNKNOWN;
|
|
796
|
+
if (status.loggedIn === false && (exitCode === 0 || exitCode === 1)) {
|
|
797
|
+
return { auth: "signed_out" };
|
|
798
|
+
}
|
|
799
|
+
if (status.loggedIn !== true || exitCode !== 0) return UNKNOWN;
|
|
800
|
+
const expires = typeof status.loginExpiresAt === "string" ? Date.parse(status.loginExpiresAt) : Number.NaN;
|
|
801
|
+
const plan = typeof status.authMethod === "string" ? CLAUDE_PLANS[status.authMethod] : void 0;
|
|
802
|
+
return {
|
|
803
|
+
auth: expires < now ? "expired" : "signed_in",
|
|
804
|
+
...plan ? { plan } : {}
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
},
|
|
808
|
+
// Prints to stderr: exit 0 `Logged in using ChatGPT` or `Logged in using an
|
|
809
|
+
// API key`, exit 1 `Not logged in`.
|
|
810
|
+
codex: {
|
|
811
|
+
command: "codex",
|
|
812
|
+
args: ["login", "status"],
|
|
813
|
+
read: ({ exitCode, stdout, stderr }) => {
|
|
814
|
+
const text = `${stdout}
|
|
815
|
+
${stderr}`;
|
|
816
|
+
if (exitCode === 0 && /^Logged in using ChatGPT/mu.test(text)) {
|
|
817
|
+
return { auth: "signed_in", plan: "subscription" };
|
|
818
|
+
}
|
|
819
|
+
if (exitCode === 0 && /^Logged in using an? API key/imu.test(text)) {
|
|
820
|
+
return { auth: "signed_in", plan: "api_key" };
|
|
821
|
+
}
|
|
822
|
+
if (exitCode !== 0 && /^Not logged in/mu.test(text)) {
|
|
823
|
+
return { auth: "signed_out" };
|
|
824
|
+
}
|
|
825
|
+
return UNKNOWN;
|
|
826
|
+
}
|
|
827
|
+
},
|
|
828
|
+
// exit 0 with `{"isAuthenticated": true, "status": "authenticated"}` or
|
|
829
|
+
// `{"isAuthenticated": false, "status": "unauthenticated"}`. No plan.
|
|
830
|
+
cursor: {
|
|
831
|
+
command: "cursor-agent",
|
|
832
|
+
args: ["status", "--format", "json"],
|
|
833
|
+
read: ({ exitCode, stdout }) => {
|
|
834
|
+
const status = parseObject(stdout);
|
|
835
|
+
if (!status || exitCode !== 0) return UNKNOWN;
|
|
836
|
+
if (status.isAuthenticated === true) return { auth: "signed_in" };
|
|
837
|
+
if (status.isAuthenticated === false) return { auth: "signed_out" };
|
|
838
|
+
return UNKNOWN;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
const PROBE_TIMEOUT_MS = 1e4;
|
|
843
|
+
const PROBE_MAX_OUTPUT = 64 * 1024;
|
|
844
|
+
function runProbe(probe, options = {}) {
|
|
845
|
+
const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
|
|
846
|
+
return new Promise((resolve) => {
|
|
847
|
+
const backstop = setTimeout(() => {
|
|
848
|
+
child.stdout?.destroy();
|
|
849
|
+
child.stderr?.destroy();
|
|
850
|
+
resolve({ exitCode: null, stdout: "", stderr: "" });
|
|
851
|
+
}, timeoutMs + 1e3);
|
|
852
|
+
const child = execFile(
|
|
853
|
+
probe.command,
|
|
854
|
+
probe.args,
|
|
855
|
+
{
|
|
856
|
+
cwd: options.cwd ?? homedir(),
|
|
857
|
+
env: { ...process.env, PATH: options.path ?? process.env.PATH ?? "" },
|
|
858
|
+
timeout: timeoutMs,
|
|
859
|
+
maxBuffer: PROBE_MAX_OUTPUT,
|
|
860
|
+
encoding: "utf8",
|
|
861
|
+
windowsHide: true
|
|
862
|
+
},
|
|
863
|
+
(error, stdout, stderr) => {
|
|
864
|
+
clearTimeout(backstop);
|
|
865
|
+
if (!error) {
|
|
866
|
+
resolve({ exitCode: 0, stdout, stderr });
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
const code = error.code;
|
|
870
|
+
resolve({
|
|
871
|
+
exitCode: typeof code === "number" && !error.killed ? code : null,
|
|
872
|
+
stdout,
|
|
873
|
+
stderr
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
);
|
|
877
|
+
child.stdin?.end();
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
function readProbe(probe, output, now) {
|
|
881
|
+
if (output.exitCode === null) return UNKNOWN;
|
|
882
|
+
return probe.read(output, now);
|
|
883
|
+
}
|
|
884
|
+
const PROBE_EVERY_MS = 5 * 6e4;
|
|
885
|
+
const PROBE_SETUP_EVERY_MS = 15e3;
|
|
886
|
+
class HarnessStatuses {
|
|
887
|
+
constructor(options) {
|
|
888
|
+
this.options = options;
|
|
889
|
+
this.probes = options.probes ?? PROBES;
|
|
890
|
+
this.now = options.now ?? Date.now;
|
|
891
|
+
}
|
|
892
|
+
last = /* @__PURE__ */ new Map();
|
|
893
|
+
running = /* @__PURE__ */ new Map();
|
|
894
|
+
lastStarted = Number.NEGATIVE_INFINITY;
|
|
895
|
+
/** Setup terminals running at the last look, by terminal id. */
|
|
896
|
+
runningSetup = /* @__PURE__ */ new Set();
|
|
897
|
+
timer;
|
|
898
|
+
probes;
|
|
899
|
+
now;
|
|
900
|
+
/** Probes every installed harness, then every 5 minutes; resolves after the first round. */
|
|
901
|
+
async start() {
|
|
902
|
+
await this.refresh();
|
|
903
|
+
this.timer = setInterval(() => void this.refresh(), PROBE_EVERY_MS);
|
|
904
|
+
}
|
|
905
|
+
stop() {
|
|
906
|
+
clearInterval(this.timer);
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Probes every installed harness that has no probe in flight, in
|
|
910
|
+
* parallel; resolves when they are done.
|
|
911
|
+
*/
|
|
912
|
+
async refresh() {
|
|
913
|
+
this.lastStarted = this.now();
|
|
914
|
+
const installed = this.options.installed();
|
|
915
|
+
const rounds = [];
|
|
916
|
+
for (const harness of Object.keys(this.probes)) {
|
|
917
|
+
if (!installed[harness]) {
|
|
918
|
+
this.last.delete(harness);
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
const inFlight = this.running.get(harness);
|
|
922
|
+
if (inFlight) {
|
|
923
|
+
rounds.push(inFlight);
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
const round = (async () => {
|
|
927
|
+
try {
|
|
928
|
+
await this.probe(harness);
|
|
929
|
+
} finally {
|
|
930
|
+
this.running.delete(harness);
|
|
931
|
+
}
|
|
932
|
+
})();
|
|
933
|
+
this.running.set(harness, round);
|
|
934
|
+
rounds.push(round);
|
|
935
|
+
}
|
|
936
|
+
await Promise.all(rounds);
|
|
937
|
+
}
|
|
938
|
+
async probe(harness) {
|
|
939
|
+
const probe = this.probes[harness];
|
|
940
|
+
const run = this.options.run ?? ((entry) => runProbe(entry));
|
|
941
|
+
let signIn;
|
|
942
|
+
try {
|
|
943
|
+
signIn = readProbe(probe, await run(probe), this.now());
|
|
944
|
+
} catch {
|
|
945
|
+
signIn = UNKNOWN;
|
|
946
|
+
}
|
|
947
|
+
const before = this.last.get(harness);
|
|
948
|
+
this.last.set(harness, signIn);
|
|
949
|
+
if (before?.auth !== signIn.auth || before.plan !== signIn.plan) {
|
|
950
|
+
this.options.changed?.(harness, signIn);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Looks at the setup terminals each heartbeat lists: probes again when
|
|
955
|
+
* one runs and 15 s have passed, or when one that ran has exited or gone.
|
|
956
|
+
*/
|
|
957
|
+
observe(terminals) {
|
|
958
|
+
const running = new Set(
|
|
959
|
+
(terminals ?? []).filter((terminal) => !terminal.exit).map((terminal) => terminal.terminal)
|
|
960
|
+
);
|
|
961
|
+
const ended = [...this.runningSetup].some((id) => !running.has(id));
|
|
962
|
+
this.runningSetup = running;
|
|
963
|
+
if (ended || running.size > 0 && this.now() - this.lastStarted >= PROBE_SETUP_EVERY_MS) {
|
|
964
|
+
void this.refresh();
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
/** What the heartbeat reports: installed from PATH, auth and plan from the last probe. */
|
|
968
|
+
current() {
|
|
969
|
+
const installed = this.options.installed();
|
|
970
|
+
const harnesses = {};
|
|
971
|
+
for (const harness of Object.keys(this.probes)) {
|
|
972
|
+
const signIn = installed[harness] ? this.last.get(harness) : void 0;
|
|
973
|
+
harnesses[harness] = {
|
|
974
|
+
installed: installed[harness],
|
|
975
|
+
...signIn ?? UNKNOWN
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
return harnesses;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
818
981
|
const DEFAULT_SLOTS = 2;
|
|
819
982
|
function linkPaths(hostDirectory) {
|
|
820
983
|
const state = path.resolve(hostDirectory, "..", "..");
|
|
@@ -843,78 +1006,677 @@ function onPath(command, pathVariable = process.env.PATH ?? "") {
|
|
|
843
1006
|
(directory) => directory && existsSync(path.join(directory, command))
|
|
844
1007
|
);
|
|
845
1008
|
}
|
|
846
|
-
function
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
1009
|
+
function installedHarnesses(pathVariable = process.env.PATH ?? "") {
|
|
1010
|
+
return {
|
|
1011
|
+
claude: onPath(HARNESS_COMMANDS.claude, pathVariable),
|
|
1012
|
+
codex: onPath(HARNESS_COMMANDS.codex, pathVariable),
|
|
1013
|
+
cursor: onPath(HARNESS_COMMANDS.cursor, pathVariable)
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
function describeMachine() {
|
|
1017
|
+
const darwin = platform() === "darwin";
|
|
1018
|
+
return {
|
|
1019
|
+
runner: darwin ? "macos" : "linux",
|
|
1020
|
+
os: {
|
|
1021
|
+
name: darwin ? "darwin" : "linux",
|
|
1022
|
+
version: release(),
|
|
1023
|
+
arch: arch() === "arm64" ? "arm64" : "amd64"
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
const EMPTY_REPORT = {
|
|
1028
|
+
capacity: { slots_total: 0, slots_free: 0 },
|
|
1029
|
+
sessions: []
|
|
1030
|
+
};
|
|
1031
|
+
async function collectReport(options) {
|
|
1032
|
+
const sessions = options.sessions ?? [];
|
|
1033
|
+
const slots = configuredSlots(options.paths);
|
|
1034
|
+
const running = sessions.filter((session) => session.state !== "ended");
|
|
1035
|
+
const checkouts = await options.repos.list();
|
|
1036
|
+
const report = {
|
|
1037
|
+
repos: checkouts.map((checkout) => checkout.repo),
|
|
1038
|
+
capacity: {
|
|
1039
|
+
slots_total: slots,
|
|
1040
|
+
slots_free: Math.max(0, slots - running.length)
|
|
1041
|
+
},
|
|
1042
|
+
sessions,
|
|
1043
|
+
features: options.features
|
|
1044
|
+
};
|
|
1045
|
+
const access = options.access.heartbeat();
|
|
1046
|
+
if (access) report.access = access;
|
|
1047
|
+
if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
|
|
1048
|
+
if (options.worktrees) report.worktrees = options.worktrees;
|
|
1049
|
+
if (options.releases && options.releases.length > 0) {
|
|
1050
|
+
report.releases = options.releases;
|
|
1051
|
+
}
|
|
1052
|
+
return report;
|
|
1053
|
+
}
|
|
1054
|
+
function buildHeartbeat(input) {
|
|
1055
|
+
const machine = describeMachine();
|
|
1056
|
+
const heartbeat = {
|
|
1057
|
+
machine_id: input.machineId,
|
|
1058
|
+
sent_at: new Date(input.now).toISOString(),
|
|
1059
|
+
protocol_version: 1,
|
|
1060
|
+
daemon_version: input.linkVersion,
|
|
1061
|
+
link_version: input.linkVersion,
|
|
1062
|
+
aibexd_version: input.aibexdVersion,
|
|
1063
|
+
self_update: input.selfUpdate.can ? { can: true } : { can: false, reason: input.selfUpdate.reason ?? "unknown" },
|
|
1064
|
+
runner: machine.runner,
|
|
1065
|
+
os: machine.os,
|
|
1066
|
+
harnesses: input.harnesses,
|
|
1067
|
+
capacity: input.report.capacity,
|
|
1068
|
+
sessions: input.report.sessions,
|
|
1069
|
+
acks: input.acks
|
|
1070
|
+
};
|
|
1071
|
+
const { repos, access, features, setup_terminals, worktrees, releases } = input.report;
|
|
1072
|
+
if (repos) heartbeat.repos = repos;
|
|
1073
|
+
if (access) heartbeat.access = access;
|
|
1074
|
+
if (features) heartbeat.features = features;
|
|
1075
|
+
if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
|
|
1076
|
+
if (worktrees) heartbeat.worktrees = worktrees;
|
|
1077
|
+
if (releases) heartbeat.releases = releases;
|
|
1078
|
+
if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
|
|
1079
|
+
return heartbeat;
|
|
1080
|
+
}
|
|
1081
|
+
const GITHUB_HOST = "github.com";
|
|
1082
|
+
const REPO_SCAN_MS = 6e4;
|
|
1083
|
+
const GITHUB_REMOTE = [
|
|
1084
|
+
/^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
|
|
1085
|
+
/^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
|
|
1086
|
+
];
|
|
1087
|
+
function parseGitHubRemote(url) {
|
|
1088
|
+
for (const pattern of GITHUB_REMOTE) {
|
|
1089
|
+
const match = pattern.exec(url.trim());
|
|
1090
|
+
if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
|
|
1091
|
+
}
|
|
1092
|
+
return void 0;
|
|
1093
|
+
}
|
|
1094
|
+
function git(cwd, args, environment) {
|
|
1095
|
+
return new Promise((resolve) => {
|
|
1096
|
+
execFile(
|
|
1097
|
+
"git",
|
|
1098
|
+
["-C", cwd, ...args],
|
|
1099
|
+
environment ? { env: { ...process.env, ...environment } } : {},
|
|
1100
|
+
(failure, stdout, stderr) => resolve({
|
|
1101
|
+
ok: failure === null,
|
|
1102
|
+
stdout: stdout.trim(),
|
|
1103
|
+
stderr: stderr.trim()
|
|
1104
|
+
})
|
|
1105
|
+
);
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
function directories(parent) {
|
|
1109
|
+
try {
|
|
1110
|
+
return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
|
|
1111
|
+
} catch {
|
|
1112
|
+
return [];
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
async function scanRepos(reposDirectory) {
|
|
1116
|
+
const github = path.join(reposDirectory, GITHUB_HOST);
|
|
1117
|
+
const candidates = directories(github).flatMap(
|
|
1118
|
+
(owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
|
|
1119
|
+
);
|
|
1120
|
+
const found = await Promise.all(
|
|
1121
|
+
candidates.map(async (directory) => {
|
|
1122
|
+
const origin = await git(directory, [
|
|
1123
|
+
"config",
|
|
1124
|
+
"--get",
|
|
1125
|
+
"remote.origin.url"
|
|
1126
|
+
]);
|
|
1127
|
+
const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
|
|
1128
|
+
return repo ? { repo, path: directory } : void 0;
|
|
1129
|
+
})
|
|
1130
|
+
);
|
|
1131
|
+
return found.filter((checkout) => checkout !== void 0);
|
|
1132
|
+
}
|
|
1133
|
+
class Repos {
|
|
1134
|
+
constructor(reposDirectory, now = Date.now) {
|
|
1135
|
+
this.reposDirectory = reposDirectory;
|
|
1136
|
+
this.now = now;
|
|
1137
|
+
}
|
|
1138
|
+
scanned = [];
|
|
1139
|
+
scannedAt = Number.NEGATIVE_INFINITY;
|
|
1140
|
+
async list(options = {}) {
|
|
1141
|
+
if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
|
|
1142
|
+
this.scanned = await scanRepos(this.reposDirectory);
|
|
1143
|
+
this.scannedAt = this.now();
|
|
1144
|
+
}
|
|
1145
|
+
return this.scanned;
|
|
1146
|
+
}
|
|
1147
|
+
/** The checkout for a repository, rescanning once when it is not known. */
|
|
1148
|
+
async find(repo) {
|
|
1149
|
+
const match = (checkouts) => checkouts.find(
|
|
1150
|
+
(checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
|
|
1151
|
+
);
|
|
1152
|
+
return match(await this.list()) ?? match(await this.list({ fresh: true }));
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
|
|
1156
|
+
function carryList(reposConfig) {
|
|
1157
|
+
const value = readJson(reposConfig);
|
|
1158
|
+
const carry = value?.carry;
|
|
1159
|
+
if (!Array.isArray(carry)) return DEFAULT_CARRY;
|
|
1160
|
+
return carry.filter(
|
|
1161
|
+
(entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
function salvageReference(threadId) {
|
|
1165
|
+
return `refs/aibex/salvage/${threadId}`;
|
|
1166
|
+
}
|
|
1167
|
+
async function defaultBranch(checkout) {
|
|
1168
|
+
const head = await git(checkout, [
|
|
1169
|
+
"symbolic-ref",
|
|
1170
|
+
"--short",
|
|
1171
|
+
"refs/remotes/origin/HEAD"
|
|
1172
|
+
]);
|
|
1173
|
+
return head.ok && head.stdout.startsWith("origin/") ? head.stdout.slice("origin/".length) : "main";
|
|
1174
|
+
}
|
|
1175
|
+
async function restoreWorktree(options) {
|
|
1176
|
+
const { checkout, worktreePath, branch, salvage } = options;
|
|
1177
|
+
const added = await git(checkout, [
|
|
1178
|
+
"worktree",
|
|
1179
|
+
"add",
|
|
1180
|
+
"--quiet",
|
|
1181
|
+
"-B",
|
|
1182
|
+
branch,
|
|
1183
|
+
worktreePath,
|
|
1184
|
+
`${salvage}^1`
|
|
1185
|
+
]);
|
|
1186
|
+
if (!added.ok) {
|
|
1187
|
+
return { ok: false, reason: added.stderr || "git worktree add failed" };
|
|
1188
|
+
}
|
|
1189
|
+
for (const step of [
|
|
1190
|
+
["read-tree", "-u", "--reset", salvage],
|
|
1191
|
+
["reset", "--quiet"]
|
|
1192
|
+
]) {
|
|
1193
|
+
const result = await git(worktreePath, step);
|
|
1194
|
+
if (!result.ok) {
|
|
1195
|
+
return {
|
|
1196
|
+
ok: false,
|
|
1197
|
+
reason: `git ${step[0]} failed while restoring ${salvage}: ${result.stderr}`
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
return { ok: true };
|
|
1202
|
+
}
|
|
1203
|
+
async function prepareWorktree(options) {
|
|
1204
|
+
const { checkout, threadId } = options;
|
|
1205
|
+
const worktreePath = path.join(options.workDirectory, threadId);
|
|
1206
|
+
const branch = `aibex/${threadId}`;
|
|
1207
|
+
const fetched = await git(checkout, ["fetch", "--quiet", "origin"]);
|
|
1208
|
+
const base = options.baseRef ?? await defaultBranch(checkout);
|
|
1209
|
+
let restored;
|
|
1210
|
+
const known = await git(checkout, [
|
|
1211
|
+
"rev-parse",
|
|
1212
|
+
"--verify",
|
|
1213
|
+
"--quiet",
|
|
1214
|
+
`refs/heads/${branch}`
|
|
1215
|
+
]);
|
|
1216
|
+
if (!existsSync(path.join(worktreePath, ".git"))) {
|
|
1217
|
+
mkdirSync(options.workDirectory, { recursive: true });
|
|
1218
|
+
const salvage = await git(checkout, [
|
|
1219
|
+
"rev-parse",
|
|
1220
|
+
"--verify",
|
|
1221
|
+
"--quiet",
|
|
1222
|
+
salvageReference(threadId)
|
|
1223
|
+
]);
|
|
1224
|
+
const salvagedHead = salvage.ok ? await git(checkout, ["rev-parse", `${salvage.stdout}^1`]) : void 0;
|
|
1225
|
+
if (salvage.ok && (!known.ok || salvagedHead?.ok && salvagedHead.stdout === known.stdout)) {
|
|
1226
|
+
const rebuilt = await restoreWorktree({
|
|
1227
|
+
checkout,
|
|
1228
|
+
worktreePath,
|
|
1229
|
+
branch,
|
|
1230
|
+
salvage: salvage.stdout
|
|
1231
|
+
});
|
|
1232
|
+
if (!rebuilt.ok) return rebuilt;
|
|
1233
|
+
restored = salvage.stdout;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
if (restored === void 0 && !existsSync(path.join(worktreePath, ".git"))) {
|
|
1237
|
+
const added = await git(
|
|
1238
|
+
checkout,
|
|
1239
|
+
known.ok ? ["worktree", "add", "--quiet", worktreePath, branch] : [
|
|
1240
|
+
"worktree",
|
|
1241
|
+
"add",
|
|
1242
|
+
"--quiet",
|
|
1243
|
+
"-b",
|
|
1244
|
+
branch,
|
|
1245
|
+
worktreePath,
|
|
1246
|
+
`origin/${base}`
|
|
1247
|
+
]
|
|
1248
|
+
);
|
|
1249
|
+
if (!added.ok) {
|
|
1250
|
+
const why = added.stderr || `git worktree add failed`;
|
|
1251
|
+
return {
|
|
1252
|
+
ok: false,
|
|
1253
|
+
reason: fetched.ok ? why : `${why} (git fetch failed too: ${fetched.stderr})`
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const carried = [];
|
|
1258
|
+
for (const file of carryList(options.reposConfig)) {
|
|
1259
|
+
const from = path.join(checkout, file);
|
|
1260
|
+
const to = path.join(worktreePath, file);
|
|
1261
|
+
if (!existsSync(from) || existsSync(to)) continue;
|
|
1262
|
+
const tracked = await git(checkout, [
|
|
1263
|
+
"ls-files",
|
|
1264
|
+
"--error-unmatch",
|
|
1265
|
+
"--",
|
|
1266
|
+
file
|
|
1267
|
+
]);
|
|
1268
|
+
if (tracked.ok) continue;
|
|
1269
|
+
mkdirSync(path.dirname(to), { recursive: true });
|
|
1270
|
+
cpSync(from, to, { recursive: true });
|
|
1271
|
+
carried.push(file);
|
|
1272
|
+
}
|
|
1273
|
+
return {
|
|
1274
|
+
ok: true,
|
|
1275
|
+
worktree: { path: worktreePath, branch, base },
|
|
1276
|
+
carried,
|
|
1277
|
+
...restored === void 0 ? {} : { restored }
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
const WORKTREE_SCAN_MS = 6e4;
|
|
1281
|
+
const HALF_MADE_AGE_MS = 10 * 6e4;
|
|
1282
|
+
const THREAD_ID = /^t_[A-Za-z0-9]{8,64}$/u;
|
|
1283
|
+
const SALVAGE_IDENTITY = {
|
|
1284
|
+
GIT_AUTHOR_NAME: "aibex",
|
|
1285
|
+
GIT_AUTHOR_EMAIL: "aibex@localhost",
|
|
1286
|
+
GIT_COMMITTER_NAME: "aibex",
|
|
1287
|
+
GIT_COMMITTER_EMAIL: "aibex@localhost"
|
|
1288
|
+
};
|
|
1289
|
+
function threadDirectories(work) {
|
|
1290
|
+
try {
|
|
1291
|
+
return readdirSync(work, { withFileTypes: true }).filter((entry) => entry.isDirectory() && THREAD_ID.test(entry.name)).map((entry) => entry.name).toSorted();
|
|
1292
|
+
} catch {
|
|
1293
|
+
return [];
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
function isWorktree(directory) {
|
|
1297
|
+
try {
|
|
1298
|
+
statSync(path.join(directory, ".git"));
|
|
1299
|
+
return true;
|
|
1300
|
+
} catch {
|
|
1301
|
+
return false;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async function checkoutOf(worktree) {
|
|
1305
|
+
const common = await git(worktree, [
|
|
1306
|
+
"rev-parse",
|
|
1307
|
+
"--path-format=absolute",
|
|
1308
|
+
"--git-common-dir"
|
|
1309
|
+
]);
|
|
1310
|
+
return common.ok && common.stdout ? path.dirname(common.stdout) : void 0;
|
|
1311
|
+
}
|
|
1312
|
+
async function hasUnpushed(worktree) {
|
|
1313
|
+
const count = await git(worktree, [
|
|
1314
|
+
"rev-list",
|
|
1315
|
+
"--count",
|
|
1316
|
+
"HEAD",
|
|
1317
|
+
"--not",
|
|
1318
|
+
"--remotes"
|
|
1319
|
+
]);
|
|
1320
|
+
return count.ok && Number(count.stdout) > 0;
|
|
1321
|
+
}
|
|
1322
|
+
async function isDirty(worktree, carry) {
|
|
1323
|
+
const status = await git(worktree, [
|
|
1324
|
+
"status",
|
|
1325
|
+
"--porcelain",
|
|
1326
|
+
"-z",
|
|
1327
|
+
"--untracked-files=all"
|
|
1328
|
+
]);
|
|
1329
|
+
if (!status.ok) return false;
|
|
1330
|
+
const entries = status.stdout.split("\0");
|
|
1331
|
+
for (let index = 0; index < entries.length; index++) {
|
|
1332
|
+
const entry = entries[index] ?? "";
|
|
1333
|
+
if (entry === "") continue;
|
|
1334
|
+
const code = entry.slice(0, 2);
|
|
1335
|
+
const file = entry.slice(3);
|
|
1336
|
+
if (code[0] === "R" || code[0] === "C") index++;
|
|
1337
|
+
const carried = code === "??" && carry.some((item) => file === item || file.startsWith(`${item}/`));
|
|
1338
|
+
if (!carried) return true;
|
|
1339
|
+
}
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
async function scanWorktrees(work, reposConfig) {
|
|
1343
|
+
const carry = carryList(reposConfig);
|
|
1344
|
+
const listings = [];
|
|
1345
|
+
for (const threadId of threadDirectories(work)) {
|
|
1346
|
+
const directory = path.join(work, threadId);
|
|
1347
|
+
let createdAt;
|
|
1348
|
+
try {
|
|
1349
|
+
createdAt = statSync(directory).mtime.toISOString();
|
|
1350
|
+
} catch {
|
|
1351
|
+
continue;
|
|
1352
|
+
}
|
|
1353
|
+
const listing = {
|
|
1354
|
+
thread_id: threadId,
|
|
1355
|
+
dirty: false,
|
|
1356
|
+
unpushed: false,
|
|
1357
|
+
created_at: createdAt
|
|
1358
|
+
};
|
|
1359
|
+
if (isWorktree(directory)) {
|
|
1360
|
+
const head = await git(directory, ["rev-parse", "--verify", "HEAD"]);
|
|
1361
|
+
if (head.ok && /^[0-9a-f]{40}$/u.test(head.stdout)) {
|
|
1362
|
+
listing.head = head.stdout;
|
|
1363
|
+
listing.dirty = await isDirty(directory, carry);
|
|
1364
|
+
listing.unpushed = await hasUnpushed(directory);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
listings.push(listing);
|
|
1368
|
+
}
|
|
1369
|
+
return listings;
|
|
1370
|
+
}
|
|
1371
|
+
async function salvageCommit(options) {
|
|
1372
|
+
const { worktree } = options;
|
|
1373
|
+
const scratch = mkdtempSync(path.join(tmpdir(), "aibex-salvage-"));
|
|
1374
|
+
const environment = {
|
|
1375
|
+
...SALVAGE_IDENTITY,
|
|
1376
|
+
GIT_INDEX_FILE: path.join(scratch, "index")
|
|
1377
|
+
};
|
|
1378
|
+
try {
|
|
1379
|
+
const steps = [
|
|
1380
|
+
["read-tree", options.head],
|
|
1381
|
+
["add", "--all", "--", "."]
|
|
1382
|
+
];
|
|
1383
|
+
for (const file of options.carry) {
|
|
1384
|
+
const tracked = await git(worktree, [
|
|
1385
|
+
"cat-file",
|
|
1386
|
+
"-e",
|
|
1387
|
+
`${options.head}:${file}`
|
|
1388
|
+
]);
|
|
1389
|
+
if (!tracked.ok) {
|
|
1390
|
+
steps.push([
|
|
1391
|
+
"rm",
|
|
1392
|
+
"-r",
|
|
1393
|
+
"--cached",
|
|
1394
|
+
"--quiet",
|
|
1395
|
+
"--ignore-unmatch",
|
|
1396
|
+
"--",
|
|
1397
|
+
file
|
|
1398
|
+
]);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
for (const step of steps) {
|
|
1402
|
+
const result = await git(worktree, step, environment);
|
|
1403
|
+
if (!result.ok) {
|
|
1404
|
+
return {
|
|
1405
|
+
ok: false,
|
|
1406
|
+
reason: `git ${step[0]} failed: ${result.stderr}`
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
const tree = await git(worktree, ["write-tree"], environment);
|
|
1411
|
+
if (!tree.ok) {
|
|
1412
|
+
return { ok: false, reason: `git write-tree failed: ${tree.stderr}` };
|
|
1413
|
+
}
|
|
1414
|
+
const commit = await git(
|
|
1415
|
+
worktree,
|
|
1416
|
+
[
|
|
1417
|
+
"commit-tree",
|
|
1418
|
+
tree.stdout,
|
|
1419
|
+
"-p",
|
|
1420
|
+
options.head,
|
|
1421
|
+
...options.previous ? ["-p", options.previous] : [],
|
|
1422
|
+
"-m",
|
|
1423
|
+
`aibex salvage ${options.threadId} epoch ${options.epoch}`
|
|
1424
|
+
],
|
|
1425
|
+
environment
|
|
1426
|
+
);
|
|
1427
|
+
if (!commit.ok) {
|
|
1428
|
+
return { ok: false, reason: `git commit-tree failed: ${commit.stderr}` };
|
|
1429
|
+
}
|
|
1430
|
+
return { ok: true, commit: commit.stdout };
|
|
1431
|
+
} finally {
|
|
1432
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
async function releaseWorktree(options) {
|
|
1436
|
+
const { threadId } = options;
|
|
1437
|
+
if (options.sessionListed) {
|
|
1438
|
+
return {
|
|
1439
|
+
outcome: "refused",
|
|
1440
|
+
reason: "a session for this thread is listed"
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
if (!THREAD_ID.test(threadId)) {
|
|
1444
|
+
return { outcome: "refused", reason: "not a thread id" };
|
|
1445
|
+
}
|
|
1446
|
+
const worktree = path.join(options.work, threadId);
|
|
1447
|
+
let exists = true;
|
|
1448
|
+
try {
|
|
1449
|
+
statSync(worktree);
|
|
1450
|
+
} catch {
|
|
1451
|
+
exists = false;
|
|
1452
|
+
}
|
|
1453
|
+
if (!exists) {
|
|
1454
|
+
let saved;
|
|
1455
|
+
for (const checkout2 of options.checkouts) {
|
|
1456
|
+
await git(checkout2, ["worktree", "prune"]);
|
|
1457
|
+
const dropped2 = await dropBranch(checkout2, threadId, options.epoch);
|
|
1458
|
+
if (!dropped2.ok) return { outcome: "refused", reason: dropped2.reason };
|
|
1459
|
+
saved = dropped2.salvage ?? saved;
|
|
1460
|
+
}
|
|
1461
|
+
return saved === void 0 ? { outcome: "released" } : { outcome: "released", salvage: saved };
|
|
1462
|
+
}
|
|
1463
|
+
if (!isWorktree(worktree)) {
|
|
1464
|
+
rmSync(worktree, { recursive: true, force: true });
|
|
1465
|
+
return { outcome: "released" };
|
|
1466
|
+
}
|
|
1467
|
+
const checkout = await checkoutOf(worktree);
|
|
1468
|
+
const head = await git(worktree, ["rev-parse", "--verify", "HEAD"]);
|
|
1469
|
+
if (!checkout || !head.ok) {
|
|
1470
|
+
return {
|
|
1471
|
+
outcome: "refused",
|
|
1472
|
+
reason: `not a usable worktree: ${head.stderr || "no checkout"}`
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
const reference = salvageReference(threadId);
|
|
1476
|
+
const carry = carryList(options.reposConfig);
|
|
1477
|
+
const dirty = await isDirty(worktree, carry);
|
|
1478
|
+
const unpushed = await hasUnpushed(worktree);
|
|
1479
|
+
let salvage;
|
|
1480
|
+
if (dirty || unpushed) {
|
|
1481
|
+
const previous = await git(checkout, [
|
|
1482
|
+
"rev-parse",
|
|
1483
|
+
"--verify",
|
|
1484
|
+
"--quiet",
|
|
1485
|
+
reference
|
|
1486
|
+
]);
|
|
1487
|
+
const made = await salvageCommit({
|
|
1488
|
+
worktree,
|
|
1489
|
+
threadId,
|
|
1490
|
+
epoch: options.epoch,
|
|
1491
|
+
head: head.stdout,
|
|
1492
|
+
carry,
|
|
1493
|
+
previous: previous.ok ? previous.stdout : void 0
|
|
1494
|
+
});
|
|
1495
|
+
if (!made.ok) return { outcome: "refused", reason: made.reason };
|
|
1496
|
+
const updated = await git(checkout, [
|
|
1497
|
+
"update-ref",
|
|
1498
|
+
"-m",
|
|
1499
|
+
`aibex salvage ${threadId}`,
|
|
1500
|
+
reference,
|
|
1501
|
+
made.commit
|
|
1502
|
+
]);
|
|
1503
|
+
if (!updated.ok) {
|
|
1504
|
+
return {
|
|
1505
|
+
outcome: "refused",
|
|
1506
|
+
reason: `could not write ${reference}: ${updated.stderr}`
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
salvage = made.commit;
|
|
1510
|
+
}
|
|
1511
|
+
const removed = await git(checkout, [
|
|
1512
|
+
"worktree",
|
|
1513
|
+
"remove",
|
|
1514
|
+
"--force",
|
|
1515
|
+
worktree
|
|
1516
|
+
]);
|
|
1517
|
+
if (!removed.ok) {
|
|
1518
|
+
return {
|
|
1519
|
+
outcome: "refused",
|
|
1520
|
+
reason: `git worktree remove failed: ${removed.stderr}`
|
|
852
1521
|
};
|
|
853
1522
|
}
|
|
854
|
-
|
|
1523
|
+
const dropped = await dropBranch(checkout, threadId, options.epoch);
|
|
1524
|
+
if (!dropped.ok) return { outcome: "refused", reason: dropped.reason };
|
|
1525
|
+
salvage = dropped.salvage ?? salvage;
|
|
1526
|
+
return salvage === void 0 ? { outcome: "released" } : { outcome: "released", salvage };
|
|
1527
|
+
}
|
|
1528
|
+
async function dropBranch(checkout, threadId, epoch) {
|
|
1529
|
+
const branch = `aibex/${threadId}`;
|
|
1530
|
+
const known = await git(checkout, [
|
|
1531
|
+
"rev-parse",
|
|
1532
|
+
"--verify",
|
|
1533
|
+
"--quiet",
|
|
1534
|
+
`refs/heads/${branch}`
|
|
1535
|
+
]);
|
|
1536
|
+
if (!known.ok) return { ok: true };
|
|
1537
|
+
const reference = salvageReference(threadId);
|
|
1538
|
+
const previous = await git(checkout, [
|
|
1539
|
+
"rev-parse",
|
|
1540
|
+
"--verify",
|
|
1541
|
+
"--quiet",
|
|
1542
|
+
reference
|
|
1543
|
+
]);
|
|
1544
|
+
const unsaved = await git(checkout, [
|
|
1545
|
+
"rev-list",
|
|
1546
|
+
"--count",
|
|
1547
|
+
known.stdout,
|
|
1548
|
+
"--not",
|
|
1549
|
+
"--remotes",
|
|
1550
|
+
...previous.ok ? [previous.stdout] : []
|
|
1551
|
+
]);
|
|
1552
|
+
if (!unsaved.ok) {
|
|
1553
|
+
return { ok: false, reason: `git rev-list failed: ${unsaved.stderr}` };
|
|
1554
|
+
}
|
|
1555
|
+
let salvage;
|
|
1556
|
+
if (Number(unsaved.stdout) > 0) {
|
|
1557
|
+
const commit = await git(
|
|
1558
|
+
checkout,
|
|
1559
|
+
[
|
|
1560
|
+
"commit-tree",
|
|
1561
|
+
`${known.stdout}^{tree}`,
|
|
1562
|
+
"-p",
|
|
1563
|
+
known.stdout,
|
|
1564
|
+
...previous.ok ? ["-p", previous.stdout] : [],
|
|
1565
|
+
"-m",
|
|
1566
|
+
`aibex salvage ${threadId} epoch ${epoch}`
|
|
1567
|
+
],
|
|
1568
|
+
SALVAGE_IDENTITY
|
|
1569
|
+
);
|
|
1570
|
+
if (!commit.ok) {
|
|
1571
|
+
return { ok: false, reason: `git commit-tree failed: ${commit.stderr}` };
|
|
1572
|
+
}
|
|
1573
|
+
const updated = await git(checkout, [
|
|
1574
|
+
"update-ref",
|
|
1575
|
+
"-m",
|
|
1576
|
+
`aibex salvage ${threadId}`,
|
|
1577
|
+
reference,
|
|
1578
|
+
commit.stdout
|
|
1579
|
+
]);
|
|
1580
|
+
if (!updated.ok) {
|
|
1581
|
+
return {
|
|
1582
|
+
ok: false,
|
|
1583
|
+
reason: `could not write ${reference}: ${updated.stderr}`
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
salvage = commit.stdout;
|
|
1587
|
+
}
|
|
1588
|
+
const deleted = await git(checkout, ["branch", "-D", "--quiet", branch]);
|
|
1589
|
+
if (!deleted.ok) {
|
|
1590
|
+
return { ok: false, reason: `git branch -D failed: ${deleted.stderr}` };
|
|
1591
|
+
}
|
|
1592
|
+
return salvage === void 0 ? { ok: true } : { ok: true, salvage };
|
|
855
1593
|
}
|
|
856
|
-
function
|
|
857
|
-
const
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
1594
|
+
async function sweep(options) {
|
|
1595
|
+
const removed = [];
|
|
1596
|
+
for (const checkout of options.checkouts) {
|
|
1597
|
+
await git(checkout, ["worktree", "prune"]);
|
|
1598
|
+
}
|
|
1599
|
+
let names = [];
|
|
1600
|
+
try {
|
|
1601
|
+
names = readdirSync(options.sessionsDirectory);
|
|
1602
|
+
} catch {
|
|
1603
|
+
}
|
|
1604
|
+
const records = new Set(
|
|
1605
|
+
names.filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5))
|
|
1606
|
+
);
|
|
1607
|
+
for (const name of names) {
|
|
1608
|
+
if (!name.endsWith(".spool") || records.has(name.slice(0, -6))) continue;
|
|
1609
|
+
rmSync(path.join(options.sessionsDirectory, name), { force: true });
|
|
1610
|
+
removed.push(path.join(options.sessionsDirectory, name));
|
|
1611
|
+
}
|
|
1612
|
+
for (const threadId of threadDirectories(options.work)) {
|
|
1613
|
+
const directory = path.join(options.work, threadId);
|
|
1614
|
+
if (isWorktree(directory)) continue;
|
|
1615
|
+
try {
|
|
1616
|
+
if (options.now - statSync(directory).mtimeMs < HALF_MADE_AGE_MS)
|
|
1617
|
+
continue;
|
|
1618
|
+
} catch {
|
|
1619
|
+
continue;
|
|
864
1620
|
}
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
const EMPTY_REPORT = {
|
|
868
|
-
capacity: { slots_total: 0, slots_free: 0 },
|
|
869
|
-
sessions: []
|
|
870
|
-
};
|
|
871
|
-
async function collectReport(options) {
|
|
872
|
-
const sessions = options.sessions ?? [];
|
|
873
|
-
const slots = configuredSlots(options.paths);
|
|
874
|
-
const running = sessions.filter((session) => session.state !== "ended");
|
|
875
|
-
const checkouts = await options.repos.list();
|
|
876
|
-
const report = {
|
|
877
|
-
repos: checkouts.map((checkout) => checkout.repo),
|
|
878
|
-
capacity: {
|
|
879
|
-
slots_total: slots,
|
|
880
|
-
slots_free: Math.max(0, slots - running.length)
|
|
881
|
-
},
|
|
882
|
-
sessions,
|
|
883
|
-
features: options.features
|
|
884
|
-
};
|
|
885
|
-
const access = options.access.heartbeat();
|
|
886
|
-
if (access) report.access = access;
|
|
887
|
-
if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
|
|
888
|
-
if (options.activations && options.activations.length > 0) {
|
|
889
|
-
report.activations = options.activations;
|
|
1621
|
+
rmSync(directory, { recursive: true, force: true });
|
|
1622
|
+
removed.push(directory);
|
|
890
1623
|
}
|
|
891
|
-
return
|
|
1624
|
+
return removed;
|
|
892
1625
|
}
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
1626
|
+
class Reaper {
|
|
1627
|
+
constructor(options) {
|
|
1628
|
+
this.options = options;
|
|
1629
|
+
}
|
|
1630
|
+
listing = [];
|
|
1631
|
+
scannedAt = Number.NEGATIVE_INFINITY;
|
|
1632
|
+
pending = [];
|
|
1633
|
+
inFlight = [];
|
|
1634
|
+
now() {
|
|
1635
|
+
return (this.options.now ?? Date.now)();
|
|
1636
|
+
}
|
|
1637
|
+
/** The listing and the outcomes to report in the next heartbeat. */
|
|
1638
|
+
async report() {
|
|
1639
|
+
const now = this.now();
|
|
1640
|
+
if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
|
|
1641
|
+
this.listing = await scanWorktrees(
|
|
1642
|
+
this.options.work,
|
|
1643
|
+
this.options.reposConfig
|
|
1644
|
+
);
|
|
1645
|
+
this.scannedAt = now;
|
|
1646
|
+
}
|
|
1647
|
+
this.inFlight = [...this.pending];
|
|
1648
|
+
return { worktrees: this.listing, releases: this.inFlight };
|
|
1649
|
+
}
|
|
1650
|
+
/** The poll that carried the last report succeeded. */
|
|
1651
|
+
delivered() {
|
|
1652
|
+
this.pending = this.pending.filter(
|
|
1653
|
+
(result) => !this.inFlight.includes(result)
|
|
1654
|
+
);
|
|
1655
|
+
this.inFlight = [];
|
|
1656
|
+
}
|
|
1657
|
+
/** Handles one `work.release`. */
|
|
1658
|
+
async release(command, sessionListed) {
|
|
1659
|
+
const outcome = await releaseWorktree({
|
|
1660
|
+
work: this.options.work,
|
|
1661
|
+
threadId: command.thread_id,
|
|
1662
|
+
epoch: command.epoch,
|
|
1663
|
+
reposConfig: this.options.reposConfig,
|
|
1664
|
+
checkouts: await this.options.checkouts(),
|
|
1665
|
+
sessionListed
|
|
1666
|
+
});
|
|
1667
|
+
const result = {
|
|
1668
|
+
command_id: command.command_id,
|
|
1669
|
+
thread_id: command.thread_id,
|
|
1670
|
+
epoch: command.epoch,
|
|
1671
|
+
...outcome
|
|
1672
|
+
};
|
|
1673
|
+
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}`
|
|
1675
|
+
);
|
|
1676
|
+
this.pending.push(result);
|
|
1677
|
+
this.scannedAt = Number.NEGATIVE_INFINITY;
|
|
1678
|
+
return result;
|
|
1679
|
+
}
|
|
918
1680
|
}
|
|
919
1681
|
const LOG_TAIL_LINES = 50;
|
|
920
1682
|
class LinkLog {
|
|
@@ -1082,7 +1844,7 @@ class Poller {
|
|
|
1082
1844
|
linkVersion: this.options.linkVersion,
|
|
1083
1845
|
aibexdVersion: status.aibexdVersion,
|
|
1084
1846
|
selfUpdate: status.selfUpdate,
|
|
1085
|
-
harnesses: this.options.harnesses,
|
|
1847
|
+
harnesses: typeof this.options.harnesses === "function" ? this.options.harnesses() : this.options.harnesses,
|
|
1086
1848
|
acks,
|
|
1087
1849
|
diagnostics,
|
|
1088
1850
|
report,
|
|
@@ -1672,79 +2434,6 @@ class Relay {
|
|
|
1672
2434
|
for (const message of queued) event(message);
|
|
1673
2435
|
}
|
|
1674
2436
|
}
|
|
1675
|
-
const GITHUB_HOST = "github.com";
|
|
1676
|
-
const REPO_SCAN_MS = 6e4;
|
|
1677
|
-
const GITHUB_REMOTE = [
|
|
1678
|
-
/^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
|
|
1679
|
-
/^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
|
|
1680
|
-
];
|
|
1681
|
-
function parseGitHubRemote(url) {
|
|
1682
|
-
for (const pattern of GITHUB_REMOTE) {
|
|
1683
|
-
const match = pattern.exec(url.trim());
|
|
1684
|
-
if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
|
|
1685
|
-
}
|
|
1686
|
-
return void 0;
|
|
1687
|
-
}
|
|
1688
|
-
function git(cwd, args) {
|
|
1689
|
-
return new Promise((resolve) => {
|
|
1690
|
-
execFile(
|
|
1691
|
-
"git",
|
|
1692
|
-
["-C", cwd, ...args],
|
|
1693
|
-
(failure, stdout, stderr) => resolve({
|
|
1694
|
-
ok: failure === null,
|
|
1695
|
-
stdout: stdout.trim(),
|
|
1696
|
-
stderr: stderr.trim()
|
|
1697
|
-
})
|
|
1698
|
-
);
|
|
1699
|
-
});
|
|
1700
|
-
}
|
|
1701
|
-
function directories(parent) {
|
|
1702
|
-
try {
|
|
1703
|
-
return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
|
|
1704
|
-
} catch {
|
|
1705
|
-
return [];
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
async function scanRepos(reposDirectory) {
|
|
1709
|
-
const github = path.join(reposDirectory, GITHUB_HOST);
|
|
1710
|
-
const candidates = directories(github).flatMap(
|
|
1711
|
-
(owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
|
|
1712
|
-
);
|
|
1713
|
-
const found = await Promise.all(
|
|
1714
|
-
candidates.map(async (directory) => {
|
|
1715
|
-
const origin = await git(directory, [
|
|
1716
|
-
"config",
|
|
1717
|
-
"--get",
|
|
1718
|
-
"remote.origin.url"
|
|
1719
|
-
]);
|
|
1720
|
-
const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
|
|
1721
|
-
return repo ? { repo, path: directory } : void 0;
|
|
1722
|
-
})
|
|
1723
|
-
);
|
|
1724
|
-
return found.filter((checkout) => checkout !== void 0);
|
|
1725
|
-
}
|
|
1726
|
-
class Repos {
|
|
1727
|
-
constructor(reposDirectory, now = Date.now) {
|
|
1728
|
-
this.reposDirectory = reposDirectory;
|
|
1729
|
-
this.now = now;
|
|
1730
|
-
}
|
|
1731
|
-
scanned = [];
|
|
1732
|
-
scannedAt = Number.NEGATIVE_INFINITY;
|
|
1733
|
-
async list(options = {}) {
|
|
1734
|
-
if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
|
|
1735
|
-
this.scanned = await scanRepos(this.reposDirectory);
|
|
1736
|
-
this.scannedAt = this.now();
|
|
1737
|
-
}
|
|
1738
|
-
return this.scanned;
|
|
1739
|
-
}
|
|
1740
|
-
/** The checkout for a repository, rescanning once when it is not known. */
|
|
1741
|
-
async find(repo) {
|
|
1742
|
-
const match = (checkouts) => checkouts.find(
|
|
1743
|
-
(checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
|
|
1744
|
-
);
|
|
1745
|
-
return match(await this.list()) ?? match(await this.list({ fresh: true }));
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
2437
|
const HARNESSES = {
|
|
1749
2438
|
// The input box: a full-width rule, then `❯` and the placeholder. The
|
|
1750
2439
|
// folder trust dialog also starts a line with `❯`, but never under a rule.
|
|
@@ -1920,79 +2609,6 @@ class Transcript {
|
|
|
1920
2609
|
rmSync(this.spoolFile, { force: true });
|
|
1921
2610
|
}
|
|
1922
2611
|
}
|
|
1923
|
-
const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
|
|
1924
|
-
function carryList(reposConfig) {
|
|
1925
|
-
const value = readJson(reposConfig);
|
|
1926
|
-
const carry = value?.carry;
|
|
1927
|
-
if (!Array.isArray(carry)) return DEFAULT_CARRY;
|
|
1928
|
-
return carry.filter(
|
|
1929
|
-
(entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
|
|
1930
|
-
);
|
|
1931
|
-
}
|
|
1932
|
-
async function defaultBranch(checkout) {
|
|
1933
|
-
const head = await git(checkout, [
|
|
1934
|
-
"symbolic-ref",
|
|
1935
|
-
"--short",
|
|
1936
|
-
"refs/remotes/origin/HEAD"
|
|
1937
|
-
]);
|
|
1938
|
-
return head.ok && head.stdout.startsWith("origin/") ? head.stdout.slice("origin/".length) : "main";
|
|
1939
|
-
}
|
|
1940
|
-
async function prepareWorktree(options) {
|
|
1941
|
-
const { checkout, threadId } = options;
|
|
1942
|
-
const worktreePath = path.join(options.workDirectory, threadId);
|
|
1943
|
-
const branch = `aibex/${threadId}`;
|
|
1944
|
-
const fetched = await git(checkout, ["fetch", "--quiet", "origin"]);
|
|
1945
|
-
const base = options.baseRef ?? await defaultBranch(checkout);
|
|
1946
|
-
if (!existsSync(path.join(worktreePath, ".git"))) {
|
|
1947
|
-
mkdirSync(options.workDirectory, { recursive: true });
|
|
1948
|
-
const known = await git(checkout, [
|
|
1949
|
-
"rev-parse",
|
|
1950
|
-
"--verify",
|
|
1951
|
-
"--quiet",
|
|
1952
|
-
`refs/heads/${branch}`
|
|
1953
|
-
]);
|
|
1954
|
-
const added = await git(
|
|
1955
|
-
checkout,
|
|
1956
|
-
known.ok ? ["worktree", "add", "--quiet", worktreePath, branch] : [
|
|
1957
|
-
"worktree",
|
|
1958
|
-
"add",
|
|
1959
|
-
"--quiet",
|
|
1960
|
-
"-b",
|
|
1961
|
-
branch,
|
|
1962
|
-
worktreePath,
|
|
1963
|
-
`origin/${base}`
|
|
1964
|
-
]
|
|
1965
|
-
);
|
|
1966
|
-
if (!added.ok) {
|
|
1967
|
-
const why = added.stderr || `git worktree add failed`;
|
|
1968
|
-
return {
|
|
1969
|
-
ok: false,
|
|
1970
|
-
reason: fetched.ok ? why : `${why} (git fetch failed too: ${fetched.stderr})`
|
|
1971
|
-
};
|
|
1972
|
-
}
|
|
1973
|
-
}
|
|
1974
|
-
const carried = [];
|
|
1975
|
-
for (const file of carryList(options.reposConfig)) {
|
|
1976
|
-
const from = path.join(checkout, file);
|
|
1977
|
-
const to = path.join(worktreePath, file);
|
|
1978
|
-
if (!existsSync(from) || existsSync(to)) continue;
|
|
1979
|
-
const tracked = await git(checkout, [
|
|
1980
|
-
"ls-files",
|
|
1981
|
-
"--error-unmatch",
|
|
1982
|
-
"--",
|
|
1983
|
-
file
|
|
1984
|
-
]);
|
|
1985
|
-
if (tracked.ok) continue;
|
|
1986
|
-
mkdirSync(path.dirname(to), { recursive: true });
|
|
1987
|
-
cpSync(from, to, { recursive: true });
|
|
1988
|
-
carried.push(file);
|
|
1989
|
-
}
|
|
1990
|
-
return {
|
|
1991
|
-
ok: true,
|
|
1992
|
-
worktree: { path: worktreePath, branch, base },
|
|
1993
|
-
carried
|
|
1994
|
-
};
|
|
1995
|
-
}
|
|
1996
2612
|
const DEFAULT_SESSION_TIMINGS = {
|
|
1997
2613
|
readyTimeoutMs: 6e4,
|
|
1998
2614
|
checkMs: 250,
|
|
@@ -2668,6 +3284,11 @@ class Sessions {
|
|
|
2668
3284
|
return;
|
|
2669
3285
|
}
|
|
2670
3286
|
record.worktree = prepared.worktree;
|
|
3287
|
+
if (prepared.restored !== void 0) {
|
|
3288
|
+
this.options.log.line(
|
|
3289
|
+
`${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
|
|
3290
|
+
);
|
|
3291
|
+
}
|
|
2671
3292
|
const socket = this.options.terminalSocket;
|
|
2672
3293
|
let client;
|
|
2673
3294
|
try {
|
|
@@ -3047,12 +3668,8 @@ class SetupTerminals {
|
|
|
3047
3668
|
}
|
|
3048
3669
|
return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
|
|
3049
3670
|
}
|
|
3050
|
-
/** `<state>/bin` first, so `aibexd activate` resolves in a harness started here. */
|
|
3051
3671
|
searchPath() {
|
|
3052
|
-
|
|
3053
|
-
(directory) => directory !== "" && directory !== this.options.binDirectory
|
|
3054
|
-
);
|
|
3055
|
-
return [this.options.binDirectory, ...rest].join(path.delimiter);
|
|
3672
|
+
return setupSearchPath(this.options.binDirectory, this.options.path);
|
|
3056
3673
|
}
|
|
3057
3674
|
/** Every setup terminal a host still keeps, running or exited. */
|
|
3058
3675
|
async list() {
|
|
@@ -3093,6 +3710,10 @@ class SetupTerminals {
|
|
|
3093
3710
|
return { kind: "home" };
|
|
3094
3711
|
}
|
|
3095
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
|
+
}
|
|
3096
3717
|
function resolveProgram(file, searchPath) {
|
|
3097
3718
|
if (file.includes("/")) return file;
|
|
3098
3719
|
for (const directory of searchPath.split(path.delimiter)) {
|
|
@@ -3157,11 +3778,13 @@ function main() {
|
|
|
3157
3778
|
const paths = linkPaths(hostDirectory);
|
|
3158
3779
|
const access = new Access(paths.access);
|
|
3159
3780
|
const repos = new Repos(paths.repos);
|
|
3160
|
-
|
|
3781
|
+
rmSync(path.join(hostDirectory, "activations.json"), { force: true });
|
|
3161
3782
|
const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
|
|
3162
3783
|
const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
|
|
3163
3784
|
let poller;
|
|
3164
3785
|
let sessions;
|
|
3786
|
+
let reaper;
|
|
3787
|
+
let statuses;
|
|
3165
3788
|
if (identity) {
|
|
3166
3789
|
sessions = new Sessions({
|
|
3167
3790
|
paths,
|
|
@@ -3187,6 +3810,25 @@ function main() {
|
|
|
3187
3810
|
log
|
|
3188
3811
|
});
|
|
3189
3812
|
const running = sessions;
|
|
3813
|
+
const probePath = setupSearchPath(path.join(paths.state, "bin"));
|
|
3814
|
+
const signIns = new HarnessStatuses({
|
|
3815
|
+
installed: () => installedHarnesses(),
|
|
3816
|
+
run: (probe) => runProbe(probe, { path: probePath }),
|
|
3817
|
+
changed: (harness, signIn) => log.line(
|
|
3818
|
+
`${harness}: ${signIn.auth}${signIn.plan ? ` (${signIn.plan})` : ""}`
|
|
3819
|
+
)
|
|
3820
|
+
});
|
|
3821
|
+
statuses = signIns;
|
|
3822
|
+
reaper = new Reaper({
|
|
3823
|
+
work: paths.work,
|
|
3824
|
+
reposConfig: paths.reposConfig,
|
|
3825
|
+
checkouts: async () => {
|
|
3826
|
+
const checkouts = await repos.list();
|
|
3827
|
+
return checkouts.map((checkout) => checkout.path);
|
|
3828
|
+
},
|
|
3829
|
+
log: (line) => log.line(line)
|
|
3830
|
+
});
|
|
3831
|
+
const reaping = reaper;
|
|
3190
3832
|
const relay = new Relay({
|
|
3191
3833
|
host: identity.host,
|
|
3192
3834
|
herd: new HerdClient(identity),
|
|
@@ -3211,28 +3853,39 @@ function main() {
|
|
|
3211
3853
|
log,
|
|
3212
3854
|
handled: new HandledCommands(hostDirectory),
|
|
3213
3855
|
status: () => status,
|
|
3214
|
-
harnesses:
|
|
3856
|
+
harnesses: () => signIns.current(),
|
|
3215
3857
|
access,
|
|
3216
|
-
report: async () =>
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3858
|
+
report: async () => {
|
|
3859
|
+
const setupTerminals = await setup.list();
|
|
3860
|
+
signIns.observe(setupTerminals);
|
|
3861
|
+
return collectReport({
|
|
3862
|
+
paths,
|
|
3863
|
+
repos,
|
|
3864
|
+
access,
|
|
3865
|
+
features: ["sessions", "relay", "setup"],
|
|
3866
|
+
sessions: running.list(),
|
|
3867
|
+
setupTerminals,
|
|
3868
|
+
...await reaping.report()
|
|
3869
|
+
});
|
|
3870
|
+
},
|
|
3225
3871
|
handleCommand: async (command) => {
|
|
3226
3872
|
if (command.type === "relay.open") {
|
|
3227
3873
|
await relay.open();
|
|
3228
3874
|
return true;
|
|
3229
3875
|
}
|
|
3876
|
+
if (command.type === "work.release") {
|
|
3877
|
+
const listed = running.list().some(
|
|
3878
|
+
(session) => session.thread_id === command.thread_id && session.state !== "ended"
|
|
3879
|
+
);
|
|
3880
|
+
await reaping.release(command, listed);
|
|
3881
|
+
return true;
|
|
3882
|
+
}
|
|
3230
3883
|
if (command.type !== "terminal.open") return running.handle(command);
|
|
3231
3884
|
await setup.open(command);
|
|
3232
3885
|
return true;
|
|
3233
3886
|
},
|
|
3234
3887
|
afterPoll: async (answer) => {
|
|
3235
|
-
|
|
3888
|
+
reaping.delivered();
|
|
3236
3889
|
await running.afterPoll(answer);
|
|
3237
3890
|
},
|
|
3238
3891
|
forward: (commandId, request) => send({ type: "control", commandId, request }),
|
|
@@ -3247,36 +3900,12 @@ function main() {
|
|
|
3247
3900
|
`aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
|
|
3248
3901
|
);
|
|
3249
3902
|
}
|
|
3250
|
-
const activate = (code) => {
|
|
3251
|
-
if (!poller) {
|
|
3252
|
-
return {
|
|
3253
|
-
type: "activated",
|
|
3254
|
-
code,
|
|
3255
|
-
ok: false,
|
|
3256
|
-
reason: "this machine has not joined a herd: run `aibexd join <key>` first"
|
|
3257
|
-
};
|
|
3258
|
-
}
|
|
3259
|
-
if (!activations.add(code)) {
|
|
3260
|
-
return {
|
|
3261
|
-
type: "activated",
|
|
3262
|
-
code,
|
|
3263
|
-
ok: false,
|
|
3264
|
-
reason: "not an activation code"
|
|
3265
|
-
};
|
|
3266
|
-
}
|
|
3267
|
-
log.line(`activation ${code} taken; reporting it until the herd confirms`);
|
|
3268
|
-
return { type: "activated", code, ok: true };
|
|
3269
|
-
};
|
|
3270
3903
|
process.on("message", (message) => {
|
|
3271
3904
|
switch (message.type) {
|
|
3272
3905
|
case "status": {
|
|
3273
3906
|
status = message;
|
|
3274
3907
|
break;
|
|
3275
3908
|
}
|
|
3276
|
-
case "activate": {
|
|
3277
|
-
void send(activate(message.code));
|
|
3278
|
-
break;
|
|
3279
|
-
}
|
|
3280
3909
|
case "diagnostics": {
|
|
3281
3910
|
const mismatch = access.mismatch;
|
|
3282
3911
|
poller?.attachDiagnostics({
|
|
@@ -3295,14 +3924,27 @@ function main() {
|
|
|
3295
3924
|
});
|
|
3296
3925
|
void send({ type: "ready" });
|
|
3297
3926
|
setInterval(() => void send({ type: "alive" }), aliveIntervalMs());
|
|
3298
|
-
if (poller && sessions) {
|
|
3299
|
-
const [started, recorded] = [poller, sessions];
|
|
3927
|
+
if (poller && sessions && statuses) {
|
|
3928
|
+
const [started, recorded, probed] = [poller, sessions, statuses];
|
|
3300
3929
|
void (async () => {
|
|
3930
|
+
try {
|
|
3931
|
+
const checkouts = await repos.list();
|
|
3932
|
+
const swept = await sweep({
|
|
3933
|
+
checkouts: checkouts.map((checkout) => checkout.path),
|
|
3934
|
+
work: paths.work,
|
|
3935
|
+
sessionsDirectory: path.join(hostDirectory, "sessions"),
|
|
3936
|
+
now: Date.now()
|
|
3937
|
+
});
|
|
3938
|
+
for (const removed of swept) log.line(`removed litter ${removed}`);
|
|
3939
|
+
} catch (error) {
|
|
3940
|
+
log.line(`the start-up sweep failed: ${String(error)}`);
|
|
3941
|
+
}
|
|
3301
3942
|
try {
|
|
3302
3943
|
await recorded.resume();
|
|
3303
3944
|
} catch (error) {
|
|
3304
3945
|
log.line(`could not pick up recorded sessions: ${String(error)}`);
|
|
3305
3946
|
}
|
|
3947
|
+
await probed.start();
|
|
3306
3948
|
started.start();
|
|
3307
3949
|
})();
|
|
3308
3950
|
}
|