@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/mcp.js
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
4
4
|
|
|
5
|
+
// src/mcp.ts
|
|
6
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
8
|
+
import { z as z5 } from "zod";
|
|
9
|
+
|
|
5
10
|
// src/config.ts
|
|
6
11
|
import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
|
|
7
12
|
import { homedir as homedir3 } from "node:os";
|
|
@@ -718,7 +723,7 @@ function registerRoster(name, rosterPath) {
|
|
|
718
723
|
if (!readResult.ok)
|
|
719
724
|
return readResult;
|
|
720
725
|
const registry = readResult.registry;
|
|
721
|
-
const collision = registry.rosters.find((
|
|
726
|
+
const collision = registry.rosters.find((entry) => entry.name.toLowerCase() === name.toLowerCase());
|
|
722
727
|
if (collision) {
|
|
723
728
|
return {
|
|
724
729
|
ok: false,
|
|
@@ -965,1259 +970,1254 @@ function isManagedRoster(directory) {
|
|
|
965
970
|
return manifest.server.managed !== undefined;
|
|
966
971
|
}
|
|
967
972
|
|
|
968
|
-
// src/
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
import { existsSync as existsSync2, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
|
|
972
|
-
import { dirname } from "node:path";
|
|
973
|
-
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
974
|
-
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
975
|
-
var POLL_INTERVAL_MS = 50;
|
|
976
|
-
var MIN_PROBE_PHASE_MS = 3000;
|
|
977
|
-
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
978
|
-
var STOP_GRACE_MS = 2000;
|
|
979
|
-
var SUPERVISE_INTERVAL_MS = 5000;
|
|
980
|
-
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
981
|
-
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
982
|
-
function sleep(ms) {
|
|
983
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
984
|
-
}
|
|
985
|
-
function readManifest(rosterPath) {
|
|
986
|
-
const raw = readFileSync4(rosterPath, "utf8");
|
|
987
|
-
const json = JSON.parse(raw);
|
|
988
|
-
return manifestSchema.parse(json);
|
|
989
|
-
}
|
|
990
|
-
function readLogTail(logPath, maxChars = 4000) {
|
|
991
|
-
try {
|
|
992
|
-
const content = readFileSync4(logPath, "utf8");
|
|
993
|
-
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
994
|
-
} catch {
|
|
995
|
-
return "";
|
|
996
|
-
}
|
|
973
|
+
// src/core.ts
|
|
974
|
+
function findProject(projects, name) {
|
|
975
|
+
return projects.find((p) => p.name === name);
|
|
997
976
|
}
|
|
998
|
-
function
|
|
999
|
-
return
|
|
977
|
+
function err(error) {
|
|
978
|
+
return { ok: false, error };
|
|
1000
979
|
}
|
|
1001
|
-
function
|
|
1002
|
-
|
|
980
|
+
function dispatchErr(error, failure) {
|
|
981
|
+
const dispatchFailure = {
|
|
982
|
+
phase: failure.phase,
|
|
983
|
+
project: failure.project,
|
|
984
|
+
...failure.sessionId !== undefined ? { sessionId: failure.sessionId } : {},
|
|
985
|
+
...failure.messageId !== undefined ? { messageId: failure.messageId } : {}
|
|
986
|
+
};
|
|
987
|
+
return { ok: false, error, dispatchFailure };
|
|
1003
988
|
}
|
|
1004
|
-
function
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
989
|
+
function toBase64(s) {
|
|
990
|
+
const bytes = new TextEncoder().encode(s);
|
|
991
|
+
let bin = "";
|
|
992
|
+
for (const b of bytes)
|
|
993
|
+
bin += String.fromCharCode(b);
|
|
994
|
+
return btoa(bin);
|
|
1008
995
|
}
|
|
1009
|
-
function
|
|
1010
|
-
|
|
996
|
+
function authHeader(credentials) {
|
|
997
|
+
if (!credentials.password)
|
|
998
|
+
return {};
|
|
999
|
+
const username = credentials.username ?? "opencode";
|
|
1000
|
+
const token = toBase64(`${username}:${credentials.password}`);
|
|
1001
|
+
return { Authorization: `Basic ${token}` };
|
|
1011
1002
|
}
|
|
1012
|
-
function
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1003
|
+
async function api(baseUrl, credentials, directory, path, init) {
|
|
1004
|
+
try {
|
|
1005
|
+
const res = await fetch(`${baseUrl}${path}`, {
|
|
1006
|
+
...init,
|
|
1007
|
+
headers: {
|
|
1008
|
+
"content-type": "application/json",
|
|
1009
|
+
"x-opencode-directory": directory,
|
|
1010
|
+
...authHeader(credentials),
|
|
1011
|
+
...init?.headers
|
|
1012
|
+
},
|
|
1013
|
+
redirect: "error",
|
|
1014
|
+
signal: AbortSignal.timeout(30000)
|
|
1015
|
+
});
|
|
1016
|
+
const bodyText = await res.text().catch(() => "<unreadable body>");
|
|
1017
|
+
return { res, bodyText };
|
|
1018
|
+
} catch (e) {
|
|
1019
|
+
const message = e.message;
|
|
1020
|
+
return {
|
|
1021
|
+
res: new Response(null, {
|
|
1022
|
+
status: 599,
|
|
1023
|
+
statusText: "space-bus: request failed"
|
|
1024
|
+
}),
|
|
1025
|
+
bodyText: `space-bus: request failed: ${message}`
|
|
1026
|
+
};
|
|
1018
1027
|
}
|
|
1028
|
+
}
|
|
1029
|
+
async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
|
|
1030
|
+
const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
|
|
1031
|
+
if (!res.ok)
|
|
1032
|
+
return [];
|
|
1033
|
+
let messages;
|
|
1019
1034
|
try {
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1035
|
+
messages = turnMessageListSchema.parse(JSON.parse(bodyText));
|
|
1036
|
+
} catch {
|
|
1037
|
+
return [];
|
|
1038
|
+
}
|
|
1039
|
+
const byFile = new Map;
|
|
1040
|
+
for (const m of messages) {
|
|
1041
|
+
if (m.info.role !== "user")
|
|
1042
|
+
continue;
|
|
1043
|
+
const diffs = m.info.summary?.diffs;
|
|
1044
|
+
if (!diffs || diffs.length === 0)
|
|
1045
|
+
continue;
|
|
1046
|
+
for (const d of diffs) {
|
|
1047
|
+
const key = d.file ?? `<unknown:${byFile.size}>`;
|
|
1048
|
+
byFile.set(key, d);
|
|
1025
1049
|
}
|
|
1026
1050
|
}
|
|
1027
|
-
|
|
1028
|
-
process.kill(pid, sig);
|
|
1029
|
-
} catch {}
|
|
1030
|
-
return false;
|
|
1051
|
+
return Array.from(byFile.values());
|
|
1031
1052
|
}
|
|
1032
|
-
function
|
|
1033
|
-
|
|
1034
|
-
|
|
1053
|
+
async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
|
|
1054
|
+
const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
|
|
1055
|
+
let diff = [];
|
|
1035
1056
|
try {
|
|
1036
|
-
|
|
1037
|
-
return true;
|
|
1057
|
+
diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
|
|
1038
1058
|
} catch {
|
|
1039
|
-
|
|
1059
|
+
diff = [];
|
|
1060
|
+
}
|
|
1061
|
+
if (diff.length > 0) {
|
|
1062
|
+
return { diff, diffSource: "session" };
|
|
1040
1063
|
}
|
|
1041
|
-
}
|
|
1042
|
-
function killIdentifiedProcess(pid, identity) {
|
|
1043
1064
|
try {
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1065
|
+
const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
|
|
1066
|
+
if (sessionRes.res.ok) {
|
|
1067
|
+
const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
|
|
1068
|
+
const summaryDiffs = parsed.summary?.diffs;
|
|
1069
|
+
if (summaryDiffs && summaryDiffs.length > 0) {
|
|
1070
|
+
return { diff: summaryDiffs, diffSource: "session" };
|
|
1071
|
+
}
|
|
1048
1072
|
}
|
|
1049
|
-
process.kill(pid, "SIGTERM");
|
|
1050
1073
|
} catch {}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
}
|
|
1055
|
-
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
1056
|
-
const deadline = Date.now() + budgetMs;
|
|
1057
|
-
const lockPath = lockFilePath(rosterPath);
|
|
1058
|
-
while (Date.now() < deadline) {
|
|
1059
|
-
const handle = attachServer(rosterPath);
|
|
1060
|
-
if (handle)
|
|
1061
|
-
return handle;
|
|
1062
|
-
const lockInfo2 = readLockFile(lockPath);
|
|
1063
|
-
const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
|
|
1064
|
-
if (!winnerAlive) {
|
|
1065
|
-
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`);
|
|
1074
|
+
try {
|
|
1075
|
+
const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
|
|
1076
|
+
if (turnDiffs.length > 0) {
|
|
1077
|
+
return { diff: turnDiffs, diffSource: "turns" };
|
|
1066
1078
|
}
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1079
|
+
} catch {}
|
|
1080
|
+
try {
|
|
1081
|
+
const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
|
|
1082
|
+
if (vcsRes.res.ok) {
|
|
1083
|
+
const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
|
|
1084
|
+
if (vcsStatus.length > 0) {
|
|
1085
|
+
return {
|
|
1086
|
+
diff: vcsStatus.map((v) => ({
|
|
1087
|
+
file: v.file,
|
|
1088
|
+
additions: v.additions,
|
|
1089
|
+
deletions: v.deletions,
|
|
1090
|
+
status: v.status
|
|
1091
|
+
})),
|
|
1092
|
+
diffSource: "working-tree"
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
} catch {}
|
|
1097
|
+
return { diff, diffSource: "session" };
|
|
1072
1098
|
}
|
|
1073
|
-
|
|
1099
|
+
function validateContext(context) {
|
|
1100
|
+
const parsed = busContextSchema.safeParse(context);
|
|
1101
|
+
if (!parsed.success) {
|
|
1102
|
+
return err(`space-bus: invalid context: ${parsed.error.message}`);
|
|
1103
|
+
}
|
|
1104
|
+
const { roster, credentials } = parsed.data;
|
|
1105
|
+
let hostname;
|
|
1074
1106
|
try {
|
|
1075
|
-
|
|
1076
|
-
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
1077
|
-
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
1078
|
-
});
|
|
1079
|
-
if (res.status === 200)
|
|
1080
|
-
return "ready";
|
|
1081
|
-
if (res.status === 401 || res.status === 403)
|
|
1082
|
-
return "auth-failure";
|
|
1083
|
-
return "retry";
|
|
1107
|
+
hostname = new URL(roster.server.baseUrl).hostname;
|
|
1084
1108
|
} catch {
|
|
1085
|
-
return "
|
|
1109
|
+
return err("space-bus: context roster server.baseUrl is not a valid URL");
|
|
1110
|
+
}
|
|
1111
|
+
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
1112
|
+
return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
1086
1113
|
}
|
|
1114
|
+
return {
|
|
1115
|
+
ok: true,
|
|
1116
|
+
baseUrl: roster.server.baseUrl,
|
|
1117
|
+
projects: roster.projects,
|
|
1118
|
+
credentials: credentials ?? {}
|
|
1119
|
+
};
|
|
1087
1120
|
}
|
|
1088
|
-
function
|
|
1089
|
-
return
|
|
1121
|
+
function isStatusBusy(entry) {
|
|
1122
|
+
return entry?.type === "busy" || entry?.type === "retry" || false;
|
|
1090
1123
|
}
|
|
1091
|
-
|
|
1092
|
-
const
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
const tail = readLogTail(logPath);
|
|
1097
|
-
const match = readinessLine.exec(tail);
|
|
1098
|
-
if (match?.[1]) {
|
|
1099
|
-
const port = Number.parseInt(match[1], 10);
|
|
1100
|
-
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
1101
|
-
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1124
|
+
function resolveProjectOrErr(projects, name) {
|
|
1125
|
+
const project = findProject(projects, name);
|
|
1126
|
+
if (!project) {
|
|
1127
|
+
const valid = projects.map((p) => p.name).join(", ");
|
|
1128
|
+
return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
|
|
1105
1129
|
}
|
|
1106
|
-
|
|
1130
|
+
if (!project.exists) {
|
|
1131
|
+
return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
|
|
1132
|
+
}
|
|
1133
|
+
return { ok: true, project };
|
|
1107
1134
|
}
|
|
1108
|
-
async function
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
}
|
|
1121
|
-
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
1122
|
-
const deadline = Date.now() + budgetMs;
|
|
1123
|
-
const logPath = logFilePath(rosterPath);
|
|
1124
|
-
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
1125
|
-
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
1126
|
-
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
1127
|
-
if (lineResult === null) {
|
|
1128
|
-
const diedEarly = childDied(child, pid);
|
|
1129
|
-
killIdentifiedProcess(pid, identity);
|
|
1130
|
-
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
1131
|
-
}
|
|
1132
|
-
const { port, baseUrl } = lineResult;
|
|
1133
|
-
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
1134
|
-
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
1135
|
-
if (outcome === "ready")
|
|
1136
|
-
return { port, baseUrl };
|
|
1137
|
-
killIdentifiedProcess(pid, identity);
|
|
1138
|
-
if (outcome === "died") {
|
|
1139
|
-
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
1140
|
-
}
|
|
1141
|
-
if (outcome === "auth-failure") {
|
|
1142
|
-
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
1143
|
-
}
|
|
1144
|
-
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
1145
|
-
}
|
|
1146
|
-
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
1147
|
-
function reapOrphanedProvisional(rosterPath) {
|
|
1148
|
-
const provisional = readProvisional(rosterPath);
|
|
1149
|
-
if (!provisional)
|
|
1150
|
-
return;
|
|
1151
|
-
const discovery = readDiscovery(rosterPath);
|
|
1152
|
-
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1153
|
-
removeProvisional(rosterPath);
|
|
1154
|
-
return;
|
|
1155
|
-
}
|
|
1156
|
-
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
1157
|
-
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
1158
|
-
if (hasIdentity || isFresh) {
|
|
1159
|
-
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
1160
|
-
}
|
|
1161
|
-
removeProvisional(rosterPath);
|
|
1162
|
-
}
|
|
1163
|
-
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
1164
|
-
reapOrphanedProvisional(rosterPath);
|
|
1165
|
-
const password = randomBytes3(32).toString("base64url");
|
|
1166
|
-
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
1167
|
-
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
1168
|
-
const requestedPort = managedConfig.port ?? 0;
|
|
1169
|
-
const logPath = logFilePath(rosterPath);
|
|
1170
|
-
const logFd = openSync3(logPath, "w", 384);
|
|
1171
|
-
let child;
|
|
1172
|
-
let pid;
|
|
1173
|
-
let spawnError;
|
|
1174
|
-
try {
|
|
1175
|
-
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
1176
|
-
cwd,
|
|
1177
|
-
detached: true,
|
|
1178
|
-
stdio: ["ignore", logFd, logFd],
|
|
1179
|
-
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
1180
|
-
});
|
|
1181
|
-
child.on("error", (err) => {
|
|
1182
|
-
spawnError = err;
|
|
1183
|
-
});
|
|
1184
|
-
child.unref();
|
|
1185
|
-
pid = child.pid;
|
|
1186
|
-
} finally {
|
|
1187
|
-
closeQuietly(logFd);
|
|
1188
|
-
}
|
|
1189
|
-
if (pid === undefined) {
|
|
1190
|
-
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
1191
|
-
}
|
|
1192
|
-
const identity = captureIdentity(pid);
|
|
1193
|
-
writeProvisional(rosterPath, {
|
|
1194
|
-
pid,
|
|
1195
|
-
identity: identity ?? "",
|
|
1196
|
-
password,
|
|
1197
|
-
since: Date.now()
|
|
1198
|
-
});
|
|
1199
|
-
let port;
|
|
1200
|
-
let baseUrl;
|
|
1201
|
-
try {
|
|
1202
|
-
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
1203
|
-
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
1204
|
-
const check = setInterval(() => {
|
|
1205
|
-
if (spawnError) {
|
|
1206
|
-
clearInterval(check);
|
|
1207
|
-
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
1208
|
-
}
|
|
1209
|
-
}, POLL_INTERVAL_MS);
|
|
1210
|
-
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
1211
|
-
});
|
|
1212
|
-
const result = await Promise.race([readiness, spawnErrorWatch]);
|
|
1213
|
-
port = result.port;
|
|
1214
|
-
baseUrl = result.baseUrl;
|
|
1215
|
-
} finally {
|
|
1216
|
-
removeProvisional(rosterPath);
|
|
1217
|
-
}
|
|
1218
|
-
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
1219
|
-
writeDiscovery(rosterPath, {
|
|
1220
|
-
port,
|
|
1221
|
-
pid,
|
|
1222
|
-
identity: finalIdentity,
|
|
1223
|
-
password,
|
|
1224
|
-
spawnConfig: { command, cwd, port: requestedPort },
|
|
1225
|
-
baseUrl,
|
|
1226
|
-
rosterPath
|
|
1227
|
-
});
|
|
1228
|
-
return {
|
|
1229
|
-
baseUrl,
|
|
1230
|
-
credentials: { username: "opencode", password },
|
|
1231
|
-
pid,
|
|
1232
|
-
port
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
async function ensureServer(rosterPath, options = {}) {
|
|
1236
|
-
if (existsSync2(rosterPath)) {
|
|
1237
|
-
rosterPath = realpathSync3(rosterPath);
|
|
1238
|
-
}
|
|
1239
|
-
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
1240
|
-
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
1241
|
-
const fastPath = attachServer(rosterPath);
|
|
1242
|
-
if (fastPath)
|
|
1243
|
-
return fastPath;
|
|
1244
|
-
const manifest = readManifest(rosterPath);
|
|
1245
|
-
if (manifest.server.managed === undefined) {
|
|
1246
|
-
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
1247
|
-
}
|
|
1248
|
-
const lock = acquireLock(rosterPath);
|
|
1249
|
-
if (lock === null) {
|
|
1250
|
-
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
1251
|
-
}
|
|
1252
|
-
try {
|
|
1253
|
-
const attached = attachServer(rosterPath);
|
|
1254
|
-
if (attached)
|
|
1255
|
-
return attached;
|
|
1256
|
-
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
1257
|
-
} finally {
|
|
1258
|
-
releaseLock(lock);
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
function serverStatus(rosterPath) {
|
|
1262
|
-
const discovery = readDiscovery(rosterPath);
|
|
1263
|
-
if (!discovery) {
|
|
1264
|
-
return { running: false };
|
|
1265
|
-
}
|
|
1266
|
-
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1267
|
-
removeDiscoveryIfMatches(rosterPath, {
|
|
1268
|
-
pid: discovery.pid,
|
|
1269
|
-
identity: discovery.identity
|
|
1270
|
-
});
|
|
1271
|
-
return { running: false };
|
|
1272
|
-
}
|
|
1273
|
-
let configDrift;
|
|
1274
|
-
try {
|
|
1275
|
-
const manifest = readManifest(rosterPath);
|
|
1276
|
-
if (manifest.server.managed) {
|
|
1277
|
-
const current = manifest.server.managed;
|
|
1278
|
-
const currentCommand = current.command ?? ["harness", "serve"];
|
|
1279
|
-
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
1280
|
-
const currentPort = current.port ?? 0;
|
|
1281
|
-
const storedCommand = discovery.spawnConfig.command ?? [
|
|
1282
|
-
"harness",
|
|
1283
|
-
"serve"
|
|
1284
|
-
];
|
|
1285
|
-
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
1286
|
-
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
1287
|
-
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
1288
|
-
}
|
|
1289
|
-
} catch {}
|
|
1290
|
-
return {
|
|
1291
|
-
running: true,
|
|
1292
|
-
port: discovery.port,
|
|
1293
|
-
pid: discovery.pid,
|
|
1294
|
-
configDrift
|
|
1295
|
-
};
|
|
1296
|
-
}
|
|
1297
|
-
async function stopServer(rosterPath) {
|
|
1298
|
-
const discovery = readDiscovery(rosterPath);
|
|
1299
|
-
if (!discovery)
|
|
1300
|
-
return { stopped: false };
|
|
1301
|
-
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1302
|
-
await reapSurvivingGroup(discovery.pid);
|
|
1303
|
-
removeDiscovery(rosterPath);
|
|
1304
|
-
return { stopped: false };
|
|
1305
|
-
}
|
|
1306
|
-
const { pid } = discovery;
|
|
1307
|
-
let groupSignaled;
|
|
1308
|
-
const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
|
|
1309
|
-
try {
|
|
1310
|
-
groupSignaled = signalGroup(pid, "SIGTERM");
|
|
1311
|
-
} catch (err) {
|
|
1312
|
-
if (isEpermError(err)) {
|
|
1313
|
-
return { stopped: false };
|
|
1314
|
-
}
|
|
1315
|
-
removeDiscovery(rosterPath);
|
|
1316
|
-
return { stopped: true };
|
|
1317
|
-
}
|
|
1318
|
-
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
1319
|
-
removeDiscovery(rosterPath);
|
|
1320
|
-
return { stopped: true };
|
|
1321
|
-
}
|
|
1322
|
-
try {
|
|
1323
|
-
groupSignaled = signalGroup(pid, "SIGKILL");
|
|
1324
|
-
} catch (err) {
|
|
1325
|
-
if (isEpermError(err)) {
|
|
1326
|
-
return { stopped: false };
|
|
1135
|
+
async function roster(opts) {
|
|
1136
|
+
const ctx = validateContext(opts.context);
|
|
1137
|
+
if (!ctx.ok)
|
|
1138
|
+
return ctx;
|
|
1139
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1140
|
+
const results = await Promise.all(projects.map(async (p) => {
|
|
1141
|
+
if (!p.exists) {
|
|
1142
|
+
return {
|
|
1143
|
+
name: p.name,
|
|
1144
|
+
path: p.expandedPath,
|
|
1145
|
+
description: p.description,
|
|
1146
|
+
pathExists: false
|
|
1147
|
+
};
|
|
1327
1148
|
}
|
|
1328
|
-
removeDiscovery(rosterPath);
|
|
1329
|
-
return { stopped: true };
|
|
1330
|
-
}
|
|
1331
|
-
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
1332
|
-
removeDiscovery(rosterPath);
|
|
1333
|
-
return { stopped: true };
|
|
1334
|
-
}
|
|
1335
|
-
return { stopped: false };
|
|
1336
|
-
}
|
|
1337
|
-
async function reapSurvivingGroup(pid) {
|
|
1338
|
-
try {
|
|
1339
|
-
if (isAlive(pid))
|
|
1340
|
-
return;
|
|
1341
|
-
let groupAlive;
|
|
1342
1149
|
try {
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1150
|
+
const [statusRes, listRes] = await Promise.all([
|
|
1151
|
+
api(baseUrl, credentials, p.expandedPath, "/session/status"),
|
|
1152
|
+
api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
|
|
1153
|
+
]);
|
|
1154
|
+
if (!statusRes.res.ok || !listRes.res.ok) {
|
|
1155
|
+
return {
|
|
1156
|
+
name: p.name,
|
|
1157
|
+
path: p.expandedPath,
|
|
1158
|
+
description: p.description,
|
|
1159
|
+
pathExists: true,
|
|
1160
|
+
statusError: `status=${statusRes.res.status}/${listRes.res.status}`
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
1164
|
+
const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
|
|
1165
|
+
const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
|
|
1166
|
+
const capped = sessions.length > 100;
|
|
1167
|
+
return {
|
|
1168
|
+
name: p.name,
|
|
1169
|
+
path: p.expandedPath,
|
|
1170
|
+
description: p.description,
|
|
1171
|
+
pathExists: true,
|
|
1172
|
+
busyCount,
|
|
1173
|
+
sessionCount: capped ? 100 : sessions.length,
|
|
1174
|
+
sessionCountCapped: capped
|
|
1175
|
+
};
|
|
1176
|
+
} catch (e) {
|
|
1177
|
+
return {
|
|
1178
|
+
name: p.name,
|
|
1179
|
+
path: p.expandedPath,
|
|
1180
|
+
description: p.description,
|
|
1181
|
+
pathExists: true,
|
|
1182
|
+
statusError: e.message
|
|
1183
|
+
};
|
|
1347
1184
|
}
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
1351
|
-
return;
|
|
1352
|
-
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
1353
|
-
return;
|
|
1354
|
-
signalGroupOnly(pid, "SIGKILL");
|
|
1355
|
-
await waitForGroupDeath(pid, STOP_GRACE_MS);
|
|
1356
|
-
} catch {}
|
|
1357
|
-
}
|
|
1358
|
-
async function stopForHung(tick) {
|
|
1359
|
-
try {
|
|
1360
|
-
await tick.stop(tick.rosterPath);
|
|
1361
|
-
} catch {}
|
|
1362
|
-
return { kind: "outcome", outcome: { reason: "hung" } };
|
|
1363
|
-
}
|
|
1364
|
-
async function superviseTick(tick, state) {
|
|
1365
|
-
const st = tick.status(tick.rosterPath);
|
|
1366
|
-
if (!st.running) {
|
|
1367
|
-
await reapSurvivingGroup(tick.handle.pid);
|
|
1368
|
-
return { kind: "outcome", outcome: { reason: "died" } };
|
|
1369
|
-
}
|
|
1370
|
-
const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
|
|
1371
|
-
const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
|
|
1372
|
-
const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
|
|
1373
|
-
if (failures >= tick.threshold) {
|
|
1374
|
-
return stopForHung(tick);
|
|
1375
|
-
}
|
|
1376
|
-
if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
|
|
1377
|
-
return stopForHung(tick);
|
|
1378
|
-
}
|
|
1379
|
-
return { kind: "tick", failures, lastReadyAt };
|
|
1380
|
-
}
|
|
1381
|
-
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
1382
|
-
return {
|
|
1383
|
-
rosterPath,
|
|
1384
|
-
handle,
|
|
1385
|
-
password: handle.credentials.password ?? "",
|
|
1386
|
-
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
1387
|
-
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
1388
|
-
now: opts.now ?? Date.now,
|
|
1389
|
-
status: opts.status ?? serverStatus,
|
|
1390
|
-
probe: opts.probe ?? probe,
|
|
1391
|
-
stop: opts.stop ?? stopServer
|
|
1392
|
-
};
|
|
1185
|
+
}));
|
|
1186
|
+
return { ok: true, projects: results };
|
|
1393
1187
|
}
|
|
1394
|
-
async function
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
return;
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
const
|
|
1401
|
-
|
|
1188
|
+
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title, messageId) {
|
|
1189
|
+
const resolved = resolveProjectOrErr(projects, project);
|
|
1190
|
+
if (!resolved.ok)
|
|
1191
|
+
return resolved;
|
|
1192
|
+
const directory = resolved.project.expandedPath;
|
|
1193
|
+
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
1194
|
+
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
1195
|
+
method: "POST",
|
|
1196
|
+
body: JSON.stringify({ title: sessionTitle })
|
|
1402
1197
|
});
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
} finally {
|
|
1406
|
-
if (timer !== undefined)
|
|
1407
|
-
clearTimeout(timer);
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
async function superviseServer(rosterPath, handle, opts = {}) {
|
|
1411
|
-
const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
|
|
1412
|
-
const tick = makeSuperviseTick(rosterPath, handle, opts);
|
|
1413
|
-
const doSleep = opts.sleep ?? sleep;
|
|
1414
|
-
const shouldStop = opts.shouldStop ?? (() => false);
|
|
1415
|
-
let state = { failures: 0, lastReadyAt: tick.now() };
|
|
1416
|
-
for (;; ) {
|
|
1417
|
-
if (shouldStop())
|
|
1418
|
-
return { reason: "signal" };
|
|
1419
|
-
const result = await superviseTick(tick, state);
|
|
1420
|
-
if (result.kind === "outcome")
|
|
1421
|
-
return result.outcome;
|
|
1422
|
-
state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
|
|
1423
|
-
if (shouldStop())
|
|
1424
|
-
return { reason: "signal" };
|
|
1425
|
-
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
1198
|
+
if (!createRes.res.ok) {
|
|
1199
|
+
return dispatchErr(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`, { phase: "indeterminate", project, messageId });
|
|
1426
1200
|
}
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
return true;
|
|
1433
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1201
|
+
let session;
|
|
1202
|
+
try {
|
|
1203
|
+
session = sessionSchema.parse(JSON.parse(createRes.bodyText));
|
|
1204
|
+
} catch (e) {
|
|
1205
|
+
return dispatchErr(`space-bus: unexpected /session response shape: ${e.message}`, { phase: "indeterminate", project, messageId });
|
|
1434
1206
|
}
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
}
|
|
1444
|
-
return false;
|
|
1445
|
-
}
|
|
1446
|
-
};
|
|
1447
|
-
while (Date.now() < deadline) {
|
|
1448
|
-
if (!groupAlive())
|
|
1449
|
-
return true;
|
|
1450
|
-
await sleep(POLL_INTERVAL_MS);
|
|
1207
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
|
|
1208
|
+
method: "POST",
|
|
1209
|
+
body: JSON.stringify({
|
|
1210
|
+
parts: [{ type: "text", text: prompt }],
|
|
1211
|
+
...messageId !== undefined ? { messageID: messageId } : {}
|
|
1212
|
+
})
|
|
1213
|
+
});
|
|
1214
|
+
if (promptRes.res.status !== 204) {
|
|
1215
|
+
return dispatchErr(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId: session.id, messageId });
|
|
1451
1216
|
}
|
|
1452
|
-
return
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
// src/core.ts
|
|
1461
|
-
function findProject(projects, name) {
|
|
1462
|
-
return projects.find((p) => p.name === name);
|
|
1463
|
-
}
|
|
1464
|
-
function err(error) {
|
|
1465
|
-
return { ok: false, error };
|
|
1466
|
-
}
|
|
1467
|
-
function dispatchErr(error, failure) {
|
|
1468
|
-
const dispatchFailure = {
|
|
1469
|
-
phase: failure.phase,
|
|
1470
|
-
project: failure.project,
|
|
1471
|
-
...failure.sessionId !== undefined ? { sessionId: failure.sessionId } : {},
|
|
1472
|
-
...failure.messageId !== undefined ? { messageId: failure.messageId } : {}
|
|
1473
|
-
};
|
|
1474
|
-
return { ok: false, error, dispatchFailure };
|
|
1475
|
-
}
|
|
1476
|
-
function toBase64(s) {
|
|
1477
|
-
const bytes = new TextEncoder().encode(s);
|
|
1478
|
-
let bin = "";
|
|
1479
|
-
for (const b of bytes)
|
|
1480
|
-
bin += String.fromCharCode(b);
|
|
1481
|
-
return btoa(bin);
|
|
1217
|
+
return {
|
|
1218
|
+
ok: true,
|
|
1219
|
+
sessionId: session.id,
|
|
1220
|
+
project,
|
|
1221
|
+
directory,
|
|
1222
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1223
|
+
};
|
|
1482
1224
|
}
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1225
|
+
var MESSAGE_ID_PATTERN = /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
|
|
1226
|
+
var INVALID_MESSAGE_ID_ERROR = "space-bus: messageId must be msg_ followed by exactly 12 hex characters and 14 alphanumeric characters";
|
|
1227
|
+
function validateMessageId(messageId) {
|
|
1228
|
+
if (!MESSAGE_ID_PATTERN.test(messageId)) {
|
|
1229
|
+
return err(INVALID_MESSAGE_ID_ERROR);
|
|
1230
|
+
}
|
|
1231
|
+
return { ok: true, messageId };
|
|
1489
1232
|
}
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1233
|
+
function toDispatchArgs(input) {
|
|
1234
|
+
if (input.onPendingQuestion !== undefined && input.onPendingQuestion !== "question-reply" && input.onPendingQuestion !== "blocked") {
|
|
1235
|
+
return err(`space-bus: onPendingQuestion must be "question-reply" or "blocked", got ${JSON.stringify(input.onPendingQuestion)}`);
|
|
1236
|
+
}
|
|
1237
|
+
if (input.sessionId !== undefined && input.sessionId === "") {
|
|
1238
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1239
|
+
}
|
|
1240
|
+
let messageId;
|
|
1241
|
+
if (input.messageId !== undefined) {
|
|
1242
|
+
const validated = validateMessageId(input.messageId);
|
|
1243
|
+
if (!validated.ok)
|
|
1244
|
+
return validated;
|
|
1245
|
+
messageId = validated.messageId;
|
|
1246
|
+
}
|
|
1247
|
+
if (!input.sessionId) {
|
|
1248
|
+
if (!input.project) {
|
|
1249
|
+
return err("space-bus: project is required when starting a new session");
|
|
1250
|
+
}
|
|
1507
1251
|
return {
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1252
|
+
ok: true,
|
|
1253
|
+
prompt: input.prompt,
|
|
1254
|
+
title: input.title,
|
|
1255
|
+
project: input.project,
|
|
1256
|
+
onPendingQuestion: input.onPendingQuestion,
|
|
1257
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1513
1258
|
};
|
|
1514
1259
|
}
|
|
1260
|
+
return {
|
|
1261
|
+
ok: true,
|
|
1262
|
+
prompt: input.prompt,
|
|
1263
|
+
title: input.title,
|
|
1264
|
+
sessionId: input.sessionId,
|
|
1265
|
+
project: input.project,
|
|
1266
|
+
onPendingQuestion: input.onPendingQuestion,
|
|
1267
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1268
|
+
};
|
|
1515
1269
|
}
|
|
1516
|
-
async function
|
|
1517
|
-
const
|
|
1518
|
-
if (!
|
|
1519
|
-
return
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1270
|
+
async function dispatchNewBranch(baseUrl, credentials, projects, args) {
|
|
1271
|
+
const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title, args.messageId);
|
|
1272
|
+
if (!r.ok)
|
|
1273
|
+
return r;
|
|
1274
|
+
return {
|
|
1275
|
+
ok: true,
|
|
1276
|
+
sessionId: r.sessionId,
|
|
1277
|
+
project: r.project,
|
|
1278
|
+
mode: "new",
|
|
1279
|
+
directory: r.directory,
|
|
1280
|
+
...r.messageId !== undefined ? { messageId: r.messageId } : {}
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
async function dispatch(args, opts) {
|
|
1284
|
+
const ctx = validateContext(opts.context);
|
|
1285
|
+
if (!ctx.ok)
|
|
1286
|
+
return ctx;
|
|
1287
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1288
|
+
if (args.messageId !== undefined) {
|
|
1289
|
+
const validated = validateMessageId(args.messageId);
|
|
1290
|
+
if (!validated.ok)
|
|
1291
|
+
return validated;
|
|
1525
1292
|
}
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1293
|
+
if (args.sessionId !== undefined && args.sessionId === "") {
|
|
1294
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1295
|
+
}
|
|
1296
|
+
if (!args.sessionId) {
|
|
1297
|
+
if (!args.project) {
|
|
1298
|
+
return err("space-bus: project is required when starting a new session");
|
|
1299
|
+
}
|
|
1300
|
+
return dispatchNewBranch(baseUrl, credentials, projects, {
|
|
1301
|
+
...args,
|
|
1302
|
+
project: args.project
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
|
|
1306
|
+
if (!loc.ok)
|
|
1307
|
+
return loc;
|
|
1308
|
+
const { directory, project } = loc;
|
|
1309
|
+
if (args.project && args.project !== project) {
|
|
1310
|
+
return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
|
|
1311
|
+
}
|
|
1312
|
+
return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project, args.onPendingQuestion ?? "question-reply", args.messageId);
|
|
1313
|
+
}
|
|
1314
|
+
async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
|
|
1315
|
+
for (const p of projects) {
|
|
1316
|
+
if (!p.exists)
|
|
1529
1317
|
continue;
|
|
1530
|
-
const
|
|
1531
|
-
if (!
|
|
1318
|
+
const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
|
|
1319
|
+
if (!res.ok)
|
|
1532
1320
|
continue;
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1321
|
+
let session;
|
|
1322
|
+
try {
|
|
1323
|
+
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
1324
|
+
} catch {
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
1328
|
+
if (owner) {
|
|
1329
|
+
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
1536
1330
|
}
|
|
1331
|
+
return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
|
|
1537
1332
|
}
|
|
1538
|
-
return
|
|
1333
|
+
return err(`space-bus: no manifest project has a session with id ${sessionId}`);
|
|
1539
1334
|
}
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1335
|
+
function deriveSessionState(input) {
|
|
1336
|
+
if (!input.resolved)
|
|
1337
|
+
return "not_found";
|
|
1338
|
+
if (input.failed)
|
|
1339
|
+
return "failed";
|
|
1340
|
+
if (input.pendingQuestion)
|
|
1341
|
+
return "blocked";
|
|
1342
|
+
if (input.busy)
|
|
1343
|
+
return "running";
|
|
1344
|
+
return "complete";
|
|
1345
|
+
}
|
|
1346
|
+
function formatQuestionEntry(entry) {
|
|
1347
|
+
const firstQuestion = entry.questions?.[0];
|
|
1348
|
+
const text = firstQuestion?.question ?? "";
|
|
1349
|
+
const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
|
|
1350
|
+
const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
|
|
1351
|
+
return { sessionId: entry.sessionID, preview, options };
|
|
1352
|
+
}
|
|
1353
|
+
async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
|
|
1543
1354
|
try {
|
|
1544
|
-
|
|
1355
|
+
const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
|
|
1356
|
+
if (!res.ok)
|
|
1357
|
+
return;
|
|
1358
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
|
|
1359
|
+
const entry = entries.find((e) => e.sessionID === sessionId);
|
|
1360
|
+
if (!entry)
|
|
1361
|
+
return;
|
|
1362
|
+
const { preview, options } = formatQuestionEntry(entry);
|
|
1363
|
+
return { preview, options };
|
|
1545
1364
|
} catch {
|
|
1546
|
-
|
|
1365
|
+
return;
|
|
1547
1366
|
}
|
|
1548
|
-
|
|
1549
|
-
|
|
1367
|
+
}
|
|
1368
|
+
async function status(sessionId, opts) {
|
|
1369
|
+
const ctx = validateContext(opts.context);
|
|
1370
|
+
if (!ctx.ok)
|
|
1371
|
+
return ctx;
|
|
1372
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1373
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
1374
|
+
if (!loc.ok)
|
|
1375
|
+
return loc;
|
|
1376
|
+
const { directory, project } = loc;
|
|
1377
|
+
const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
|
|
1378
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
|
|
1379
|
+
api(baseUrl, credentials, directory, "/session/status"),
|
|
1380
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
|
|
1381
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
|
|
1382
|
+
fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
|
|
1383
|
+
]);
|
|
1384
|
+
if (!sessionRes.res.ok) {
|
|
1385
|
+
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
1550
1386
|
}
|
|
1387
|
+
let session;
|
|
1388
|
+
let statusMap;
|
|
1389
|
+
let todos;
|
|
1551
1390
|
try {
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1391
|
+
session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
|
|
1392
|
+
statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
|
|
1393
|
+
todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
|
|
1394
|
+
} catch (e) {
|
|
1395
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
1396
|
+
}
|
|
1397
|
+
const entry = statusMap[sessionId];
|
|
1398
|
+
const busy = isStatusBusy(entry);
|
|
1399
|
+
const { diff, diffSource } = diffResult;
|
|
1400
|
+
const additions = diff.reduce((sum, d) => sum + d.additions, 0);
|
|
1401
|
+
const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
|
|
1402
|
+
const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
|
|
1403
|
+
return {
|
|
1404
|
+
ok: true,
|
|
1405
|
+
sessionId,
|
|
1406
|
+
project,
|
|
1407
|
+
busy,
|
|
1408
|
+
title: session.title,
|
|
1409
|
+
todos,
|
|
1410
|
+
diff: { files: diff.length, additions, deletions },
|
|
1411
|
+
diffSource,
|
|
1412
|
+
pendingQuestion,
|
|
1413
|
+
state,
|
|
1414
|
+
resultAvailable: state === "complete"
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
async function resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, project, onPendingQuestion) {
|
|
1418
|
+
const questionsRes = await api(baseUrl, credentials, directory, "/question");
|
|
1419
|
+
if (!questionsRes.res.ok) {
|
|
1420
|
+
if (onPendingQuestion === "blocked") {
|
|
1421
|
+
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 });
|
|
1565
1422
|
}
|
|
1566
|
-
|
|
1423
|
+
return { ok: true, pending: undefined };
|
|
1424
|
+
}
|
|
1425
|
+
let pendingList;
|
|
1567
1426
|
try {
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
return {
|
|
1573
|
-
diff: vcsStatus.map((v) => ({
|
|
1574
|
-
file: v.file,
|
|
1575
|
-
additions: v.additions,
|
|
1576
|
-
deletions: v.deletions,
|
|
1577
|
-
status: v.status
|
|
1578
|
-
})),
|
|
1579
|
-
diffSource: "working-tree"
|
|
1580
|
-
};
|
|
1581
|
-
}
|
|
1427
|
+
pendingList = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
|
|
1428
|
+
} catch (e) {
|
|
1429
|
+
if (onPendingQuestion === "blocked") {
|
|
1430
|
+
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 });
|
|
1582
1431
|
}
|
|
1583
|
-
|
|
1584
|
-
|
|
1432
|
+
return { ok: true, pending: undefined };
|
|
1433
|
+
}
|
|
1434
|
+
return {
|
|
1435
|
+
ok: true,
|
|
1436
|
+
pending: pendingList.find((q) => q.sessionID === sessionId)
|
|
1437
|
+
};
|
|
1585
1438
|
}
|
|
1586
|
-
function
|
|
1587
|
-
const
|
|
1588
|
-
if (!
|
|
1589
|
-
return
|
|
1439
|
+
async function steerSession(baseUrl, credentials, sessionId, message, directory, project, onPendingQuestion, messageId) {
|
|
1440
|
+
const pendingRes = await resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, project, onPendingQuestion);
|
|
1441
|
+
if (!pendingRes.ok)
|
|
1442
|
+
return pendingRes;
|
|
1443
|
+
const { pending } = pendingRes;
|
|
1444
|
+
if (pending && onPendingQuestion === "blocked") {
|
|
1445
|
+
return {
|
|
1446
|
+
ok: true,
|
|
1447
|
+
sessionId,
|
|
1448
|
+
project,
|
|
1449
|
+
mode: "blocked",
|
|
1450
|
+
requestId: pending.id
|
|
1451
|
+
};
|
|
1590
1452
|
}
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1453
|
+
if (pending) {
|
|
1454
|
+
const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
|
|
1455
|
+
method: "POST",
|
|
1456
|
+
body: JSON.stringify({ answers: [[message]] })
|
|
1457
|
+
});
|
|
1458
|
+
if (!replyRes.res.ok) {
|
|
1459
|
+
return dispatchErr(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`, { phase: "indeterminate", project, sessionId });
|
|
1460
|
+
}
|
|
1461
|
+
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
1597
1462
|
}
|
|
1598
|
-
|
|
1599
|
-
|
|
1463
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
1464
|
+
method: "POST",
|
|
1465
|
+
body: JSON.stringify({
|
|
1466
|
+
parts: [{ type: "text", text: message }],
|
|
1467
|
+
...messageId !== undefined ? { messageID: messageId } : {}
|
|
1468
|
+
})
|
|
1469
|
+
});
|
|
1470
|
+
if (promptRes.res.status !== 204) {
|
|
1471
|
+
return dispatchErr(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId, messageId });
|
|
1600
1472
|
}
|
|
1601
1473
|
return {
|
|
1602
1474
|
ok: true,
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1475
|
+
sessionId,
|
|
1476
|
+
project,
|
|
1477
|
+
mode: "follow-up",
|
|
1478
|
+
...messageId !== undefined ? { messageId } : {}
|
|
1606
1479
|
};
|
|
1607
1480
|
}
|
|
1608
|
-
function
|
|
1609
|
-
|
|
1481
|
+
async function result(sessionId, opts) {
|
|
1482
|
+
const ctx = validateContext(opts.context);
|
|
1483
|
+
if (!ctx.ok)
|
|
1484
|
+
return ctx;
|
|
1485
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1486
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
1487
|
+
if (!loc.ok)
|
|
1488
|
+
return loc;
|
|
1489
|
+
const { directory, project } = loc;
|
|
1490
|
+
const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
|
|
1491
|
+
if (statusMapRes.res.ok) {
|
|
1492
|
+
try {
|
|
1493
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
1494
|
+
const entry = statusMap[sessionId];
|
|
1495
|
+
if (isStatusBusy(entry)) {
|
|
1496
|
+
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
1497
|
+
}
|
|
1498
|
+
} catch {}
|
|
1499
|
+
}
|
|
1500
|
+
const [messageRes, diffResult] = await Promise.all([
|
|
1501
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
|
|
1502
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
|
|
1503
|
+
]);
|
|
1504
|
+
if (!messageRes.res.ok) {
|
|
1505
|
+
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
1506
|
+
}
|
|
1507
|
+
let messages;
|
|
1508
|
+
try {
|
|
1509
|
+
messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
|
|
1510
|
+
} catch (e) {
|
|
1511
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
1512
|
+
}
|
|
1513
|
+
const { diff, diffSource } = diffResult;
|
|
1514
|
+
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
1515
|
+
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
1516
|
+
`).trim() : "";
|
|
1517
|
+
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
1610
1518
|
}
|
|
1611
|
-
function
|
|
1612
|
-
const
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1519
|
+
async function mapWithConcurrency(items, concurrency, fn) {
|
|
1520
|
+
const results = new Array(items.length);
|
|
1521
|
+
let next = 0;
|
|
1522
|
+
const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
|
|
1523
|
+
const workers = Array.from({ length: limit }, async () => {
|
|
1524
|
+
while (true) {
|
|
1525
|
+
const i = next++;
|
|
1526
|
+
if (i >= items.length)
|
|
1527
|
+
return;
|
|
1528
|
+
results[i] = await fn(items[i]);
|
|
1529
|
+
}
|
|
1530
|
+
});
|
|
1531
|
+
await Promise.all(workers);
|
|
1532
|
+
return results;
|
|
1533
|
+
}
|
|
1534
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 60000;
|
|
1535
|
+
var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
|
|
1536
|
+
var DEFAULT_WAIT_CONCURRENCY = 4;
|
|
1537
|
+
var NEEDS_ATTENTION_STATES = [
|
|
1538
|
+
"complete",
|
|
1539
|
+
"blocked",
|
|
1540
|
+
"failed",
|
|
1541
|
+
"not_found"
|
|
1542
|
+
];
|
|
1543
|
+
function sleep(ms) {
|
|
1544
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1545
|
+
}
|
|
1546
|
+
async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
|
|
1547
|
+
const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
|
|
1548
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
|
|
1549
|
+
return { id, loc };
|
|
1550
|
+
});
|
|
1551
|
+
const locationById = new Map;
|
|
1552
|
+
for (const { id, loc } of locations) {
|
|
1553
|
+
locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
|
|
1616
1554
|
}
|
|
1617
|
-
|
|
1618
|
-
|
|
1555
|
+
const groups = new Map;
|
|
1556
|
+
for (const id of sessionIds) {
|
|
1557
|
+
const loc = locationById.get(id);
|
|
1558
|
+
if (!loc)
|
|
1559
|
+
continue;
|
|
1560
|
+
const group = groups.get(loc.directory) ?? {
|
|
1561
|
+
directory: loc.directory,
|
|
1562
|
+
sessionIds: []
|
|
1563
|
+
};
|
|
1564
|
+
group.sessionIds.push(id);
|
|
1565
|
+
groups.set(loc.directory, group);
|
|
1619
1566
|
}
|
|
1620
|
-
|
|
1567
|
+
const lastKnown = new Map;
|
|
1568
|
+
for (const id of sessionIds) {
|
|
1569
|
+
const loc = locationById.get(id);
|
|
1570
|
+
lastKnown.set(id, {
|
|
1571
|
+
sessionId: id,
|
|
1572
|
+
project: loc?.project ?? "",
|
|
1573
|
+
state: loc ? "running" : "not_found",
|
|
1574
|
+
resultAvailable: false
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
return { locationById, groupList: Array.from(groups.values()), lastKnown };
|
|
1621
1578
|
}
|
|
1622
|
-
async function
|
|
1579
|
+
async function wait(sessionIds, opts) {
|
|
1623
1580
|
const ctx = validateContext(opts.context);
|
|
1624
1581
|
if (!ctx.ok)
|
|
1625
1582
|
return ctx;
|
|
1626
1583
|
const { baseUrl, projects, credentials } = ctx;
|
|
1627
|
-
const
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1584
|
+
const uniqueIds = Array.from(new Set(sessionIds));
|
|
1585
|
+
if (uniqueIds.length === 0) {
|
|
1586
|
+
return { ok: true, sessions: [], waker: [], timedOut: true };
|
|
1587
|
+
}
|
|
1588
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
1589
|
+
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
|
|
1590
|
+
const deadline = Date.now() + timeoutMs;
|
|
1591
|
+
const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
|
|
1592
|
+
async function pollGroup(group) {
|
|
1593
|
+
const [statusRes, questionRes] = await Promise.all([
|
|
1594
|
+
api(baseUrl, credentials, group.directory, "/session/status"),
|
|
1595
|
+
api(baseUrl, credentials, group.directory, "/question")
|
|
1596
|
+
]);
|
|
1597
|
+
if (!statusRes.res.ok)
|
|
1598
|
+
return;
|
|
1599
|
+
let statusMap;
|
|
1636
1600
|
try {
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
pathExists: true,
|
|
1659
|
-
busyCount,
|
|
1660
|
-
sessionCount: capped ? 100 : sessions.length,
|
|
1661
|
-
sessionCountCapped: capped
|
|
1662
|
-
};
|
|
1663
|
-
} catch (e) {
|
|
1664
|
-
return {
|
|
1665
|
-
name: p.name,
|
|
1666
|
-
path: p.expandedPath,
|
|
1667
|
-
description: p.description,
|
|
1668
|
-
pathExists: true,
|
|
1669
|
-
statusError: e.message
|
|
1670
|
-
};
|
|
1601
|
+
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
1602
|
+
} catch {
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const pendingBySession = parsePendingQuestions(questionRes);
|
|
1606
|
+
for (const id of group.sessionIds) {
|
|
1607
|
+
const entry = statusMap[id];
|
|
1608
|
+
const busy = isStatusBusy(entry);
|
|
1609
|
+
const pendingQuestion = pendingBySession.get(id);
|
|
1610
|
+
const state = deriveSessionState({
|
|
1611
|
+
busy,
|
|
1612
|
+
pendingQuestion,
|
|
1613
|
+
resolved: true
|
|
1614
|
+
});
|
|
1615
|
+
lastKnown.set(id, {
|
|
1616
|
+
sessionId: id,
|
|
1617
|
+
project: locationById.get(id)?.project ?? "",
|
|
1618
|
+
state,
|
|
1619
|
+
resultAvailable: state === "complete",
|
|
1620
|
+
pendingQuestion
|
|
1621
|
+
});
|
|
1671
1622
|
}
|
|
1672
|
-
}));
|
|
1673
|
-
return { ok: true, projects: results };
|
|
1674
|
-
}
|
|
1675
|
-
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title, messageId) {
|
|
1676
|
-
const resolved = resolveProjectOrErr(projects, project);
|
|
1677
|
-
if (!resolved.ok)
|
|
1678
|
-
return resolved;
|
|
1679
|
-
const directory = resolved.project.expandedPath;
|
|
1680
|
-
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
1681
|
-
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
1682
|
-
method: "POST",
|
|
1683
|
-
body: JSON.stringify({ title: sessionTitle })
|
|
1684
|
-
});
|
|
1685
|
-
if (!createRes.res.ok) {
|
|
1686
|
-
return dispatchErr(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`, { phase: "indeterminate", project, messageId });
|
|
1687
1623
|
}
|
|
1688
|
-
|
|
1624
|
+
while (true) {
|
|
1625
|
+
await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
|
|
1626
|
+
const sessions = uniqueIds.map((id) => lastKnown.get(id));
|
|
1627
|
+
const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
|
|
1628
|
+
if (waker.length > 0) {
|
|
1629
|
+
return { ok: true, sessions, waker, timedOut: false };
|
|
1630
|
+
}
|
|
1631
|
+
if (Date.now() >= deadline) {
|
|
1632
|
+
return { ok: true, sessions, waker: [], timedOut: true };
|
|
1633
|
+
}
|
|
1634
|
+
const remaining = deadline - Date.now();
|
|
1635
|
+
await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
function parsePendingQuestions(questionRes) {
|
|
1639
|
+
if (!questionRes.res.ok)
|
|
1640
|
+
return new Map;
|
|
1689
1641
|
try {
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1642
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
|
|
1643
|
+
return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
|
|
1644
|
+
} catch {
|
|
1645
|
+
return new Map;
|
|
1693
1646
|
}
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
// src/format.ts
|
|
1650
|
+
function formatRosterHeader(source) {
|
|
1651
|
+
return `roster: ${source.name ?? source.path}`;
|
|
1652
|
+
}
|
|
1653
|
+
function formatRoster(projects) {
|
|
1654
|
+
return projects.map((p) => {
|
|
1655
|
+
if (!p.pathExists)
|
|
1656
|
+
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
1657
|
+
if (p.statusError)
|
|
1658
|
+
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
1659
|
+
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
1660
|
+
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
1661
|
+
}).join(`
|
|
1662
|
+
`);
|
|
1663
|
+
}
|
|
1664
|
+
function formatDispatch(r) {
|
|
1665
|
+
switch (r.mode) {
|
|
1666
|
+
case "new":
|
|
1667
|
+
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
1668
|
+
case "question-reply":
|
|
1669
|
+
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
1670
|
+
case "follow-up":
|
|
1671
|
+
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
1672
|
+
case "blocked":
|
|
1673
|
+
return `Blocked: session ${r.sessionId} (${r.project}) has a pending question (${r.requestId}) — no reply or prompt sent.`;
|
|
1703
1674
|
}
|
|
1675
|
+
}
|
|
1676
|
+
function dispatchMetadata(r) {
|
|
1677
|
+
const messageId = (r.mode === "new" || r.mode === "follow-up") && r.messageId !== undefined ? r.messageId : undefined;
|
|
1704
1678
|
return {
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
directory,
|
|
1679
|
+
sessionId: r.sessionId,
|
|
1680
|
+
project: r.project,
|
|
1681
|
+
mode: r.mode,
|
|
1709
1682
|
...messageId !== undefined ? { messageId } : {}
|
|
1710
1683
|
};
|
|
1711
1684
|
}
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1685
|
+
function formatStatus(r) {
|
|
1686
|
+
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
1687
|
+
`) : " (none)";
|
|
1688
|
+
const lines = [
|
|
1689
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1690
|
+
`title: ${r.title ?? "(untitled)"}`,
|
|
1691
|
+
`busy: ${r.busy}`
|
|
1692
|
+
];
|
|
1693
|
+
if (r.pendingQuestion) {
|
|
1694
|
+
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
1695
|
+
if (r.pendingQuestion.options.length > 0) {
|
|
1696
|
+
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
1697
|
+
}
|
|
1698
|
+
lines.push(` (answer with bus_task using sessionId)`);
|
|
1717
1699
|
}
|
|
1718
|
-
|
|
1700
|
+
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);
|
|
1701
|
+
return lines.join(`
|
|
1702
|
+
`);
|
|
1719
1703
|
}
|
|
1720
|
-
function
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
messageId = validated.messageId;
|
|
1733
|
-
}
|
|
1734
|
-
if (!input.sessionId) {
|
|
1735
|
-
if (!input.project) {
|
|
1736
|
-
return err("space-bus: project is required when starting a new session");
|
|
1704
|
+
function formatWait(r) {
|
|
1705
|
+
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
1706
|
+
const sessionLines = r.sessions.map((s) => {
|
|
1707
|
+
const parts = [
|
|
1708
|
+
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
1709
|
+
];
|
|
1710
|
+
if (s.pendingQuestion) {
|
|
1711
|
+
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
1712
|
+
if (s.pendingQuestion.options.length > 0) {
|
|
1713
|
+
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
1714
|
+
}
|
|
1715
|
+
parts.push(` (answer with bus_task using sessionId)`);
|
|
1737
1716
|
}
|
|
1738
|
-
return
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
onPendingQuestion: input.onPendingQuestion,
|
|
1744
|
-
...messageId !== undefined ? { messageId } : {}
|
|
1745
|
-
};
|
|
1746
|
-
}
|
|
1747
|
-
return {
|
|
1748
|
-
ok: true,
|
|
1749
|
-
prompt: input.prompt,
|
|
1750
|
-
title: input.title,
|
|
1751
|
-
sessionId: input.sessionId,
|
|
1752
|
-
project: input.project,
|
|
1753
|
-
onPendingQuestion: input.onPendingQuestion,
|
|
1754
|
-
...messageId !== undefined ? { messageId } : {}
|
|
1755
|
-
};
|
|
1717
|
+
return parts.join(`
|
|
1718
|
+
`);
|
|
1719
|
+
});
|
|
1720
|
+
return [header, ...sessionLines].join(`
|
|
1721
|
+
`);
|
|
1756
1722
|
}
|
|
1757
|
-
|
|
1758
|
-
const
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
};
|
|
1723
|
+
function formatResult(r) {
|
|
1724
|
+
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
1725
|
+
`) : " (no changes)";
|
|
1726
|
+
return [
|
|
1727
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1728
|
+
`--- reply ---`,
|
|
1729
|
+
r.text || "(empty)",
|
|
1730
|
+
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
1731
|
+
diffLines
|
|
1732
|
+
].join(`
|
|
1733
|
+
`);
|
|
1769
1734
|
}
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1735
|
+
|
|
1736
|
+
// src/server.ts
|
|
1737
|
+
import { spawn } from "node:child_process";
|
|
1738
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
1739
|
+
import { existsSync as existsSync2, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
|
|
1740
|
+
import { dirname } from "node:path";
|
|
1741
|
+
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
1742
|
+
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
1743
|
+
var POLL_INTERVAL_MS = 50;
|
|
1744
|
+
var MIN_PROBE_PHASE_MS = 3000;
|
|
1745
|
+
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
1746
|
+
var STOP_GRACE_MS = 2000;
|
|
1747
|
+
var SUPERVISE_INTERVAL_MS = 5000;
|
|
1748
|
+
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
1749
|
+
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
1750
|
+
function sleep2(ms) {
|
|
1751
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1752
|
+
}
|
|
1753
|
+
function readManifest(rosterPath) {
|
|
1754
|
+
const raw = readFileSync4(rosterPath, "utf8");
|
|
1755
|
+
const json = JSON.parse(raw);
|
|
1756
|
+
return manifestSchema.parse(json);
|
|
1757
|
+
}
|
|
1758
|
+
function readLogTail(logPath, maxChars = 4000) {
|
|
1759
|
+
try {
|
|
1760
|
+
const content = readFileSync4(logPath, "utf8");
|
|
1761
|
+
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
1762
|
+
} catch {
|
|
1763
|
+
return "";
|
|
1779
1764
|
}
|
|
1780
|
-
|
|
1781
|
-
|
|
1765
|
+
}
|
|
1766
|
+
function basicAuthToken(password) {
|
|
1767
|
+
return Buffer.from(`opencode:${password}`).toString("base64");
|
|
1768
|
+
}
|
|
1769
|
+
function redactSensitive(tail, password) {
|
|
1770
|
+
return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
|
|
1771
|
+
}
|
|
1772
|
+
function redactedReadinessError(rosterPath, password, reason) {
|
|
1773
|
+
const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
|
|
1774
|
+
return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
|
|
1775
|
+
${tail}`);
|
|
1776
|
+
}
|
|
1777
|
+
function isEpermError(err) {
|
|
1778
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "EPERM";
|
|
1779
|
+
}
|
|
1780
|
+
function signalGroup(pid, sig) {
|
|
1781
|
+
if (pid <= 1) {
|
|
1782
|
+
try {
|
|
1783
|
+
process.kill(pid, sig);
|
|
1784
|
+
} catch {}
|
|
1785
|
+
return false;
|
|
1782
1786
|
}
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1787
|
+
try {
|
|
1788
|
+
process.kill(-pid, sig);
|
|
1789
|
+
return true;
|
|
1790
|
+
} catch (err) {
|
|
1791
|
+
if (err.code === "EPERM") {
|
|
1792
|
+
throw err;
|
|
1786
1793
|
}
|
|
1787
|
-
return dispatchNewBranch(baseUrl, credentials, projects, {
|
|
1788
|
-
...args,
|
|
1789
|
-
project: args.project
|
|
1790
|
-
});
|
|
1791
1794
|
}
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1795
|
+
try {
|
|
1796
|
+
process.kill(pid, sig);
|
|
1797
|
+
} catch {}
|
|
1798
|
+
return false;
|
|
1799
|
+
}
|
|
1800
|
+
function signalGroupOnly(pid, sig) {
|
|
1801
|
+
if (pid <= 1)
|
|
1802
|
+
return false;
|
|
1803
|
+
try {
|
|
1804
|
+
process.kill(-pid, sig);
|
|
1805
|
+
return true;
|
|
1806
|
+
} catch {
|
|
1807
|
+
return false;
|
|
1798
1808
|
}
|
|
1799
|
-
return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project, args.onPendingQuestion ?? "question-reply", args.messageId);
|
|
1800
1809
|
}
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
if (
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
continue;
|
|
1808
|
-
let session;
|
|
1809
|
-
try {
|
|
1810
|
-
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
1811
|
-
} catch {
|
|
1812
|
-
continue;
|
|
1813
|
-
}
|
|
1814
|
-
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
1815
|
-
if (owner) {
|
|
1816
|
-
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
1810
|
+
function killIdentifiedProcess(pid, identity) {
|
|
1811
|
+
try {
|
|
1812
|
+
if (identity !== null && identity !== undefined && identity !== "") {
|
|
1813
|
+
if (verifyIdentity(pid, identity))
|
|
1814
|
+
signalGroup(pid, "SIGTERM");
|
|
1815
|
+
return;
|
|
1817
1816
|
}
|
|
1818
|
-
|
|
1819
|
-
}
|
|
1820
|
-
return err(`space-bus: no manifest project has a session with id ${sessionId}`);
|
|
1817
|
+
process.kill(pid, "SIGTERM");
|
|
1818
|
+
} catch {}
|
|
1821
1819
|
}
|
|
1822
|
-
function
|
|
1823
|
-
|
|
1824
|
-
return "not_found";
|
|
1825
|
-
if (input.failed)
|
|
1826
|
-
return "failed";
|
|
1827
|
-
if (input.pendingQuestion)
|
|
1828
|
-
return "blocked";
|
|
1829
|
-
if (input.busy)
|
|
1830
|
-
return "running";
|
|
1831
|
-
return "complete";
|
|
1820
|
+
function attachServer(rosterPath) {
|
|
1821
|
+
return attachLive(rosterPath);
|
|
1832
1822
|
}
|
|
1833
|
-
function
|
|
1834
|
-
const
|
|
1835
|
-
const
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1823
|
+
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
1824
|
+
const deadline = Date.now() + budgetMs;
|
|
1825
|
+
const lockPath = lockFilePath(rosterPath);
|
|
1826
|
+
while (Date.now() < deadline) {
|
|
1827
|
+
const handle = attachServer(rosterPath);
|
|
1828
|
+
if (handle)
|
|
1829
|
+
return handle;
|
|
1830
|
+
const lockInfo = readLockFile(lockPath);
|
|
1831
|
+
const winnerAlive = lockInfo !== null && verifyIdentity(lockInfo.pid, lockInfo.startTime);
|
|
1832
|
+
if (!winnerAlive) {
|
|
1833
|
+
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`);
|
|
1834
|
+
}
|
|
1835
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
1836
|
+
}
|
|
1837
|
+
const lockInfo = readLockFile(lockPath);
|
|
1838
|
+
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
1839
|
+
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
1839
1840
|
}
|
|
1840
|
-
async function
|
|
1841
|
+
async function probe(baseUrl, password) {
|
|
1841
1842
|
try {
|
|
1842
|
-
const
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
return
|
|
1843
|
+
const res = await fetch(`${baseUrl}/session?limit=1`, {
|
|
1844
|
+
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
1845
|
+
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
1846
|
+
});
|
|
1847
|
+
if (res.status === 200)
|
|
1848
|
+
return "ready";
|
|
1849
|
+
if (res.status === 401 || res.status === 403)
|
|
1850
|
+
return "auth-failure";
|
|
1851
|
+
return "retry";
|
|
1851
1852
|
} catch {
|
|
1852
|
-
return;
|
|
1853
|
+
return "retry";
|
|
1853
1854
|
}
|
|
1854
1855
|
}
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
const
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
1856
|
+
function childDied(child, pid) {
|
|
1857
|
+
return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
|
|
1858
|
+
}
|
|
1859
|
+
async function waitForReadinessLine(logPath, child, pid, deadline) {
|
|
1860
|
+
const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
|
|
1861
|
+
while (Date.now() < deadline) {
|
|
1862
|
+
if (childDied(child, pid))
|
|
1863
|
+
return null;
|
|
1864
|
+
const tail = readLogTail(logPath);
|
|
1865
|
+
const match = readinessLine.exec(tail);
|
|
1866
|
+
if (match?.[1]) {
|
|
1867
|
+
const port = Number.parseInt(match[1], 10);
|
|
1868
|
+
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
1869
|
+
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
1873
1873
|
}
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1874
|
+
return null;
|
|
1875
|
+
}
|
|
1876
|
+
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
1877
|
+
while (Date.now() < deadline) {
|
|
1878
|
+
if (childDied(child, pid))
|
|
1879
|
+
return "died";
|
|
1880
|
+
const outcome = await probe(baseUrl, password);
|
|
1881
|
+
if (outcome === "ready")
|
|
1882
|
+
return "ready";
|
|
1883
|
+
if (outcome === "auth-failure")
|
|
1884
|
+
return "auth-failure";
|
|
1885
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
1883
1886
|
}
|
|
1884
|
-
|
|
1885
|
-
const busy = isStatusBusy(entry);
|
|
1886
|
-
const { diff, diffSource } = diffResult;
|
|
1887
|
-
const additions = diff.reduce((sum, d) => sum + d.additions, 0);
|
|
1888
|
-
const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
|
|
1889
|
-
const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
|
|
1890
|
-
return {
|
|
1891
|
-
ok: true,
|
|
1892
|
-
sessionId,
|
|
1893
|
-
project,
|
|
1894
|
-
busy,
|
|
1895
|
-
title: session.title,
|
|
1896
|
-
todos,
|
|
1897
|
-
diff: { files: diff.length, additions, deletions },
|
|
1898
|
-
diffSource,
|
|
1899
|
-
pendingQuestion,
|
|
1900
|
-
state,
|
|
1901
|
-
resultAvailable: state === "complete"
|
|
1902
|
-
};
|
|
1887
|
+
return "timeout";
|
|
1903
1888
|
}
|
|
1904
|
-
async function
|
|
1905
|
-
const
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1889
|
+
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
1890
|
+
const deadline = Date.now() + budgetMs;
|
|
1891
|
+
const logPath = logFilePath(rosterPath);
|
|
1892
|
+
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
1893
|
+
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
1894
|
+
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
1895
|
+
if (lineResult === null) {
|
|
1896
|
+
const diedEarly = childDied(child, pid);
|
|
1897
|
+
killIdentifiedProcess(pid, identity);
|
|
1898
|
+
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
1911
1899
|
}
|
|
1912
|
-
|
|
1900
|
+
const { port, baseUrl } = lineResult;
|
|
1901
|
+
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
1902
|
+
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
1903
|
+
if (outcome === "ready")
|
|
1904
|
+
return { port, baseUrl };
|
|
1905
|
+
killIdentifiedProcess(pid, identity);
|
|
1906
|
+
if (outcome === "died") {
|
|
1907
|
+
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
1908
|
+
}
|
|
1909
|
+
if (outcome === "auth-failure") {
|
|
1910
|
+
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
1911
|
+
}
|
|
1912
|
+
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
1913
|
+
}
|
|
1914
|
+
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
1915
|
+
function reapOrphanedProvisional(rosterPath) {
|
|
1916
|
+
const provisional = readProvisional(rosterPath);
|
|
1917
|
+
if (!provisional)
|
|
1918
|
+
return;
|
|
1919
|
+
const discovery = readDiscovery(rosterPath);
|
|
1920
|
+
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1921
|
+
removeProvisional(rosterPath);
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
1925
|
+
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
1926
|
+
if (hasIdentity || isFresh) {
|
|
1927
|
+
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
1928
|
+
}
|
|
1929
|
+
removeProvisional(rosterPath);
|
|
1930
|
+
}
|
|
1931
|
+
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
1932
|
+
reapOrphanedProvisional(rosterPath);
|
|
1933
|
+
const password = randomBytes3(32).toString("base64url");
|
|
1934
|
+
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
1935
|
+
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
1936
|
+
const requestedPort = managedConfig.port ?? 0;
|
|
1937
|
+
const logPath = logFilePath(rosterPath);
|
|
1938
|
+
const logFd = openSync3(logPath, "w", 384);
|
|
1939
|
+
let child;
|
|
1940
|
+
let pid;
|
|
1941
|
+
let spawnError;
|
|
1913
1942
|
try {
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1943
|
+
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
1944
|
+
cwd,
|
|
1945
|
+
detached: true,
|
|
1946
|
+
stdio: ["ignore", logFd, logFd],
|
|
1947
|
+
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
1948
|
+
});
|
|
1949
|
+
child.on("error", (err) => {
|
|
1950
|
+
spawnError = err;
|
|
1951
|
+
});
|
|
1952
|
+
child.unref();
|
|
1953
|
+
pid = child.pid;
|
|
1954
|
+
} finally {
|
|
1955
|
+
closeQuietly(logFd);
|
|
1920
1956
|
}
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
pending: pendingList.find((q) => q.sessionID === sessionId)
|
|
1924
|
-
};
|
|
1925
|
-
}
|
|
1926
|
-
async function steerSession(baseUrl, credentials, sessionId, message, directory, project, onPendingQuestion, messageId) {
|
|
1927
|
-
const pendingRes = await resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, project, onPendingQuestion);
|
|
1928
|
-
if (!pendingRes.ok)
|
|
1929
|
-
return pendingRes;
|
|
1930
|
-
const { pending } = pendingRes;
|
|
1931
|
-
if (pending && onPendingQuestion === "blocked") {
|
|
1932
|
-
return {
|
|
1933
|
-
ok: true,
|
|
1934
|
-
sessionId,
|
|
1935
|
-
project,
|
|
1936
|
-
mode: "blocked",
|
|
1937
|
-
requestId: pending.id
|
|
1938
|
-
};
|
|
1957
|
+
if (pid === undefined) {
|
|
1958
|
+
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
1939
1959
|
}
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1960
|
+
const identity = captureIdentity(pid);
|
|
1961
|
+
writeProvisional(rosterPath, {
|
|
1962
|
+
pid,
|
|
1963
|
+
identity: identity ?? "",
|
|
1964
|
+
password,
|
|
1965
|
+
since: Date.now()
|
|
1966
|
+
});
|
|
1967
|
+
let port;
|
|
1968
|
+
let baseUrl;
|
|
1969
|
+
try {
|
|
1970
|
+
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
1971
|
+
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
1972
|
+
const check = setInterval(() => {
|
|
1973
|
+
if (spawnError) {
|
|
1974
|
+
clearInterval(check);
|
|
1975
|
+
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
1976
|
+
}
|
|
1977
|
+
}, POLL_INTERVAL_MS);
|
|
1978
|
+
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
1944
1979
|
});
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1980
|
+
const result = await Promise.race([readiness, spawnErrorWatch]);
|
|
1981
|
+
port = result.port;
|
|
1982
|
+
baseUrl = result.baseUrl;
|
|
1983
|
+
} finally {
|
|
1984
|
+
removeProvisional(rosterPath);
|
|
1949
1985
|
}
|
|
1950
|
-
const
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1986
|
+
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
1987
|
+
writeDiscovery(rosterPath, {
|
|
1988
|
+
port,
|
|
1989
|
+
pid,
|
|
1990
|
+
identity: finalIdentity,
|
|
1991
|
+
password,
|
|
1992
|
+
spawnConfig: { command, cwd, port: requestedPort },
|
|
1993
|
+
baseUrl,
|
|
1994
|
+
rosterPath
|
|
1956
1995
|
});
|
|
1957
|
-
if (promptRes.res.status !== 204) {
|
|
1958
|
-
return dispatchErr(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`, { phase: "indeterminate", project, sessionId, messageId });
|
|
1959
|
-
}
|
|
1960
1996
|
return {
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
...messageId !== undefined ? { messageId } : {}
|
|
1997
|
+
baseUrl,
|
|
1998
|
+
credentials: { username: "opencode", password },
|
|
1999
|
+
pid,
|
|
2000
|
+
port
|
|
1966
2001
|
};
|
|
1967
2002
|
}
|
|
1968
|
-
async function
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
return ctx;
|
|
1972
|
-
const { baseUrl, projects, credentials } = ctx;
|
|
1973
|
-
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
1974
|
-
if (!loc.ok)
|
|
1975
|
-
return loc;
|
|
1976
|
-
const { directory, project } = loc;
|
|
1977
|
-
const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
|
|
1978
|
-
if (statusMapRes.res.ok) {
|
|
1979
|
-
try {
|
|
1980
|
-
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
1981
|
-
const entry = statusMap[sessionId];
|
|
1982
|
-
if (isStatusBusy(entry)) {
|
|
1983
|
-
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
1984
|
-
}
|
|
1985
|
-
} catch {}
|
|
2003
|
+
async function ensureServer(rosterPath, options = {}) {
|
|
2004
|
+
if (existsSync2(rosterPath)) {
|
|
2005
|
+
rosterPath = realpathSync3(rosterPath);
|
|
1986
2006
|
}
|
|
1987
|
-
const
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
2007
|
+
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
2008
|
+
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
2009
|
+
const fastPath = attachServer(rosterPath);
|
|
2010
|
+
if (fastPath)
|
|
2011
|
+
return fastPath;
|
|
2012
|
+
const manifest = readManifest(rosterPath);
|
|
2013
|
+
if (manifest.server.managed === undefined) {
|
|
2014
|
+
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
2015
|
+
}
|
|
2016
|
+
const lock = acquireLock(rosterPath);
|
|
2017
|
+
if (lock === null) {
|
|
2018
|
+
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
1993
2019
|
}
|
|
1994
|
-
let messages;
|
|
1995
2020
|
try {
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
2021
|
+
const attached = attachServer(rosterPath);
|
|
2022
|
+
if (attached)
|
|
2023
|
+
return attached;
|
|
2024
|
+
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
2025
|
+
} finally {
|
|
2026
|
+
releaseLock(lock);
|
|
1999
2027
|
}
|
|
2000
|
-
const { diff, diffSource } = diffResult;
|
|
2001
|
-
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
2002
|
-
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
2003
|
-
`).trim() : "";
|
|
2004
|
-
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
2005
|
-
}
|
|
2006
|
-
async function mapWithConcurrency(items, concurrency, fn) {
|
|
2007
|
-
const results = new Array(items.length);
|
|
2008
|
-
let next = 0;
|
|
2009
|
-
const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
|
|
2010
|
-
const workers = Array.from({ length: limit }, async () => {
|
|
2011
|
-
while (true) {
|
|
2012
|
-
const i = next++;
|
|
2013
|
-
if (i >= items.length)
|
|
2014
|
-
return;
|
|
2015
|
-
results[i] = await fn(items[i]);
|
|
2016
|
-
}
|
|
2017
|
-
});
|
|
2018
|
-
await Promise.all(workers);
|
|
2019
|
-
return results;
|
|
2020
|
-
}
|
|
2021
|
-
var DEFAULT_WAIT_TIMEOUT_MS = 60000;
|
|
2022
|
-
var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
|
|
2023
|
-
var DEFAULT_WAIT_CONCURRENCY = 4;
|
|
2024
|
-
var NEEDS_ATTENTION_STATES = [
|
|
2025
|
-
"complete",
|
|
2026
|
-
"blocked",
|
|
2027
|
-
"failed",
|
|
2028
|
-
"not_found"
|
|
2029
|
-
];
|
|
2030
|
-
function sleep2(ms) {
|
|
2031
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2032
2028
|
}
|
|
2033
|
-
|
|
2034
|
-
const
|
|
2035
|
-
|
|
2036
|
-
return {
|
|
2037
|
-
});
|
|
2038
|
-
const locationById = new Map;
|
|
2039
|
-
for (const { id, loc } of locations) {
|
|
2040
|
-
locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
|
|
2041
|
-
}
|
|
2042
|
-
const groups = new Map;
|
|
2043
|
-
for (const id of sessionIds) {
|
|
2044
|
-
const loc = locationById.get(id);
|
|
2045
|
-
if (!loc)
|
|
2046
|
-
continue;
|
|
2047
|
-
const group = groups.get(loc.directory) ?? {
|
|
2048
|
-
directory: loc.directory,
|
|
2049
|
-
sessionIds: []
|
|
2050
|
-
};
|
|
2051
|
-
group.sessionIds.push(id);
|
|
2052
|
-
groups.set(loc.directory, group);
|
|
2029
|
+
function serverStatus(rosterPath) {
|
|
2030
|
+
const discovery = readDiscovery(rosterPath);
|
|
2031
|
+
if (!discovery) {
|
|
2032
|
+
return { running: false };
|
|
2053
2033
|
}
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
sessionId: id,
|
|
2059
|
-
project: loc?.project ?? "",
|
|
2060
|
-
state: loc ? "running" : "not_found",
|
|
2061
|
-
resultAvailable: false
|
|
2034
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
2035
|
+
removeDiscoveryIfMatches(rosterPath, {
|
|
2036
|
+
pid: discovery.pid,
|
|
2037
|
+
identity: discovery.identity
|
|
2062
2038
|
});
|
|
2039
|
+
return { running: false };
|
|
2063
2040
|
}
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
async function pollGroup(group) {
|
|
2080
|
-
const [statusRes, questionRes] = await Promise.all([
|
|
2081
|
-
api(baseUrl, credentials, group.directory, "/session/status"),
|
|
2082
|
-
api(baseUrl, credentials, group.directory, "/question")
|
|
2083
|
-
]);
|
|
2084
|
-
if (!statusRes.res.ok)
|
|
2085
|
-
return;
|
|
2086
|
-
let statusMap;
|
|
2087
|
-
try {
|
|
2088
|
-
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
2089
|
-
} catch {
|
|
2090
|
-
return;
|
|
2091
|
-
}
|
|
2092
|
-
const pendingBySession = parsePendingQuestions(questionRes);
|
|
2093
|
-
for (const id of group.sessionIds) {
|
|
2094
|
-
const entry = statusMap[id];
|
|
2095
|
-
const busy = isStatusBusy(entry);
|
|
2096
|
-
const pendingQuestion = pendingBySession.get(id);
|
|
2097
|
-
const state = deriveSessionState({
|
|
2098
|
-
busy,
|
|
2099
|
-
pendingQuestion,
|
|
2100
|
-
resolved: true
|
|
2101
|
-
});
|
|
2102
|
-
lastKnown.set(id, {
|
|
2103
|
-
sessionId: id,
|
|
2104
|
-
project: locationById.get(id)?.project ?? "",
|
|
2105
|
-
state,
|
|
2106
|
-
resultAvailable: state === "complete",
|
|
2107
|
-
pendingQuestion
|
|
2108
|
-
});
|
|
2041
|
+
let configDrift;
|
|
2042
|
+
try {
|
|
2043
|
+
const manifest = readManifest(rosterPath);
|
|
2044
|
+
if (manifest.server.managed) {
|
|
2045
|
+
const current = manifest.server.managed;
|
|
2046
|
+
const currentCommand = current.command ?? ["harness", "serve"];
|
|
2047
|
+
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
2048
|
+
const currentPort = current.port ?? 0;
|
|
2049
|
+
const storedCommand = discovery.spawnConfig.command ?? [
|
|
2050
|
+
"harness",
|
|
2051
|
+
"serve"
|
|
2052
|
+
];
|
|
2053
|
+
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
2054
|
+
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
2055
|
+
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
2109
2056
|
}
|
|
2057
|
+
} catch {}
|
|
2058
|
+
return {
|
|
2059
|
+
running: true,
|
|
2060
|
+
port: discovery.port,
|
|
2061
|
+
pid: discovery.pid,
|
|
2062
|
+
configDrift
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
async function stopServer(rosterPath) {
|
|
2066
|
+
const discovery = readDiscovery(rosterPath);
|
|
2067
|
+
if (!discovery)
|
|
2068
|
+
return { stopped: false };
|
|
2069
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
2070
|
+
await reapSurvivingGroup(discovery.pid);
|
|
2071
|
+
removeDiscovery(rosterPath);
|
|
2072
|
+
return { stopped: false };
|
|
2110
2073
|
}
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
return { ok: true, sessions, waker: [], timedOut: true };
|
|
2074
|
+
const { pid } = discovery;
|
|
2075
|
+
let groupSignaled;
|
|
2076
|
+
const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
|
|
2077
|
+
try {
|
|
2078
|
+
groupSignaled = signalGroup(pid, "SIGTERM");
|
|
2079
|
+
} catch (err) {
|
|
2080
|
+
if (isEpermError(err)) {
|
|
2081
|
+
return { stopped: false };
|
|
2120
2082
|
}
|
|
2121
|
-
|
|
2122
|
-
|
|
2083
|
+
removeDiscovery(rosterPath);
|
|
2084
|
+
return { stopped: true };
|
|
2085
|
+
}
|
|
2086
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
2087
|
+
removeDiscovery(rosterPath);
|
|
2088
|
+
return { stopped: true };
|
|
2123
2089
|
}
|
|
2124
|
-
}
|
|
2125
|
-
function parsePendingQuestions(questionRes) {
|
|
2126
|
-
if (!questionRes.res.ok)
|
|
2127
|
-
return new Map;
|
|
2128
2090
|
try {
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2091
|
+
groupSignaled = signalGroup(pid, "SIGKILL");
|
|
2092
|
+
} catch (err) {
|
|
2093
|
+
if (isEpermError(err)) {
|
|
2094
|
+
return { stopped: false };
|
|
2095
|
+
}
|
|
2096
|
+
removeDiscovery(rosterPath);
|
|
2097
|
+
return { stopped: true };
|
|
2098
|
+
}
|
|
2099
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
2100
|
+
removeDiscovery(rosterPath);
|
|
2101
|
+
return { stopped: true };
|
|
2133
2102
|
}
|
|
2103
|
+
return { stopped: false };
|
|
2134
2104
|
}
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2105
|
+
async function reapSurvivingGroup(pid) {
|
|
2106
|
+
try {
|
|
2107
|
+
if (isAlive(pid))
|
|
2108
|
+
return;
|
|
2109
|
+
let groupAlive;
|
|
2110
|
+
try {
|
|
2111
|
+
process.kill(-pid, 0);
|
|
2112
|
+
groupAlive = true;
|
|
2113
|
+
} catch {
|
|
2114
|
+
groupAlive = false;
|
|
2115
|
+
}
|
|
2116
|
+
if (!groupAlive)
|
|
2117
|
+
return;
|
|
2118
|
+
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
2119
|
+
return;
|
|
2120
|
+
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
2121
|
+
return;
|
|
2122
|
+
signalGroupOnly(pid, "SIGKILL");
|
|
2123
|
+
await waitForGroupDeath(pid, STOP_GRACE_MS);
|
|
2124
|
+
} catch {}
|
|
2139
2125
|
}
|
|
2140
|
-
function
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
2146
|
-
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
2147
|
-
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
2148
|
-
}).join(`
|
|
2149
|
-
`);
|
|
2126
|
+
async function stopForHung(tick) {
|
|
2127
|
+
try {
|
|
2128
|
+
await tick.stop(tick.rosterPath);
|
|
2129
|
+
} catch {}
|
|
2130
|
+
return { kind: "outcome", outcome: { reason: "hung" } };
|
|
2150
2131
|
}
|
|
2151
|
-
function
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2132
|
+
async function superviseTick(tick, state) {
|
|
2133
|
+
const st = tick.status(tick.rosterPath);
|
|
2134
|
+
if (!st.running) {
|
|
2135
|
+
await reapSurvivingGroup(tick.handle.pid);
|
|
2136
|
+
return { kind: "outcome", outcome: { reason: "died" } };
|
|
2137
|
+
}
|
|
2138
|
+
const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
|
|
2139
|
+
const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
|
|
2140
|
+
const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
|
|
2141
|
+
if (failures >= tick.threshold) {
|
|
2142
|
+
return stopForHung(tick);
|
|
2161
2143
|
}
|
|
2144
|
+
if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
|
|
2145
|
+
return stopForHung(tick);
|
|
2146
|
+
}
|
|
2147
|
+
return { kind: "tick", failures, lastReadyAt };
|
|
2162
2148
|
}
|
|
2163
|
-
function
|
|
2164
|
-
const messageId = (r.mode === "new" || r.mode === "follow-up") && r.messageId !== undefined ? r.messageId : undefined;
|
|
2149
|
+
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
2165
2150
|
return {
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2151
|
+
rosterPath,
|
|
2152
|
+
handle,
|
|
2153
|
+
password: handle.credentials.password ?? "",
|
|
2154
|
+
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
2155
|
+
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
2156
|
+
now: opts.now ?? Date.now,
|
|
2157
|
+
status: opts.status ?? serverStatus,
|
|
2158
|
+
probe: opts.probe ?? probe,
|
|
2159
|
+
stop: opts.stop ?? stopServer
|
|
2170
2160
|
};
|
|
2171
2161
|
}
|
|
2172
|
-
function
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
`session: ${r.sessionId} (${r.project})`,
|
|
2177
|
-
`title: ${r.title ?? "(untitled)"}`,
|
|
2178
|
-
`busy: ${r.busy}`
|
|
2179
|
-
];
|
|
2180
|
-
if (r.pendingQuestion) {
|
|
2181
|
-
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
2182
|
-
if (r.pendingQuestion.options.length > 0) {
|
|
2183
|
-
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
2184
|
-
}
|
|
2185
|
-
lines.push(` (answer with bus_task using sessionId)`);
|
|
2162
|
+
async function interruptibleSleep(doSleep, intervalMs, interrupt) {
|
|
2163
|
+
if (!interrupt) {
|
|
2164
|
+
await doSleep(intervalMs);
|
|
2165
|
+
return;
|
|
2186
2166
|
}
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
}
|
|
2191
|
-
function formatWait(r) {
|
|
2192
|
-
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
2193
|
-
const sessionLines = r.sessions.map((s) => {
|
|
2194
|
-
const parts = [
|
|
2195
|
-
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
2196
|
-
];
|
|
2197
|
-
if (s.pendingQuestion) {
|
|
2198
|
-
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
2199
|
-
if (s.pendingQuestion.options.length > 0) {
|
|
2200
|
-
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
2201
|
-
}
|
|
2202
|
-
parts.push(` (answer with bus_task using sessionId)`);
|
|
2203
|
-
}
|
|
2204
|
-
return parts.join(`
|
|
2205
|
-
`);
|
|
2167
|
+
let timer;
|
|
2168
|
+
const timed = new Promise((resolve) => {
|
|
2169
|
+
timer = setTimeout(resolve, intervalMs);
|
|
2206
2170
|
});
|
|
2207
|
-
|
|
2208
|
-
|
|
2171
|
+
try {
|
|
2172
|
+
await Promise.race([timed, interrupt]);
|
|
2173
|
+
} finally {
|
|
2174
|
+
if (timer !== undefined)
|
|
2175
|
+
clearTimeout(timer);
|
|
2176
|
+
}
|
|
2209
2177
|
}
|
|
2210
|
-
function
|
|
2211
|
-
const
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2178
|
+
async function superviseServer(rosterPath, handle, opts = {}) {
|
|
2179
|
+
const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
|
|
2180
|
+
const tick = makeSuperviseTick(rosterPath, handle, opts);
|
|
2181
|
+
const doSleep = opts.sleep ?? sleep2;
|
|
2182
|
+
const shouldStop = opts.shouldStop ?? (() => false);
|
|
2183
|
+
let state = { failures: 0, lastReadyAt: tick.now() };
|
|
2184
|
+
for (;; ) {
|
|
2185
|
+
if (shouldStop())
|
|
2186
|
+
return { reason: "signal" };
|
|
2187
|
+
const result = await superviseTick(tick, state);
|
|
2188
|
+
if (result.kind === "outcome")
|
|
2189
|
+
return result.outcome;
|
|
2190
|
+
state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
|
|
2191
|
+
if (shouldStop())
|
|
2192
|
+
return { reason: "signal" };
|
|
2193
|
+
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
async function waitForDeath(pid, budgetMs) {
|
|
2197
|
+
const deadline = Date.now() + budgetMs;
|
|
2198
|
+
while (Date.now() < deadline) {
|
|
2199
|
+
if (!isAlive(pid))
|
|
2200
|
+
return true;
|
|
2201
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2202
|
+
}
|
|
2203
|
+
return !isAlive(pid);
|
|
2204
|
+
}
|
|
2205
|
+
async function waitForGroupDeath(pid, budgetMs) {
|
|
2206
|
+
const deadline = Date.now() + budgetMs;
|
|
2207
|
+
const groupAlive = () => {
|
|
2208
|
+
try {
|
|
2209
|
+
process.kill(-pid, 0);
|
|
2210
|
+
return true;
|
|
2211
|
+
} catch {
|
|
2212
|
+
return false;
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
while (Date.now() < deadline) {
|
|
2216
|
+
if (!groupAlive())
|
|
2217
|
+
return true;
|
|
2218
|
+
await sleep2(POLL_INTERVAL_MS);
|
|
2219
|
+
}
|
|
2220
|
+
return !groupAlive();
|
|
2221
2221
|
}
|
|
2222
2222
|
|
|
2223
2223
|
// src/tools/bus_registry.ts
|
|
@@ -2246,8 +2246,8 @@ function closeQuietly3(fd) {
|
|
|
2246
2246
|
closeSync3(fd);
|
|
2247
2247
|
} catch {}
|
|
2248
2248
|
}
|
|
2249
|
-
function isErrnoCode3(
|
|
2250
|
-
return typeof
|
|
2249
|
+
function isErrnoCode3(err, code) {
|
|
2250
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === code;
|
|
2251
2251
|
}
|
|
2252
2252
|
function duplicateProjectName(projects) {
|
|
2253
2253
|
const seen = new Set;
|
|
@@ -2286,19 +2286,19 @@ function readManifest2(rosterPath) {
|
|
|
2286
2286
|
let raw;
|
|
2287
2287
|
try {
|
|
2288
2288
|
raw = readFileSync5(rosterPath, "utf8");
|
|
2289
|
-
} catch (
|
|
2289
|
+
} catch (err) {
|
|
2290
2290
|
return {
|
|
2291
2291
|
ok: false,
|
|
2292
|
-
error: `space-bus: cannot read roster at ${rosterPath}: ${String(
|
|
2292
|
+
error: `space-bus: cannot read roster at ${rosterPath}: ${String(err)}`
|
|
2293
2293
|
};
|
|
2294
2294
|
}
|
|
2295
2295
|
let json;
|
|
2296
2296
|
try {
|
|
2297
2297
|
json = JSON.parse(raw);
|
|
2298
|
-
} catch (
|
|
2298
|
+
} catch (err) {
|
|
2299
2299
|
return {
|
|
2300
2300
|
ok: false,
|
|
2301
|
-
error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(
|
|
2301
|
+
error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
|
|
2302
2302
|
};
|
|
2303
2303
|
}
|
|
2304
2304
|
return validateManifest(json);
|
|
@@ -2307,10 +2307,10 @@ function writeManifestAtomic(rosterPath, data) {
|
|
|
2307
2307
|
const dir = join4(rosterPath, "..");
|
|
2308
2308
|
try {
|
|
2309
2309
|
mkdirSync3(dir, { recursive: true });
|
|
2310
|
-
} catch (
|
|
2310
|
+
} catch (err) {
|
|
2311
2311
|
return {
|
|
2312
2312
|
ok: false,
|
|
2313
|
-
error: `space-bus: failed to create directory ${dir}: ${String(
|
|
2313
|
+
error: `space-bus: failed to create directory ${dir}: ${String(err)}`
|
|
2314
2314
|
};
|
|
2315
2315
|
}
|
|
2316
2316
|
let existingMode;
|
|
@@ -2330,7 +2330,7 @@ function writeManifestAtomic(rosterPath, data) {
|
|
|
2330
2330
|
closeSync3(fd);
|
|
2331
2331
|
fd = undefined;
|
|
2332
2332
|
renameSync3(tempPath, rosterPath);
|
|
2333
|
-
} catch (
|
|
2333
|
+
} catch (err) {
|
|
2334
2334
|
if (fd !== undefined)
|
|
2335
2335
|
closeQuietly3(fd);
|
|
2336
2336
|
try {
|
|
@@ -2338,7 +2338,7 @@ function writeManifestAtomic(rosterPath, data) {
|
|
|
2338
2338
|
} catch {}
|
|
2339
2339
|
return {
|
|
2340
2340
|
ok: false,
|
|
2341
|
-
error: `space-bus: failed to write roster at ${rosterPath}: ${String(
|
|
2341
|
+
error: `space-bus: failed to write roster at ${rosterPath}: ${String(err)}`
|
|
2342
2342
|
};
|
|
2343
2343
|
}
|
|
2344
2344
|
return { ok: true };
|
|
@@ -2347,17 +2347,17 @@ function writeRosterExclusive(rosterPath, data) {
|
|
|
2347
2347
|
const dir = join4(rosterPath, "..");
|
|
2348
2348
|
try {
|
|
2349
2349
|
mkdirSync3(dir, { recursive: true });
|
|
2350
|
-
} catch (
|
|
2350
|
+
} catch (err) {
|
|
2351
2351
|
return {
|
|
2352
2352
|
ok: false,
|
|
2353
|
-
error: `space-bus: failed to create directory ${dir}: ${String(
|
|
2353
|
+
error: `space-bus: failed to create directory ${dir}: ${String(err)}`
|
|
2354
2354
|
};
|
|
2355
2355
|
}
|
|
2356
2356
|
let fd;
|
|
2357
2357
|
try {
|
|
2358
2358
|
fd = openSync4(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
|
|
2359
|
-
} catch (
|
|
2360
|
-
if (isErrnoCode3(
|
|
2359
|
+
} catch (err) {
|
|
2360
|
+
if (isErrnoCode3(err, "EEXIST")) {
|
|
2361
2361
|
return {
|
|
2362
2362
|
ok: false,
|
|
2363
2363
|
error: `space-bus: refusing to overwrite existing roster file at ${rosterPath}`
|
|
@@ -2365,19 +2365,19 @@ function writeRosterExclusive(rosterPath, data) {
|
|
|
2365
2365
|
}
|
|
2366
2366
|
return {
|
|
2367
2367
|
ok: false,
|
|
2368
|
-
error: `space-bus: failed to create roster file at ${rosterPath}: ${String(
|
|
2368
|
+
error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err)}`
|
|
2369
2369
|
};
|
|
2370
2370
|
}
|
|
2371
2371
|
try {
|
|
2372
2372
|
writeSync2(fd, JSON.stringify(data, null, 2));
|
|
2373
|
-
} catch (
|
|
2373
|
+
} catch (err) {
|
|
2374
2374
|
closeQuietly3(fd);
|
|
2375
2375
|
try {
|
|
2376
2376
|
unlinkSync3(rosterPath);
|
|
2377
2377
|
} catch {}
|
|
2378
2378
|
return {
|
|
2379
2379
|
ok: false,
|
|
2380
|
-
error: `space-bus: failed to write roster file at ${rosterPath}: ${String(
|
|
2380
|
+
error: `space-bus: failed to write roster file at ${rosterPath}: ${String(err)}`
|
|
2381
2381
|
};
|
|
2382
2382
|
}
|
|
2383
2383
|
closeQuietly3(fd);
|
|
@@ -2667,29 +2667,29 @@ function runUse(args, session) {
|
|
|
2667
2667
|
};
|
|
2668
2668
|
}
|
|
2669
2669
|
function runCreate(args) {
|
|
2670
|
-
const
|
|
2670
|
+
const result = createRoster({
|
|
2671
2671
|
name: args.name,
|
|
2672
2672
|
rosterPath: args.path,
|
|
2673
2673
|
server: args.server
|
|
2674
2674
|
});
|
|
2675
|
-
if (!
|
|
2676
|
-
throw new Error(`bus_registry create: ${
|
|
2675
|
+
if (!result.ok)
|
|
2676
|
+
throw new Error(`bus_registry create: ${result.error}`);
|
|
2677
2677
|
return {
|
|
2678
2678
|
text: `bus_registry create: ${formatRosterHeader({ name: args.name, path: args.path })} created and registered`
|
|
2679
2679
|
};
|
|
2680
2680
|
}
|
|
2681
2681
|
function runRegister(args) {
|
|
2682
|
-
const
|
|
2683
|
-
if (!
|
|
2684
|
-
throw new Error(`bus_registry register: ${
|
|
2682
|
+
const result = registerRoster(args.name, args.path);
|
|
2683
|
+
if (!result.ok)
|
|
2684
|
+
throw new Error(`bus_registry register: ${result.error}`);
|
|
2685
2685
|
return {
|
|
2686
2686
|
text: `bus_registry register: ${formatRosterHeader({ name: args.name, path: args.path })} registered`
|
|
2687
2687
|
};
|
|
2688
2688
|
}
|
|
2689
2689
|
function runUnregister(args, session) {
|
|
2690
|
-
const
|
|
2691
|
-
if (!
|
|
2692
|
-
throw new Error(`bus_registry unregister: ${
|
|
2690
|
+
const result = unregisterRoster(args.name);
|
|
2691
|
+
if (!result.ok)
|
|
2692
|
+
throw new Error(`bus_registry unregister: ${result.error}`);
|
|
2693
2693
|
const active = session?.getActive();
|
|
2694
2694
|
if (active !== undefined && active.toLowerCase() === args.name.toLowerCase()) {
|
|
2695
2695
|
session?.clearActive();
|
|
@@ -2700,9 +2700,9 @@ function runUnregister(args, session) {
|
|
|
2700
2700
|
return { text: `bus_registry unregister: "${args.name}" unregistered` };
|
|
2701
2701
|
}
|
|
2702
2702
|
function runSetDefault(args) {
|
|
2703
|
-
const
|
|
2704
|
-
if (!
|
|
2705
|
-
throw new Error(`bus_registry set-default: ${
|
|
2703
|
+
const result = setDefaultRoster(args.name);
|
|
2704
|
+
if (!result.ok)
|
|
2705
|
+
throw new Error(`bus_registry set-default: ${result.error}`);
|
|
2706
2706
|
return {
|
|
2707
2707
|
text: `bus_registry set-default: "${args.name}" is now the default roster`
|
|
2708
2708
|
};
|
|
@@ -2711,9 +2711,9 @@ function runAddProject(args) {
|
|
|
2711
2711
|
const resolved = resolveRosterByName(args.roster);
|
|
2712
2712
|
if (!resolved.ok)
|
|
2713
2713
|
throw new Error(`bus_registry add-project: ${resolved.error}`);
|
|
2714
|
-
const
|
|
2715
|
-
if (!
|
|
2716
|
-
throw new Error(`bus_registry add-project: ${
|
|
2714
|
+
const result = addProject(resolved.path, args.project);
|
|
2715
|
+
if (!result.ok)
|
|
2716
|
+
throw new Error(`bus_registry add-project: ${result.error}`);
|
|
2717
2717
|
return {
|
|
2718
2718
|
text: `bus_registry add-project: added "${args.project.name}" to ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
|
|
2719
2719
|
};
|
|
@@ -2722,9 +2722,9 @@ function runRemoveProject(args) {
|
|
|
2722
2722
|
const resolved = resolveRosterByName(args.roster);
|
|
2723
2723
|
if (!resolved.ok)
|
|
2724
2724
|
throw new Error(`bus_registry remove-project: ${resolved.error}`);
|
|
2725
|
-
const
|
|
2726
|
-
if (!
|
|
2727
|
-
throw new Error(`bus_registry remove-project: ${
|
|
2725
|
+
const result = removeProject(resolved.path, args.projectName);
|
|
2726
|
+
if (!result.ok)
|
|
2727
|
+
throw new Error(`bus_registry remove-project: ${result.error}`);
|
|
2728
2728
|
return {
|
|
2729
2729
|
text: `bus_registry remove-project: removed "${args.projectName}" from ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
|
|
2730
2730
|
};
|
|
@@ -2733,9 +2733,9 @@ function runUpdateProject(args) {
|
|
|
2733
2733
|
const resolved = resolveRosterByName(args.roster);
|
|
2734
2734
|
if (!resolved.ok)
|
|
2735
2735
|
throw new Error(`bus_registry update-project: ${resolved.error}`);
|
|
2736
|
-
const
|
|
2737
|
-
if (!
|
|
2738
|
-
throw new Error(`bus_registry update-project: ${
|
|
2736
|
+
const result = updateProject(resolved.path, args.projectName, args.patch);
|
|
2737
|
+
if (!result.ok)
|
|
2738
|
+
throw new Error(`bus_registry update-project: ${result.error}`);
|
|
2739
2739
|
return {
|
|
2740
2740
|
text: `bus_registry update-project: updated "${args.projectName}" on ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
|
|
2741
2741
|
};
|
|
@@ -2791,12 +2791,12 @@ async function ensureAndLoadContext(directory, rosterName, ensure = ensureServer
|
|
|
2791
2791
|
const resolved = resolveRosterByName(rosterName);
|
|
2792
2792
|
if (!resolved.ok)
|
|
2793
2793
|
throw new Error(resolved.error);
|
|
2794
|
-
const
|
|
2795
|
-
if (isManagedRosterAtPath(
|
|
2796
|
-
await ensure(
|
|
2794
|
+
const rosterPath = resolved.path;
|
|
2795
|
+
if (isManagedRosterAtPath(rosterPath)) {
|
|
2796
|
+
await ensure(rosterPath);
|
|
2797
2797
|
}
|
|
2798
|
-
const context = loadContextForRosterPath(
|
|
2799
|
-
return { context, rosterName: resolved.name, rosterPath
|
|
2798
|
+
const context = loadContextForRosterPath(rosterPath);
|
|
2799
|
+
return { context, rosterName: resolved.name, rosterPath };
|
|
2800
2800
|
}
|
|
2801
2801
|
const rosterPath = resolveRosterPath(directory);
|
|
2802
2802
|
if (isManagedRoster(directory)) {
|
|
@@ -3015,7 +3015,7 @@ async function mcpLoadContext(rosterName, ensure = ensureServer) {
|
|
|
3015
3015
|
}
|
|
3016
3016
|
throw ambientError;
|
|
3017
3017
|
}
|
|
3018
|
-
var version = "0.15.
|
|
3018
|
+
var version = "0.15.1";
|
|
3019
3019
|
var server = new McpServer({
|
|
3020
3020
|
name: "space-bus",
|
|
3021
3021
|
version
|
|
@@ -3216,8 +3216,8 @@ async function main() {
|
|
|
3216
3216
|
await server.connect(transport);
|
|
3217
3217
|
}
|
|
3218
3218
|
if (__require.main == __require.module) {
|
|
3219
|
-
main().catch((
|
|
3220
|
-
console.error("space-bus mcp: fatal startup error:",
|
|
3219
|
+
main().catch((err) => {
|
|
3220
|
+
console.error("space-bus mcp: fatal startup error:", err);
|
|
3221
3221
|
process.exit(1);
|
|
3222
3222
|
});
|
|
3223
3223
|
}
|