@fro.bot/space-bus 0.15.0 → 0.15.1
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/README.md +5 -2
- package/dist/attach.js +2 -2
- package/dist/cli.js +9 -9
- package/dist/config.js +14 -17
- package/dist/contract.js +30 -30
- package/dist/core.js +11 -11
- package/dist/format.js +6 -6
- package/dist/index.js +1052 -1055
- package/dist/mcp.js +1164 -1164
- package/dist/registry-entry.js +189 -190
- package/dist/server.js +18 -19
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// src/tools/bus_registry.ts
|
|
2
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
3
|
+
import { tool } from "@opencode-ai/plugin";
|
|
4
|
+
import { z as z4 } from "zod";
|
|
3
5
|
|
|
4
6
|
// src/config.ts
|
|
5
7
|
import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
|
|
@@ -717,7 +719,7 @@ function registerRoster(name, rosterPath) {
|
|
|
717
719
|
if (!readResult.ok)
|
|
718
720
|
return readResult;
|
|
719
721
|
const registry = readResult.registry;
|
|
720
|
-
const collision = registry.rosters.find((
|
|
722
|
+
const collision = registry.rosters.find((entry) => entry.name.toLowerCase() === name.toLowerCase());
|
|
721
723
|
if (collision) {
|
|
722
724
|
return {
|
|
723
725
|
ok: false,
|
|
@@ -964,683 +966,191 @@ function isManagedRoster(directory) {
|
|
|
964
966
|
return manifest.server.managed !== undefined;
|
|
965
967
|
}
|
|
966
968
|
|
|
967
|
-
// src/
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
import { existsSync as existsSync2, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
|
|
971
|
-
import { dirname } from "node:path";
|
|
972
|
-
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
973
|
-
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
974
|
-
var POLL_INTERVAL_MS = 50;
|
|
975
|
-
var MIN_PROBE_PHASE_MS = 3000;
|
|
976
|
-
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
977
|
-
var STOP_GRACE_MS = 2000;
|
|
978
|
-
var SUPERVISE_INTERVAL_MS = 5000;
|
|
979
|
-
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
980
|
-
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
981
|
-
function sleep(ms) {
|
|
982
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
969
|
+
// src/format.ts
|
|
970
|
+
function formatRosterHeader(source) {
|
|
971
|
+
return `roster: ${source.name ?? source.path}`;
|
|
983
972
|
}
|
|
984
|
-
function
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
973
|
+
function formatRoster(projects) {
|
|
974
|
+
return projects.map((p) => {
|
|
975
|
+
if (!p.pathExists)
|
|
976
|
+
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
977
|
+
if (p.statusError)
|
|
978
|
+
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
979
|
+
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
980
|
+
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
981
|
+
}).join(`
|
|
982
|
+
`);
|
|
988
983
|
}
|
|
989
|
-
function
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
984
|
+
function formatDispatch(r) {
|
|
985
|
+
switch (r.mode) {
|
|
986
|
+
case "new":
|
|
987
|
+
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
988
|
+
case "question-reply":
|
|
989
|
+
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
990
|
+
case "follow-up":
|
|
991
|
+
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
992
|
+
case "blocked":
|
|
993
|
+
return `Blocked: session ${r.sessionId} (${r.project}) has a pending question (${r.requestId}) — no reply or prompt sent.`;
|
|
995
994
|
}
|
|
996
995
|
}
|
|
997
|
-
function
|
|
998
|
-
|
|
996
|
+
function dispatchMetadata(r) {
|
|
997
|
+
const messageId = (r.mode === "new" || r.mode === "follow-up") && r.messageId !== undefined ? r.messageId : undefined;
|
|
998
|
+
return {
|
|
999
|
+
sessionId: r.sessionId,
|
|
1000
|
+
project: r.project,
|
|
1001
|
+
mode: r.mode,
|
|
1002
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1003
|
+
};
|
|
999
1004
|
}
|
|
1000
|
-
function
|
|
1001
|
-
|
|
1005
|
+
function formatStatus(r) {
|
|
1006
|
+
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
1007
|
+
`) : " (none)";
|
|
1008
|
+
const lines = [
|
|
1009
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1010
|
+
`title: ${r.title ?? "(untitled)"}`,
|
|
1011
|
+
`busy: ${r.busy}`
|
|
1012
|
+
];
|
|
1013
|
+
if (r.pendingQuestion) {
|
|
1014
|
+
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
1015
|
+
if (r.pendingQuestion.options.length > 0) {
|
|
1016
|
+
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
1017
|
+
}
|
|
1018
|
+
lines.push(` (answer with bus_task using sessionId)`);
|
|
1019
|
+
}
|
|
1020
|
+
lines.push(r.diffSource === "working-tree" ? `diff (working tree — repo-wide, may include changes from other sessions): ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}` : `diff: ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}`, `todos:`, todoLines);
|
|
1021
|
+
return lines.join(`
|
|
1022
|
+
`);
|
|
1002
1023
|
}
|
|
1003
|
-
function
|
|
1004
|
-
const
|
|
1005
|
-
|
|
1006
|
-
|
|
1024
|
+
function formatWait(r) {
|
|
1025
|
+
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
1026
|
+
const sessionLines = r.sessions.map((s) => {
|
|
1027
|
+
const parts = [
|
|
1028
|
+
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
1029
|
+
];
|
|
1030
|
+
if (s.pendingQuestion) {
|
|
1031
|
+
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
1032
|
+
if (s.pendingQuestion.options.length > 0) {
|
|
1033
|
+
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
1034
|
+
}
|
|
1035
|
+
parts.push(` (answer with bus_task using sessionId)`);
|
|
1036
|
+
}
|
|
1037
|
+
return parts.join(`
|
|
1038
|
+
`);
|
|
1039
|
+
});
|
|
1040
|
+
return [header, ...sessionLines].join(`
|
|
1041
|
+
`);
|
|
1007
1042
|
}
|
|
1008
|
-
function
|
|
1009
|
-
|
|
1043
|
+
function formatResult(r) {
|
|
1044
|
+
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
1045
|
+
`) : " (no changes)";
|
|
1046
|
+
return [
|
|
1047
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1048
|
+
`--- reply ---`,
|
|
1049
|
+
r.text || "(empty)",
|
|
1050
|
+
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
1051
|
+
diffLines
|
|
1052
|
+
].join(`
|
|
1053
|
+
`);
|
|
1010
1054
|
}
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1055
|
+
|
|
1056
|
+
// src/roster-edit.ts
|
|
1057
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
1058
|
+
import {
|
|
1059
|
+
chmodSync as chmodSync2,
|
|
1060
|
+
closeSync as closeSync3,
|
|
1061
|
+
constants as fsConstants3,
|
|
1062
|
+
lstatSync as lstatSync2,
|
|
1063
|
+
mkdirSync as mkdirSync3,
|
|
1064
|
+
openSync as openSync3,
|
|
1065
|
+
readFileSync as readFileSync4,
|
|
1066
|
+
renameSync as renameSync3,
|
|
1067
|
+
statSync as statSync3,
|
|
1068
|
+
unlinkSync as unlinkSync3,
|
|
1069
|
+
writeSync as writeSync2
|
|
1070
|
+
} from "node:fs";
|
|
1071
|
+
import { join as join4 } from "node:path";
|
|
1072
|
+
function closeQuietly3(fd) {
|
|
1073
|
+
try {
|
|
1074
|
+
closeSync3(fd);
|
|
1075
|
+
} catch {}
|
|
1076
|
+
}
|
|
1077
|
+
function isErrnoCode3(err, code) {
|
|
1078
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === code;
|
|
1079
|
+
}
|
|
1080
|
+
function duplicateProjectName(projects) {
|
|
1081
|
+
const seen = new Set;
|
|
1082
|
+
for (const p of projects) {
|
|
1083
|
+
if (seen.has(p.name))
|
|
1084
|
+
return p.name;
|
|
1085
|
+
seen.add(p.name);
|
|
1086
|
+
}
|
|
1087
|
+
return null;
|
|
1088
|
+
}
|
|
1089
|
+
function validateManifest(data) {
|
|
1090
|
+
const parsed = manifestSchema.safeParse(data);
|
|
1091
|
+
if (!parsed.success) {
|
|
1092
|
+
return {
|
|
1093
|
+
ok: false,
|
|
1094
|
+
error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
|
|
1095
|
+
};
|
|
1017
1096
|
}
|
|
1097
|
+
const baseUrl = parsed.data.server.baseUrl;
|
|
1098
|
+
if (baseUrl !== undefined && !loopbackOk(baseUrl)) {
|
|
1099
|
+
return {
|
|
1100
|
+
ok: false,
|
|
1101
|
+
error: `space-bus: roster's server.baseUrl must point to localhost (got ${baseUrl}) — refusing to send credentials off-machine`
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
const dup = duplicateProjectName(parsed.data.projects);
|
|
1105
|
+
if (dup !== null) {
|
|
1106
|
+
return {
|
|
1107
|
+
ok: false,
|
|
1108
|
+
error: `space-bus: roster document has duplicate project name "${dup}"`
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
return { ok: true, manifest: parsed.data };
|
|
1112
|
+
}
|
|
1113
|
+
function readManifest(rosterPath) {
|
|
1114
|
+
let raw;
|
|
1018
1115
|
try {
|
|
1019
|
-
|
|
1020
|
-
return true;
|
|
1116
|
+
raw = readFileSync4(rosterPath, "utf8");
|
|
1021
1117
|
} catch (err) {
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1118
|
+
return {
|
|
1119
|
+
ok: false,
|
|
1120
|
+
error: `space-bus: cannot read roster at ${rosterPath}: ${String(err)}`
|
|
1121
|
+
};
|
|
1025
1122
|
}
|
|
1123
|
+
let json;
|
|
1026
1124
|
try {
|
|
1027
|
-
|
|
1028
|
-
} catch {
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
return false;
|
|
1034
|
-
try {
|
|
1035
|
-
process.kill(-pid, sig);
|
|
1036
|
-
return true;
|
|
1037
|
-
} catch {
|
|
1038
|
-
return false;
|
|
1125
|
+
json = JSON.parse(raw);
|
|
1126
|
+
} catch (err) {
|
|
1127
|
+
return {
|
|
1128
|
+
ok: false,
|
|
1129
|
+
error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
|
|
1130
|
+
};
|
|
1039
1131
|
}
|
|
1132
|
+
return validateManifest(json);
|
|
1040
1133
|
}
|
|
1041
|
-
function
|
|
1134
|
+
function writeManifestAtomic(rosterPath, data) {
|
|
1135
|
+
const dir = join4(rosterPath, "..");
|
|
1042
1136
|
try {
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
} catch {}
|
|
1050
|
-
}
|
|
1051
|
-
function attachServer(rosterPath) {
|
|
1052
|
-
return attachLive(rosterPath);
|
|
1053
|
-
}
|
|
1054
|
-
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
1055
|
-
const deadline = Date.now() + budgetMs;
|
|
1056
|
-
const lockPath = lockFilePath(rosterPath);
|
|
1057
|
-
while (Date.now() < deadline) {
|
|
1058
|
-
const handle = attachServer(rosterPath);
|
|
1059
|
-
if (handle)
|
|
1060
|
-
return handle;
|
|
1061
|
-
const lockInfo2 = readLockFile(lockPath);
|
|
1062
|
-
const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
|
|
1063
|
-
if (!winnerAlive) {
|
|
1064
|
-
throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
|
|
1065
|
-
}
|
|
1066
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1137
|
+
mkdirSync3(dir, { recursive: true });
|
|
1138
|
+
} catch (err) {
|
|
1139
|
+
return {
|
|
1140
|
+
ok: false,
|
|
1141
|
+
error: `space-bus: failed to create directory ${dir}: ${String(err)}`
|
|
1142
|
+
};
|
|
1067
1143
|
}
|
|
1068
|
-
|
|
1069
|
-
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
1070
|
-
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
1071
|
-
}
|
|
1072
|
-
async function probe(baseUrl, password) {
|
|
1144
|
+
let existingMode;
|
|
1073
1145
|
try {
|
|
1074
|
-
|
|
1075
|
-
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
1076
|
-
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
1077
|
-
});
|
|
1078
|
-
if (res.status === 200)
|
|
1079
|
-
return "ready";
|
|
1080
|
-
if (res.status === 401 || res.status === 403)
|
|
1081
|
-
return "auth-failure";
|
|
1082
|
-
return "retry";
|
|
1146
|
+
existingMode = statSync3(rosterPath).mode & 511;
|
|
1083
1147
|
} catch {
|
|
1084
|
-
|
|
1148
|
+
existingMode = undefined;
|
|
1085
1149
|
}
|
|
1086
|
-
}
|
|
1087
|
-
function childDied(child, pid) {
|
|
1088
|
-
return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
|
|
1089
|
-
}
|
|
1090
|
-
async function waitForReadinessLine(logPath, child, pid, deadline) {
|
|
1091
|
-
const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
|
|
1092
|
-
while (Date.now() < deadline) {
|
|
1093
|
-
if (childDied(child, pid))
|
|
1094
|
-
return null;
|
|
1095
|
-
const tail = readLogTail(logPath);
|
|
1096
|
-
const match = readinessLine.exec(tail);
|
|
1097
|
-
if (match?.[1]) {
|
|
1098
|
-
const port = Number.parseInt(match[1], 10);
|
|
1099
|
-
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
1100
|
-
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1104
|
-
}
|
|
1105
|
-
return null;
|
|
1106
|
-
}
|
|
1107
|
-
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
1108
|
-
while (Date.now() < deadline) {
|
|
1109
|
-
if (childDied(child, pid))
|
|
1110
|
-
return "died";
|
|
1111
|
-
const outcome = await probe(baseUrl, password);
|
|
1112
|
-
if (outcome === "ready")
|
|
1113
|
-
return "ready";
|
|
1114
|
-
if (outcome === "auth-failure")
|
|
1115
|
-
return "auth-failure";
|
|
1116
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1117
|
-
}
|
|
1118
|
-
return "timeout";
|
|
1119
|
-
}
|
|
1120
|
-
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
1121
|
-
const deadline = Date.now() + budgetMs;
|
|
1122
|
-
const logPath = logFilePath(rosterPath);
|
|
1123
|
-
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
1124
|
-
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
1125
|
-
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
1126
|
-
if (lineResult === null) {
|
|
1127
|
-
const diedEarly = childDied(child, pid);
|
|
1128
|
-
killIdentifiedProcess(pid, identity);
|
|
1129
|
-
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
1130
|
-
}
|
|
1131
|
-
const { port, baseUrl } = lineResult;
|
|
1132
|
-
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
1133
|
-
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
1134
|
-
if (outcome === "ready")
|
|
1135
|
-
return { port, baseUrl };
|
|
1136
|
-
killIdentifiedProcess(pid, identity);
|
|
1137
|
-
if (outcome === "died") {
|
|
1138
|
-
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
1139
|
-
}
|
|
1140
|
-
if (outcome === "auth-failure") {
|
|
1141
|
-
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
1142
|
-
}
|
|
1143
|
-
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
1144
|
-
}
|
|
1145
|
-
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
1146
|
-
function reapOrphanedProvisional(rosterPath) {
|
|
1147
|
-
const provisional = readProvisional(rosterPath);
|
|
1148
|
-
if (!provisional)
|
|
1149
|
-
return;
|
|
1150
|
-
const discovery = readDiscovery(rosterPath);
|
|
1151
|
-
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1152
|
-
removeProvisional(rosterPath);
|
|
1153
|
-
return;
|
|
1154
|
-
}
|
|
1155
|
-
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
1156
|
-
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
1157
|
-
if (hasIdentity || isFresh) {
|
|
1158
|
-
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
1159
|
-
}
|
|
1160
|
-
removeProvisional(rosterPath);
|
|
1161
|
-
}
|
|
1162
|
-
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
1163
|
-
reapOrphanedProvisional(rosterPath);
|
|
1164
|
-
const password = randomBytes3(32).toString("base64url");
|
|
1165
|
-
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
1166
|
-
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
1167
|
-
const requestedPort = managedConfig.port ?? 0;
|
|
1168
|
-
const logPath = logFilePath(rosterPath);
|
|
1169
|
-
const logFd = openSync3(logPath, "w", 384);
|
|
1170
|
-
let child;
|
|
1171
|
-
let pid;
|
|
1172
|
-
let spawnError;
|
|
1173
|
-
try {
|
|
1174
|
-
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
1175
|
-
cwd,
|
|
1176
|
-
detached: true,
|
|
1177
|
-
stdio: ["ignore", logFd, logFd],
|
|
1178
|
-
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
1179
|
-
});
|
|
1180
|
-
child.on("error", (err) => {
|
|
1181
|
-
spawnError = err;
|
|
1182
|
-
});
|
|
1183
|
-
child.unref();
|
|
1184
|
-
pid = child.pid;
|
|
1185
|
-
} finally {
|
|
1186
|
-
closeQuietly(logFd);
|
|
1187
|
-
}
|
|
1188
|
-
if (pid === undefined) {
|
|
1189
|
-
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
1190
|
-
}
|
|
1191
|
-
const identity = captureIdentity(pid);
|
|
1192
|
-
writeProvisional(rosterPath, {
|
|
1193
|
-
pid,
|
|
1194
|
-
identity: identity ?? "",
|
|
1195
|
-
password,
|
|
1196
|
-
since: Date.now()
|
|
1197
|
-
});
|
|
1198
|
-
let port;
|
|
1199
|
-
let baseUrl;
|
|
1200
|
-
try {
|
|
1201
|
-
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
1202
|
-
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
1203
|
-
const check = setInterval(() => {
|
|
1204
|
-
if (spawnError) {
|
|
1205
|
-
clearInterval(check);
|
|
1206
|
-
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
1207
|
-
}
|
|
1208
|
-
}, POLL_INTERVAL_MS);
|
|
1209
|
-
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
1210
|
-
});
|
|
1211
|
-
const result = await Promise.race([readiness, spawnErrorWatch]);
|
|
1212
|
-
port = result.port;
|
|
1213
|
-
baseUrl = result.baseUrl;
|
|
1214
|
-
} finally {
|
|
1215
|
-
removeProvisional(rosterPath);
|
|
1216
|
-
}
|
|
1217
|
-
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
1218
|
-
writeDiscovery(rosterPath, {
|
|
1219
|
-
port,
|
|
1220
|
-
pid,
|
|
1221
|
-
identity: finalIdentity,
|
|
1222
|
-
password,
|
|
1223
|
-
spawnConfig: { command, cwd, port: requestedPort },
|
|
1224
|
-
baseUrl,
|
|
1225
|
-
rosterPath
|
|
1226
|
-
});
|
|
1227
|
-
return {
|
|
1228
|
-
baseUrl,
|
|
1229
|
-
credentials: { username: "opencode", password },
|
|
1230
|
-
pid,
|
|
1231
|
-
port
|
|
1232
|
-
};
|
|
1233
|
-
}
|
|
1234
|
-
async function ensureServer(rosterPath, options = {}) {
|
|
1235
|
-
if (existsSync2(rosterPath)) {
|
|
1236
|
-
rosterPath = realpathSync3(rosterPath);
|
|
1237
|
-
}
|
|
1238
|
-
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
1239
|
-
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
1240
|
-
const fastPath = attachServer(rosterPath);
|
|
1241
|
-
if (fastPath)
|
|
1242
|
-
return fastPath;
|
|
1243
|
-
const manifest = readManifest(rosterPath);
|
|
1244
|
-
if (manifest.server.managed === undefined) {
|
|
1245
|
-
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
1246
|
-
}
|
|
1247
|
-
const lock = acquireLock(rosterPath);
|
|
1248
|
-
if (lock === null) {
|
|
1249
|
-
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
1250
|
-
}
|
|
1251
|
-
try {
|
|
1252
|
-
const attached = attachServer(rosterPath);
|
|
1253
|
-
if (attached)
|
|
1254
|
-
return attached;
|
|
1255
|
-
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
1256
|
-
} finally {
|
|
1257
|
-
releaseLock(lock);
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
function serverStatus(rosterPath) {
|
|
1261
|
-
const discovery = readDiscovery(rosterPath);
|
|
1262
|
-
if (!discovery) {
|
|
1263
|
-
return { running: false };
|
|
1264
|
-
}
|
|
1265
|
-
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1266
|
-
removeDiscoveryIfMatches(rosterPath, {
|
|
1267
|
-
pid: discovery.pid,
|
|
1268
|
-
identity: discovery.identity
|
|
1269
|
-
});
|
|
1270
|
-
return { running: false };
|
|
1271
|
-
}
|
|
1272
|
-
let configDrift;
|
|
1273
|
-
try {
|
|
1274
|
-
const manifest = readManifest(rosterPath);
|
|
1275
|
-
if (manifest.server.managed) {
|
|
1276
|
-
const current = manifest.server.managed;
|
|
1277
|
-
const currentCommand = current.command ?? ["harness", "serve"];
|
|
1278
|
-
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
1279
|
-
const currentPort = current.port ?? 0;
|
|
1280
|
-
const storedCommand = discovery.spawnConfig.command ?? [
|
|
1281
|
-
"harness",
|
|
1282
|
-
"serve"
|
|
1283
|
-
];
|
|
1284
|
-
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
1285
|
-
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
1286
|
-
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
1287
|
-
}
|
|
1288
|
-
} catch {}
|
|
1289
|
-
return {
|
|
1290
|
-
running: true,
|
|
1291
|
-
port: discovery.port,
|
|
1292
|
-
pid: discovery.pid,
|
|
1293
|
-
configDrift
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
async function stopServer(rosterPath) {
|
|
1297
|
-
const discovery = readDiscovery(rosterPath);
|
|
1298
|
-
if (!discovery)
|
|
1299
|
-
return { stopped: false };
|
|
1300
|
-
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1301
|
-
await reapSurvivingGroup(discovery.pid);
|
|
1302
|
-
removeDiscovery(rosterPath);
|
|
1303
|
-
return { stopped: false };
|
|
1304
|
-
}
|
|
1305
|
-
const { pid } = discovery;
|
|
1306
|
-
let groupSignaled;
|
|
1307
|
-
const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
|
|
1308
|
-
try {
|
|
1309
|
-
groupSignaled = signalGroup(pid, "SIGTERM");
|
|
1310
|
-
} catch (err) {
|
|
1311
|
-
if (isEpermError(err)) {
|
|
1312
|
-
return { stopped: false };
|
|
1313
|
-
}
|
|
1314
|
-
removeDiscovery(rosterPath);
|
|
1315
|
-
return { stopped: true };
|
|
1316
|
-
}
|
|
1317
|
-
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
1318
|
-
removeDiscovery(rosterPath);
|
|
1319
|
-
return { stopped: true };
|
|
1320
|
-
}
|
|
1321
|
-
try {
|
|
1322
|
-
groupSignaled = signalGroup(pid, "SIGKILL");
|
|
1323
|
-
} catch (err) {
|
|
1324
|
-
if (isEpermError(err)) {
|
|
1325
|
-
return { stopped: false };
|
|
1326
|
-
}
|
|
1327
|
-
removeDiscovery(rosterPath);
|
|
1328
|
-
return { stopped: true };
|
|
1329
|
-
}
|
|
1330
|
-
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
1331
|
-
removeDiscovery(rosterPath);
|
|
1332
|
-
return { stopped: true };
|
|
1333
|
-
}
|
|
1334
|
-
return { stopped: false };
|
|
1335
|
-
}
|
|
1336
|
-
async function reapSurvivingGroup(pid) {
|
|
1337
|
-
try {
|
|
1338
|
-
if (isAlive(pid))
|
|
1339
|
-
return;
|
|
1340
|
-
let groupAlive;
|
|
1341
|
-
try {
|
|
1342
|
-
process.kill(-pid, 0);
|
|
1343
|
-
groupAlive = true;
|
|
1344
|
-
} catch {
|
|
1345
|
-
groupAlive = false;
|
|
1346
|
-
}
|
|
1347
|
-
if (!groupAlive)
|
|
1348
|
-
return;
|
|
1349
|
-
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
1350
|
-
return;
|
|
1351
|
-
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
1352
|
-
return;
|
|
1353
|
-
signalGroupOnly(pid, "SIGKILL");
|
|
1354
|
-
await waitForGroupDeath(pid, STOP_GRACE_MS);
|
|
1355
|
-
} catch {}
|
|
1356
|
-
}
|
|
1357
|
-
async function stopForHung(tick) {
|
|
1358
|
-
try {
|
|
1359
|
-
await tick.stop(tick.rosterPath);
|
|
1360
|
-
} catch {}
|
|
1361
|
-
return { kind: "outcome", outcome: { reason: "hung" } };
|
|
1362
|
-
}
|
|
1363
|
-
async function superviseTick(tick, state) {
|
|
1364
|
-
const st = tick.status(tick.rosterPath);
|
|
1365
|
-
if (!st.running) {
|
|
1366
|
-
await reapSurvivingGroup(tick.handle.pid);
|
|
1367
|
-
return { kind: "outcome", outcome: { reason: "died" } };
|
|
1368
|
-
}
|
|
1369
|
-
const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
|
|
1370
|
-
const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
|
|
1371
|
-
const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
|
|
1372
|
-
if (failures >= tick.threshold) {
|
|
1373
|
-
return stopForHung(tick);
|
|
1374
|
-
}
|
|
1375
|
-
if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
|
|
1376
|
-
return stopForHung(tick);
|
|
1377
|
-
}
|
|
1378
|
-
return { kind: "tick", failures, lastReadyAt };
|
|
1379
|
-
}
|
|
1380
|
-
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
1381
|
-
return {
|
|
1382
|
-
rosterPath,
|
|
1383
|
-
handle,
|
|
1384
|
-
password: handle.credentials.password ?? "",
|
|
1385
|
-
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
1386
|
-
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
1387
|
-
now: opts.now ?? Date.now,
|
|
1388
|
-
status: opts.status ?? serverStatus,
|
|
1389
|
-
probe: opts.probe ?? probe,
|
|
1390
|
-
stop: opts.stop ?? stopServer
|
|
1391
|
-
};
|
|
1392
|
-
}
|
|
1393
|
-
async function interruptibleSleep(doSleep, intervalMs, interrupt) {
|
|
1394
|
-
if (!interrupt) {
|
|
1395
|
-
await doSleep(intervalMs);
|
|
1396
|
-
return;
|
|
1397
|
-
}
|
|
1398
|
-
let timer;
|
|
1399
|
-
const timed = new Promise((resolve) => {
|
|
1400
|
-
timer = setTimeout(resolve, intervalMs);
|
|
1401
|
-
});
|
|
1402
|
-
try {
|
|
1403
|
-
await Promise.race([timed, interrupt]);
|
|
1404
|
-
} finally {
|
|
1405
|
-
if (timer !== undefined)
|
|
1406
|
-
clearTimeout(timer);
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
async function superviseServer(rosterPath, handle, opts = {}) {
|
|
1410
|
-
const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
|
|
1411
|
-
const tick = makeSuperviseTick(rosterPath, handle, opts);
|
|
1412
|
-
const doSleep = opts.sleep ?? sleep;
|
|
1413
|
-
const shouldStop = opts.shouldStop ?? (() => false);
|
|
1414
|
-
let state = { failures: 0, lastReadyAt: tick.now() };
|
|
1415
|
-
for (;; ) {
|
|
1416
|
-
if (shouldStop())
|
|
1417
|
-
return { reason: "signal" };
|
|
1418
|
-
const result = await superviseTick(tick, state);
|
|
1419
|
-
if (result.kind === "outcome")
|
|
1420
|
-
return result.outcome;
|
|
1421
|
-
state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
|
|
1422
|
-
if (shouldStop())
|
|
1423
|
-
return { reason: "signal" };
|
|
1424
|
-
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
async function waitForDeath(pid, budgetMs) {
|
|
1428
|
-
const deadline = Date.now() + budgetMs;
|
|
1429
|
-
while (Date.now() < deadline) {
|
|
1430
|
-
if (!isAlive(pid))
|
|
1431
|
-
return true;
|
|
1432
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1433
|
-
}
|
|
1434
|
-
return !isAlive(pid);
|
|
1435
|
-
}
|
|
1436
|
-
async function waitForGroupDeath(pid, budgetMs) {
|
|
1437
|
-
const deadline = Date.now() + budgetMs;
|
|
1438
|
-
const groupAlive = () => {
|
|
1439
|
-
try {
|
|
1440
|
-
process.kill(-pid, 0);
|
|
1441
|
-
return true;
|
|
1442
|
-
} catch {
|
|
1443
|
-
return false;
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
1446
|
-
while (Date.now() < deadline) {
|
|
1447
|
-
if (!groupAlive())
|
|
1448
|
-
return true;
|
|
1449
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1450
|
-
}
|
|
1451
|
-
return !groupAlive();
|
|
1452
|
-
}
|
|
1453
|
-
|
|
1454
|
-
// src/tools/bus_registry.ts
|
|
1455
|
-
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
1456
|
-
import { tool } from "@opencode-ai/plugin";
|
|
1457
|
-
import { z as z4 } from "zod";
|
|
1458
|
-
|
|
1459
|
-
// src/format.ts
|
|
1460
|
-
function formatRosterHeader(source) {
|
|
1461
|
-
return `roster: ${source.name ?? source.path}`;
|
|
1462
|
-
}
|
|
1463
|
-
function formatRoster(projects) {
|
|
1464
|
-
return projects.map((p) => {
|
|
1465
|
-
if (!p.pathExists)
|
|
1466
|
-
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
1467
|
-
if (p.statusError)
|
|
1468
|
-
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
1469
|
-
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
1470
|
-
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
1471
|
-
}).join(`
|
|
1472
|
-
`);
|
|
1473
|
-
}
|
|
1474
|
-
function formatDispatch(r) {
|
|
1475
|
-
switch (r.mode) {
|
|
1476
|
-
case "new":
|
|
1477
|
-
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
1478
|
-
case "question-reply":
|
|
1479
|
-
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
1480
|
-
case "follow-up":
|
|
1481
|
-
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
1482
|
-
case "blocked":
|
|
1483
|
-
return `Blocked: session ${r.sessionId} (${r.project}) has a pending question (${r.requestId}) — no reply or prompt sent.`;
|
|
1484
|
-
}
|
|
1485
|
-
}
|
|
1486
|
-
function dispatchMetadata(r) {
|
|
1487
|
-
const messageId = (r.mode === "new" || r.mode === "follow-up") && r.messageId !== undefined ? r.messageId : undefined;
|
|
1488
|
-
return {
|
|
1489
|
-
sessionId: r.sessionId,
|
|
1490
|
-
project: r.project,
|
|
1491
|
-
mode: r.mode,
|
|
1492
|
-
...messageId !== undefined ? { messageId } : {}
|
|
1493
|
-
};
|
|
1494
|
-
}
|
|
1495
|
-
function formatStatus(r) {
|
|
1496
|
-
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
1497
|
-
`) : " (none)";
|
|
1498
|
-
const lines = [
|
|
1499
|
-
`session: ${r.sessionId} (${r.project})`,
|
|
1500
|
-
`title: ${r.title ?? "(untitled)"}`,
|
|
1501
|
-
`busy: ${r.busy}`
|
|
1502
|
-
];
|
|
1503
|
-
if (r.pendingQuestion) {
|
|
1504
|
-
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
1505
|
-
if (r.pendingQuestion.options.length > 0) {
|
|
1506
|
-
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
1507
|
-
}
|
|
1508
|
-
lines.push(` (answer with bus_task using sessionId)`);
|
|
1509
|
-
}
|
|
1510
|
-
lines.push(r.diffSource === "working-tree" ? `diff (working tree — repo-wide, may include changes from other sessions): ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}` : `diff: ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}`, `todos:`, todoLines);
|
|
1511
|
-
return lines.join(`
|
|
1512
|
-
`);
|
|
1513
|
-
}
|
|
1514
|
-
function formatWait(r) {
|
|
1515
|
-
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
1516
|
-
const sessionLines = r.sessions.map((s) => {
|
|
1517
|
-
const parts = [
|
|
1518
|
-
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
1519
|
-
];
|
|
1520
|
-
if (s.pendingQuestion) {
|
|
1521
|
-
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
1522
|
-
if (s.pendingQuestion.options.length > 0) {
|
|
1523
|
-
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
1524
|
-
}
|
|
1525
|
-
parts.push(` (answer with bus_task using sessionId)`);
|
|
1526
|
-
}
|
|
1527
|
-
return parts.join(`
|
|
1528
|
-
`);
|
|
1529
|
-
});
|
|
1530
|
-
return [header, ...sessionLines].join(`
|
|
1531
|
-
`);
|
|
1532
|
-
}
|
|
1533
|
-
function formatResult(r) {
|
|
1534
|
-
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
1535
|
-
`) : " (no changes)";
|
|
1536
|
-
return [
|
|
1537
|
-
`session: ${r.sessionId} (${r.project})`,
|
|
1538
|
-
`--- reply ---`,
|
|
1539
|
-
r.text || "(empty)",
|
|
1540
|
-
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
1541
|
-
diffLines
|
|
1542
|
-
].join(`
|
|
1543
|
-
`);
|
|
1544
|
-
}
|
|
1545
|
-
|
|
1546
|
-
// src/roster-edit.ts
|
|
1547
|
-
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
1548
|
-
import {
|
|
1549
|
-
chmodSync as chmodSync2,
|
|
1550
|
-
closeSync as closeSync3,
|
|
1551
|
-
constants as fsConstants3,
|
|
1552
|
-
lstatSync as lstatSync2,
|
|
1553
|
-
mkdirSync as mkdirSync3,
|
|
1554
|
-
openSync as openSync4,
|
|
1555
|
-
readFileSync as readFileSync5,
|
|
1556
|
-
renameSync as renameSync3,
|
|
1557
|
-
statSync as statSync3,
|
|
1558
|
-
unlinkSync as unlinkSync3,
|
|
1559
|
-
writeSync as writeSync2
|
|
1560
|
-
} from "node:fs";
|
|
1561
|
-
import { join as join4 } from "node:path";
|
|
1562
|
-
function closeQuietly3(fd) {
|
|
1563
|
-
try {
|
|
1564
|
-
closeSync3(fd);
|
|
1565
|
-
} catch {}
|
|
1566
|
-
}
|
|
1567
|
-
function isErrnoCode3(err, code) {
|
|
1568
|
-
return typeof err === "object" && err !== null && "code" in err && err.code === code;
|
|
1569
|
-
}
|
|
1570
|
-
function duplicateProjectName(projects) {
|
|
1571
|
-
const seen = new Set;
|
|
1572
|
-
for (const p of projects) {
|
|
1573
|
-
if (seen.has(p.name))
|
|
1574
|
-
return p.name;
|
|
1575
|
-
seen.add(p.name);
|
|
1576
|
-
}
|
|
1577
|
-
return null;
|
|
1578
|
-
}
|
|
1579
|
-
function validateManifest(data) {
|
|
1580
|
-
const parsed = manifestSchema.safeParse(data);
|
|
1581
|
-
if (!parsed.success) {
|
|
1582
|
-
return {
|
|
1583
|
-
ok: false,
|
|
1584
|
-
error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
const baseUrl = parsed.data.server.baseUrl;
|
|
1588
|
-
if (baseUrl !== undefined && !loopbackOk(baseUrl)) {
|
|
1589
|
-
return {
|
|
1590
|
-
ok: false,
|
|
1591
|
-
error: `space-bus: roster's server.baseUrl must point to localhost (got ${baseUrl}) — refusing to send credentials off-machine`
|
|
1592
|
-
};
|
|
1593
|
-
}
|
|
1594
|
-
const dup = duplicateProjectName(parsed.data.projects);
|
|
1595
|
-
if (dup !== null) {
|
|
1596
|
-
return {
|
|
1597
|
-
ok: false,
|
|
1598
|
-
error: `space-bus: roster document has duplicate project name "${dup}"`
|
|
1599
|
-
};
|
|
1600
|
-
}
|
|
1601
|
-
return { ok: true, manifest: parsed.data };
|
|
1602
|
-
}
|
|
1603
|
-
function readManifest2(rosterPath) {
|
|
1604
|
-
let raw;
|
|
1605
|
-
try {
|
|
1606
|
-
raw = readFileSync5(rosterPath, "utf8");
|
|
1607
|
-
} catch (err) {
|
|
1608
|
-
return {
|
|
1609
|
-
ok: false,
|
|
1610
|
-
error: `space-bus: cannot read roster at ${rosterPath}: ${String(err)}`
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
let json;
|
|
1614
|
-
try {
|
|
1615
|
-
json = JSON.parse(raw);
|
|
1616
|
-
} catch (err) {
|
|
1617
|
-
return {
|
|
1618
|
-
ok: false,
|
|
1619
|
-
error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
|
|
1620
|
-
};
|
|
1621
|
-
}
|
|
1622
|
-
return validateManifest(json);
|
|
1623
|
-
}
|
|
1624
|
-
function writeManifestAtomic(rosterPath, data) {
|
|
1625
|
-
const dir = join4(rosterPath, "..");
|
|
1626
|
-
try {
|
|
1627
|
-
mkdirSync3(dir, { recursive: true });
|
|
1628
|
-
} catch (err) {
|
|
1629
|
-
return {
|
|
1630
|
-
ok: false,
|
|
1631
|
-
error: `space-bus: failed to create directory ${dir}: ${String(err)}`
|
|
1632
|
-
};
|
|
1633
|
-
}
|
|
1634
|
-
let existingMode;
|
|
1635
|
-
try {
|
|
1636
|
-
existingMode = statSync3(rosterPath).mode & 511;
|
|
1637
|
-
} catch {
|
|
1638
|
-
existingMode = undefined;
|
|
1639
|
-
}
|
|
1640
|
-
const tempPath = join4(dir, `.spacebus.${randomBytes4(8).toString("hex")}.tmp`);
|
|
1150
|
+
const tempPath = join4(dir, `.spacebus.${randomBytes3(8).toString("hex")}.tmp`);
|
|
1641
1151
|
let fd;
|
|
1642
1152
|
try {
|
|
1643
|
-
fd =
|
|
1153
|
+
fd = openSync3(tempPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY, 420);
|
|
1644
1154
|
writeSync2(fd, JSON.stringify(data, null, 2));
|
|
1645
1155
|
if (existingMode !== undefined) {
|
|
1646
1156
|
chmodSync2(tempPath, existingMode);
|
|
@@ -1673,7 +1183,7 @@ function writeRosterExclusive(rosterPath, data) {
|
|
|
1673
1183
|
}
|
|
1674
1184
|
let fd;
|
|
1675
1185
|
try {
|
|
1676
|
-
fd =
|
|
1186
|
+
fd = openSync3(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
|
|
1677
1187
|
} catch (err) {
|
|
1678
1188
|
if (isErrnoCode3(err, "EEXIST")) {
|
|
1679
1189
|
return {
|
|
@@ -1710,7 +1220,7 @@ function editManifest(rosterPath, mutate) {
|
|
|
1710
1220
|
};
|
|
1711
1221
|
}
|
|
1712
1222
|
} catch {}
|
|
1713
|
-
const current =
|
|
1223
|
+
const current = readManifest(rosterPath);
|
|
1714
1224
|
if (!current.ok)
|
|
1715
1225
|
return current;
|
|
1716
1226
|
const mutated = mutate(current.manifest);
|
|
@@ -2318,465 +1828,952 @@ async function roster(opts) {
|
|
|
2318
1828
|
}));
|
|
2319
1829
|
return { ok: true, projects: results };
|
|
2320
1830
|
}
|
|
2321
|
-
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title, messageId) {
|
|
2322
|
-
const resolved = resolveProjectOrErr(projects, project);
|
|
2323
|
-
if (!resolved.ok)
|
|
2324
|
-
return resolved;
|
|
2325
|
-
const directory = resolved.project.expandedPath;
|
|
2326
|
-
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
2327
|
-
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
2328
|
-
method: "POST",
|
|
2329
|
-
body: JSON.stringify({ title: sessionTitle })
|
|
2330
|
-
});
|
|
2331
|
-
if (!createRes.res.ok) {
|
|
2332
|
-
return dispatchErr(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`, { phase: "indeterminate", project, messageId });
|
|
1831
|
+
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title, messageId) {
|
|
1832
|
+
const resolved = resolveProjectOrErr(projects, project);
|
|
1833
|
+
if (!resolved.ok)
|
|
1834
|
+
return resolved;
|
|
1835
|
+
const directory = resolved.project.expandedPath;
|
|
1836
|
+
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
1837
|
+
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
1838
|
+
method: "POST",
|
|
1839
|
+
body: JSON.stringify({ title: sessionTitle })
|
|
1840
|
+
});
|
|
1841
|
+
if (!createRes.res.ok) {
|
|
1842
|
+
return dispatchErr(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`, { phase: "indeterminate", project, messageId });
|
|
1843
|
+
}
|
|
1844
|
+
let session;
|
|
1845
|
+
try {
|
|
1846
|
+
session = sessionSchema.parse(JSON.parse(createRes.bodyText));
|
|
1847
|
+
} catch (e) {
|
|
1848
|
+
return dispatchErr(`space-bus: unexpected /session response shape: ${e.message}`, { phase: "indeterminate", project, messageId });
|
|
1849
|
+
}
|
|
1850
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
|
|
1851
|
+
method: "POST",
|
|
1852
|
+
body: JSON.stringify({
|
|
1853
|
+
parts: [{ type: "text", text: prompt }],
|
|
1854
|
+
...messageId !== undefined ? { messageID: messageId } : {}
|
|
1855
|
+
})
|
|
1856
|
+
});
|
|
1857
|
+
if (promptRes.res.status !== 204) {
|
|
1858
|
+
return dispatchErr(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId: session.id, messageId });
|
|
1859
|
+
}
|
|
1860
|
+
return {
|
|
1861
|
+
ok: true,
|
|
1862
|
+
sessionId: session.id,
|
|
1863
|
+
project,
|
|
1864
|
+
directory,
|
|
1865
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
var MESSAGE_ID_PATTERN = /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
|
|
1869
|
+
var INVALID_MESSAGE_ID_ERROR = "space-bus: messageId must be msg_ followed by exactly 12 hex characters and 14 alphanumeric characters";
|
|
1870
|
+
function validateMessageId(messageId) {
|
|
1871
|
+
if (!MESSAGE_ID_PATTERN.test(messageId)) {
|
|
1872
|
+
return err(INVALID_MESSAGE_ID_ERROR);
|
|
1873
|
+
}
|
|
1874
|
+
return { ok: true, messageId };
|
|
1875
|
+
}
|
|
1876
|
+
function toDispatchArgs(input) {
|
|
1877
|
+
if (input.onPendingQuestion !== undefined && input.onPendingQuestion !== "question-reply" && input.onPendingQuestion !== "blocked") {
|
|
1878
|
+
return err(`space-bus: onPendingQuestion must be "question-reply" or "blocked", got ${JSON.stringify(input.onPendingQuestion)}`);
|
|
1879
|
+
}
|
|
1880
|
+
if (input.sessionId !== undefined && input.sessionId === "") {
|
|
1881
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1882
|
+
}
|
|
1883
|
+
let messageId;
|
|
1884
|
+
if (input.messageId !== undefined) {
|
|
1885
|
+
const validated = validateMessageId(input.messageId);
|
|
1886
|
+
if (!validated.ok)
|
|
1887
|
+
return validated;
|
|
1888
|
+
messageId = validated.messageId;
|
|
1889
|
+
}
|
|
1890
|
+
if (!input.sessionId) {
|
|
1891
|
+
if (!input.project) {
|
|
1892
|
+
return err("space-bus: project is required when starting a new session");
|
|
1893
|
+
}
|
|
1894
|
+
return {
|
|
1895
|
+
ok: true,
|
|
1896
|
+
prompt: input.prompt,
|
|
1897
|
+
title: input.title,
|
|
1898
|
+
project: input.project,
|
|
1899
|
+
onPendingQuestion: input.onPendingQuestion,
|
|
1900
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1903
|
+
return {
|
|
1904
|
+
ok: true,
|
|
1905
|
+
prompt: input.prompt,
|
|
1906
|
+
title: input.title,
|
|
1907
|
+
sessionId: input.sessionId,
|
|
1908
|
+
project: input.project,
|
|
1909
|
+
onPendingQuestion: input.onPendingQuestion,
|
|
1910
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1911
|
+
};
|
|
1912
|
+
}
|
|
1913
|
+
async function dispatchNewBranch(baseUrl, credentials, projects, args) {
|
|
1914
|
+
const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title, args.messageId);
|
|
1915
|
+
if (!r.ok)
|
|
1916
|
+
return r;
|
|
1917
|
+
return {
|
|
1918
|
+
ok: true,
|
|
1919
|
+
sessionId: r.sessionId,
|
|
1920
|
+
project: r.project,
|
|
1921
|
+
mode: "new",
|
|
1922
|
+
directory: r.directory,
|
|
1923
|
+
...r.messageId !== undefined ? { messageId: r.messageId } : {}
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
async function dispatch(args, opts) {
|
|
1927
|
+
const ctx = validateContext(opts.context);
|
|
1928
|
+
if (!ctx.ok)
|
|
1929
|
+
return ctx;
|
|
1930
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1931
|
+
if (args.messageId !== undefined) {
|
|
1932
|
+
const validated = validateMessageId(args.messageId);
|
|
1933
|
+
if (!validated.ok)
|
|
1934
|
+
return validated;
|
|
1935
|
+
}
|
|
1936
|
+
if (args.sessionId !== undefined && args.sessionId === "") {
|
|
1937
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1938
|
+
}
|
|
1939
|
+
if (!args.sessionId) {
|
|
1940
|
+
if (!args.project) {
|
|
1941
|
+
return err("space-bus: project is required when starting a new session");
|
|
1942
|
+
}
|
|
1943
|
+
return dispatchNewBranch(baseUrl, credentials, projects, {
|
|
1944
|
+
...args,
|
|
1945
|
+
project: args.project
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
|
|
1949
|
+
if (!loc.ok)
|
|
1950
|
+
return loc;
|
|
1951
|
+
const { directory, project } = loc;
|
|
1952
|
+
if (args.project && args.project !== project) {
|
|
1953
|
+
return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
|
|
1954
|
+
}
|
|
1955
|
+
return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project, args.onPendingQuestion ?? "question-reply", args.messageId);
|
|
1956
|
+
}
|
|
1957
|
+
async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
|
|
1958
|
+
for (const p of projects) {
|
|
1959
|
+
if (!p.exists)
|
|
1960
|
+
continue;
|
|
1961
|
+
const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
|
|
1962
|
+
if (!res.ok)
|
|
1963
|
+
continue;
|
|
1964
|
+
let session;
|
|
1965
|
+
try {
|
|
1966
|
+
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
1967
|
+
} catch {
|
|
1968
|
+
continue;
|
|
1969
|
+
}
|
|
1970
|
+
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
1971
|
+
if (owner) {
|
|
1972
|
+
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
1973
|
+
}
|
|
1974
|
+
return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
|
|
1975
|
+
}
|
|
1976
|
+
return err(`space-bus: no manifest project has a session with id ${sessionId}`);
|
|
1977
|
+
}
|
|
1978
|
+
function deriveSessionState(input) {
|
|
1979
|
+
if (!input.resolved)
|
|
1980
|
+
return "not_found";
|
|
1981
|
+
if (input.failed)
|
|
1982
|
+
return "failed";
|
|
1983
|
+
if (input.pendingQuestion)
|
|
1984
|
+
return "blocked";
|
|
1985
|
+
if (input.busy)
|
|
1986
|
+
return "running";
|
|
1987
|
+
return "complete";
|
|
1988
|
+
}
|
|
1989
|
+
function formatQuestionEntry(entry) {
|
|
1990
|
+
const firstQuestion = entry.questions?.[0];
|
|
1991
|
+
const text = firstQuestion?.question ?? "";
|
|
1992
|
+
const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
|
|
1993
|
+
const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
|
|
1994
|
+
return { sessionId: entry.sessionID, preview, options };
|
|
1995
|
+
}
|
|
1996
|
+
async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
|
|
1997
|
+
try {
|
|
1998
|
+
const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
|
|
1999
|
+
if (!res.ok)
|
|
2000
|
+
return;
|
|
2001
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
|
|
2002
|
+
const entry = entries.find((e) => e.sessionID === sessionId);
|
|
2003
|
+
if (!entry)
|
|
2004
|
+
return;
|
|
2005
|
+
const { preview, options } = formatQuestionEntry(entry);
|
|
2006
|
+
return { preview, options };
|
|
2007
|
+
} catch {
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
async function status(sessionId, opts) {
|
|
2012
|
+
const ctx = validateContext(opts.context);
|
|
2013
|
+
if (!ctx.ok)
|
|
2014
|
+
return ctx;
|
|
2015
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
2016
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
2017
|
+
if (!loc.ok)
|
|
2018
|
+
return loc;
|
|
2019
|
+
const { directory, project } = loc;
|
|
2020
|
+
const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
|
|
2021
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
|
|
2022
|
+
api(baseUrl, credentials, directory, "/session/status"),
|
|
2023
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
|
|
2024
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
|
|
2025
|
+
fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
|
|
2026
|
+
]);
|
|
2027
|
+
if (!sessionRes.res.ok) {
|
|
2028
|
+
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
2029
|
+
}
|
|
2030
|
+
let session;
|
|
2031
|
+
let statusMap;
|
|
2032
|
+
let todos;
|
|
2033
|
+
try {
|
|
2034
|
+
session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
|
|
2035
|
+
statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
|
|
2036
|
+
todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
|
|
2037
|
+
} catch (e) {
|
|
2038
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
2039
|
+
}
|
|
2040
|
+
const entry = statusMap[sessionId];
|
|
2041
|
+
const busy = isStatusBusy(entry);
|
|
2042
|
+
const { diff, diffSource } = diffResult;
|
|
2043
|
+
const additions = diff.reduce((sum, d) => sum + d.additions, 0);
|
|
2044
|
+
const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
|
|
2045
|
+
const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
|
|
2046
|
+
return {
|
|
2047
|
+
ok: true,
|
|
2048
|
+
sessionId,
|
|
2049
|
+
project,
|
|
2050
|
+
busy,
|
|
2051
|
+
title: session.title,
|
|
2052
|
+
todos,
|
|
2053
|
+
diff: { files: diff.length, additions, deletions },
|
|
2054
|
+
diffSource,
|
|
2055
|
+
pendingQuestion,
|
|
2056
|
+
state,
|
|
2057
|
+
resultAvailable: state === "complete"
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
2060
|
+
async function resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, project, onPendingQuestion) {
|
|
2061
|
+
const questionsRes = await api(baseUrl, credentials, directory, "/question");
|
|
2062
|
+
if (!questionsRes.res.ok) {
|
|
2063
|
+
if (onPendingQuestion === "blocked") {
|
|
2064
|
+
return dispatchErr(`space-bus: could not verify pending-question state for session ${sessionId} (/question ${questionsRes.res.status}) — refusing to dispatch under the blocked policy`, { phase: "not_sent", project, sessionId });
|
|
2065
|
+
}
|
|
2066
|
+
return { ok: true, pending: undefined };
|
|
2333
2067
|
}
|
|
2334
|
-
let
|
|
2068
|
+
let pendingList;
|
|
2335
2069
|
try {
|
|
2336
|
-
|
|
2070
|
+
pendingList = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
|
|
2337
2071
|
} catch (e) {
|
|
2338
|
-
|
|
2072
|
+
if (onPendingQuestion === "blocked") {
|
|
2073
|
+
return dispatchErr(`space-bus: could not parse pending-question state for session ${sessionId}: ${e.message} — refusing to dispatch under the blocked policy`, { phase: "not_sent", project, sessionId });
|
|
2074
|
+
}
|
|
2075
|
+
return { ok: true, pending: undefined };
|
|
2339
2076
|
}
|
|
2340
|
-
|
|
2077
|
+
return {
|
|
2078
|
+
ok: true,
|
|
2079
|
+
pending: pendingList.find((q) => q.sessionID === sessionId)
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
async function steerSession(baseUrl, credentials, sessionId, message, directory, project, onPendingQuestion, messageId) {
|
|
2083
|
+
const pendingRes = await resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, project, onPendingQuestion);
|
|
2084
|
+
if (!pendingRes.ok)
|
|
2085
|
+
return pendingRes;
|
|
2086
|
+
const { pending } = pendingRes;
|
|
2087
|
+
if (pending && onPendingQuestion === "blocked") {
|
|
2088
|
+
return {
|
|
2089
|
+
ok: true,
|
|
2090
|
+
sessionId,
|
|
2091
|
+
project,
|
|
2092
|
+
mode: "blocked",
|
|
2093
|
+
requestId: pending.id
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
if (pending) {
|
|
2097
|
+
const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
|
|
2098
|
+
method: "POST",
|
|
2099
|
+
body: JSON.stringify({ answers: [[message]] })
|
|
2100
|
+
});
|
|
2101
|
+
if (!replyRes.res.ok) {
|
|
2102
|
+
return dispatchErr(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`, { phase: "indeterminate", project, sessionId });
|
|
2103
|
+
}
|
|
2104
|
+
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
2105
|
+
}
|
|
2106
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
2341
2107
|
method: "POST",
|
|
2342
2108
|
body: JSON.stringify({
|
|
2343
|
-
parts: [{ type: "text", text:
|
|
2109
|
+
parts: [{ type: "text", text: message }],
|
|
2344
2110
|
...messageId !== undefined ? { messageID: messageId } : {}
|
|
2345
2111
|
})
|
|
2346
2112
|
});
|
|
2347
2113
|
if (promptRes.res.status !== 204) {
|
|
2348
|
-
return dispatchErr(`space-bus:
|
|
2114
|
+
return dispatchErr(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId, messageId });
|
|
2349
2115
|
}
|
|
2350
2116
|
return {
|
|
2351
2117
|
ok: true,
|
|
2352
|
-
sessionId
|
|
2118
|
+
sessionId,
|
|
2353
2119
|
project,
|
|
2354
|
-
|
|
2120
|
+
mode: "follow-up",
|
|
2355
2121
|
...messageId !== undefined ? { messageId } : {}
|
|
2356
2122
|
};
|
|
2357
2123
|
}
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2124
|
+
async function result(sessionId, opts) {
|
|
2125
|
+
const ctx = validateContext(opts.context);
|
|
2126
|
+
if (!ctx.ok)
|
|
2127
|
+
return ctx;
|
|
2128
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
2129
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
2130
|
+
if (!loc.ok)
|
|
2131
|
+
return loc;
|
|
2132
|
+
const { directory, project } = loc;
|
|
2133
|
+
const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
|
|
2134
|
+
if (statusMapRes.res.ok) {
|
|
2135
|
+
try {
|
|
2136
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
2137
|
+
const entry = statusMap[sessionId];
|
|
2138
|
+
if (isStatusBusy(entry)) {
|
|
2139
|
+
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
2140
|
+
}
|
|
2141
|
+
} catch {}
|
|
2142
|
+
}
|
|
2143
|
+
const [messageRes, diffResult] = await Promise.all([
|
|
2144
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
|
|
2145
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
|
|
2146
|
+
]);
|
|
2147
|
+
if (!messageRes.res.ok) {
|
|
2148
|
+
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
2149
|
+
}
|
|
2150
|
+
let messages;
|
|
2151
|
+
try {
|
|
2152
|
+
messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
|
|
2153
|
+
} catch (e) {
|
|
2154
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
2155
|
+
}
|
|
2156
|
+
const { diff, diffSource } = diffResult;
|
|
2157
|
+
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
2158
|
+
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
2159
|
+
`).trim() : "";
|
|
2160
|
+
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
2161
|
+
}
|
|
2162
|
+
async function mapWithConcurrency(items, concurrency, fn) {
|
|
2163
|
+
const results = new Array(items.length);
|
|
2164
|
+
let next = 0;
|
|
2165
|
+
const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
|
|
2166
|
+
const workers = Array.from({ length: limit }, async () => {
|
|
2167
|
+
while (true) {
|
|
2168
|
+
const i = next++;
|
|
2169
|
+
if (i >= items.length)
|
|
2170
|
+
return;
|
|
2171
|
+
results[i] = await fn(items[i]);
|
|
2172
|
+
}
|
|
2173
|
+
});
|
|
2174
|
+
await Promise.all(workers);
|
|
2175
|
+
return results;
|
|
2176
|
+
}
|
|
2177
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 60000;
|
|
2178
|
+
var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
|
|
2179
|
+
var DEFAULT_WAIT_CONCURRENCY = 4;
|
|
2180
|
+
var NEEDS_ATTENTION_STATES = [
|
|
2181
|
+
"complete",
|
|
2182
|
+
"blocked",
|
|
2183
|
+
"failed",
|
|
2184
|
+
"not_found"
|
|
2185
|
+
];
|
|
2186
|
+
function sleep(ms) {
|
|
2187
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2188
|
+
}
|
|
2189
|
+
async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
|
|
2190
|
+
const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
|
|
2191
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
|
|
2192
|
+
return { id, loc };
|
|
2193
|
+
});
|
|
2194
|
+
const locationById = new Map;
|
|
2195
|
+
for (const { id, loc } of locations) {
|
|
2196
|
+
locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
|
|
2197
|
+
}
|
|
2198
|
+
const groups = new Map;
|
|
2199
|
+
for (const id of sessionIds) {
|
|
2200
|
+
const loc = locationById.get(id);
|
|
2201
|
+
if (!loc)
|
|
2202
|
+
continue;
|
|
2203
|
+
const group = groups.get(loc.directory) ?? {
|
|
2204
|
+
directory: loc.directory,
|
|
2205
|
+
sessionIds: []
|
|
2206
|
+
};
|
|
2207
|
+
group.sessionIds.push(id);
|
|
2208
|
+
groups.set(loc.directory, group);
|
|
2209
|
+
}
|
|
2210
|
+
const lastKnown = new Map;
|
|
2211
|
+
for (const id of sessionIds) {
|
|
2212
|
+
const loc = locationById.get(id);
|
|
2213
|
+
lastKnown.set(id, {
|
|
2214
|
+
sessionId: id,
|
|
2215
|
+
project: loc?.project ?? "",
|
|
2216
|
+
state: loc ? "running" : "not_found",
|
|
2217
|
+
resultAvailable: false
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
return { locationById, groupList: Array.from(groups.values()), lastKnown };
|
|
2221
|
+
}
|
|
2222
|
+
async function wait(sessionIds, opts) {
|
|
2223
|
+
const ctx = validateContext(opts.context);
|
|
2224
|
+
if (!ctx.ok)
|
|
2225
|
+
return ctx;
|
|
2226
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
2227
|
+
const uniqueIds = Array.from(new Set(sessionIds));
|
|
2228
|
+
if (uniqueIds.length === 0) {
|
|
2229
|
+
return { ok: true, sessions: [], waker: [], timedOut: true };
|
|
2230
|
+
}
|
|
2231
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
2232
|
+
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
|
|
2233
|
+
const deadline = Date.now() + timeoutMs;
|
|
2234
|
+
const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
|
|
2235
|
+
async function pollGroup(group) {
|
|
2236
|
+
const [statusRes, questionRes] = await Promise.all([
|
|
2237
|
+
api(baseUrl, credentials, group.directory, "/session/status"),
|
|
2238
|
+
api(baseUrl, credentials, group.directory, "/question")
|
|
2239
|
+
]);
|
|
2240
|
+
if (!statusRes.res.ok)
|
|
2241
|
+
return;
|
|
2242
|
+
let statusMap;
|
|
2243
|
+
try {
|
|
2244
|
+
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
2245
|
+
} catch {
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
const pendingBySession = parsePendingQuestions(questionRes);
|
|
2249
|
+
for (const id of group.sessionIds) {
|
|
2250
|
+
const entry = statusMap[id];
|
|
2251
|
+
const busy = isStatusBusy(entry);
|
|
2252
|
+
const pendingQuestion = pendingBySession.get(id);
|
|
2253
|
+
const state = deriveSessionState({
|
|
2254
|
+
busy,
|
|
2255
|
+
pendingQuestion,
|
|
2256
|
+
resolved: true
|
|
2257
|
+
});
|
|
2258
|
+
lastKnown.set(id, {
|
|
2259
|
+
sessionId: id,
|
|
2260
|
+
project: locationById.get(id)?.project ?? "",
|
|
2261
|
+
state,
|
|
2262
|
+
resultAvailable: state === "complete",
|
|
2263
|
+
pendingQuestion
|
|
2264
|
+
});
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
while (true) {
|
|
2268
|
+
await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
|
|
2269
|
+
const sessions = uniqueIds.map((id) => lastKnown.get(id));
|
|
2270
|
+
const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
|
|
2271
|
+
if (waker.length > 0) {
|
|
2272
|
+
return { ok: true, sessions, waker, timedOut: false };
|
|
2273
|
+
}
|
|
2274
|
+
if (Date.now() >= deadline) {
|
|
2275
|
+
return { ok: true, sessions, waker: [], timedOut: true };
|
|
2276
|
+
}
|
|
2277
|
+
const remaining = deadline - Date.now();
|
|
2278
|
+
await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
function parsePendingQuestions(questionRes) {
|
|
2282
|
+
if (!questionRes.res.ok)
|
|
2283
|
+
return new Map;
|
|
2284
|
+
try {
|
|
2285
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
|
|
2286
|
+
return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
|
|
2287
|
+
} catch {
|
|
2288
|
+
return new Map;
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
// src/server.ts
|
|
2293
|
+
import { spawn } from "node:child_process";
|
|
2294
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
2295
|
+
import { existsSync as existsSync2, openSync as openSync4, readFileSync as readFileSync5, realpathSync as realpathSync3 } from "node:fs";
|
|
2296
|
+
import { dirname } from "node:path";
|
|
2297
|
+
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
2298
|
+
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
2299
|
+
var POLL_INTERVAL_MS = 50;
|
|
2300
|
+
var MIN_PROBE_PHASE_MS = 3000;
|
|
2301
|
+
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
2302
|
+
var STOP_GRACE_MS = 2000;
|
|
2303
|
+
var SUPERVISE_INTERVAL_MS = 5000;
|
|
2304
|
+
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
2305
|
+
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
2306
|
+
function sleep2(ms) {
|
|
2307
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2308
|
+
}
|
|
2309
|
+
function readManifest2(rosterPath) {
|
|
2310
|
+
const raw = readFileSync5(rosterPath, "utf8");
|
|
2311
|
+
const json = JSON.parse(raw);
|
|
2312
|
+
return manifestSchema.parse(json);
|
|
2313
|
+
}
|
|
2314
|
+
function readLogTail(logPath, maxChars = 4000) {
|
|
2315
|
+
try {
|
|
2316
|
+
const content = readFileSync5(logPath, "utf8");
|
|
2317
|
+
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
2318
|
+
} catch {
|
|
2319
|
+
return "";
|
|
2363
2320
|
}
|
|
2364
|
-
return { ok: true, messageId };
|
|
2365
2321
|
}
|
|
2366
|
-
function
|
|
2367
|
-
|
|
2368
|
-
|
|
2322
|
+
function basicAuthToken(password) {
|
|
2323
|
+
return Buffer.from(`opencode:${password}`).toString("base64");
|
|
2324
|
+
}
|
|
2325
|
+
function redactSensitive(tail, password) {
|
|
2326
|
+
return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
|
|
2327
|
+
}
|
|
2328
|
+
function redactedReadinessError(rosterPath, password, reason) {
|
|
2329
|
+
const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
|
|
2330
|
+
return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
|
|
2331
|
+
${tail}`);
|
|
2332
|
+
}
|
|
2333
|
+
function isEpermError(err) {
|
|
2334
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "EPERM";
|
|
2335
|
+
}
|
|
2336
|
+
function signalGroup(pid, sig) {
|
|
2337
|
+
if (pid <= 1) {
|
|
2338
|
+
try {
|
|
2339
|
+
process.kill(pid, sig);
|
|
2340
|
+
} catch {}
|
|
2341
|
+
return false;
|
|
2369
2342
|
}
|
|
2370
|
-
|
|
2371
|
-
|
|
2343
|
+
try {
|
|
2344
|
+
process.kill(-pid, sig);
|
|
2345
|
+
return true;
|
|
2346
|
+
} catch (err) {
|
|
2347
|
+
if (err.code === "EPERM") {
|
|
2348
|
+
throw err;
|
|
2349
|
+
}
|
|
2372
2350
|
}
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2351
|
+
try {
|
|
2352
|
+
process.kill(pid, sig);
|
|
2353
|
+
} catch {}
|
|
2354
|
+
return false;
|
|
2355
|
+
}
|
|
2356
|
+
function signalGroupOnly(pid, sig) {
|
|
2357
|
+
if (pid <= 1)
|
|
2358
|
+
return false;
|
|
2359
|
+
try {
|
|
2360
|
+
process.kill(-pid, sig);
|
|
2361
|
+
return true;
|
|
2362
|
+
} catch {
|
|
2363
|
+
return false;
|
|
2379
2364
|
}
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2365
|
+
}
|
|
2366
|
+
function killIdentifiedProcess(pid, identity) {
|
|
2367
|
+
try {
|
|
2368
|
+
if (identity !== null && identity !== undefined && identity !== "") {
|
|
2369
|
+
if (verifyIdentity(pid, identity))
|
|
2370
|
+
signalGroup(pid, "SIGTERM");
|
|
2371
|
+
return;
|
|
2383
2372
|
}
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
prompt: input.prompt,
|
|
2387
|
-
title: input.title,
|
|
2388
|
-
project: input.project,
|
|
2389
|
-
onPendingQuestion: input.onPendingQuestion,
|
|
2390
|
-
...messageId !== undefined ? { messageId } : {}
|
|
2391
|
-
};
|
|
2392
|
-
}
|
|
2393
|
-
return {
|
|
2394
|
-
ok: true,
|
|
2395
|
-
prompt: input.prompt,
|
|
2396
|
-
title: input.title,
|
|
2397
|
-
sessionId: input.sessionId,
|
|
2398
|
-
project: input.project,
|
|
2399
|
-
onPendingQuestion: input.onPendingQuestion,
|
|
2400
|
-
...messageId !== undefined ? { messageId } : {}
|
|
2401
|
-
};
|
|
2373
|
+
process.kill(pid, "SIGTERM");
|
|
2374
|
+
} catch {}
|
|
2402
2375
|
}
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
if (!r.ok)
|
|
2406
|
-
return r;
|
|
2407
|
-
return {
|
|
2408
|
-
ok: true,
|
|
2409
|
-
sessionId: r.sessionId,
|
|
2410
|
-
project: r.project,
|
|
2411
|
-
mode: "new",
|
|
2412
|
-
directory: r.directory,
|
|
2413
|
-
...r.messageId !== undefined ? { messageId: r.messageId } : {}
|
|
2414
|
-
};
|
|
2376
|
+
function attachServer(rosterPath) {
|
|
2377
|
+
return attachLive(rosterPath);
|
|
2415
2378
|
}
|
|
2416
|
-
async function
|
|
2417
|
-
const
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
return err("space-bus: sessionId must be a non-empty string");
|
|
2428
|
-
}
|
|
2429
|
-
if (!args.sessionId) {
|
|
2430
|
-
if (!args.project) {
|
|
2431
|
-
return err("space-bus: project is required when starting a new session");
|
|
2379
|
+
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
2380
|
+
const deadline = Date.now() + budgetMs;
|
|
2381
|
+
const lockPath = lockFilePath(rosterPath);
|
|
2382
|
+
while (Date.now() < deadline) {
|
|
2383
|
+
const handle = attachServer(rosterPath);
|
|
2384
|
+
if (handle)
|
|
2385
|
+
return handle;
|
|
2386
|
+
const lockInfo = readLockFile(lockPath);
|
|
2387
|
+
const winnerAlive = lockInfo !== null && verifyIdentity(lockInfo.pid, lockInfo.startTime);
|
|
2388
|
+
if (!winnerAlive) {
|
|
2389
|
+
throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
|
|
2432
2390
|
}
|
|
2433
|
-
|
|
2434
|
-
...args,
|
|
2435
|
-
project: args.project
|
|
2436
|
-
});
|
|
2391
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2437
2392
|
}
|
|
2438
|
-
const
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2393
|
+
const lockInfo = readLockFile(lockPath);
|
|
2394
|
+
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
2395
|
+
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
2396
|
+
}
|
|
2397
|
+
async function probe(baseUrl, password) {
|
|
2398
|
+
try {
|
|
2399
|
+
const res = await fetch(`${baseUrl}/session?limit=1`, {
|
|
2400
|
+
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
2401
|
+
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
2402
|
+
});
|
|
2403
|
+
if (res.status === 200)
|
|
2404
|
+
return "ready";
|
|
2405
|
+
if (res.status === 401 || res.status === 403)
|
|
2406
|
+
return "auth-failure";
|
|
2407
|
+
return "retry";
|
|
2408
|
+
} catch {
|
|
2409
|
+
return "retry";
|
|
2444
2410
|
}
|
|
2445
|
-
return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project, args.onPendingQuestion ?? "question-reply", args.messageId);
|
|
2446
2411
|
}
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
2412
|
+
function childDied(child, pid) {
|
|
2413
|
+
return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
|
|
2414
|
+
}
|
|
2415
|
+
async function waitForReadinessLine(logPath, child, pid, deadline) {
|
|
2416
|
+
const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
|
|
2417
|
+
while (Date.now() < deadline) {
|
|
2418
|
+
if (childDied(child, pid))
|
|
2419
|
+
return null;
|
|
2420
|
+
const tail = readLogTail(logPath);
|
|
2421
|
+
const match = readinessLine.exec(tail);
|
|
2422
|
+
if (match?.[1]) {
|
|
2423
|
+
const port = Number.parseInt(match[1], 10);
|
|
2424
|
+
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
2425
|
+
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
2426
|
+
}
|
|
2463
2427
|
}
|
|
2464
|
-
|
|
2428
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2465
2429
|
}
|
|
2466
|
-
return
|
|
2467
|
-
}
|
|
2468
|
-
function deriveSessionState(input) {
|
|
2469
|
-
if (!input.resolved)
|
|
2470
|
-
return "not_found";
|
|
2471
|
-
if (input.failed)
|
|
2472
|
-
return "failed";
|
|
2473
|
-
if (input.pendingQuestion)
|
|
2474
|
-
return "blocked";
|
|
2475
|
-
if (input.busy)
|
|
2476
|
-
return "running";
|
|
2477
|
-
return "complete";
|
|
2430
|
+
return null;
|
|
2478
2431
|
}
|
|
2479
|
-
function
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2432
|
+
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
2433
|
+
while (Date.now() < deadline) {
|
|
2434
|
+
if (childDied(child, pid))
|
|
2435
|
+
return "died";
|
|
2436
|
+
const outcome = await probe(baseUrl, password);
|
|
2437
|
+
if (outcome === "ready")
|
|
2438
|
+
return "ready";
|
|
2439
|
+
if (outcome === "auth-failure")
|
|
2440
|
+
return "auth-failure";
|
|
2441
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2442
|
+
}
|
|
2443
|
+
return "timeout";
|
|
2485
2444
|
}
|
|
2486
|
-
async function
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
}
|
|
2445
|
+
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
2446
|
+
const deadline = Date.now() + budgetMs;
|
|
2447
|
+
const logPath = logFilePath(rosterPath);
|
|
2448
|
+
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
2449
|
+
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
2450
|
+
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
2451
|
+
if (lineResult === null) {
|
|
2452
|
+
const diedEarly = childDied(child, pid);
|
|
2453
|
+
killIdentifiedProcess(pid, identity);
|
|
2454
|
+
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
2455
|
+
}
|
|
2456
|
+
const { port, baseUrl } = lineResult;
|
|
2457
|
+
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
2458
|
+
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
2459
|
+
if (outcome === "ready")
|
|
2460
|
+
return { port, baseUrl };
|
|
2461
|
+
killIdentifiedProcess(pid, identity);
|
|
2462
|
+
if (outcome === "died") {
|
|
2463
|
+
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
2464
|
+
}
|
|
2465
|
+
if (outcome === "auth-failure") {
|
|
2466
|
+
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
2467
|
+
}
|
|
2468
|
+
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
2469
|
+
}
|
|
2470
|
+
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
2471
|
+
function reapOrphanedProvisional(rosterPath) {
|
|
2472
|
+
const provisional = readProvisional(rosterPath);
|
|
2473
|
+
if (!provisional)
|
|
2474
|
+
return;
|
|
2475
|
+
const discovery = readDiscovery(rosterPath);
|
|
2476
|
+
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
2477
|
+
removeProvisional(rosterPath);
|
|
2498
2478
|
return;
|
|
2499
2479
|
}
|
|
2480
|
+
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
2481
|
+
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
2482
|
+
if (hasIdentity || isFresh) {
|
|
2483
|
+
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
2484
|
+
}
|
|
2485
|
+
removeProvisional(rosterPath);
|
|
2500
2486
|
}
|
|
2501
|
-
async function
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
const
|
|
2506
|
-
const
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2487
|
+
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
2488
|
+
reapOrphanedProvisional(rosterPath);
|
|
2489
|
+
const password = randomBytes4(32).toString("base64url");
|
|
2490
|
+
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
2491
|
+
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
2492
|
+
const requestedPort = managedConfig.port ?? 0;
|
|
2493
|
+
const logPath = logFilePath(rosterPath);
|
|
2494
|
+
const logFd = openSync4(logPath, "w", 384);
|
|
2495
|
+
let child;
|
|
2496
|
+
let pid;
|
|
2497
|
+
let spawnError;
|
|
2498
|
+
try {
|
|
2499
|
+
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
2500
|
+
cwd,
|
|
2501
|
+
detached: true,
|
|
2502
|
+
stdio: ["ignore", logFd, logFd],
|
|
2503
|
+
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
2504
|
+
});
|
|
2505
|
+
child.on("error", (err) => {
|
|
2506
|
+
spawnError = err;
|
|
2507
|
+
});
|
|
2508
|
+
child.unref();
|
|
2509
|
+
pid = child.pid;
|
|
2510
|
+
} finally {
|
|
2511
|
+
closeQuietly(logFd);
|
|
2519
2512
|
}
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2513
|
+
if (pid === undefined) {
|
|
2514
|
+
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
2515
|
+
}
|
|
2516
|
+
const identity = captureIdentity(pid);
|
|
2517
|
+
writeProvisional(rosterPath, {
|
|
2518
|
+
pid,
|
|
2519
|
+
identity: identity ?? "",
|
|
2520
|
+
password,
|
|
2521
|
+
since: Date.now()
|
|
2522
|
+
});
|
|
2523
|
+
let port;
|
|
2524
|
+
let baseUrl;
|
|
2523
2525
|
try {
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2526
|
+
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
2527
|
+
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
2528
|
+
const check = setInterval(() => {
|
|
2529
|
+
if (spawnError) {
|
|
2530
|
+
clearInterval(check);
|
|
2531
|
+
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
2532
|
+
}
|
|
2533
|
+
}, POLL_INTERVAL_MS);
|
|
2534
|
+
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
2535
|
+
});
|
|
2536
|
+
const result = await Promise.race([readiness, spawnErrorWatch]);
|
|
2537
|
+
port = result.port;
|
|
2538
|
+
baseUrl = result.baseUrl;
|
|
2539
|
+
} finally {
|
|
2540
|
+
removeProvisional(rosterPath);
|
|
2529
2541
|
}
|
|
2530
|
-
const
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2542
|
+
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
2543
|
+
writeDiscovery(rosterPath, {
|
|
2544
|
+
port,
|
|
2545
|
+
pid,
|
|
2546
|
+
identity: finalIdentity,
|
|
2547
|
+
password,
|
|
2548
|
+
spawnConfig: { command, cwd, port: requestedPort },
|
|
2549
|
+
baseUrl,
|
|
2550
|
+
rosterPath
|
|
2551
|
+
});
|
|
2536
2552
|
return {
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
title: session.title,
|
|
2542
|
-
todos,
|
|
2543
|
-
diff: { files: diff.length, additions, deletions },
|
|
2544
|
-
diffSource,
|
|
2545
|
-
pendingQuestion,
|
|
2546
|
-
state,
|
|
2547
|
-
resultAvailable: state === "complete"
|
|
2553
|
+
baseUrl,
|
|
2554
|
+
credentials: { username: "opencode", password },
|
|
2555
|
+
pid,
|
|
2556
|
+
port
|
|
2548
2557
|
};
|
|
2549
2558
|
}
|
|
2550
|
-
async function
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2559
|
+
async function ensureServer(rosterPath, options = {}) {
|
|
2560
|
+
if (existsSync2(rosterPath)) {
|
|
2561
|
+
rosterPath = realpathSync3(rosterPath);
|
|
2562
|
+
}
|
|
2563
|
+
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
2564
|
+
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
2565
|
+
const fastPath = attachServer(rosterPath);
|
|
2566
|
+
if (fastPath)
|
|
2567
|
+
return fastPath;
|
|
2568
|
+
const manifest = readManifest2(rosterPath);
|
|
2569
|
+
if (manifest.server.managed === undefined) {
|
|
2570
|
+
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
2571
|
+
}
|
|
2572
|
+
const lock = acquireLock(rosterPath);
|
|
2573
|
+
if (lock === null) {
|
|
2574
|
+
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
2557
2575
|
}
|
|
2558
|
-
let pendingList;
|
|
2559
2576
|
try {
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2577
|
+
const attached = attachServer(rosterPath);
|
|
2578
|
+
if (attached)
|
|
2579
|
+
return attached;
|
|
2580
|
+
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
2581
|
+
} finally {
|
|
2582
|
+
releaseLock(lock);
|
|
2566
2583
|
}
|
|
2567
|
-
return {
|
|
2568
|
-
ok: true,
|
|
2569
|
-
pending: pendingList.find((q) => q.sessionID === sessionId)
|
|
2570
|
-
};
|
|
2571
2584
|
}
|
|
2572
|
-
|
|
2573
|
-
const
|
|
2574
|
-
if (!
|
|
2575
|
-
return
|
|
2576
|
-
const { pending } = pendingRes;
|
|
2577
|
-
if (pending && onPendingQuestion === "blocked") {
|
|
2578
|
-
return {
|
|
2579
|
-
ok: true,
|
|
2580
|
-
sessionId,
|
|
2581
|
-
project,
|
|
2582
|
-
mode: "blocked",
|
|
2583
|
-
requestId: pending.id
|
|
2584
|
-
};
|
|
2585
|
+
function serverStatus(rosterPath) {
|
|
2586
|
+
const discovery = readDiscovery(rosterPath);
|
|
2587
|
+
if (!discovery) {
|
|
2588
|
+
return { running: false };
|
|
2585
2589
|
}
|
|
2586
|
-
if (
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
2591
|
+
removeDiscoveryIfMatches(rosterPath, {
|
|
2592
|
+
pid: discovery.pid,
|
|
2593
|
+
identity: discovery.identity
|
|
2590
2594
|
});
|
|
2591
|
-
|
|
2592
|
-
return dispatchErr(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`, { phase: "indeterminate", project, sessionId });
|
|
2593
|
-
}
|
|
2594
|
-
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
2595
|
-
}
|
|
2596
|
-
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
2597
|
-
method: "POST",
|
|
2598
|
-
body: JSON.stringify({
|
|
2599
|
-
parts: [{ type: "text", text: message }],
|
|
2600
|
-
...messageId !== undefined ? { messageID: messageId } : {}
|
|
2601
|
-
})
|
|
2602
|
-
});
|
|
2603
|
-
if (promptRes.res.status !== 204) {
|
|
2604
|
-
return dispatchErr(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId, messageId });
|
|
2595
|
+
return { running: false };
|
|
2605
2596
|
}
|
|
2597
|
+
let configDrift;
|
|
2598
|
+
try {
|
|
2599
|
+
const manifest = readManifest2(rosterPath);
|
|
2600
|
+
if (manifest.server.managed) {
|
|
2601
|
+
const current = manifest.server.managed;
|
|
2602
|
+
const currentCommand = current.command ?? ["harness", "serve"];
|
|
2603
|
+
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
2604
|
+
const currentPort = current.port ?? 0;
|
|
2605
|
+
const storedCommand = discovery.spawnConfig.command ?? [
|
|
2606
|
+
"harness",
|
|
2607
|
+
"serve"
|
|
2608
|
+
];
|
|
2609
|
+
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
2610
|
+
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
2611
|
+
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
2612
|
+
}
|
|
2613
|
+
} catch {}
|
|
2606
2614
|
return {
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
...messageId !== undefined ? { messageId } : {}
|
|
2615
|
+
running: true,
|
|
2616
|
+
port: discovery.port,
|
|
2617
|
+
pid: discovery.pid,
|
|
2618
|
+
configDrift
|
|
2612
2619
|
};
|
|
2613
2620
|
}
|
|
2614
|
-
async function
|
|
2615
|
-
const
|
|
2616
|
-
if (!
|
|
2617
|
-
return
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
return
|
|
2622
|
-
|
|
2623
|
-
const
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
}
|
|
2631
|
-
}
|
|
2621
|
+
async function stopServer(rosterPath) {
|
|
2622
|
+
const discovery = readDiscovery(rosterPath);
|
|
2623
|
+
if (!discovery)
|
|
2624
|
+
return { stopped: false };
|
|
2625
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
2626
|
+
await reapSurvivingGroup(discovery.pid);
|
|
2627
|
+
removeDiscovery(rosterPath);
|
|
2628
|
+
return { stopped: false };
|
|
2629
|
+
}
|
|
2630
|
+
const { pid } = discovery;
|
|
2631
|
+
let groupSignaled;
|
|
2632
|
+
const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
|
|
2633
|
+
try {
|
|
2634
|
+
groupSignaled = signalGroup(pid, "SIGTERM");
|
|
2635
|
+
} catch (err) {
|
|
2636
|
+
if (isEpermError(err)) {
|
|
2637
|
+
return { stopped: false };
|
|
2638
|
+
}
|
|
2639
|
+
removeDiscovery(rosterPath);
|
|
2640
|
+
return { stopped: true };
|
|
2632
2641
|
}
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
]);
|
|
2637
|
-
if (!messageRes.res.ok) {
|
|
2638
|
-
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
2642
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
2643
|
+
removeDiscovery(rosterPath);
|
|
2644
|
+
return { stopped: true };
|
|
2639
2645
|
}
|
|
2640
|
-
let messages;
|
|
2641
2646
|
try {
|
|
2642
|
-
|
|
2643
|
-
} catch (
|
|
2644
|
-
|
|
2647
|
+
groupSignaled = signalGroup(pid, "SIGKILL");
|
|
2648
|
+
} catch (err) {
|
|
2649
|
+
if (isEpermError(err)) {
|
|
2650
|
+
return { stopped: false };
|
|
2651
|
+
}
|
|
2652
|
+
removeDiscovery(rosterPath);
|
|
2653
|
+
return { stopped: true };
|
|
2645
2654
|
}
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
return {
|
|
2655
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
2656
|
+
removeDiscovery(rosterPath);
|
|
2657
|
+
return { stopped: true };
|
|
2658
|
+
}
|
|
2659
|
+
return { stopped: false };
|
|
2651
2660
|
}
|
|
2652
|
-
async function
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2661
|
+
async function reapSurvivingGroup(pid) {
|
|
2662
|
+
try {
|
|
2663
|
+
if (isAlive(pid))
|
|
2664
|
+
return;
|
|
2665
|
+
let groupAlive;
|
|
2666
|
+
try {
|
|
2667
|
+
process.kill(-pid, 0);
|
|
2668
|
+
groupAlive = true;
|
|
2669
|
+
} catch {
|
|
2670
|
+
groupAlive = false;
|
|
2662
2671
|
}
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2672
|
+
if (!groupAlive)
|
|
2673
|
+
return;
|
|
2674
|
+
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
2675
|
+
return;
|
|
2676
|
+
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
2677
|
+
return;
|
|
2678
|
+
signalGroupOnly(pid, "SIGKILL");
|
|
2679
|
+
await waitForGroupDeath(pid, STOP_GRACE_MS);
|
|
2680
|
+
} catch {}
|
|
2666
2681
|
}
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
"
|
|
2672
|
-
"blocked",
|
|
2673
|
-
"failed",
|
|
2674
|
-
"not_found"
|
|
2675
|
-
];
|
|
2676
|
-
function sleep2(ms) {
|
|
2677
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2682
|
+
async function stopForHung(tick) {
|
|
2683
|
+
try {
|
|
2684
|
+
await tick.stop(tick.rosterPath);
|
|
2685
|
+
} catch {}
|
|
2686
|
+
return { kind: "outcome", outcome: { reason: "hung" } };
|
|
2678
2687
|
}
|
|
2679
|
-
async function
|
|
2680
|
-
const
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
const locationById = new Map;
|
|
2685
|
-
for (const { id, loc } of locations) {
|
|
2686
|
-
locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
|
|
2688
|
+
async function superviseTick(tick, state) {
|
|
2689
|
+
const st = tick.status(tick.rosterPath);
|
|
2690
|
+
if (!st.running) {
|
|
2691
|
+
await reapSurvivingGroup(tick.handle.pid);
|
|
2692
|
+
return { kind: "outcome", outcome: { reason: "died" } };
|
|
2687
2693
|
}
|
|
2688
|
-
const
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
const group = groups.get(loc.directory) ?? {
|
|
2694
|
-
directory: loc.directory,
|
|
2695
|
-
sessionIds: []
|
|
2696
|
-
};
|
|
2697
|
-
group.sessionIds.push(id);
|
|
2698
|
-
groups.set(loc.directory, group);
|
|
2694
|
+
const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
|
|
2695
|
+
const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
|
|
2696
|
+
const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
|
|
2697
|
+
if (failures >= tick.threshold) {
|
|
2698
|
+
return stopForHung(tick);
|
|
2699
2699
|
}
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
const loc = locationById.get(id);
|
|
2703
|
-
lastKnown.set(id, {
|
|
2704
|
-
sessionId: id,
|
|
2705
|
-
project: loc?.project ?? "",
|
|
2706
|
-
state: loc ? "running" : "not_found",
|
|
2707
|
-
resultAvailable: false
|
|
2708
|
-
});
|
|
2700
|
+
if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
|
|
2701
|
+
return stopForHung(tick);
|
|
2709
2702
|
}
|
|
2710
|
-
return {
|
|
2703
|
+
return { kind: "tick", failures, lastReadyAt };
|
|
2711
2704
|
}
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2705
|
+
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
2706
|
+
return {
|
|
2707
|
+
rosterPath,
|
|
2708
|
+
handle,
|
|
2709
|
+
password: handle.credentials.password ?? "",
|
|
2710
|
+
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
2711
|
+
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
2712
|
+
now: opts.now ?? Date.now,
|
|
2713
|
+
status: opts.status ?? serverStatus,
|
|
2714
|
+
probe: opts.probe ?? probe,
|
|
2715
|
+
stop: opts.stop ?? stopServer
|
|
2716
|
+
};
|
|
2717
|
+
}
|
|
2718
|
+
async function interruptibleSleep(doSleep, intervalMs, interrupt) {
|
|
2719
|
+
if (!interrupt) {
|
|
2720
|
+
await doSleep(intervalMs);
|
|
2721
|
+
return;
|
|
2720
2722
|
}
|
|
2721
|
-
|
|
2722
|
-
const
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
if (!statusRes.res.ok)
|
|
2731
|
-
return;
|
|
2732
|
-
let statusMap;
|
|
2733
|
-
try {
|
|
2734
|
-
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
2735
|
-
} catch {
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
const pendingBySession = parsePendingQuestions(questionRes);
|
|
2739
|
-
for (const id of group.sessionIds) {
|
|
2740
|
-
const entry = statusMap[id];
|
|
2741
|
-
const busy = isStatusBusy(entry);
|
|
2742
|
-
const pendingQuestion = pendingBySession.get(id);
|
|
2743
|
-
const state = deriveSessionState({
|
|
2744
|
-
busy,
|
|
2745
|
-
pendingQuestion,
|
|
2746
|
-
resolved: true
|
|
2747
|
-
});
|
|
2748
|
-
lastKnown.set(id, {
|
|
2749
|
-
sessionId: id,
|
|
2750
|
-
project: locationById.get(id)?.project ?? "",
|
|
2751
|
-
state,
|
|
2752
|
-
resultAvailable: state === "complete",
|
|
2753
|
-
pendingQuestion
|
|
2754
|
-
});
|
|
2755
|
-
}
|
|
2723
|
+
let timer;
|
|
2724
|
+
const timed = new Promise((resolve) => {
|
|
2725
|
+
timer = setTimeout(resolve, intervalMs);
|
|
2726
|
+
});
|
|
2727
|
+
try {
|
|
2728
|
+
await Promise.race([timed, interrupt]);
|
|
2729
|
+
} finally {
|
|
2730
|
+
if (timer !== undefined)
|
|
2731
|
+
clearTimeout(timer);
|
|
2756
2732
|
}
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
const
|
|
2768
|
-
|
|
2733
|
+
}
|
|
2734
|
+
async function superviseServer(rosterPath, handle, opts = {}) {
|
|
2735
|
+
const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
|
|
2736
|
+
const tick = makeSuperviseTick(rosterPath, handle, opts);
|
|
2737
|
+
const doSleep = opts.sleep ?? sleep2;
|
|
2738
|
+
const shouldStop = opts.shouldStop ?? (() => false);
|
|
2739
|
+
let state = { failures: 0, lastReadyAt: tick.now() };
|
|
2740
|
+
for (;; ) {
|
|
2741
|
+
if (shouldStop())
|
|
2742
|
+
return { reason: "signal" };
|
|
2743
|
+
const result = await superviseTick(tick, state);
|
|
2744
|
+
if (result.kind === "outcome")
|
|
2745
|
+
return result.outcome;
|
|
2746
|
+
state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
|
|
2747
|
+
if (shouldStop())
|
|
2748
|
+
return { reason: "signal" };
|
|
2749
|
+
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
2769
2750
|
}
|
|
2770
2751
|
}
|
|
2771
|
-
function
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
}
|
|
2778
|
-
|
|
2752
|
+
async function waitForDeath(pid, budgetMs) {
|
|
2753
|
+
const deadline = Date.now() + budgetMs;
|
|
2754
|
+
while (Date.now() < deadline) {
|
|
2755
|
+
if (!isAlive(pid))
|
|
2756
|
+
return true;
|
|
2757
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2758
|
+
}
|
|
2759
|
+
return !isAlive(pid);
|
|
2760
|
+
}
|
|
2761
|
+
async function waitForGroupDeath(pid, budgetMs) {
|
|
2762
|
+
const deadline = Date.now() + budgetMs;
|
|
2763
|
+
const groupAlive = () => {
|
|
2764
|
+
try {
|
|
2765
|
+
process.kill(-pid, 0);
|
|
2766
|
+
return true;
|
|
2767
|
+
} catch {
|
|
2768
|
+
return false;
|
|
2769
|
+
}
|
|
2770
|
+
};
|
|
2771
|
+
while (Date.now() < deadline) {
|
|
2772
|
+
if (!groupAlive())
|
|
2773
|
+
return true;
|
|
2774
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2779
2775
|
}
|
|
2776
|
+
return !groupAlive();
|
|
2780
2777
|
}
|
|
2781
2778
|
|
|
2782
2779
|
// src/tools/shared.ts
|
|
@@ -2785,12 +2782,12 @@ async function ensureAndLoadContext(directory, rosterName, ensure = ensureServer
|
|
|
2785
2782
|
const resolved = resolveRosterByName(rosterName);
|
|
2786
2783
|
if (!resolved.ok)
|
|
2787
2784
|
throw new Error(resolved.error);
|
|
2788
|
-
const
|
|
2789
|
-
if (isManagedRosterAtPath(
|
|
2790
|
-
await ensure(
|
|
2785
|
+
const rosterPath = resolved.path;
|
|
2786
|
+
if (isManagedRosterAtPath(rosterPath)) {
|
|
2787
|
+
await ensure(rosterPath);
|
|
2791
2788
|
}
|
|
2792
|
-
const context = loadContextForRosterPath(
|
|
2793
|
-
return { context, rosterName: resolved.name, rosterPath
|
|
2789
|
+
const context = loadContextForRosterPath(rosterPath);
|
|
2790
|
+
return { context, rosterName: resolved.name, rosterPath };
|
|
2794
2791
|
}
|
|
2795
2792
|
const rosterPath = resolveRosterPath(directory);
|
|
2796
2793
|
if (isManagedRoster(directory)) {
|