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