@aibexhq/aibex-link 0.0.11 → 0.0.13
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 +614 -329
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
|
|
1
|
+
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, realpathSync, lstatSync, cpSync, statSync, 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";
|
|
@@ -700,6 +700,239 @@ class Access {
|
|
|
700
700
|
return { accept: file.accept, integrations: file.integrations };
|
|
701
701
|
}
|
|
702
702
|
}
|
|
703
|
+
const GITHUB_HOST = "github.com";
|
|
704
|
+
const REPO_SCAN_MS = 6e4;
|
|
705
|
+
const GITHUB_REMOTE = [
|
|
706
|
+
/^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
|
|
707
|
+
/^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
|
|
708
|
+
];
|
|
709
|
+
function parseGitHubRemote(url) {
|
|
710
|
+
for (const pattern of GITHUB_REMOTE) {
|
|
711
|
+
const match = pattern.exec(url.trim());
|
|
712
|
+
if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
|
|
713
|
+
}
|
|
714
|
+
return void 0;
|
|
715
|
+
}
|
|
716
|
+
function git(cwd, args, environment) {
|
|
717
|
+
return new Promise((resolve) => {
|
|
718
|
+
execFile(
|
|
719
|
+
"git",
|
|
720
|
+
["-C", cwd, ...args],
|
|
721
|
+
environment ? { env: { ...process.env, ...environment } } : {},
|
|
722
|
+
(failure, stdout, stderr) => resolve({
|
|
723
|
+
ok: failure === null,
|
|
724
|
+
stdout: stdout.trim(),
|
|
725
|
+
stderr: stderr.trim()
|
|
726
|
+
})
|
|
727
|
+
);
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
function directories(parent) {
|
|
731
|
+
try {
|
|
732
|
+
return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
|
|
733
|
+
} catch {
|
|
734
|
+
return [];
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
async function scanRepos(reposDirectory) {
|
|
738
|
+
const github = path.join(reposDirectory, GITHUB_HOST);
|
|
739
|
+
const candidates = directories(github).flatMap(
|
|
740
|
+
(owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
|
|
741
|
+
);
|
|
742
|
+
const found = await Promise.all(
|
|
743
|
+
candidates.map(async (directory) => {
|
|
744
|
+
const origin = await git(directory, [
|
|
745
|
+
"config",
|
|
746
|
+
"--get",
|
|
747
|
+
"remote.origin.url"
|
|
748
|
+
]);
|
|
749
|
+
const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
|
|
750
|
+
return repo ? { repo, path: directory } : void 0;
|
|
751
|
+
})
|
|
752
|
+
);
|
|
753
|
+
return found.filter((checkout) => checkout !== void 0);
|
|
754
|
+
}
|
|
755
|
+
class Repos {
|
|
756
|
+
constructor(reposDirectory, now = Date.now) {
|
|
757
|
+
this.reposDirectory = reposDirectory;
|
|
758
|
+
this.now = now;
|
|
759
|
+
}
|
|
760
|
+
scanned = [];
|
|
761
|
+
scannedAt = Number.NEGATIVE_INFINITY;
|
|
762
|
+
async list(options = {}) {
|
|
763
|
+
if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
|
|
764
|
+
this.scanned = await scanRepos(this.reposDirectory);
|
|
765
|
+
this.scannedAt = this.now();
|
|
766
|
+
}
|
|
767
|
+
return this.scanned;
|
|
768
|
+
}
|
|
769
|
+
/** The checkout for a repository, rescanning once when it is not known. */
|
|
770
|
+
async find(repo) {
|
|
771
|
+
const match = (checkouts) => checkouts.find(
|
|
772
|
+
(checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
|
|
773
|
+
);
|
|
774
|
+
return match(await this.list()) ?? match(await this.list({ fresh: true }));
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const REPO_FILE = ".aibex/repo.json";
|
|
778
|
+
const CARRY_MAX = 20;
|
|
779
|
+
const CARRY_ENTRY_MAX = 200;
|
|
780
|
+
const REPO_FILE_MAX_BYTES = 64 * 1024;
|
|
781
|
+
function carryEntryProblem(entry) {
|
|
782
|
+
if (typeof entry !== "string") return "is not a string";
|
|
783
|
+
if (entry === "") return "is empty";
|
|
784
|
+
if (entry.length > CARRY_ENTRY_MAX)
|
|
785
|
+
return `is longer than ${CARRY_ENTRY_MAX} characters`;
|
|
786
|
+
if (entry.includes("\0") || entry.includes("\\"))
|
|
787
|
+
return "holds a backslash or a NUL";
|
|
788
|
+
if (path.isAbsolute(entry) || path.win32.isAbsolute(entry))
|
|
789
|
+
return "is absolute";
|
|
790
|
+
if (/[*?[]/u.test(entry) || entry.startsWith(":"))
|
|
791
|
+
return 'holds a glob character or starts with ":"';
|
|
792
|
+
const parts = entry.split("/");
|
|
793
|
+
if (parts.some((part) => part === "" || part === "." || part === ".."))
|
|
794
|
+
return 'is not a plain relative path (no "..", ".", "//" or trailing "/")';
|
|
795
|
+
if (parts.some((part) => part.toLowerCase() === ".git"))
|
|
796
|
+
return "is inside .git";
|
|
797
|
+
return void 0;
|
|
798
|
+
}
|
|
799
|
+
function carryList(worktree) {
|
|
800
|
+
const file = path.join(worktree, REPO_FILE);
|
|
801
|
+
let stats;
|
|
802
|
+
try {
|
|
803
|
+
stats = lstatSync(file);
|
|
804
|
+
} catch {
|
|
805
|
+
return { carry: [], problems: [] };
|
|
806
|
+
}
|
|
807
|
+
if (!stats.isFile()) {
|
|
808
|
+
return { carry: [], problems: [`${REPO_FILE} is not a regular file`] };
|
|
809
|
+
}
|
|
810
|
+
if (stats.size > REPO_FILE_MAX_BYTES) {
|
|
811
|
+
return {
|
|
812
|
+
carry: [],
|
|
813
|
+
problems: [`${REPO_FILE} is larger than ${REPO_FILE_MAX_BYTES} bytes`]
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
let parsed;
|
|
817
|
+
try {
|
|
818
|
+
parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
819
|
+
} catch {
|
|
820
|
+
return { carry: [], problems: [`${REPO_FILE} is not valid JSON`] };
|
|
821
|
+
}
|
|
822
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
823
|
+
return { carry: [], problems: [`${REPO_FILE} is not a JSON object`] };
|
|
824
|
+
}
|
|
825
|
+
const value = parsed.carry;
|
|
826
|
+
if (value === void 0) return { carry: [], problems: [] };
|
|
827
|
+
if (!Array.isArray(value)) {
|
|
828
|
+
return { carry: [], problems: [`${REPO_FILE}: "carry" is not a list`] };
|
|
829
|
+
}
|
|
830
|
+
const carry = [];
|
|
831
|
+
const problems = [];
|
|
832
|
+
if (value.length > CARRY_MAX) {
|
|
833
|
+
problems.push(
|
|
834
|
+
`${REPO_FILE}: "carry" lists ${value.length} entries; only the first ${CARRY_MAX} are read`
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
for (const entry of value.slice(0, CARRY_MAX)) {
|
|
838
|
+
const problem = carryEntryProblem(entry);
|
|
839
|
+
if (problem !== void 0) {
|
|
840
|
+
problems.push(
|
|
841
|
+
`${REPO_FILE}: carry entry ${JSON.stringify(entry)} skipped: it ${problem}`
|
|
842
|
+
);
|
|
843
|
+
} else if (!carry.includes(entry)) {
|
|
844
|
+
carry.push(entry);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return { carry, problems };
|
|
848
|
+
}
|
|
849
|
+
function inside(parent, child) {
|
|
850
|
+
const relative = path.relative(parent, child);
|
|
851
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
852
|
+
}
|
|
853
|
+
function realAncestor(target) {
|
|
854
|
+
let current = target;
|
|
855
|
+
for (; ; ) {
|
|
856
|
+
try {
|
|
857
|
+
return realpathSync(current);
|
|
858
|
+
} catch {
|
|
859
|
+
const parent = path.dirname(current);
|
|
860
|
+
if (parent === current) return current;
|
|
861
|
+
current = parent;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
async function carryInto(checkout, worktree) {
|
|
866
|
+
const { carry, problems } = carryList(worktree);
|
|
867
|
+
const carried = [];
|
|
868
|
+
let checkoutReal;
|
|
869
|
+
let worktreeReal;
|
|
870
|
+
try {
|
|
871
|
+
checkoutReal = realpathSync(checkout);
|
|
872
|
+
worktreeReal = realpathSync(worktree);
|
|
873
|
+
} catch (error) {
|
|
874
|
+
problems.push(`carry skipped: ${error.message}`);
|
|
875
|
+
return { carried, problems };
|
|
876
|
+
}
|
|
877
|
+
for (const entry of carry) {
|
|
878
|
+
const from = path.join(checkout, entry);
|
|
879
|
+
const to = path.join(worktree, entry);
|
|
880
|
+
const skip = (why) => problems.push(`carry entry ${JSON.stringify(entry)} skipped: ${why}`);
|
|
881
|
+
let source;
|
|
882
|
+
try {
|
|
883
|
+
source = lstatSync(from);
|
|
884
|
+
} catch {
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
if (source.isSymbolicLink()) {
|
|
888
|
+
skip("it is a symbolic link in the checkout");
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
if (!source.isFile() && !source.isDirectory()) {
|
|
892
|
+
skip("it is not a file or a directory");
|
|
893
|
+
continue;
|
|
894
|
+
}
|
|
895
|
+
if (!inside(checkoutReal, realpathSync(from))) {
|
|
896
|
+
skip("it leads out of the checkout");
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
if (existsSync(to) || isLink(to)) continue;
|
|
900
|
+
const tracked = await git(checkout, [
|
|
901
|
+
"--literal-pathspecs",
|
|
902
|
+
"ls-files",
|
|
903
|
+
"--error-unmatch",
|
|
904
|
+
"--",
|
|
905
|
+
entry
|
|
906
|
+
]);
|
|
907
|
+
if (tracked.ok) continue;
|
|
908
|
+
if (!inside(worktreeReal, realAncestor(path.dirname(to)))) {
|
|
909
|
+
skip("it leads out of the worktree");
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
try {
|
|
913
|
+
mkdirSync(path.dirname(to), { recursive: true });
|
|
914
|
+
cpSync(from, to, {
|
|
915
|
+
recursive: true,
|
|
916
|
+
filter: (item) => !lstatSync(item).isSymbolicLink()
|
|
917
|
+
});
|
|
918
|
+
carried.push(entry);
|
|
919
|
+
} catch (error) {
|
|
920
|
+
skip(`the copy failed: ${error.message}`);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
return { carried, problems };
|
|
924
|
+
}
|
|
925
|
+
function isLink(file) {
|
|
926
|
+
try {
|
|
927
|
+
return lstatSync(file).isSymbolicLink();
|
|
928
|
+
} catch {
|
|
929
|
+
return false;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function retiredReposConfigNotice(file) {
|
|
933
|
+
if (!existsSync(file)) return void 0;
|
|
934
|
+
return `${file} is no longer read: nothing is carried into worktrees unless a repository lists it under "carry" in its own ${REPO_FILE}`;
|
|
935
|
+
}
|
|
703
936
|
const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
|
|
704
937
|
const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
|
|
705
938
|
const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
|
|
@@ -986,7 +1219,9 @@ function linkPaths(hostDirectory) {
|
|
|
986
1219
|
state,
|
|
987
1220
|
repos: path.join(state, "repos"),
|
|
988
1221
|
work: path.join(state, "work"),
|
|
989
|
-
|
|
1222
|
+
scratch: path.join(state, "scratch"),
|
|
1223
|
+
bin: path.join(state, "bin"),
|
|
1224
|
+
retiredReposConfig: path.join(state, "repos.json"),
|
|
990
1225
|
config: path.join(state, "config.json"),
|
|
991
1226
|
access: path.join(hostDirectory, "access.json")
|
|
992
1227
|
};
|
|
@@ -1096,88 +1331,57 @@ function buildHeartbeat(input) {
|
|
|
1096
1331
|
if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
|
|
1097
1332
|
return heartbeat;
|
|
1098
1333
|
}
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1334
|
+
const THREAD_ID$1 = /^t_[A-Za-z0-9]{8,64}$/u;
|
|
1335
|
+
function prepareScratch(scratch, threadId) {
|
|
1336
|
+
if (!THREAD_ID$1.test(threadId))
|
|
1337
|
+
return { ok: false, reason: "not a thread id" };
|
|
1338
|
+
const directory = path.join(scratch, threadId);
|
|
1339
|
+
try {
|
|
1340
|
+
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
1341
|
+
return { ok: true, directory };
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
return { ok: false, reason: error.message };
|
|
1109
1344
|
}
|
|
1110
|
-
return void 0;
|
|
1111
|
-
}
|
|
1112
|
-
function git(cwd, args, environment) {
|
|
1113
|
-
return new Promise((resolve) => {
|
|
1114
|
-
execFile(
|
|
1115
|
-
"git",
|
|
1116
|
-
["-C", cwd, ...args],
|
|
1117
|
-
environment ? { env: { ...process.env, ...environment } } : {},
|
|
1118
|
-
(failure, stdout, stderr) => resolve({
|
|
1119
|
-
ok: failure === null,
|
|
1120
|
-
stdout: stdout.trim(),
|
|
1121
|
-
stderr: stderr.trim()
|
|
1122
|
-
})
|
|
1123
|
-
);
|
|
1124
|
-
});
|
|
1125
1345
|
}
|
|
1126
|
-
function
|
|
1346
|
+
function entries(directory) {
|
|
1127
1347
|
try {
|
|
1128
|
-
return readdirSync(
|
|
1348
|
+
return readdirSync(directory, { withFileTypes: true });
|
|
1129
1349
|
} catch {
|
|
1130
1350
|
return [];
|
|
1131
1351
|
}
|
|
1132
1352
|
}
|
|
1133
|
-
|
|
1134
|
-
const
|
|
1135
|
-
const
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
"remote.origin.url"
|
|
1144
|
-
]);
|
|
1145
|
-
const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
|
|
1146
|
-
return repo ? { repo, path: directory } : void 0;
|
|
1147
|
-
})
|
|
1148
|
-
);
|
|
1149
|
-
return found.filter((checkout) => checkout !== void 0);
|
|
1150
|
-
}
|
|
1151
|
-
class Repos {
|
|
1152
|
-
constructor(reposDirectory, now = Date.now) {
|
|
1153
|
-
this.reposDirectory = reposDirectory;
|
|
1154
|
-
this.now = now;
|
|
1155
|
-
}
|
|
1156
|
-
scanned = [];
|
|
1157
|
-
scannedAt = Number.NEGATIVE_INFINITY;
|
|
1158
|
-
async list(options = {}) {
|
|
1159
|
-
if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
|
|
1160
|
-
this.scanned = await scanRepos(this.reposDirectory);
|
|
1161
|
-
this.scannedAt = this.now();
|
|
1353
|
+
function scanScratch(scratch) {
|
|
1354
|
+
const listings = [];
|
|
1355
|
+
for (const entry of entries(scratch)) {
|
|
1356
|
+
if (!entry.isDirectory() || !THREAD_ID$1.test(entry.name)) continue;
|
|
1357
|
+
const directory = path.join(scratch, entry.name);
|
|
1358
|
+
let createdAt;
|
|
1359
|
+
try {
|
|
1360
|
+
createdAt = statSync(directory).mtime.toISOString();
|
|
1361
|
+
} catch {
|
|
1362
|
+
continue;
|
|
1162
1363
|
}
|
|
1163
|
-
|
|
1364
|
+
listings.push({
|
|
1365
|
+
thread_id: entry.name,
|
|
1366
|
+
scratch: true,
|
|
1367
|
+
dirty: entries(directory).length > 0,
|
|
1368
|
+
unpushed: false,
|
|
1369
|
+
created_at: createdAt
|
|
1370
|
+
});
|
|
1164
1371
|
}
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
return
|
|
1372
|
+
return listings.toSorted((a, b) => a.thread_id.localeCompare(b.thread_id));
|
|
1373
|
+
}
|
|
1374
|
+
function hasScratch(scratch, threadId) {
|
|
1375
|
+
if (!THREAD_ID$1.test(threadId)) return false;
|
|
1376
|
+
try {
|
|
1377
|
+
return statSync(path.join(scratch, threadId)).isDirectory();
|
|
1378
|
+
} catch {
|
|
1379
|
+
return false;
|
|
1171
1380
|
}
|
|
1172
1381
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
const carry = value?.carry;
|
|
1177
|
-
if (!Array.isArray(carry)) return DEFAULT_CARRY;
|
|
1178
|
-
return carry.filter(
|
|
1179
|
-
(entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
|
|
1180
|
-
);
|
|
1382
|
+
function removeScratch(scratch, threadId) {
|
|
1383
|
+
if (!THREAD_ID$1.test(threadId)) return;
|
|
1384
|
+
rmSync(path.join(scratch, threadId), { recursive: true, force: true });
|
|
1181
1385
|
}
|
|
1182
1386
|
function salvageReference(threadId) {
|
|
1183
1387
|
return `refs/aibex/salvage/${threadId}`;
|
|
@@ -1272,26 +1476,12 @@ async function prepareWorktree(options) {
|
|
|
1272
1476
|
};
|
|
1273
1477
|
}
|
|
1274
1478
|
}
|
|
1275
|
-
const carried =
|
|
1276
|
-
for (const file of carryList(options.reposConfig)) {
|
|
1277
|
-
const from = path.join(checkout, file);
|
|
1278
|
-
const to = path.join(worktreePath, file);
|
|
1279
|
-
if (!existsSync(from) || existsSync(to)) continue;
|
|
1280
|
-
const tracked = await git(checkout, [
|
|
1281
|
-
"ls-files",
|
|
1282
|
-
"--error-unmatch",
|
|
1283
|
-
"--",
|
|
1284
|
-
file
|
|
1285
|
-
]);
|
|
1286
|
-
if (tracked.ok) continue;
|
|
1287
|
-
mkdirSync(path.dirname(to), { recursive: true });
|
|
1288
|
-
cpSync(from, to, { recursive: true });
|
|
1289
|
-
carried.push(file);
|
|
1290
|
-
}
|
|
1479
|
+
const { carried, problems } = await carryInto(checkout, worktreePath);
|
|
1291
1480
|
return {
|
|
1292
1481
|
ok: true,
|
|
1293
1482
|
worktree: { path: worktreePath, branch, base },
|
|
1294
1483
|
carried,
|
|
1484
|
+
carryProblems: problems,
|
|
1295
1485
|
...restored === void 0 ? {} : { restored }
|
|
1296
1486
|
};
|
|
1297
1487
|
}
|
|
@@ -1345,9 +1535,9 @@ async function isDirty(worktree, carry) {
|
|
|
1345
1535
|
"--untracked-files=all"
|
|
1346
1536
|
]);
|
|
1347
1537
|
if (!status.ok) return false;
|
|
1348
|
-
const
|
|
1349
|
-
for (let index = 0; index <
|
|
1350
|
-
const entry =
|
|
1538
|
+
const entries2 = status.stdout.split("\0");
|
|
1539
|
+
for (let index = 0; index < entries2.length; index++) {
|
|
1540
|
+
const entry = entries2[index] ?? "";
|
|
1351
1541
|
if (entry === "") continue;
|
|
1352
1542
|
const code = entry.slice(0, 2);
|
|
1353
1543
|
const file = entry.slice(3);
|
|
@@ -1357,8 +1547,7 @@ async function isDirty(worktree, carry) {
|
|
|
1357
1547
|
}
|
|
1358
1548
|
return false;
|
|
1359
1549
|
}
|
|
1360
|
-
async function scanWorktrees(work
|
|
1361
|
-
const carry = carryList(reposConfig);
|
|
1550
|
+
async function scanWorktrees(work) {
|
|
1362
1551
|
const listings = [];
|
|
1363
1552
|
for (const threadId of threadDirectories(work)) {
|
|
1364
1553
|
const directory = path.join(work, threadId);
|
|
@@ -1378,7 +1567,7 @@ async function scanWorktrees(work, reposConfig) {
|
|
|
1378
1567
|
const head = await git(directory, ["rev-parse", "--verify", "HEAD"]);
|
|
1379
1568
|
if (head.ok && /^[0-9a-f]{40}$/u.test(head.stdout)) {
|
|
1380
1569
|
listing.head = head.stdout;
|
|
1381
|
-
listing.dirty = await isDirty(directory, carry);
|
|
1570
|
+
listing.dirty = await isDirty(directory, carryList(directory).carry);
|
|
1382
1571
|
listing.unpushed = await hasUnpushed(directory);
|
|
1383
1572
|
}
|
|
1384
1573
|
}
|
|
@@ -1491,7 +1680,7 @@ async function releaseWorktree(options) {
|
|
|
1491
1680
|
};
|
|
1492
1681
|
}
|
|
1493
1682
|
const reference = salvageReference(threadId);
|
|
1494
|
-
const carry = carryList(
|
|
1683
|
+
const carry = carryList(worktree).carry;
|
|
1495
1684
|
const dirty = await isDirty(worktree, carry);
|
|
1496
1685
|
const unpushed = await hasUnpushed(worktree);
|
|
1497
1686
|
let salvage;
|
|
@@ -1656,10 +1845,10 @@ class Reaper {
|
|
|
1656
1845
|
async report() {
|
|
1657
1846
|
const now = this.now();
|
|
1658
1847
|
if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
|
|
1659
|
-
this.listing =
|
|
1660
|
-
this.options.work,
|
|
1661
|
-
this.options.
|
|
1662
|
-
|
|
1848
|
+
this.listing = [
|
|
1849
|
+
...await scanWorktrees(this.options.work),
|
|
1850
|
+
...scanScratch(this.options.scratch)
|
|
1851
|
+
];
|
|
1663
1852
|
this.scannedAt = now;
|
|
1664
1853
|
}
|
|
1665
1854
|
this.inFlight = [...this.pending];
|
|
@@ -1672,24 +1861,40 @@ class Reaper {
|
|
|
1672
1861
|
);
|
|
1673
1862
|
this.inFlight = [];
|
|
1674
1863
|
}
|
|
1864
|
+
/** A scratch directory: refused while its session is listed, else removed. */
|
|
1865
|
+
releaseScratch(threadId, sessionListed) {
|
|
1866
|
+
if (sessionListed) {
|
|
1867
|
+
return {
|
|
1868
|
+
outcome: "refused",
|
|
1869
|
+
reason: "a session for this thread is listed"
|
|
1870
|
+
};
|
|
1871
|
+
}
|
|
1872
|
+
removeScratch(this.options.scratch, threadId);
|
|
1873
|
+
return { outcome: "released", scratch: true };
|
|
1874
|
+
}
|
|
1675
1875
|
/** Handles one `work.release`. */
|
|
1676
1876
|
async release(command, sessionListed) {
|
|
1677
|
-
const outcome = await releaseWorktree({
|
|
1877
|
+
const outcome = hasScratch(this.options.scratch, command.thread_id) ? this.releaseScratch(command.thread_id, sessionListed) : await releaseWorktree({
|
|
1678
1878
|
work: this.options.work,
|
|
1679
1879
|
threadId: command.thread_id,
|
|
1680
1880
|
epoch: command.epoch,
|
|
1681
|
-
reposConfig: this.options.reposConfig,
|
|
1682
1881
|
checkouts: await this.options.checkouts(),
|
|
1683
1882
|
sessionListed
|
|
1684
1883
|
});
|
|
1685
|
-
const result = {
|
|
1884
|
+
const result = outcome.outcome === "released" ? {
|
|
1885
|
+
command_id: command.command_id,
|
|
1886
|
+
thread_id: command.thread_id,
|
|
1887
|
+
epoch: command.epoch,
|
|
1888
|
+
outcome: "released",
|
|
1889
|
+
...outcome.salvage === void 0 ? {} : { salvage: outcome.salvage }
|
|
1890
|
+
} : {
|
|
1686
1891
|
command_id: command.command_id,
|
|
1687
1892
|
thread_id: command.thread_id,
|
|
1688
1893
|
epoch: command.epoch,
|
|
1689
1894
|
...outcome
|
|
1690
1895
|
};
|
|
1691
1896
|
this.options.log(
|
|
1692
|
-
outcome.outcome === "released" ? `${command.thread_id}: worktree released${outcome.salvage ? `; its work is saved at ${salvageReference(command.thread_id)} (${outcome.salvage})` : ""}` : `${command.thread_id}: release refused: ${outcome.reason}`
|
|
1897
|
+
outcome.outcome === "released" ? `${command.thread_id}: ${outcome.scratch ? "scratch directory" : "worktree"} released${outcome.salvage ? `; its work is saved at ${salvageReference(command.thread_id)} (${outcome.salvage})` : ""}` : `${command.thread_id}: release refused: ${outcome.reason}`
|
|
1693
1898
|
);
|
|
1694
1899
|
this.pending.push(result);
|
|
1695
1900
|
this.scannedAt = Number.NEGATIVE_INFINITY;
|
|
@@ -2765,25 +2970,204 @@ class Transcript {
|
|
|
2765
2970
|
rmSync(this.spoolFile, { force: true });
|
|
2766
2971
|
}
|
|
2767
2972
|
}
|
|
2768
|
-
const
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
quietMs: 750,
|
|
2772
|
-
statusIntervalMs: 5e3,
|
|
2773
|
-
uploadIntervalMs: 5e3,
|
|
2774
|
-
uploadThresholdBytes: 256 * 1024,
|
|
2775
|
-
settleMs: 150,
|
|
2776
|
-
reattachMs: 5e3,
|
|
2777
|
-
reattachMaxMs: 6e4
|
|
2778
|
-
};
|
|
2779
|
-
const STATUS_MAX = 200;
|
|
2780
|
-
function newEventId() {
|
|
2781
|
-
return `e_${randomBytes(12).toString("base64url")}`;
|
|
2973
|
+
const SETUP_LABEL = "setup:";
|
|
2974
|
+
function isProgram(value) {
|
|
2975
|
+
return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
|
|
2782
2976
|
}
|
|
2783
|
-
|
|
2784
|
-
|
|
2977
|
+
const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
|
|
2978
|
+
function isAddRepo(value) {
|
|
2979
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2980
|
+
const { owner, name } = value;
|
|
2981
|
+
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;
|
|
2785
2982
|
}
|
|
2786
|
-
class
|
|
2983
|
+
class SetupTerminals {
|
|
2984
|
+
constructor(options) {
|
|
2985
|
+
this.options = options;
|
|
2986
|
+
this.home = options.home ?? homedir();
|
|
2987
|
+
}
|
|
2988
|
+
home;
|
|
2989
|
+
sockets() {
|
|
2990
|
+
return hostSockets(
|
|
2991
|
+
this.options.terminalsDirectory,
|
|
2992
|
+
this.options.terminalSocket
|
|
2993
|
+
);
|
|
2994
|
+
}
|
|
2995
|
+
/** `terminal.open`: checks the envelope and the program, then starts it. */
|
|
2996
|
+
async open(command) {
|
|
2997
|
+
const { log } = this.options;
|
|
2998
|
+
const opened = await this.options.access.open(
|
|
2999
|
+
command.request
|
|
3000
|
+
);
|
|
3001
|
+
if (!opened.ok) {
|
|
3002
|
+
log.line(`terminal.open refused: ${opened.reason}`);
|
|
3003
|
+
return;
|
|
3004
|
+
}
|
|
3005
|
+
const { open_id: openId, program, cwd, repo } = opened.payload;
|
|
3006
|
+
if (!isProgram(program)) {
|
|
3007
|
+
log.line(
|
|
3008
|
+
`terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
|
|
3009
|
+
);
|
|
3010
|
+
return;
|
|
3011
|
+
}
|
|
3012
|
+
if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
|
|
3013
|
+
log.line(
|
|
3014
|
+
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`
|
|
3015
|
+
);
|
|
3016
|
+
return;
|
|
3017
|
+
}
|
|
3018
|
+
if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
|
|
3019
|
+
log.line(`terminal.open ${openId} refused: unknown working directory`);
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
3022
|
+
let directory = this.home;
|
|
3023
|
+
if (cwd.kind === "repo" && program !== "repo-add") {
|
|
3024
|
+
const checkout = await this.options.repos.find(cwd.repo);
|
|
3025
|
+
if (!checkout) {
|
|
3026
|
+
log.line(
|
|
3027
|
+
`terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
|
|
3028
|
+
);
|
|
3029
|
+
return;
|
|
3030
|
+
}
|
|
3031
|
+
directory = checkout.path;
|
|
3032
|
+
}
|
|
3033
|
+
const label = `${SETUP_LABEL}${openId}`;
|
|
3034
|
+
const existing = await listTerminals(this.sockets());
|
|
3035
|
+
if (existing.some((terminal) => terminal.label === label)) return;
|
|
3036
|
+
const searchPath = this.searchPath();
|
|
3037
|
+
const run = this.command(program, repo);
|
|
3038
|
+
const args = run.args;
|
|
3039
|
+
const file = resolveProgram(run.file, searchPath);
|
|
3040
|
+
const socket = this.options.terminalSocket;
|
|
3041
|
+
if (socket === void 0) {
|
|
3042
|
+
log.line(`terminal.open ${openId}: no terminal host is set`);
|
|
3043
|
+
return;
|
|
3044
|
+
}
|
|
3045
|
+
let client;
|
|
3046
|
+
try {
|
|
3047
|
+
client = await HostClient.connect(socket);
|
|
3048
|
+
} catch (error) {
|
|
3049
|
+
log.line(
|
|
3050
|
+
`terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
|
|
3051
|
+
);
|
|
3052
|
+
return;
|
|
3053
|
+
}
|
|
3054
|
+
try {
|
|
3055
|
+
const created = await client.request({
|
|
3056
|
+
type: "create",
|
|
3057
|
+
file,
|
|
3058
|
+
args,
|
|
3059
|
+
cwd: directory,
|
|
3060
|
+
env: { PATH: searchPath },
|
|
3061
|
+
label
|
|
3062
|
+
});
|
|
3063
|
+
log.line(
|
|
3064
|
+
created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
|
|
3065
|
+
);
|
|
3066
|
+
} finally {
|
|
3067
|
+
client.close();
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
/** The file and arguments a program runs; `repo` is checked already. */
|
|
3071
|
+
command(program, repo) {
|
|
3072
|
+
if (program === "repo-add" && repo) {
|
|
3073
|
+
return {
|
|
3074
|
+
file: path.join(this.options.binDirectory, "aibexd"),
|
|
3075
|
+
args: ["repo", "add", `${repo.owner}/${repo.name}`]
|
|
3076
|
+
};
|
|
3077
|
+
}
|
|
3078
|
+
if (program === "shell") {
|
|
3079
|
+
return {
|
|
3080
|
+
file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
|
|
3081
|
+
args: ["-l"]
|
|
3082
|
+
};
|
|
3083
|
+
}
|
|
3084
|
+
return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
|
|
3085
|
+
}
|
|
3086
|
+
searchPath() {
|
|
3087
|
+
return setupSearchPath(this.options.binDirectory, this.options.path);
|
|
3088
|
+
}
|
|
3089
|
+
/** Every setup terminal a host still keeps, running or exited. */
|
|
3090
|
+
async list() {
|
|
3091
|
+
const terminals = await listTerminals(this.sockets());
|
|
3092
|
+
return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
|
|
3093
|
+
const program = this.program(terminal.file);
|
|
3094
|
+
const entry = {
|
|
3095
|
+
open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
|
|
3096
|
+
terminal: terminal.id,
|
|
3097
|
+
program,
|
|
3098
|
+
cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
|
|
3099
|
+
};
|
|
3100
|
+
if (program === "repo-add") {
|
|
3101
|
+
const [owner, name] = (terminal.args?.[2] ?? "").split("/");
|
|
3102
|
+
if (owner && name) entry.repo = { owner, name };
|
|
3103
|
+
}
|
|
3104
|
+
if (terminal.exited) entry.exit = terminal.exited;
|
|
3105
|
+
return entry;
|
|
3106
|
+
});
|
|
3107
|
+
}
|
|
3108
|
+
program(file) {
|
|
3109
|
+
const name = path.basename(file);
|
|
3110
|
+
const found = Object.entries(SETUP_PROGRAMS).find(
|
|
3111
|
+
([, command]) => command === name
|
|
3112
|
+
);
|
|
3113
|
+
return found?.[0] ?? "shell";
|
|
3114
|
+
}
|
|
3115
|
+
cwd(directory) {
|
|
3116
|
+
const relative = path.relative(
|
|
3117
|
+
path.join(this.options.reposDirectory, GITHUB_HOST),
|
|
3118
|
+
directory
|
|
3119
|
+
);
|
|
3120
|
+
const [owner, name, ...rest] = relative.split(path.sep);
|
|
3121
|
+
if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
|
|
3122
|
+
const repo = { owner, name };
|
|
3123
|
+
return { kind: "repo", repo };
|
|
3124
|
+
}
|
|
3125
|
+
return { kind: "home" };
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
|
|
3129
|
+
const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
|
|
3130
|
+
return [binDirectory, ...rest].join(path.delimiter);
|
|
3131
|
+
}
|
|
3132
|
+
function resolveProgram(file, searchPath) {
|
|
3133
|
+
if (file.includes("/")) return file;
|
|
3134
|
+
for (const directory of searchPath.split(path.delimiter)) {
|
|
3135
|
+
if (directory === "") continue;
|
|
3136
|
+
const candidate = path.join(directory, file);
|
|
3137
|
+
try {
|
|
3138
|
+
if (!statSync(candidate).isFile()) continue;
|
|
3139
|
+
accessSync(candidate, constants.X_OK);
|
|
3140
|
+
return candidate;
|
|
3141
|
+
} catch {
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
return file;
|
|
3145
|
+
}
|
|
3146
|
+
const DEFAULT_SESSION_TIMINGS = {
|
|
3147
|
+
readyTimeoutMs: 6e4,
|
|
3148
|
+
checkMs: 250,
|
|
3149
|
+
quietMs: 750,
|
|
3150
|
+
statusIntervalMs: 5e3,
|
|
3151
|
+
uploadIntervalMs: 5e3,
|
|
3152
|
+
uploadThresholdBytes: 256 * 1024,
|
|
3153
|
+
settleMs: 150,
|
|
3154
|
+
reattachMs: 5e3,
|
|
3155
|
+
reattachMaxMs: 6e4
|
|
3156
|
+
};
|
|
3157
|
+
const STATUS_MAX = 200;
|
|
3158
|
+
function newEventId() {
|
|
3159
|
+
return `e_${randomBytes(12).toString("base64url")}`;
|
|
3160
|
+
}
|
|
3161
|
+
function sameToken(expected, given) {
|
|
3162
|
+
if (!expected) return false;
|
|
3163
|
+
const a = Buffer.from(expected);
|
|
3164
|
+
const b = Buffer.from(given);
|
|
3165
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
3166
|
+
}
|
|
3167
|
+
function errorText(error) {
|
|
3168
|
+
return error instanceof Error ? error.message : String(error);
|
|
3169
|
+
}
|
|
3170
|
+
class Session {
|
|
2787
3171
|
constructor(record, manager) {
|
|
2788
3172
|
this.record = record;
|
|
2789
3173
|
this.manager = manager;
|
|
@@ -3427,7 +3811,8 @@ class Sessions {
|
|
|
3427
3811
|
prompted: false,
|
|
3428
3812
|
messages: [],
|
|
3429
3813
|
transcript: { base: 0, uploaded: 0, seqOffset: 0 },
|
|
3430
|
-
outbox: []
|
|
3814
|
+
outbox: [],
|
|
3815
|
+
handoff_token: randomBytes(32).toString("base64url")
|
|
3431
3816
|
};
|
|
3432
3817
|
const session = new Session(record, this);
|
|
3433
3818
|
this.sessions.set(record.thread_id, session);
|
|
@@ -3449,39 +3834,62 @@ class Sessions {
|
|
|
3449
3834
|
}
|
|
3450
3835
|
const request = opened.payload;
|
|
3451
3836
|
const entry = harness ? this.harnesses[harness] : void 0;
|
|
3452
|
-
if (!entry || typeof request.prompt !== "string"
|
|
3837
|
+
if (!entry || typeof request.prompt !== "string") {
|
|
3453
3838
|
refuse("the request is not one this link can run");
|
|
3454
3839
|
return;
|
|
3455
3840
|
}
|
|
3456
|
-
record.repo = request.repo;
|
|
3457
3841
|
record.queue = [request.prompt];
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
)
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3842
|
+
let directory;
|
|
3843
|
+
if (request.repo) {
|
|
3844
|
+
record.repo = request.repo;
|
|
3845
|
+
this.save(session);
|
|
3846
|
+
const checkout = await this.options.repos.find(request.repo);
|
|
3847
|
+
if (stale()) return;
|
|
3848
|
+
if (!checkout) {
|
|
3849
|
+
refuse(
|
|
3850
|
+
`no checkout of ${request.repo.owner}/${request.repo.name} under ${this.options.paths.repos}`
|
|
3851
|
+
);
|
|
3852
|
+
return;
|
|
3853
|
+
}
|
|
3854
|
+
const prepared = await prepareWorktree({
|
|
3855
|
+
checkout: checkout.path,
|
|
3856
|
+
workDirectory: this.options.paths.work,
|
|
3857
|
+
threadId: record.thread_id,
|
|
3858
|
+
baseRef: request.base_ref
|
|
3859
|
+
});
|
|
3860
|
+
if (stale()) return;
|
|
3861
|
+
if (!prepared.ok) {
|
|
3862
|
+
refuse(`the worktree could not be made: ${prepared.reason}`);
|
|
3863
|
+
return;
|
|
3864
|
+
}
|
|
3865
|
+
record.worktree = prepared.worktree;
|
|
3866
|
+
directory = prepared.worktree.path;
|
|
3867
|
+
if (prepared.carried.length > 0) {
|
|
3868
|
+
this.options.log.line(
|
|
3869
|
+
`${record.thread_id}: carried ${prepared.carried.join(", ")} from the checkout`
|
|
3870
|
+
);
|
|
3871
|
+
}
|
|
3872
|
+
for (const problem of prepared.carryProblems) {
|
|
3873
|
+
this.options.log.line(`${record.thread_id}: ${problem}`);
|
|
3874
|
+
}
|
|
3875
|
+
if (prepared.restored !== void 0) {
|
|
3876
|
+
this.options.log.line(
|
|
3877
|
+
`${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
|
|
3878
|
+
);
|
|
3879
|
+
}
|
|
3880
|
+
} else {
|
|
3881
|
+
const prepared = prepareScratch(
|
|
3882
|
+
this.options.paths.scratch,
|
|
3883
|
+
record.thread_id
|
|
3483
3884
|
);
|
|
3885
|
+
if (!prepared.ok) {
|
|
3886
|
+
refuse(`the scratch directory could not be made: ${prepared.reason}`);
|
|
3887
|
+
return;
|
|
3888
|
+
}
|
|
3889
|
+
record.scratch = prepared.directory;
|
|
3890
|
+
directory = prepared.directory;
|
|
3484
3891
|
}
|
|
3892
|
+
this.save(session);
|
|
3485
3893
|
const socket = this.options.terminalSocket;
|
|
3486
3894
|
let client;
|
|
3487
3895
|
try {
|
|
@@ -3497,11 +3905,20 @@ class Sessions {
|
|
|
3497
3905
|
client.close();
|
|
3498
3906
|
return;
|
|
3499
3907
|
}
|
|
3908
|
+
const searchPath = setupSearchPath(
|
|
3909
|
+
this.options.paths.bin,
|
|
3910
|
+
this.options.path
|
|
3911
|
+
);
|
|
3500
3912
|
const created = await client.request({
|
|
3501
3913
|
type: "create",
|
|
3502
|
-
file: entry.command,
|
|
3914
|
+
file: resolveProgram(entry.command, searchPath),
|
|
3503
3915
|
args: entry.args,
|
|
3504
|
-
cwd:
|
|
3916
|
+
cwd: directory,
|
|
3917
|
+
env: {
|
|
3918
|
+
PATH: searchPath,
|
|
3919
|
+
AIBEX_THREAD_ID: record.thread_id,
|
|
3920
|
+
AIBEX_HANDOFF_TOKEN: record.handoff_token ?? ""
|
|
3921
|
+
},
|
|
3505
3922
|
label: `thread:${record.thread_id}`
|
|
3506
3923
|
});
|
|
3507
3924
|
if (!created.ok) {
|
|
@@ -3521,10 +3938,40 @@ class Sessions {
|
|
|
3521
3938
|
session.move({ type: "launched" });
|
|
3522
3939
|
this.save(session);
|
|
3523
3940
|
this.log.line(
|
|
3524
|
-
`${record.thread_id}: started ${entry.command} in ${
|
|
3941
|
+
`${record.thread_id}: started ${entry.command} in ${directory} as ${record.terminal}`
|
|
3525
3942
|
);
|
|
3526
3943
|
await session.drive(client);
|
|
3527
3944
|
}
|
|
3945
|
+
/**
|
|
3946
|
+
* `aibexd handoff` from inside a session: queues a `reroute` event under
|
|
3947
|
+
* the session's lease when the thread runs here with no repository, its
|
|
3948
|
+
* session is running or detached, and the token is the session's.
|
|
3949
|
+
*/
|
|
3950
|
+
handoff(request) {
|
|
3951
|
+
const session = this.sessions.get(request.threadId);
|
|
3952
|
+
if (!session || session.phase !== "running" && session.phase !== "detached") {
|
|
3953
|
+
return { ok: false, reason: "no running session of that thread here" };
|
|
3954
|
+
}
|
|
3955
|
+
const { record } = session;
|
|
3956
|
+
if (!sameToken(record.handoff_token, request.token)) {
|
|
3957
|
+
return { ok: false, reason: "the handoff token is not this thread's" };
|
|
3958
|
+
}
|
|
3959
|
+
if (record.repo || record.scratch === void 0) {
|
|
3960
|
+
return {
|
|
3961
|
+
ok: false,
|
|
3962
|
+
reason: "this thread already has a repository; only a thread without one hands off"
|
|
3963
|
+
};
|
|
3964
|
+
}
|
|
3965
|
+
this.event(session, {
|
|
3966
|
+
type: "reroute",
|
|
3967
|
+
repo: { owner: request.repo.owner, name: request.repo.name },
|
|
3968
|
+
...request.note ? { note: request.note } : {}
|
|
3969
|
+
});
|
|
3970
|
+
this.log.line(
|
|
3971
|
+
`${record.thread_id}: handing off to ${request.repo.owner}/${request.repo.name}`
|
|
3972
|
+
);
|
|
3973
|
+
return { ok: true };
|
|
3974
|
+
}
|
|
3528
3975
|
async message(command) {
|
|
3529
3976
|
const session = this.sessions.get(command.thread_id);
|
|
3530
3977
|
if (!session || session.record.ended) {
|
|
@@ -3748,179 +4195,6 @@ class Sessions {
|
|
|
3748
4195
|
for (const session of this.sessions.values()) session.dispose();
|
|
3749
4196
|
}
|
|
3750
4197
|
}
|
|
3751
|
-
const SETUP_LABEL = "setup:";
|
|
3752
|
-
function isProgram(value) {
|
|
3753
|
-
return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
|
|
3754
|
-
}
|
|
3755
|
-
const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
|
|
3756
|
-
function isAddRepo(value) {
|
|
3757
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3758
|
-
const { owner, name } = value;
|
|
3759
|
-
return Object.keys(value).length === 2 && typeof owner === "string" && typeof name === "string" && REPO_PART.test(owner) && REPO_PART.test(name) && owner.length <= 100 && name.length <= 100;
|
|
3760
|
-
}
|
|
3761
|
-
class SetupTerminals {
|
|
3762
|
-
constructor(options) {
|
|
3763
|
-
this.options = options;
|
|
3764
|
-
this.home = options.home ?? homedir();
|
|
3765
|
-
}
|
|
3766
|
-
home;
|
|
3767
|
-
sockets() {
|
|
3768
|
-
return hostSockets(
|
|
3769
|
-
this.options.terminalsDirectory,
|
|
3770
|
-
this.options.terminalSocket
|
|
3771
|
-
);
|
|
3772
|
-
}
|
|
3773
|
-
/** `terminal.open`: checks the envelope and the program, then starts it. */
|
|
3774
|
-
async open(command) {
|
|
3775
|
-
const { log } = this.options;
|
|
3776
|
-
const opened = await this.options.access.open(
|
|
3777
|
-
command.request
|
|
3778
|
-
);
|
|
3779
|
-
if (!opened.ok) {
|
|
3780
|
-
log.line(`terminal.open refused: ${opened.reason}`);
|
|
3781
|
-
return;
|
|
3782
|
-
}
|
|
3783
|
-
const { open_id: openId, program, cwd, repo } = opened.payload;
|
|
3784
|
-
if (!isProgram(program)) {
|
|
3785
|
-
log.line(
|
|
3786
|
-
`terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
|
|
3787
|
-
);
|
|
3788
|
-
return;
|
|
3789
|
-
}
|
|
3790
|
-
if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
|
|
3791
|
-
log.line(
|
|
3792
|
-
program === "repo-add" ? `terminal.open ${openId} refused: repo-add needs a repository whose owner and name are letters, digits, _, . and -, starting with neither - nor .` : `terminal.open ${openId} refused: only repo-add takes a repository`
|
|
3793
|
-
);
|
|
3794
|
-
return;
|
|
3795
|
-
}
|
|
3796
|
-
if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
|
|
3797
|
-
log.line(`terminal.open ${openId} refused: unknown working directory`);
|
|
3798
|
-
return;
|
|
3799
|
-
}
|
|
3800
|
-
let directory = this.home;
|
|
3801
|
-
if (cwd.kind === "repo" && program !== "repo-add") {
|
|
3802
|
-
const checkout = await this.options.repos.find(cwd.repo);
|
|
3803
|
-
if (!checkout) {
|
|
3804
|
-
log.line(
|
|
3805
|
-
`terminal.open ${openId} refused: no checkout of ${cwd.repo.owner}/${cwd.repo.name}`
|
|
3806
|
-
);
|
|
3807
|
-
return;
|
|
3808
|
-
}
|
|
3809
|
-
directory = checkout.path;
|
|
3810
|
-
}
|
|
3811
|
-
const label = `${SETUP_LABEL}${openId}`;
|
|
3812
|
-
const existing = await listTerminals(this.sockets());
|
|
3813
|
-
if (existing.some((terminal) => terminal.label === label)) return;
|
|
3814
|
-
const searchPath = this.searchPath();
|
|
3815
|
-
const run = this.command(program, repo);
|
|
3816
|
-
const args = run.args;
|
|
3817
|
-
const file = resolveProgram(run.file, searchPath);
|
|
3818
|
-
const socket = this.options.terminalSocket;
|
|
3819
|
-
if (socket === void 0) {
|
|
3820
|
-
log.line(`terminal.open ${openId}: no terminal host is set`);
|
|
3821
|
-
return;
|
|
3822
|
-
}
|
|
3823
|
-
let client;
|
|
3824
|
-
try {
|
|
3825
|
-
client = await HostClient.connect(socket);
|
|
3826
|
-
} catch (error) {
|
|
3827
|
-
log.line(
|
|
3828
|
-
`terminal.open ${openId}: the terminal host cannot be reached: ${error.message}`
|
|
3829
|
-
);
|
|
3830
|
-
return;
|
|
3831
|
-
}
|
|
3832
|
-
try {
|
|
3833
|
-
const created = await client.request({
|
|
3834
|
-
type: "create",
|
|
3835
|
-
file,
|
|
3836
|
-
args,
|
|
3837
|
-
cwd: directory,
|
|
3838
|
-
env: { PATH: searchPath },
|
|
3839
|
-
label
|
|
3840
|
-
});
|
|
3841
|
-
log.line(
|
|
3842
|
-
created.ok ? `terminal.open ${openId}: ${file} in ${directory} as ${String(created.terminal)}` : `terminal.open ${openId}: ${file} could not start: ${created.error?.message}`
|
|
3843
|
-
);
|
|
3844
|
-
} finally {
|
|
3845
|
-
client.close();
|
|
3846
|
-
}
|
|
3847
|
-
}
|
|
3848
|
-
/** The file and arguments a program runs; `repo` is checked already. */
|
|
3849
|
-
command(program, repo) {
|
|
3850
|
-
if (program === "repo-add" && repo) {
|
|
3851
|
-
return {
|
|
3852
|
-
file: path.join(this.options.binDirectory, "aibexd"),
|
|
3853
|
-
args: ["repo", "add", `${repo.owner}/${repo.name}`]
|
|
3854
|
-
};
|
|
3855
|
-
}
|
|
3856
|
-
if (program === "shell") {
|
|
3857
|
-
return {
|
|
3858
|
-
file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
|
|
3859
|
-
args: ["-l"]
|
|
3860
|
-
};
|
|
3861
|
-
}
|
|
3862
|
-
return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
|
|
3863
|
-
}
|
|
3864
|
-
searchPath() {
|
|
3865
|
-
return setupSearchPath(this.options.binDirectory, this.options.path);
|
|
3866
|
-
}
|
|
3867
|
-
/** Every setup terminal a host still keeps, running or exited. */
|
|
3868
|
-
async list() {
|
|
3869
|
-
const terminals = await listTerminals(this.sockets());
|
|
3870
|
-
return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
|
|
3871
|
-
const program = this.program(terminal.file);
|
|
3872
|
-
const entry = {
|
|
3873
|
-
open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
|
|
3874
|
-
terminal: terminal.id,
|
|
3875
|
-
program,
|
|
3876
|
-
cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
|
|
3877
|
-
};
|
|
3878
|
-
if (program === "repo-add") {
|
|
3879
|
-
const [owner, name] = (terminal.args?.[2] ?? "").split("/");
|
|
3880
|
-
if (owner && name) entry.repo = { owner, name };
|
|
3881
|
-
}
|
|
3882
|
-
if (terminal.exited) entry.exit = terminal.exited;
|
|
3883
|
-
return entry;
|
|
3884
|
-
});
|
|
3885
|
-
}
|
|
3886
|
-
program(file) {
|
|
3887
|
-
const name = path.basename(file);
|
|
3888
|
-
const found = Object.entries(SETUP_PROGRAMS).find(
|
|
3889
|
-
([, command]) => command === name
|
|
3890
|
-
);
|
|
3891
|
-
return found?.[0] ?? "shell";
|
|
3892
|
-
}
|
|
3893
|
-
cwd(directory) {
|
|
3894
|
-
const relative = path.relative(
|
|
3895
|
-
path.join(this.options.reposDirectory, GITHUB_HOST),
|
|
3896
|
-
directory
|
|
3897
|
-
);
|
|
3898
|
-
const [owner, name, ...rest] = relative.split(path.sep);
|
|
3899
|
-
if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
|
|
3900
|
-
const repo = { owner, name };
|
|
3901
|
-
return { kind: "repo", repo };
|
|
3902
|
-
}
|
|
3903
|
-
return { kind: "home" };
|
|
3904
|
-
}
|
|
3905
|
-
}
|
|
3906
|
-
function setupSearchPath(binDirectory, searchPath = process.env.PATH ?? "") {
|
|
3907
|
-
const rest = searchPath.split(path.delimiter).filter((directory) => directory !== "" && directory !== binDirectory);
|
|
3908
|
-
return [binDirectory, ...rest].join(path.delimiter);
|
|
3909
|
-
}
|
|
3910
|
-
function resolveProgram(file, searchPath) {
|
|
3911
|
-
if (file.includes("/")) return file;
|
|
3912
|
-
for (const directory of searchPath.split(path.delimiter)) {
|
|
3913
|
-
if (directory === "") continue;
|
|
3914
|
-
const candidate = path.join(directory, file);
|
|
3915
|
-
try {
|
|
3916
|
-
if (!statSync(candidate).isFile()) continue;
|
|
3917
|
-
accessSync(candidate, constants.X_OK);
|
|
3918
|
-
return candidate;
|
|
3919
|
-
} catch {
|
|
3920
|
-
}
|
|
3921
|
-
}
|
|
3922
|
-
return file;
|
|
3923
|
-
}
|
|
3924
4198
|
function send(message) {
|
|
3925
4199
|
return new Promise((resolve) => {
|
|
3926
4200
|
if (!process.send) {
|
|
@@ -3980,6 +4254,8 @@ function main() {
|
|
|
3980
4254
|
const access = new Access(paths.access);
|
|
3981
4255
|
const repos = new Repos(paths.repos);
|
|
3982
4256
|
rmSync(path.join(hostDirectory, "activations.json"), { force: true });
|
|
4257
|
+
const retired = retiredReposConfigNotice(paths.retiredReposConfig);
|
|
4258
|
+
if (retired !== void 0) log.line(retired);
|
|
3983
4259
|
const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
|
|
3984
4260
|
const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
|
|
3985
4261
|
let poller;
|
|
@@ -4005,7 +4281,7 @@ function main() {
|
|
|
4005
4281
|
access,
|
|
4006
4282
|
repos,
|
|
4007
4283
|
reposDirectory: paths.repos,
|
|
4008
|
-
binDirectory:
|
|
4284
|
+
binDirectory: paths.bin,
|
|
4009
4285
|
terminalSocket,
|
|
4010
4286
|
terminalsDirectory,
|
|
4011
4287
|
log
|
|
@@ -4022,7 +4298,7 @@ function main() {
|
|
|
4022
4298
|
statuses = signIns;
|
|
4023
4299
|
reaper = new Reaper({
|
|
4024
4300
|
work: paths.work,
|
|
4025
|
-
|
|
4301
|
+
scratch: paths.scratch,
|
|
4026
4302
|
checkouts: async () => {
|
|
4027
4303
|
const checkouts = await repos.list();
|
|
4028
4304
|
return checkouts.map((checkout) => checkout.path);
|
|
@@ -4063,7 +4339,7 @@ function main() {
|
|
|
4063
4339
|
paths,
|
|
4064
4340
|
repos,
|
|
4065
4341
|
access,
|
|
4066
|
-
features: ["sessions", "relay", "setup"],
|
|
4342
|
+
features: ["sessions", "relay", "setup", "scratch", "handoff"],
|
|
4067
4343
|
sessions: running.list(),
|
|
4068
4344
|
setupTerminals,
|
|
4069
4345
|
...await reaping.report()
|
|
@@ -4110,6 +4386,15 @@ function main() {
|
|
|
4110
4386
|
};
|
|
4111
4387
|
break;
|
|
4112
4388
|
}
|
|
4389
|
+
case "handoff": {
|
|
4390
|
+
const { requestId, ...request } = message;
|
|
4391
|
+
const answer = sessions ? sessions.handoff(request) : {
|
|
4392
|
+
ok: false,
|
|
4393
|
+
reason: "this machine has not joined a herd"
|
|
4394
|
+
};
|
|
4395
|
+
void send({ type: "handed-off", requestId, ...answer });
|
|
4396
|
+
break;
|
|
4397
|
+
}
|
|
4113
4398
|
case "diagnostics": {
|
|
4114
4399
|
const mismatch = access.mismatch;
|
|
4115
4400
|
poller?.attachDiagnostics({
|