@aibexhq/aibex-link 0.0.6 → 0.0.8
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 +591 -93
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, appendFileSync, openSync, readSync, closeSync, cpSync } from "node:fs";
|
|
2
|
-
import { randomBytes, createHash } from "node:crypto";
|
|
3
1
|
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
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
4
4
|
import { platform, arch, release, homedir } from "node:os";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { createConnection } from "node:net";
|
|
@@ -700,6 +700,51 @@ 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
|
+
}
|
|
703
748
|
const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
|
|
704
749
|
const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
|
|
705
750
|
const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
|
|
@@ -840,6 +885,9 @@ async function collectReport(options) {
|
|
|
840
885
|
const access = options.access.heartbeat();
|
|
841
886
|
if (access) report.access = access;
|
|
842
887
|
if (options.setupTerminals) report.setup_terminals = options.setupTerminals;
|
|
888
|
+
if (options.activations && options.activations.length > 0) {
|
|
889
|
+
report.activations = options.activations;
|
|
890
|
+
}
|
|
843
891
|
return report;
|
|
844
892
|
}
|
|
845
893
|
function buildHeartbeat(input) {
|
|
@@ -859,11 +907,12 @@ function buildHeartbeat(input) {
|
|
|
859
907
|
sessions: input.report.sessions,
|
|
860
908
|
acks: input.acks
|
|
861
909
|
};
|
|
862
|
-
const { repos, access, features, setup_terminals } = input.report;
|
|
910
|
+
const { repos, access, features, setup_terminals, activations } = input.report;
|
|
863
911
|
if (repos) heartbeat.repos = repos;
|
|
864
912
|
if (access) heartbeat.access = access;
|
|
865
913
|
if (features) heartbeat.features = features;
|
|
866
914
|
if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
|
|
915
|
+
if (activations) heartbeat.activations = activations;
|
|
867
916
|
if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
|
|
868
917
|
return heartbeat;
|
|
869
918
|
}
|
|
@@ -1362,6 +1411,11 @@ class Relay {
|
|
|
1362
1411
|
idleTimer;
|
|
1363
1412
|
/** Connections to terminal hosts made for this relay, by socket path. */
|
|
1364
1413
|
hosts = /* @__PURE__ */ new Map();
|
|
1414
|
+
/**
|
|
1415
|
+
* Each viewer's requests still being handled, by `conn`: the tail of a
|
|
1416
|
+
* chain that runs them one at a time in the order they arrived.
|
|
1417
|
+
*/
|
|
1418
|
+
queues = /* @__PURE__ */ new Map();
|
|
1365
1419
|
/** Nonces seen, with when they may be forgotten. */
|
|
1366
1420
|
nonces = /* @__PURE__ */ new Map();
|
|
1367
1421
|
timings;
|
|
@@ -1432,6 +1486,7 @@ class Relay {
|
|
|
1432
1486
|
end() {
|
|
1433
1487
|
clearTimeout(this.idleTimer);
|
|
1434
1488
|
this.idleTimer = void 0;
|
|
1489
|
+
this.queues.clear();
|
|
1435
1490
|
for (const pending of this.hosts.values()) {
|
|
1436
1491
|
void (async () => {
|
|
1437
1492
|
try {
|
|
@@ -1469,9 +1524,36 @@ class Relay {
|
|
|
1469
1524
|
if (frame.type === "viewers") {
|
|
1470
1525
|
this.viewers(frame.count);
|
|
1471
1526
|
} else if (frame.type === "request" && typeof frame.conn === "string") {
|
|
1472
|
-
await this.
|
|
1527
|
+
await this.enqueue(frame.conn, frame.envelope);
|
|
1473
1528
|
}
|
|
1474
1529
|
}
|
|
1530
|
+
/**
|
|
1531
|
+
* Runs a viewer's request after every earlier request from the same
|
|
1532
|
+
* `conn` has reached its terminal host and been answered, so two
|
|
1533
|
+
* keystrokes are never swapped. Different viewers stay concurrent.
|
|
1534
|
+
*/
|
|
1535
|
+
enqueue(conn, envelope) {
|
|
1536
|
+
const socket = this.socket;
|
|
1537
|
+
const previous = this.queues.get(conn);
|
|
1538
|
+
const run = (async () => {
|
|
1539
|
+
await previous;
|
|
1540
|
+
if (this.socket === socket) {
|
|
1541
|
+
try {
|
|
1542
|
+
await this.request(conn, envelope);
|
|
1543
|
+
} catch (error) {
|
|
1544
|
+
this.options.log.line(
|
|
1545
|
+
`a relayed request failed: ${error instanceof Error ? error.message : String(error)}`
|
|
1546
|
+
);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
})();
|
|
1550
|
+
this.queues.set(conn, run);
|
|
1551
|
+
void (async () => {
|
|
1552
|
+
await run;
|
|
1553
|
+
if (this.queues.get(conn) === run) this.queues.delete(conn);
|
|
1554
|
+
})();
|
|
1555
|
+
return run;
|
|
1556
|
+
}
|
|
1475
1557
|
viewers(count) {
|
|
1476
1558
|
clearTimeout(this.idleTimer);
|
|
1477
1559
|
this.idleTimer = void 0;
|
|
@@ -1590,6 +1672,7 @@ class Relay {
|
|
|
1590
1672
|
for (const message of queued) event(message);
|
|
1591
1673
|
}
|
|
1592
1674
|
}
|
|
1675
|
+
const GITHUB_HOST = "github.com";
|
|
1593
1676
|
const REPO_SCAN_MS = 6e4;
|
|
1594
1677
|
const GITHUB_REMOTE = [
|
|
1595
1678
|
/^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
|
|
@@ -1623,8 +1706,9 @@ function directories(parent) {
|
|
|
1623
1706
|
}
|
|
1624
1707
|
}
|
|
1625
1708
|
async function scanRepos(reposDirectory) {
|
|
1626
|
-
const
|
|
1627
|
-
|
|
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")))
|
|
1628
1712
|
);
|
|
1629
1713
|
const found = await Promise.all(
|
|
1630
1714
|
candidates.map(async (directory) => {
|
|
@@ -1691,11 +1775,54 @@ const SETUP_PROGRAMS = {
|
|
|
1691
1775
|
shell: void 0,
|
|
1692
1776
|
claude: "claude",
|
|
1693
1777
|
codex: "codex",
|
|
1694
|
-
cursor: "cursor-agent"
|
|
1778
|
+
cursor: "cursor-agent",
|
|
1779
|
+
"repo-add": "aibexd"
|
|
1695
1780
|
};
|
|
1696
1781
|
function bracketedPaste(text) {
|
|
1697
1782
|
return `\x1B[200~${text}\x1B[201~`;
|
|
1698
1783
|
}
|
|
1784
|
+
function transitionSession(phase, change) {
|
|
1785
|
+
switch (change.type) {
|
|
1786
|
+
case "launched": {
|
|
1787
|
+
return phase === "preparing" ? "launching" : void 0;
|
|
1788
|
+
}
|
|
1789
|
+
case "prompted": {
|
|
1790
|
+
return phase === "launching" ? "running" : void 0;
|
|
1791
|
+
}
|
|
1792
|
+
case "host-lost": {
|
|
1793
|
+
return phase === "launching" || phase === "running" ? "detached" : void 0;
|
|
1794
|
+
}
|
|
1795
|
+
case "reattached": {
|
|
1796
|
+
if (phase !== "detached") return void 0;
|
|
1797
|
+
return change.prompted ? "running" : "launching";
|
|
1798
|
+
}
|
|
1799
|
+
case "ended": {
|
|
1800
|
+
return phase === "ended" || phase === "fenced" ? void 0 : "ended";
|
|
1801
|
+
}
|
|
1802
|
+
case "fenced": {
|
|
1803
|
+
return phase === "fenced" ? void 0 : "fenced";
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
function reportedState(phase, hints) {
|
|
1808
|
+
switch (phase) {
|
|
1809
|
+
case "preparing": {
|
|
1810
|
+
return { state: "starting" };
|
|
1811
|
+
}
|
|
1812
|
+
case "launching": {
|
|
1813
|
+
return hints.notReady ? { state: "waiting", waiting_on: "login" } : { state: "starting" };
|
|
1814
|
+
}
|
|
1815
|
+
case "running": {
|
|
1816
|
+
return { state: hints.activity };
|
|
1817
|
+
}
|
|
1818
|
+
case "detached": {
|
|
1819
|
+
return { state: "waiting", waiting_on: "host" };
|
|
1820
|
+
}
|
|
1821
|
+
case "ended": {
|
|
1822
|
+
return { state: "ended" };
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1699
1826
|
const MAX_CHUNK_BYTES = 1024 * 1024;
|
|
1700
1827
|
class Transcript {
|
|
1701
1828
|
constructor(spoolFile, state) {
|
|
@@ -1873,7 +2000,9 @@ const DEFAULT_SESSION_TIMINGS = {
|
|
|
1873
2000
|
statusIntervalMs: 5e3,
|
|
1874
2001
|
uploadIntervalMs: 5e3,
|
|
1875
2002
|
uploadThresholdBytes: 256 * 1024,
|
|
1876
|
-
settleMs: 150
|
|
2003
|
+
settleMs: 150,
|
|
2004
|
+
reattachMs: 5e3,
|
|
2005
|
+
reattachMaxMs: 6e4
|
|
1877
2006
|
};
|
|
1878
2007
|
const STATUS_MAX = 200;
|
|
1879
2008
|
function newEventId() {
|
|
@@ -1889,24 +2018,38 @@ class Session {
|
|
|
1889
2018
|
const now = manager.now();
|
|
1890
2019
|
this.lastProgressAt = now;
|
|
1891
2020
|
this.quietSince = now;
|
|
1892
|
-
this.readySince = now;
|
|
1893
2021
|
this.transcript = new Transcript(
|
|
1894
2022
|
manager.spoolFile(record.thread_id),
|
|
1895
2023
|
record.transcript
|
|
1896
2024
|
);
|
|
1897
|
-
if (record.ended) this.
|
|
1898
|
-
else if (record.
|
|
2025
|
+
if (record.ended) this.phase = "ended";
|
|
2026
|
+
else if (record.terminal === void 0) this.phase = "preparing";
|
|
2027
|
+
else if (record.prompted) {
|
|
2028
|
+
this.phase = "running";
|
|
2029
|
+
this.activity = "idle";
|
|
2030
|
+
} else {
|
|
2031
|
+
this.phase = "launching";
|
|
2032
|
+
this.readySince = now;
|
|
2033
|
+
}
|
|
1899
2034
|
}
|
|
1900
2035
|
client;
|
|
1901
|
-
|
|
1902
|
-
|
|
2036
|
+
phase;
|
|
2037
|
+
/** The host's last output hint, once the prompt is in. */
|
|
2038
|
+
activity = "working";
|
|
2039
|
+
/** The harness showed no ready marker within the timeout. */
|
|
2040
|
+
notReady = false;
|
|
1903
2041
|
lastProgressAt;
|
|
1904
2042
|
busy = false;
|
|
1905
2043
|
lastScreenSeq = -1;
|
|
1906
2044
|
quietSince;
|
|
1907
2045
|
lastSendAt = 0;
|
|
1908
2046
|
sending = false;
|
|
2047
|
+
/** When the session entered `launching`: the ready clock starts there. */
|
|
1909
2048
|
readySince;
|
|
2049
|
+
/** A stop that came while detached, carried out on reattach. */
|
|
2050
|
+
stopPending;
|
|
2051
|
+
reattachDelayMs = 0;
|
|
2052
|
+
reattachTimer;
|
|
1910
2053
|
timer;
|
|
1911
2054
|
uploadTimer;
|
|
1912
2055
|
uploading;
|
|
@@ -1914,10 +2057,20 @@ class Session {
|
|
|
1914
2057
|
statusSent;
|
|
1915
2058
|
statusPending;
|
|
1916
2059
|
statusTimer;
|
|
1917
|
-
/** Set when the server fenced the lease: nothing more is sent. */
|
|
1918
|
-
fenced = false;
|
|
1919
2060
|
disposed = false;
|
|
1920
2061
|
transcript;
|
|
2062
|
+
/** Set when the server fenced the lease: nothing more is sent. */
|
|
2063
|
+
get fenced() {
|
|
2064
|
+
return this.phase === "fenced";
|
|
2065
|
+
}
|
|
2066
|
+
/** Moves through `transitionSession`; answers whether the phase changed. */
|
|
2067
|
+
move(change) {
|
|
2068
|
+
const next = transitionSession(this.phase, change);
|
|
2069
|
+
if (next === void 0) return false;
|
|
2070
|
+
this.phase = next;
|
|
2071
|
+
if (next === "launching") this.readySince ??= this.manager.now();
|
|
2072
|
+
return true;
|
|
2073
|
+
}
|
|
1921
2074
|
get harness() {
|
|
1922
2075
|
return this.manager.harnesses[this.record.harness];
|
|
1923
2076
|
}
|
|
@@ -1927,23 +2080,26 @@ class Session {
|
|
|
1927
2080
|
save() {
|
|
1928
2081
|
this.manager.save(this);
|
|
1929
2082
|
}
|
|
1930
|
-
/**
|
|
2083
|
+
/**
|
|
2084
|
+
* Attaches for the transcript and watches for state, then starts checking.
|
|
2085
|
+
* Losing the connection, now or later, detaches the session rather than
|
|
2086
|
+
* ending it: the terminal may still run.
|
|
2087
|
+
*/
|
|
1931
2088
|
async drive(client) {
|
|
1932
2089
|
this.client = client;
|
|
1933
2090
|
const terminal = this.record.terminal;
|
|
1934
2091
|
client.onClose(() => {
|
|
1935
|
-
if (
|
|
1936
|
-
this.
|
|
1937
|
-
`lost the terminal host for ${this.record.thread_id}; it is picked up again when the link restarts`
|
|
1938
|
-
);
|
|
1939
|
-
}
|
|
2092
|
+
if (this.client === client)
|
|
2093
|
+
this.detach("the terminal host connection closed");
|
|
1940
2094
|
});
|
|
1941
2095
|
const watched = await client.subscribe(
|
|
1942
2096
|
{ type: "watch", terminal },
|
|
1943
2097
|
(event) => this.onWatch(event)
|
|
1944
2098
|
);
|
|
1945
2099
|
if (!watched.ok) {
|
|
1946
|
-
|
|
2100
|
+
if (watched.error?.code === "closed") {
|
|
2101
|
+
this.detach("the terminal host connection closed");
|
|
2102
|
+
} else this.end("the terminal is gone");
|
|
1947
2103
|
return;
|
|
1948
2104
|
}
|
|
1949
2105
|
const since = this.transcript.seq();
|
|
@@ -1969,11 +2125,76 @@ class Session {
|
|
|
1969
2125
|
this.end("exited");
|
|
1970
2126
|
return;
|
|
1971
2127
|
}
|
|
2128
|
+
if (this.client !== client || this.phase === "detached") return;
|
|
2129
|
+
this.reattachDelayMs = 0;
|
|
2130
|
+
this.stopTimers();
|
|
1972
2131
|
this.timer = setInterval(() => void this.check(), this.timings.checkMs);
|
|
1973
2132
|
this.uploadTimer = setInterval(
|
|
1974
2133
|
() => void this.upload(),
|
|
1975
2134
|
this.timings.uploadIntervalMs
|
|
1976
2135
|
);
|
|
2136
|
+
const pending = this.stopPending;
|
|
2137
|
+
if (pending !== void 0) {
|
|
2138
|
+
this.stopPending = void 0;
|
|
2139
|
+
await this.manager.stopSession(this, pending);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* The host connection is gone, or a subscription was dropped: the session
|
|
2144
|
+
* is `detached`, listed as waiting on the host, and looks for its terminal
|
|
2145
|
+
* again with backoff.
|
|
2146
|
+
*/
|
|
2147
|
+
detach(reason) {
|
|
2148
|
+
if (this.disposed || !this.move({ type: "host-lost" })) return;
|
|
2149
|
+
this.manager.log.line(
|
|
2150
|
+
`${this.record.thread_id}: detached from its terminal (${reason}); finding it again`
|
|
2151
|
+
);
|
|
2152
|
+
clearInterval(this.timer);
|
|
2153
|
+
const client = this.client;
|
|
2154
|
+
this.client = void 0;
|
|
2155
|
+
client?.close();
|
|
2156
|
+
this.scheduleReattach();
|
|
2157
|
+
}
|
|
2158
|
+
scheduleReattach() {
|
|
2159
|
+
if (this.disposed || this.phase !== "detached") return;
|
|
2160
|
+
this.reattachDelayMs = this.reattachDelayMs === 0 ? this.timings.reattachMs : Math.min(this.reattachDelayMs * 2, this.timings.reattachMaxMs);
|
|
2161
|
+
clearTimeout(this.reattachTimer);
|
|
2162
|
+
this.reattachTimer = setTimeout(
|
|
2163
|
+
() => void this.reattach(),
|
|
2164
|
+
this.reattachDelayMs
|
|
2165
|
+
);
|
|
2166
|
+
}
|
|
2167
|
+
/** Finds the terminal on any host and drives it again, or ends the session when it is gone. */
|
|
2168
|
+
async reattach() {
|
|
2169
|
+
if (this.disposed || this.phase !== "detached") return;
|
|
2170
|
+
const found = await this.manager.locate(this.record);
|
|
2171
|
+
if (this.disposed || this.phase !== "detached") return;
|
|
2172
|
+
if (found.kind === "unreachable") {
|
|
2173
|
+
this.scheduleReattach();
|
|
2174
|
+
return;
|
|
2175
|
+
}
|
|
2176
|
+
if (found.kind !== "running") {
|
|
2177
|
+
this.end(found.kind === "exited" ? "exited" : "its terminal is gone");
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
let client;
|
|
2181
|
+
try {
|
|
2182
|
+
client = await HostClient.connect(found.socket);
|
|
2183
|
+
} catch {
|
|
2184
|
+
this.scheduleReattach();
|
|
2185
|
+
return;
|
|
2186
|
+
}
|
|
2187
|
+
if (this.disposed || this.phase !== "detached") {
|
|
2188
|
+
client.close();
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
this.record.socket = found.socket;
|
|
2192
|
+
this.move({ type: "reattached", prompted: this.record.prompted });
|
|
2193
|
+
this.save();
|
|
2194
|
+
this.manager.log.line(
|
|
2195
|
+
`${this.record.thread_id}: found ${this.record.terminal} again on ${path.basename(found.socket)}`
|
|
2196
|
+
);
|
|
2197
|
+
await this.drive(client);
|
|
1977
2198
|
}
|
|
1978
2199
|
onOutput(event) {
|
|
1979
2200
|
if (event.event === "output" && !this.fenced) {
|
|
@@ -1983,6 +2204,8 @@ class Session {
|
|
|
1983
2204
|
}
|
|
1984
2205
|
} else if (event.event === "exit") {
|
|
1985
2206
|
this.end("exited");
|
|
2207
|
+
} else if (event.event === "dropped") {
|
|
2208
|
+
this.detach("the terminal host dropped the output subscription");
|
|
1986
2209
|
}
|
|
1987
2210
|
}
|
|
1988
2211
|
onWatch(event) {
|
|
@@ -1995,12 +2218,12 @@ class Session {
|
|
|
1995
2218
|
}
|
|
1996
2219
|
case "active": {
|
|
1997
2220
|
this.busy = true;
|
|
1998
|
-
|
|
2221
|
+
this.activity = "working";
|
|
1999
2222
|
break;
|
|
2000
2223
|
}
|
|
2001
2224
|
case "idle": {
|
|
2002
2225
|
this.busy = false;
|
|
2003
|
-
|
|
2226
|
+
this.activity = "idle";
|
|
2004
2227
|
break;
|
|
2005
2228
|
}
|
|
2006
2229
|
case "title": {
|
|
@@ -2012,6 +2235,10 @@ class Session {
|
|
|
2012
2235
|
this.end("exited");
|
|
2013
2236
|
break;
|
|
2014
2237
|
}
|
|
2238
|
+
case "dropped": {
|
|
2239
|
+
this.detach("the terminal host dropped the watch subscription");
|
|
2240
|
+
break;
|
|
2241
|
+
}
|
|
2015
2242
|
}
|
|
2016
2243
|
}
|
|
2017
2244
|
/** Whether output has been quiet long enough to type. */
|
|
@@ -2025,7 +2252,7 @@ class Session {
|
|
|
2025
2252
|
}
|
|
2026
2253
|
/** Types the prompt once the harness is ready, then one follow-up per idle. */
|
|
2027
2254
|
async check() {
|
|
2028
|
-
if (this.sending || this.
|
|
2255
|
+
if (this.sending || this.phase !== "launching" && this.phase !== "running" || !this.client) {
|
|
2029
2256
|
return;
|
|
2030
2257
|
}
|
|
2031
2258
|
const next = this.record.queue[0];
|
|
@@ -2043,9 +2270,8 @@ class Session {
|
|
|
2043
2270
|
const quiet = this.quiet(screen.seq);
|
|
2044
2271
|
const ready = this.record.prompted || this.harness.ready.test(String(screen.text));
|
|
2045
2272
|
if (!quiet || !ready) {
|
|
2046
|
-
if (!this.
|
|
2047
|
-
this.
|
|
2048
|
-
this.waitingOn = "login";
|
|
2273
|
+
if (this.phase === "launching" && !this.notReady && this.readySince !== void 0 && this.manager.now() - this.readySince >= this.timings.readyTimeoutMs) {
|
|
2274
|
+
this.notReady = true;
|
|
2049
2275
|
this.setStatus("harness not ready");
|
|
2050
2276
|
this.manager.log.line(
|
|
2051
2277
|
`${this.record.thread_id}: ${this.record.harness} showed no ready marker in ${Math.round(this.timings.readyTimeoutMs / 1e3)}s; nothing typed`
|
|
@@ -2058,6 +2284,15 @@ class Session {
|
|
|
2058
2284
|
this.sending = false;
|
|
2059
2285
|
}
|
|
2060
2286
|
}
|
|
2287
|
+
/** Whether the session may still be typed into by this client. */
|
|
2288
|
+
live(client) {
|
|
2289
|
+
return this.client === client && (this.phase === "launching" || this.phase === "running");
|
|
2290
|
+
}
|
|
2291
|
+
/**
|
|
2292
|
+
* Types one queued text and presses Enter. The phase is read again after
|
|
2293
|
+
* every await, so a session that ended, detached or was fenced meanwhile
|
|
2294
|
+
* is never marked as working.
|
|
2295
|
+
*/
|
|
2061
2296
|
async send(text) {
|
|
2062
2297
|
const client = this.client;
|
|
2063
2298
|
if (!client) return;
|
|
@@ -2068,15 +2303,22 @@ class Session {
|
|
|
2068
2303
|
terminal,
|
|
2069
2304
|
data: bracketedPaste(text)
|
|
2070
2305
|
}) : await client.request({ type: "type", terminal, text });
|
|
2071
|
-
if (!sent.ok) return;
|
|
2306
|
+
if (!sent.ok || !this.live(client)) return;
|
|
2072
2307
|
await new Promise((resolve) => setTimeout(resolve, this.timings.settleMs));
|
|
2073
|
-
|
|
2308
|
+
if (!this.live(client)) return;
|
|
2309
|
+
const pressed = await client.request({
|
|
2310
|
+
type: "press",
|
|
2311
|
+
terminal,
|
|
2312
|
+
keys: ["Enter"]
|
|
2313
|
+
});
|
|
2314
|
+
if (!pressed.ok || !this.live(client)) return;
|
|
2074
2315
|
this.record.queue.shift();
|
|
2075
2316
|
const first = !this.record.prompted;
|
|
2076
2317
|
this.record.prompted = true;
|
|
2077
2318
|
this.lastSendAt = this.manager.now();
|
|
2078
|
-
this.
|
|
2079
|
-
this.
|
|
2319
|
+
this.move({ type: "prompted" });
|
|
2320
|
+
this.activity = "working";
|
|
2321
|
+
this.notReady = false;
|
|
2080
2322
|
this.save();
|
|
2081
2323
|
this.manager.log.line(
|
|
2082
2324
|
`${this.record.thread_id}: ${first ? "typed the prompt" : "typed a follow-up"} into ${this.record.harness}`
|
|
@@ -2113,19 +2355,32 @@ class Session {
|
|
|
2113
2355
|
}
|
|
2114
2356
|
/** The program exited, or the session never started: report it once. */
|
|
2115
2357
|
end(reason) {
|
|
2116
|
-
if (this.record.ended || this.
|
|
2358
|
+
if (this.record.ended || !this.move({ type: "ended" })) return;
|
|
2117
2359
|
this.record.ended = reason;
|
|
2118
|
-
this.state = "ended";
|
|
2119
2360
|
this.stopTimers();
|
|
2361
|
+
clearTimeout(this.reattachTimer);
|
|
2120
2362
|
this.manager.event(this, { type: "session.ended", without_done: true });
|
|
2121
2363
|
this.manager.log.line(
|
|
2122
2364
|
`${this.record.thread_id}: session ended (${reason})`
|
|
2123
2365
|
);
|
|
2124
2366
|
void this.upload();
|
|
2125
2367
|
}
|
|
2368
|
+
/** Kills the terminal; the reply says whether the host confirmed it. */
|
|
2126
2369
|
async kill() {
|
|
2127
|
-
if (!this.client || this.record.terminal === void 0)
|
|
2128
|
-
|
|
2370
|
+
if (!this.client || this.record.terminal === void 0) {
|
|
2371
|
+
return {
|
|
2372
|
+
ok: false,
|
|
2373
|
+
error: { code: "closed", message: "no terminal host connection" }
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
return this.client.request({
|
|
2377
|
+
type: "kill",
|
|
2378
|
+
terminal: this.record.terminal
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
/** Remembers a stop that came while detached, for the reattach. */
|
|
2382
|
+
stopLater(why) {
|
|
2383
|
+
this.stopPending = why;
|
|
2129
2384
|
}
|
|
2130
2385
|
/** Sends the spool from the server's offset. */
|
|
2131
2386
|
upload() {
|
|
@@ -2183,21 +2438,27 @@ class Session {
|
|
|
2183
2438
|
this.disposed = true;
|
|
2184
2439
|
this.stopTimers();
|
|
2185
2440
|
clearTimeout(this.statusTimer);
|
|
2441
|
+
clearTimeout(this.reattachTimer);
|
|
2186
2442
|
this.client?.close();
|
|
2187
2443
|
}
|
|
2188
2444
|
heartbeat() {
|
|
2189
2445
|
const { record } = this;
|
|
2446
|
+
const phase = this.phase === "fenced" ? "ended" : this.phase;
|
|
2447
|
+
const reported = reportedState(phase, {
|
|
2448
|
+
activity: this.activity,
|
|
2449
|
+
notReady: this.notReady
|
|
2450
|
+
});
|
|
2190
2451
|
const session = {
|
|
2191
2452
|
thread_id: record.thread_id,
|
|
2192
2453
|
lease_id: record.lease_id,
|
|
2193
2454
|
epoch: record.epoch,
|
|
2194
2455
|
harness: record.harness,
|
|
2195
|
-
state:
|
|
2456
|
+
state: reported.state,
|
|
2196
2457
|
last_progress_at: new Date(this.lastProgressAt).toISOString(),
|
|
2197
2458
|
transcript_offset: record.transcript.base + record.transcript.uploaded,
|
|
2198
2459
|
started_at: record.started_at
|
|
2199
2460
|
};
|
|
2200
|
-
if (
|
|
2461
|
+
if (reported.waiting_on) session.waiting_on = reported.waiting_on;
|
|
2201
2462
|
if (record.repo) session.repo = record.repo;
|
|
2202
2463
|
if (record.worktree) session.worktree = record.worktree;
|
|
2203
2464
|
return session;
|
|
@@ -2237,28 +2498,44 @@ class Sessions {
|
|
|
2237
2498
|
list() {
|
|
2238
2499
|
return [...this.sessions.values()].filter((session) => !session.fenced).map((session) => session.heartbeat());
|
|
2239
2500
|
}
|
|
2240
|
-
/**
|
|
2501
|
+
/**
|
|
2502
|
+
* Picks up every recorded session from whichever terminal host runs it.
|
|
2503
|
+
* A record that never got its terminal ends: the link restarted while it
|
|
2504
|
+
* was being prepared, and its `work.assign` will not come again.
|
|
2505
|
+
*/
|
|
2241
2506
|
async resume() {
|
|
2242
2507
|
mkdirSync(this.directory, { recursive: true, mode: 448 });
|
|
2243
2508
|
const files = readdirSync(this.directory).filter(
|
|
2244
2509
|
(name) => name.endsWith(".json")
|
|
2245
2510
|
);
|
|
2246
|
-
const terminals = await listTerminals(
|
|
2247
|
-
hostSockets(this.options.terminalsDirectory, this.options.terminalSocket)
|
|
2248
|
-
);
|
|
2249
2511
|
for (const file of files) {
|
|
2250
2512
|
const record = readJson(path.join(this.directory, file));
|
|
2251
2513
|
if (!record?.thread_id || this.sessions.has(record.thread_id)) continue;
|
|
2252
2514
|
const session = new Session(record, this);
|
|
2253
2515
|
this.sessions.set(record.thread_id, session);
|
|
2254
|
-
|
|
2255
|
-
(
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2516
|
+
if (session.phase === "ended") {
|
|
2517
|
+
this.settle(session);
|
|
2518
|
+
continue;
|
|
2519
|
+
}
|
|
2520
|
+
if (session.phase === "preparing") {
|
|
2521
|
+
const why = "the link restarted before the session started";
|
|
2522
|
+
this.event(session, { type: "status", text: why });
|
|
2523
|
+
session.end(why);
|
|
2259
2524
|
this.settle(session);
|
|
2260
2525
|
continue;
|
|
2261
2526
|
}
|
|
2527
|
+
const found = await this.locate(record);
|
|
2528
|
+
if (found.kind === "exited" || found.kind === "gone") {
|
|
2529
|
+
session.end(
|
|
2530
|
+
found.kind === "exited" ? "exited" : "its terminal is gone"
|
|
2531
|
+
);
|
|
2532
|
+
this.settle(session);
|
|
2533
|
+
continue;
|
|
2534
|
+
}
|
|
2535
|
+
if (found.kind === "unreachable") {
|
|
2536
|
+
session.detach("its terminal host cannot be reached");
|
|
2537
|
+
continue;
|
|
2538
|
+
}
|
|
2262
2539
|
record.socket = found.socket;
|
|
2263
2540
|
try {
|
|
2264
2541
|
await session.drive(await HostClient.connect(found.socket));
|
|
@@ -2266,10 +2543,36 @@ class Sessions {
|
|
|
2266
2543
|
`${record.thread_id}: picked up ${record.terminal} on ${path.basename(found.socket)}`
|
|
2267
2544
|
);
|
|
2268
2545
|
} catch (error) {
|
|
2269
|
-
session.
|
|
2546
|
+
session.detach(
|
|
2547
|
+
`its terminal host cannot be reached: ${errorText(error)}`
|
|
2548
|
+
);
|
|
2270
2549
|
}
|
|
2271
2550
|
}
|
|
2272
2551
|
}
|
|
2552
|
+
/**
|
|
2553
|
+
* Where a recorded session's terminal is: running on some host, exited,
|
|
2554
|
+
* gone (the host that ran it answers without it, or nothing listens on
|
|
2555
|
+
* its socket any more), or unreachable for now.
|
|
2556
|
+
*/
|
|
2557
|
+
async locate(record) {
|
|
2558
|
+
const terminals = await listTerminals(
|
|
2559
|
+
hostSockets(this.options.terminalsDirectory, this.options.terminalSocket)
|
|
2560
|
+
);
|
|
2561
|
+
const found = terminals.find((terminal) => terminal.id === record.terminal);
|
|
2562
|
+
if (found) {
|
|
2563
|
+
return found.exited ? { kind: "exited" } : { kind: "running", socket: found.socket };
|
|
2564
|
+
}
|
|
2565
|
+
if (record.socket === void 0) return { kind: "gone" };
|
|
2566
|
+
try {
|
|
2567
|
+
const client = await HostClient.connect(record.socket);
|
|
2568
|
+
const listed = await client.request({ type: "list" });
|
|
2569
|
+
client.close();
|
|
2570
|
+
return listed.ok ? { kind: "gone" } : { kind: "unreachable" };
|
|
2571
|
+
} catch (error) {
|
|
2572
|
+
const code = error.code;
|
|
2573
|
+
return code === "ECONNREFUSED" || code === "ENOENT" ? { kind: "gone" } : { kind: "unreachable" };
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2273
2576
|
/** Handles a command the poller recorded; anything else is ignored. */
|
|
2274
2577
|
async handle(command) {
|
|
2275
2578
|
switch (command.type) {
|
|
@@ -2281,12 +2584,12 @@ class Sessions {
|
|
|
2281
2584
|
await this.message(command);
|
|
2282
2585
|
return true;
|
|
2283
2586
|
}
|
|
2284
|
-
case "thread.stop":
|
|
2587
|
+
case "thread.stop": {
|
|
2588
|
+
await this.stop(command.thread_id, command.type, command.lease_id);
|
|
2589
|
+
return true;
|
|
2590
|
+
}
|
|
2285
2591
|
case "control.drop_session": {
|
|
2286
|
-
await this.stop(
|
|
2287
|
-
command.thread_id,
|
|
2288
|
-
command.type
|
|
2289
|
-
);
|
|
2592
|
+
await this.stop(command.thread_id, command.type);
|
|
2290
2593
|
return true;
|
|
2291
2594
|
}
|
|
2292
2595
|
default: {
|
|
@@ -2294,18 +2597,22 @@ class Sessions {
|
|
|
2294
2597
|
}
|
|
2295
2598
|
}
|
|
2296
2599
|
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Starts a session for `work.assign`. Its record is saved before the first
|
|
2602
|
+
* await, so a link that restarts while it is being prepared ends it
|
|
2603
|
+
* visibly instead of forgetting it. A stop or fence while it is being
|
|
2604
|
+
* prepared ends the start after the step in flight.
|
|
2605
|
+
*/
|
|
2297
2606
|
async assign(command) {
|
|
2298
2607
|
const { lease } = command;
|
|
2299
2608
|
const existing = this.sessions.get(lease.thread_id);
|
|
2300
2609
|
if (existing && existing.record.lease_id === lease.lease_id) return;
|
|
2301
2610
|
if (existing) await this.fence(existing);
|
|
2302
|
-
const opened = await this.options.access.open(command.request);
|
|
2303
|
-
const harness = opened.ok ? opened.payload.needs?.harness : void 0;
|
|
2304
2611
|
const record = {
|
|
2305
2612
|
thread_id: lease.thread_id,
|
|
2306
2613
|
lease_id: lease.lease_id,
|
|
2307
2614
|
epoch: lease.epoch,
|
|
2308
|
-
harness:
|
|
2615
|
+
harness: "claude",
|
|
2309
2616
|
started_at: new Date(this.now()).toISOString(),
|
|
2310
2617
|
queue: [],
|
|
2311
2618
|
prompted: false,
|
|
@@ -2315,12 +2622,18 @@ class Sessions {
|
|
|
2315
2622
|
};
|
|
2316
2623
|
const session = new Session(record, this);
|
|
2317
2624
|
this.sessions.set(record.thread_id, session);
|
|
2625
|
+
this.save(session);
|
|
2626
|
+
const stale = () => session.phase !== "preparing" || session.disposed;
|
|
2318
2627
|
const refuse = (reason) => {
|
|
2319
2628
|
this.log.line(`work.assign for ${record.thread_id} refused: ${reason}`);
|
|
2320
2629
|
this.event(session, { type: "status", text: `refused: ${reason}` });
|
|
2321
2630
|
session.end(reason);
|
|
2322
2631
|
this.settle(session);
|
|
2323
2632
|
};
|
|
2633
|
+
const opened = await this.options.access.open(command.request);
|
|
2634
|
+
if (stale()) return;
|
|
2635
|
+
const harness = opened.ok ? opened.payload.needs?.harness : void 0;
|
|
2636
|
+
if (harness) record.harness = harness;
|
|
2324
2637
|
if (!opened.ok) {
|
|
2325
2638
|
refuse(`the request did not pass the accept check (${opened.reason})`);
|
|
2326
2639
|
return;
|
|
@@ -2333,7 +2646,9 @@ class Sessions {
|
|
|
2333
2646
|
}
|
|
2334
2647
|
record.repo = request.repo;
|
|
2335
2648
|
record.queue = [request.prompt];
|
|
2649
|
+
this.save(session);
|
|
2336
2650
|
const checkout = await this.options.repos.find(request.repo);
|
|
2651
|
+
if (stale()) return;
|
|
2337
2652
|
if (!checkout) {
|
|
2338
2653
|
refuse(
|
|
2339
2654
|
`no checkout of ${request.repo.owner}/${request.repo.name} under ${this.options.paths.repos}`
|
|
@@ -2347,6 +2662,7 @@ class Sessions {
|
|
|
2347
2662
|
baseRef: request.base_ref,
|
|
2348
2663
|
reposConfig: this.options.paths.reposConfig
|
|
2349
2664
|
});
|
|
2665
|
+
if (stale()) return;
|
|
2350
2666
|
if (!prepared.ok) {
|
|
2351
2667
|
refuse(`the worktree could not be made: ${prepared.reason}`);
|
|
2352
2668
|
return;
|
|
@@ -2358,7 +2674,13 @@ class Sessions {
|
|
|
2358
2674
|
if (socket === void 0) throw new Error("no terminal host is set");
|
|
2359
2675
|
client = await HostClient.connect(socket);
|
|
2360
2676
|
} catch (error) {
|
|
2361
|
-
|
|
2677
|
+
if (!stale()) {
|
|
2678
|
+
refuse(`the terminal host cannot be reached: ${errorText(error)}`);
|
|
2679
|
+
}
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
if (stale()) {
|
|
2683
|
+
client.close();
|
|
2362
2684
|
return;
|
|
2363
2685
|
}
|
|
2364
2686
|
const created = await client.request({
|
|
@@ -2370,11 +2692,19 @@ class Sessions {
|
|
|
2370
2692
|
});
|
|
2371
2693
|
if (!created.ok) {
|
|
2372
2694
|
client.close();
|
|
2373
|
-
|
|
2695
|
+
if (!stale()) {
|
|
2696
|
+
refuse(`${entry.command} could not start: ${created.error?.message}`);
|
|
2697
|
+
}
|
|
2698
|
+
return;
|
|
2699
|
+
}
|
|
2700
|
+
if (stale()) {
|
|
2701
|
+
await client.request({ type: "kill", terminal: created.terminal });
|
|
2702
|
+
client.close();
|
|
2374
2703
|
return;
|
|
2375
2704
|
}
|
|
2376
2705
|
record.socket = socket;
|
|
2377
2706
|
record.terminal = created.terminal;
|
|
2707
|
+
session.move({ type: "launched" });
|
|
2378
2708
|
this.save(session);
|
|
2379
2709
|
this.log.line(
|
|
2380
2710
|
`${record.thread_id}: started ${entry.command} in ${prepared.worktree.path} as ${record.terminal}`
|
|
@@ -2389,6 +2719,12 @@ class Sessions {
|
|
|
2389
2719
|
);
|
|
2390
2720
|
return;
|
|
2391
2721
|
}
|
|
2722
|
+
if (command.lease_id !== void 0 && command.lease_id !== session.record.lease_id) {
|
|
2723
|
+
this.log.line(
|
|
2724
|
+
`thread.message for lease ${command.lease_id} of ${command.thread_id}, but this session holds ${session.record.lease_id}; acked`
|
|
2725
|
+
);
|
|
2726
|
+
return;
|
|
2727
|
+
}
|
|
2392
2728
|
const opened = await this.options.access.open(command.message);
|
|
2393
2729
|
if (!opened.ok || typeof opened.payload.text !== "string") {
|
|
2394
2730
|
const reason = opened.ok ? "malformed" : opened.reason;
|
|
@@ -2406,7 +2742,7 @@ class Sessions {
|
|
|
2406
2742
|
session.record.messages.push(messageId);
|
|
2407
2743
|
session.queueText(text);
|
|
2408
2744
|
}
|
|
2409
|
-
async stop(threadId, why) {
|
|
2745
|
+
async stop(threadId, why, leaseId) {
|
|
2410
2746
|
const session = this.sessions.get(threadId);
|
|
2411
2747
|
if (!session || session.record.ended) {
|
|
2412
2748
|
this.log.line(
|
|
@@ -2414,9 +2750,41 @@ class Sessions {
|
|
|
2414
2750
|
);
|
|
2415
2751
|
return;
|
|
2416
2752
|
}
|
|
2753
|
+
if (leaseId !== void 0 && leaseId !== session.record.lease_id) {
|
|
2754
|
+
this.log.line(
|
|
2755
|
+
`${why} for lease ${leaseId} of ${threadId}, but this session holds ${session.record.lease_id}; acked`
|
|
2756
|
+
);
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2417
2759
|
this.log.line(`${threadId}: ${why}; ending the session`);
|
|
2418
|
-
await
|
|
2419
|
-
|
|
2760
|
+
await this.stopSession(session, why);
|
|
2761
|
+
}
|
|
2762
|
+
/**
|
|
2763
|
+
* Kills a session's terminal and ends it once the host confirms the kill,
|
|
2764
|
+
* or says the terminal is gone. A session being prepared ends at once; a
|
|
2765
|
+
* detached one, or one whose kill met a closed connection, is killed when
|
|
2766
|
+
* it reattaches.
|
|
2767
|
+
*/
|
|
2768
|
+
async stopSession(session, why) {
|
|
2769
|
+
if (session.phase === "preparing") {
|
|
2770
|
+
session.end(why);
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
if (session.phase === "detached") {
|
|
2774
|
+
session.stopLater(why);
|
|
2775
|
+
return;
|
|
2776
|
+
}
|
|
2777
|
+
const reply = await session.kill();
|
|
2778
|
+
if (reply.ok || reply.error?.code === "exited") {
|
|
2779
|
+
session.end(why);
|
|
2780
|
+
} else if (reply.error?.code === "closed") {
|
|
2781
|
+
session.stopLater(why);
|
|
2782
|
+
session.detach("the terminal host connection closed during a kill");
|
|
2783
|
+
} else {
|
|
2784
|
+
session.end(
|
|
2785
|
+
reply.error?.code === "unknown-terminal" ? "its terminal is gone" : why
|
|
2786
|
+
);
|
|
2787
|
+
}
|
|
2420
2788
|
}
|
|
2421
2789
|
/** After each poll: fences, then everything still owed to the herd. */
|
|
2422
2790
|
async afterPoll(answer) {
|
|
@@ -2435,16 +2803,50 @@ class Sessions {
|
|
|
2435
2803
|
}
|
|
2436
2804
|
}
|
|
2437
2805
|
}
|
|
2438
|
-
/**
|
|
2806
|
+
/**
|
|
2807
|
+
* Kills the terminal and forgets the session, sending nothing more for it.
|
|
2808
|
+
* A session with no live host connection (detached, or one that closed
|
|
2809
|
+
* under the kill) has its terminal found on any host and killed there,
|
|
2810
|
+
* since nothing will look for it once the session is forgotten.
|
|
2811
|
+
*/
|
|
2439
2812
|
async fence(session) {
|
|
2440
|
-
|
|
2441
|
-
session.fenced
|
|
2813
|
+
const ended = session.record.ended !== void 0;
|
|
2814
|
+
if (!session.move({ type: "fenced" })) return;
|
|
2442
2815
|
this.log.line(
|
|
2443
2816
|
`${session.record.thread_id}: lease ${session.record.lease_id} is fenced; ending the session and sending nothing more`
|
|
2444
2817
|
);
|
|
2445
|
-
if (!
|
|
2818
|
+
if (!ended) {
|
|
2819
|
+
const reply = await session.kill();
|
|
2820
|
+
if (!reply.ok && reply.error?.code === "closed") {
|
|
2821
|
+
await this.killAnywhere(session.record);
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2446
2824
|
this.forget(session);
|
|
2447
2825
|
}
|
|
2826
|
+
/** Finds a recorded terminal on whichever host runs it and kills it there. */
|
|
2827
|
+
async killAnywhere(record) {
|
|
2828
|
+
if (record.terminal === void 0) return;
|
|
2829
|
+
const found = await this.locate(record);
|
|
2830
|
+
if (found.kind === "unreachable") {
|
|
2831
|
+
this.log.line(
|
|
2832
|
+
`${record.thread_id}: could not reach the terminal host to kill ${record.terminal}`
|
|
2833
|
+
);
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2836
|
+
if (found.kind !== "running") return;
|
|
2837
|
+
try {
|
|
2838
|
+
const client = await HostClient.connect(found.socket);
|
|
2839
|
+
try {
|
|
2840
|
+
await client.request({ type: "kill", terminal: record.terminal });
|
|
2841
|
+
} finally {
|
|
2842
|
+
client.close();
|
|
2843
|
+
}
|
|
2844
|
+
} catch (error) {
|
|
2845
|
+
this.log.line(
|
|
2846
|
+
`${record.thread_id}: could not kill ${record.terminal}: ${errorText(error)}`
|
|
2847
|
+
);
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2448
2850
|
forget(session) {
|
|
2449
2851
|
session.dispose();
|
|
2450
2852
|
if (this.sessions.get(session.record.thread_id) === session) {
|
|
@@ -2536,6 +2938,12 @@ const SETUP_LABEL = "setup:";
|
|
|
2536
2938
|
function isProgram(value) {
|
|
2537
2939
|
return typeof value === "string" && Object.hasOwn(SETUP_PROGRAMS, value);
|
|
2538
2940
|
}
|
|
2941
|
+
const REPO_PART = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
|
|
2942
|
+
function isAddRepo(value) {
|
|
2943
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2944
|
+
const { owner, name } = value;
|
|
2945
|
+
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;
|
|
2946
|
+
}
|
|
2539
2947
|
class SetupTerminals {
|
|
2540
2948
|
constructor(options) {
|
|
2541
2949
|
this.options = options;
|
|
@@ -2558,15 +2966,25 @@ class SetupTerminals {
|
|
|
2558
2966
|
log.line(`terminal.open refused: ${opened.reason}`);
|
|
2559
2967
|
return;
|
|
2560
2968
|
}
|
|
2561
|
-
const { open_id: openId, program, cwd } = opened.payload;
|
|
2969
|
+
const { open_id: openId, program, cwd, repo } = opened.payload;
|
|
2562
2970
|
if (!isProgram(program)) {
|
|
2563
2971
|
log.line(
|
|
2564
2972
|
`terminal.open ${String(openId)} refused: ${JSON.stringify(program)} is not a setup program`
|
|
2565
2973
|
);
|
|
2566
2974
|
return;
|
|
2567
2975
|
}
|
|
2976
|
+
if (program === "repo-add" ? !isAddRepo(repo) : repo !== void 0) {
|
|
2977
|
+
log.line(
|
|
2978
|
+
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`
|
|
2979
|
+
);
|
|
2980
|
+
return;
|
|
2981
|
+
}
|
|
2982
|
+
if (cwd?.kind !== "home" && cwd?.kind !== "repo") {
|
|
2983
|
+
log.line(`terminal.open ${openId} refused: unknown working directory`);
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2568
2986
|
let directory = this.home;
|
|
2569
|
-
if (cwd
|
|
2987
|
+
if (cwd.kind === "repo" && program !== "repo-add") {
|
|
2570
2988
|
const checkout = await this.options.repos.find(cwd.repo);
|
|
2571
2989
|
if (!checkout) {
|
|
2572
2990
|
log.line(
|
|
@@ -2575,15 +2993,14 @@ class SetupTerminals {
|
|
|
2575
2993
|
return;
|
|
2576
2994
|
}
|
|
2577
2995
|
directory = checkout.path;
|
|
2578
|
-
} else if (cwd?.kind !== "home") {
|
|
2579
|
-
log.line(`terminal.open ${openId} refused: unknown working directory`);
|
|
2580
|
-
return;
|
|
2581
2996
|
}
|
|
2582
2997
|
const label = `${SETUP_LABEL}${openId}`;
|
|
2583
2998
|
const existing = await listTerminals(this.sockets());
|
|
2584
2999
|
if (existing.some((terminal) => terminal.label === label)) return;
|
|
2585
|
-
const
|
|
2586
|
-
const
|
|
3000
|
+
const searchPath = this.searchPath();
|
|
3001
|
+
const run = this.command(program, repo);
|
|
3002
|
+
const args = run.args;
|
|
3003
|
+
const file = resolveProgram(run.file, searchPath);
|
|
2587
3004
|
const socket = this.options.terminalSocket;
|
|
2588
3005
|
if (socket === void 0) {
|
|
2589
3006
|
log.line(`terminal.open ${openId}: no terminal host is set`);
|
|
@@ -2602,8 +3019,9 @@ class SetupTerminals {
|
|
|
2602
3019
|
const created = await client.request({
|
|
2603
3020
|
type: "create",
|
|
2604
3021
|
file,
|
|
2605
|
-
args
|
|
3022
|
+
args,
|
|
2606
3023
|
cwd: directory,
|
|
3024
|
+
env: { PATH: searchPath },
|
|
2607
3025
|
label
|
|
2608
3026
|
});
|
|
2609
3027
|
log.line(
|
|
@@ -2613,16 +3031,44 @@ class SetupTerminals {
|
|
|
2613
3031
|
client.close();
|
|
2614
3032
|
}
|
|
2615
3033
|
}
|
|
3034
|
+
/** The file and arguments a program runs; `repo` is checked already. */
|
|
3035
|
+
command(program, repo) {
|
|
3036
|
+
if (program === "repo-add" && repo) {
|
|
3037
|
+
return {
|
|
3038
|
+
file: path.join(this.options.binDirectory, "aibexd"),
|
|
3039
|
+
args: ["repo", "add", `${repo.owner}/${repo.name}`]
|
|
3040
|
+
};
|
|
3041
|
+
}
|
|
3042
|
+
if (program === "shell") {
|
|
3043
|
+
return {
|
|
3044
|
+
file: this.options.shell ?? process.env.SHELL ?? "/bin/sh",
|
|
3045
|
+
args: ["-l"]
|
|
3046
|
+
};
|
|
3047
|
+
}
|
|
3048
|
+
return { file: SETUP_PROGRAMS[program] ?? "/bin/sh", args: [] };
|
|
3049
|
+
}
|
|
3050
|
+
/** `<state>/bin` first, so `aibexd activate` resolves in a harness started here. */
|
|
3051
|
+
searchPath() {
|
|
3052
|
+
const rest = (this.options.path ?? process.env.PATH ?? "").split(path.delimiter).filter(
|
|
3053
|
+
(directory) => directory !== "" && directory !== this.options.binDirectory
|
|
3054
|
+
);
|
|
3055
|
+
return [this.options.binDirectory, ...rest].join(path.delimiter);
|
|
3056
|
+
}
|
|
2616
3057
|
/** Every setup terminal a host still keeps, running or exited. */
|
|
2617
3058
|
async list() {
|
|
2618
3059
|
const terminals = await listTerminals(this.sockets());
|
|
2619
3060
|
return terminals.filter((terminal) => terminal.label?.startsWith(SETUP_LABEL)).map((terminal) => {
|
|
3061
|
+
const program = this.program(terminal.file);
|
|
2620
3062
|
const entry = {
|
|
2621
3063
|
open_id: (terminal.label ?? "").slice(SETUP_LABEL.length),
|
|
2622
3064
|
terminal: terminal.id,
|
|
2623
|
-
program
|
|
2624
|
-
cwd: this.cwd(terminal.cwd)
|
|
3065
|
+
program,
|
|
3066
|
+
cwd: program === "repo-add" ? { kind: "home" } : this.cwd(terminal.cwd)
|
|
2625
3067
|
};
|
|
3068
|
+
if (program === "repo-add") {
|
|
3069
|
+
const [owner, name] = (terminal.args?.[2] ?? "").split("/");
|
|
3070
|
+
if (owner && name) entry.repo = { owner, name };
|
|
3071
|
+
}
|
|
2626
3072
|
if (terminal.exited) entry.exit = terminal.exited;
|
|
2627
3073
|
return entry;
|
|
2628
3074
|
});
|
|
@@ -2635,7 +3081,10 @@ class SetupTerminals {
|
|
|
2635
3081
|
return found?.[0] ?? "shell";
|
|
2636
3082
|
}
|
|
2637
3083
|
cwd(directory) {
|
|
2638
|
-
const relative = path.relative(
|
|
3084
|
+
const relative = path.relative(
|
|
3085
|
+
path.join(this.options.reposDirectory, GITHUB_HOST),
|
|
3086
|
+
directory
|
|
3087
|
+
);
|
|
2639
3088
|
const [owner, name, ...rest] = relative.split(path.sep);
|
|
2640
3089
|
if (!relative.startsWith("..") && !path.isAbsolute(relative) && owner && name && rest.length === 0) {
|
|
2641
3090
|
const repo = { owner, name };
|
|
@@ -2644,6 +3093,20 @@ class SetupTerminals {
|
|
|
2644
3093
|
return { kind: "home" };
|
|
2645
3094
|
}
|
|
2646
3095
|
}
|
|
3096
|
+
function resolveProgram(file, searchPath) {
|
|
3097
|
+
if (file.includes("/")) return file;
|
|
3098
|
+
for (const directory of searchPath.split(path.delimiter)) {
|
|
3099
|
+
if (directory === "") continue;
|
|
3100
|
+
const candidate = path.join(directory, file);
|
|
3101
|
+
try {
|
|
3102
|
+
if (!statSync(candidate).isFile()) continue;
|
|
3103
|
+
accessSync(candidate, constants.X_OK);
|
|
3104
|
+
return candidate;
|
|
3105
|
+
} catch {
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
return file;
|
|
3109
|
+
}
|
|
2647
3110
|
function send(message) {
|
|
2648
3111
|
return new Promise((resolve) => {
|
|
2649
3112
|
if (!process.send) {
|
|
@@ -2694,6 +3157,7 @@ function main() {
|
|
|
2694
3157
|
const paths = linkPaths(hostDirectory);
|
|
2695
3158
|
const access = new Access(paths.access);
|
|
2696
3159
|
const repos = new Repos(paths.repos);
|
|
3160
|
+
const activations = new Activations(hostDirectory);
|
|
2697
3161
|
const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
|
|
2698
3162
|
const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
|
|
2699
3163
|
let poller;
|
|
@@ -2717,6 +3181,7 @@ function main() {
|
|
|
2717
3181
|
access,
|
|
2718
3182
|
repos,
|
|
2719
3183
|
reposDirectory: paths.repos,
|
|
3184
|
+
binDirectory: path.join(paths.state, "bin"),
|
|
2720
3185
|
terminalSocket,
|
|
2721
3186
|
terminalsDirectory,
|
|
2722
3187
|
log
|
|
@@ -2752,9 +3217,10 @@ function main() {
|
|
|
2752
3217
|
paths,
|
|
2753
3218
|
repos,
|
|
2754
3219
|
access,
|
|
2755
|
-
features: ["sessions", "relay"],
|
|
3220
|
+
features: ["sessions", "relay", "setup"],
|
|
2756
3221
|
sessions: running.list(),
|
|
2757
|
-
setupTerminals: await setup.list()
|
|
3222
|
+
setupTerminals: await setup.list(),
|
|
3223
|
+
activations: activations.list()
|
|
2758
3224
|
}),
|
|
2759
3225
|
handleCommand: async (command) => {
|
|
2760
3226
|
if (command.type === "relay.open") {
|
|
@@ -2765,7 +3231,10 @@ function main() {
|
|
|
2765
3231
|
await setup.open(command);
|
|
2766
3232
|
return true;
|
|
2767
3233
|
},
|
|
2768
|
-
afterPoll: (answer) =>
|
|
3234
|
+
afterPoll: async (answer) => {
|
|
3235
|
+
activations.confirm(answer.activations_confirmed);
|
|
3236
|
+
await running.afterPoll(answer);
|
|
3237
|
+
},
|
|
2769
3238
|
forward: (commandId, request) => send({ type: "control", commandId, request }),
|
|
2770
3239
|
backoffInitialMs: timing(
|
|
2771
3240
|
"pollBackoffInitialMs",
|
|
@@ -2778,21 +3247,50 @@ function main() {
|
|
|
2778
3247
|
`aibex-link ${info.version} linked to ${host}, not joined: run \`aibexd join <key>\` to join this machine to a herd`
|
|
2779
3248
|
);
|
|
2780
3249
|
}
|
|
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
|
+
};
|
|
2781
3270
|
process.on("message", (message) => {
|
|
2782
|
-
|
|
2783
|
-
status
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
3271
|
+
switch (message.type) {
|
|
3272
|
+
case "status": {
|
|
3273
|
+
status = message;
|
|
3274
|
+
break;
|
|
3275
|
+
}
|
|
3276
|
+
case "activate": {
|
|
3277
|
+
void send(activate(message.code));
|
|
3278
|
+
break;
|
|
3279
|
+
}
|
|
3280
|
+
case "diagnostics": {
|
|
3281
|
+
const mismatch = access.mismatch;
|
|
3282
|
+
poller?.attachDiagnostics({
|
|
3283
|
+
...message.diagnostics,
|
|
3284
|
+
warnings: [
|
|
3285
|
+
...message.diagnostics.warnings,
|
|
3286
|
+
...mismatch === void 0 ? [] : [`access.json does not match the herd's trust: ${mismatch}`]
|
|
3287
|
+
],
|
|
3288
|
+
collected_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3289
|
+
command_id: message.commandId,
|
|
3290
|
+
log_tail: log.tail()
|
|
3291
|
+
});
|
|
3292
|
+
break;
|
|
3293
|
+
}
|
|
2796
3294
|
}
|
|
2797
3295
|
});
|
|
2798
3296
|
void send({ type: "ready" });
|