@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/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { createRequire } from "node:module";
2
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
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((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
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/server.ts
968
- import { spawn } from "node:child_process";
969
- import { randomBytes as randomBytes3 } from "node:crypto";
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 readManifest(rosterPath) {
985
- const raw = readFileSync4(rosterPath, "utf8");
986
- const json = JSON.parse(raw);
987
- return manifestSchema.parse(json);
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 readLogTail(logPath, maxChars = 4000) {
990
- try {
991
- const content = readFileSync4(logPath, "utf8");
992
- return content.length > maxChars ? content.slice(-maxChars) : content;
993
- } catch {
994
- return "";
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 basicAuthToken(password) {
998
- return Buffer.from(`opencode:${password}`).toString("base64");
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 redactSensitive(tail, password) {
1001
- return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
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 redactedReadinessError(rosterPath, password, reason) {
1004
- const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
1005
- return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
1006
- ${tail}`);
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 isEpermError(err) {
1009
- return typeof err === "object" && err !== null && "code" in err && err.code === "EPERM";
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
- function signalGroup(pid, sig) {
1012
- if (pid <= 1) {
1013
- try {
1014
- process.kill(pid, sig);
1015
- } catch {}
1016
- return false;
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
- process.kill(-pid, sig);
1020
- return true;
1116
+ raw = readFileSync4(rosterPath, "utf8");
1021
1117
  } catch (err) {
1022
- if (err.code === "EPERM") {
1023
- throw err;
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
- process.kill(pid, sig);
1028
- } catch {}
1029
- return false;
1125
+ json = JSON.parse(raw);
1126
+ } catch (err) {
1127
+ return {
1128
+ ok: false,
1129
+ error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
1130
+ };
1131
+ }
1132
+ return validateManifest(json);
1030
1133
  }
1031
- function signalGroupOnly(pid, sig) {
1032
- if (pid <= 1)
1033
- return false;
1134
+ function writeManifestAtomic(rosterPath, data) {
1135
+ const dir = join4(rosterPath, "..");
1034
1136
  try {
1035
- process.kill(-pid, sig);
1036
- return true;
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
- return false;
1148
+ existingMode = undefined;
1039
1149
  }
1040
- }
1041
- function killIdentifiedProcess(pid, identity) {
1150
+ const tempPath = join4(dir, `.spacebus.${randomBytes3(8).toString("hex")}.tmp`);
1151
+ let fd;
1042
1152
  try {
1043
- if (identity !== null && identity !== undefined && identity !== "") {
1044
- if (verifyIdentity(pid, identity))
1045
- signalGroup(pid, "SIGTERM");
1046
- return;
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
- await sleep(POLL_INTERVAL_MS);
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
- const lockInfo = readLockFile(lockPath);
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
- async function probe(baseUrl, password) {
1174
+ function writeRosterExclusive(rosterPath, data) {
1175
+ const dir = join4(rosterPath, "..");
1073
1176
  try {
1074
- const res = await fetch(`${baseUrl}/session?limit=1`, {
1075
- headers: { authorization: `Basic ${basicAuthToken(password)}` },
1076
- signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
1077
- });
1078
- if (res.status === 200)
1079
- return "ready";
1080
- if (res.status === 401 || res.status === 403)
1081
- return "auth-failure";
1082
- return "retry";
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
- function childDied(child, pid) {
1088
- return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
1089
- }
1090
- async function waitForReadinessLine(logPath, child, pid, deadline) {
1091
- const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
1092
- while (Date.now() < deadline) {
1093
- if (childDied(child, pid))
1094
- return null;
1095
- const tail = readLogTail(logPath);
1096
- const match = readinessLine.exec(tail);
1097
- if (match?.[1]) {
1098
- const port = Number.parseInt(match[1], 10);
1099
- if (Number.isInteger(port) && port > 0 && port <= 65535) {
1100
- return { port, baseUrl: `http://127.0.0.1:${port}` };
1101
- }
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
- await sleep(POLL_INTERVAL_MS);
1194
+ return {
1195
+ ok: false,
1196
+ error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err)}`
1197
+ };
1104
1198
  }
1105
- return null;
1106
- }
1107
- async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1108
- while (Date.now() < deadline) {
1109
- if (childDied(child, pid))
1110
- return "died";
1111
- const outcome = await probe(baseUrl, password);
1112
- if (outcome === "ready")
1113
- return "ready";
1114
- if (outcome === "auth-failure")
1115
- return "auth-failure";
1116
- await sleep(POLL_INTERVAL_MS);
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
- return "timeout";
1211
+ closeQuietly3(fd);
1212
+ return { ok: true };
1119
1213
  }
1120
- async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
1121
- const deadline = Date.now() + budgetMs;
1122
- const logPath = logFilePath(rosterPath);
1123
- const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
1124
- const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
1125
- const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
1126
- if (lineResult === null) {
1127
- const diedEarly = childDied(child, pid);
1128
- killIdentifiedProcess(pid, identity);
1129
- throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
1130
- }
1131
- const { port, baseUrl } = lineResult;
1132
- const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
1133
- const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
1134
- if (outcome === "ready")
1135
- return { port, baseUrl };
1136
- killIdentifiedProcess(pid, identity);
1137
- if (outcome === "died") {
1138
- throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
1139
- }
1140
- if (outcome === "auth-failure") {
1141
- throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
1142
- }
1143
- throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
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
- var PROVISIONAL_FRESH_WINDOW_MS = 5000;
1146
- function reapOrphanedProvisional(rosterPath) {
1147
- const provisional = readProvisional(rosterPath);
1148
- if (!provisional)
1149
- return;
1150
- const discovery = readDiscovery(rosterPath);
1151
- if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
1152
- removeProvisional(rosterPath);
1153
- return;
1154
- }
1155
- const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
1156
- const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
1157
- if (hasIdentity || isFresh) {
1158
- killIdentifiedProcess(provisional.pid, provisional.identity);
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
- removeProvisional(rosterPath);
1161
- }
1162
- async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
1163
- reapOrphanedProvisional(rosterPath);
1164
- const password = randomBytes3(32).toString("base64url");
1165
- const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
1166
- const cwd = managedConfig.cwd ?? dirname(rosterPath);
1167
- const requestedPort = managedConfig.port ?? 0;
1168
- const logPath = logFilePath(rosterPath);
1169
- const logFd = openSync3(logPath, "w", 384);
1170
- let child;
1171
- let pid;
1172
- let spawnError;
1173
- try {
1174
- child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
1175
- cwd,
1176
- detached: true,
1177
- stdio: ["ignore", logFd, logFd],
1178
- env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
1179
- });
1180
- child.on("error", (err) => {
1181
- spawnError = err;
1182
- });
1183
- child.unref();
1184
- pid = child.pid;
1185
- } finally {
1186
- closeQuietly(logFd);
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
- if (pid === undefined) {
1189
- throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
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
- const identity = captureIdentity(pid);
1192
- writeProvisional(rosterPath, {
1193
- pid,
1194
- identity: identity ?? "",
1195
- password,
1196
- since: Date.now()
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
- let port;
1199
- let baseUrl;
1200
- try {
1201
- const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
1202
- const spawnErrorWatch = new Promise((_resolve, reject) => {
1203
- const check = setInterval(() => {
1204
- if (spawnError) {
1205
- clearInterval(check);
1206
- reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
1207
- }
1208
- }, POLL_INTERVAL_MS);
1209
- readiness.finally(() => clearInterval(check)).catch(() => {});
1210
- });
1211
- const result = await Promise.race([readiness, spawnErrorWatch]);
1212
- port = result.port;
1213
- baseUrl = result.baseUrl;
1214
- } finally {
1215
- removeProvisional(rosterPath);
1216
- }
1217
- const finalIdentity = identity ?? captureIdentity(pid) ?? "";
1218
- writeDiscovery(rosterPath, {
1219
- port,
1220
- pid,
1221
- identity: finalIdentity,
1222
- password,
1223
- spawnConfig: { command, cwd, port: requestedPort },
1224
- baseUrl,
1225
- rosterPath
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
- async function ensureServer(rosterPath, options = {}) {
1235
- if (existsSync2(rosterPath)) {
1236
- rosterPath = realpathSync3(rosterPath);
1237
- }
1238
- const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
1239
- const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
1240
- const fastPath = attachServer(rosterPath);
1241
- if (fastPath)
1242
- return fastPath;
1243
- const manifest = readManifest(rosterPath);
1244
- if (manifest.server.managed === undefined) {
1245
- throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
1246
- }
1247
- const lock = acquireLock(rosterPath);
1248
- if (lock === null) {
1249
- return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
1250
- }
1251
- try {
1252
- const attached = attachServer(rosterPath);
1253
- if (attached)
1254
- return attached;
1255
- return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
1256
- } finally {
1257
- releaseLock(lock);
1258
- }
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 serverStatus(rosterPath) {
1261
- const discovery = readDiscovery(rosterPath);
1262
- if (!discovery) {
1263
- return { running: false };
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
- if (!verifyIdentity(discovery.pid, discovery.identity)) {
1266
- removeDiscoveryIfMatches(rosterPath, {
1267
- pid: discovery.pid,
1268
- identity: discovery.identity
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
- let configDrift;
1273
- try {
1274
- const manifest = readManifest(rosterPath);
1275
- if (manifest.server.managed) {
1276
- const current = manifest.server.managed;
1277
- const currentCommand = current.command ?? ["harness", "serve"];
1278
- const currentCwd = current.cwd ?? dirname(rosterPath);
1279
- const currentPort = current.port ?? 0;
1280
- const storedCommand = discovery.spawnConfig.command ?? [
1281
- "harness",
1282
- "serve"
1283
- ];
1284
- const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
1285
- const storedPort = discovery.spawnConfig.port ?? 0;
1286
- configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
1287
- }
1288
- } catch {}
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
- running: true,
1291
- port: discovery.port,
1292
- pid: discovery.pid,
1293
- configDrift
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
- async function stopServer(rosterPath) {
1297
- const discovery = readDiscovery(rosterPath);
1298
- if (!discovery)
1299
- return { stopped: false };
1300
- if (!verifyIdentity(discovery.pid, discovery.identity)) {
1301
- await reapSurvivingGroup(discovery.pid);
1302
- removeDiscovery(rosterPath);
1303
- return { stopped: false };
1304
- }
1305
- const { pid } = discovery;
1306
- let groupSignaled;
1307
- const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
1308
- try {
1309
- groupSignaled = signalGroup(pid, "SIGTERM");
1310
- } catch (err) {
1311
- if (isEpermError(err)) {
1312
- return { stopped: false };
1313
- }
1314
- removeDiscovery(rosterPath);
1315
- return { stopped: true };
1316
- }
1317
- if (await waitForCompletion(STOP_GRACE_MS)) {
1318
- removeDiscovery(rosterPath);
1319
- return { stopped: true };
1320
- }
1321
- try {
1322
- groupSignaled = signalGroup(pid, "SIGKILL");
1323
- } catch (err) {
1324
- if (isEpermError(err)) {
1325
- return { stopped: false };
1326
- }
1327
- removeDiscovery(rosterPath);
1328
- return { stopped: true };
1329
- }
1330
- if (await waitForCompletion(STOP_GRACE_MS)) {
1331
- removeDiscovery(rosterPath);
1332
- return { stopped: true };
1333
- }
1334
- return { stopped: false };
1335
- }
1336
- async function reapSurvivingGroup(pid) {
1337
- try {
1338
- if (isAlive(pid))
1339
- return;
1340
- let groupAlive;
1341
- try {
1342
- process.kill(-pid, 0);
1343
- groupAlive = true;
1344
- } catch {
1345
- groupAlive = false;
1346
- }
1347
- if (!groupAlive)
1348
- return;
1349
- if (!signalGroupOnly(pid, "SIGTERM"))
1350
- return;
1351
- if (await waitForGroupDeath(pid, STOP_GRACE_MS))
1352
- return;
1353
- signalGroupOnly(pid, "SIGKILL");
1354
- await waitForGroupDeath(pid, STOP_GRACE_MS);
1355
- } catch {}
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
- async function stopForHung(tick) {
1358
- try {
1359
- await tick.stop(tick.rosterPath);
1360
- } catch {}
1361
- return { kind: "outcome", outcome: { reason: "hung" } };
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
- async function superviseTick(tick, state) {
1364
- const st = tick.status(tick.rosterPath);
1365
- if (!st.running) {
1366
- await reapSurvivingGroup(tick.handle.pid);
1367
- return { kind: "outcome", outcome: { reason: "died" } };
1368
- }
1369
- const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1370
- const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1371
- const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1372
- if (failures >= tick.threshold) {
1373
- return stopForHung(tick);
1374
- }
1375
- if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1376
- return stopForHung(tick);
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
- return { kind: "tick", failures, lastReadyAt };
1379
- }
1380
- function makeSuperviseTick(rosterPath, handle, opts) {
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
- rosterPath,
1383
- handle,
1384
- password: handle.credentials.password ?? "",
1385
- threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1386
- unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1387
- now: opts.now ?? Date.now,
1388
- status: opts.status ?? serverStatus,
1389
- probe: opts.probe ?? probe,
1390
- stop: opts.stop ?? stopServer
1494
+ text: `bus_registry use: active roster set to "${resolved.name}" (${resolved.path})`
1391
1495
  };
1392
1496
  }
1393
- async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1394
- if (!interrupt) {
1395
- await doSleep(intervalMs);
1396
- return;
1397
- }
1398
- let timer;
1399
- const timed = new Promise((resolve) => {
1400
- timer = setTimeout(resolve, intervalMs);
1497
+ function runCreate(args) {
1498
+ const result = createRoster({
1499
+ name: args.name,
1500
+ rosterPath: args.path,
1501
+ server: args.server
1401
1502
  });
1402
- try {
1403
- await Promise.race([timed, interrupt]);
1404
- } finally {
1405
- if (timer !== undefined)
1406
- clearTimeout(timer);
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
- async function superviseServer(rosterPath, handle, opts = {}) {
1410
- const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1411
- const tick = makeSuperviseTick(rosterPath, handle, opts);
1412
- const doSleep = opts.sleep ?? sleep;
1413
- const shouldStop = opts.shouldStop ?? (() => false);
1414
- let state = { failures: 0, lastReadyAt: tick.now() };
1415
- for (;; ) {
1416
- if (shouldStop())
1417
- return { reason: "signal" };
1418
- const result = await superviseTick(tick, state);
1419
- if (result.kind === "outcome")
1420
- return result.outcome;
1421
- state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
1422
- if (shouldStop())
1423
- return { reason: "signal" };
1424
- await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1425
- }
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
- async function waitForDeath(pid, budgetMs) {
1428
- const deadline = Date.now() + budgetMs;
1429
- while (Date.now() < deadline) {
1430
- if (!isAlive(pid))
1431
- return true;
1432
- await sleep(POLL_INTERVAL_MS);
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 !isAlive(pid);
1528
+ return { text: `bus_registry unregister: "${args.name}" unregistered` };
1435
1529
  }
1436
- async function waitForGroupDeath(pid, budgetMs) {
1437
- const deadline = Date.now() + budgetMs;
1438
- const groupAlive = () => {
1439
- try {
1440
- process.kill(-pid, 0);
1441
- return true;
1442
- } catch {
1443
- return false;
1444
- }
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
- // src/tools/bus_registry.ts
1455
- import { isAbsolute as isAbsolute2 } from "node:path";
1456
- import { tool } from "@opencode-ai/plugin";
1457
- import { z as z4 } from "zod";
1458
-
1459
- // src/format.ts
1460
- function formatRosterHeader(source) {
1461
- return `roster: ${source.name ?? source.path}`;
1462
- }
1463
- function formatRoster(projects) {
1464
- return projects.map((p) => {
1465
- if (!p.pathExists)
1466
- return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
1467
- if (p.statusError)
1468
- return `${p.name}: status error (${p.statusError}) — ${p.description}`;
1469
- const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
1470
- return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
1471
- }).join(`
1472
- `);
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 formatDispatch(r) {
1475
- switch (r.mode) {
1476
- case "new":
1477
- return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
1478
- case "question-reply":
1479
- return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
1480
- case "follow-up":
1481
- return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
1482
- case "blocked":
1483
- return `Blocked: session ${r.sessionId} (${r.project}) has a pending question (${r.requestId}) — no reply or prompt sent.`;
1484
- }
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 dispatchMetadata(r) {
1487
- return { sessionId: r.sessionId, project: r.project, mode: r.mode };
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 formatStatus(r) {
1490
- const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
1491
- `) : " (none)";
1492
- const lines = [
1493
- `session: ${r.sessionId} (${r.project})`,
1494
- `title: ${r.title ?? "(untitled)"}`,
1495
- `busy: ${r.busy}`
1496
- ];
1497
- if (r.pendingQuestion) {
1498
- lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
1499
- if (r.pendingQuestion.options.length > 0) {
1500
- lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
1501
- }
1502
- lines.push(` (answer with bus_task using sessionId)`);
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 formatWait(r) {
1509
- const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
1510
- const sessionLines = r.sessions.map((s) => {
1511
- const parts = [
1512
- ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
1513
- ];
1514
- if (s.pendingQuestion) {
1515
- parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
1516
- if (s.pendingQuestion.options.length > 0) {
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/roster-edit.ts
1541
- import { randomBytes as randomBytes4 } from "node:crypto";
1542
- import {
1543
- chmodSync as chmodSync2,
1544
- closeSync as closeSync3,
1545
- constants as fsConstants3,
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 isErrnoCode3(err, code) {
1562
- return typeof err === "object" && err !== null && "code" in err && err.code === code;
1620
+ function err(error) {
1621
+ return { ok: false, error };
1563
1622
  }
1564
- function duplicateProjectName(projects) {
1565
- const seen = new Set;
1566
- for (const p of projects) {
1567
- if (seen.has(p.name))
1568
- return p.name;
1569
- seen.add(p.name);
1570
- }
1571
- return null;
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 validateManifest(data) {
1574
- const parsed = manifestSchema.safeParse(data);
1575
- if (!parsed.success) {
1576
- return {
1577
- ok: false,
1578
- error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
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 readManifest2(rosterPath) {
1598
- let raw;
1599
- try {
1600
- raw = readFileSync5(rosterPath, "utf8");
1601
- } catch (err) {
1602
- return {
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 writeManifestAtomic(rosterPath, data) {
1619
- const dir = join4(rosterPath, "..");
1646
+ async function api(baseUrl, credentials, directory, path, init) {
1620
1647
  try {
1621
- mkdirSync3(dir, { recursive: true });
1622
- } catch (err) {
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
- ok: false,
1625
- error: `space-bus: failed to create directory ${dir}: ${String(err)}`
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
- let existingMode;
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
- existingMode = statSync3(rosterPath).mode & 511;
1678
+ messages = turnMessageListSchema.parse(JSON.parse(bodyText));
1631
1679
  } catch {
1632
- existingMode = undefined;
1680
+ return [];
1633
1681
  }
1634
- const tempPath = join4(dir, `.spacebus.${randomBytes4(8).toString("hex")}.tmp`);
1635
- let fd;
1636
- try {
1637
- fd = openSync4(tempPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY, 420);
1638
- writeSync2(fd, JSON.stringify(data, null, 2));
1639
- if (existingMode !== undefined) {
1640
- chmodSync2(tempPath, existingMode);
1641
- }
1642
- closeSync3(fd);
1643
- fd = undefined;
1644
- renameSync3(tempPath, rosterPath);
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 { ok: true };
1694
+ return Array.from(byFile.values());
1657
1695
  }
1658
- function writeRosterExclusive(rosterPath, data) {
1659
- const dir = join4(rosterPath, "..");
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
- mkdirSync3(dir, { recursive: true });
1662
- } catch (err) {
1663
- return {
1664
- ok: false,
1665
- error: `space-bus: failed to create directory ${dir}: ${String(err)}`
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
- fd = openSync4(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
1671
- } catch (err) {
1672
- if (isErrnoCode3(err, "EEXIST")) {
1673
- return {
1674
- ok: false,
1675
- error: `space-bus: refusing to overwrite existing roster file at ${rosterPath}`
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
- return {
1679
- ok: false,
1680
- error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err)}`
1681
- };
1682
- }
1716
+ } catch {}
1683
1717
  try {
1684
- writeSync2(fd, JSON.stringify(data, null, 2));
1685
- } catch (err) {
1686
- closeQuietly3(fd);
1687
- try {
1688
- unlinkSync3(rosterPath);
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
- if (lstatSync2(rosterPath).isSymbolicLink()) {
1701
- return {
1702
- ok: false,
1703
- error: `space-bus: refusing to edit a symlinked roster file at ${rosterPath}`
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
- const current = readManifest2(rosterPath);
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 createRoster(opts) {
1719
- const nameCheck = /^[a-z0-9-]{1,64}$/.test(opts.name);
1720
- if (!nameCheck) {
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 readResult = readRegistry();
1727
- if (!readResult.ok)
1728
- return readResult;
1729
- const collision = readResult.registry.rosters.find((entry) => entry.name.toLowerCase() === opts.name.toLowerCase());
1730
- if (collision) {
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
- const candidate = {
1737
- server: opts.server ?? { managed: {} },
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 { ok: true };
1757
+ return {
1758
+ ok: true,
1759
+ baseUrl: roster.server.baseUrl,
1760
+ projects: roster.projects,
1761
+ credentials: credentials ?? {}
1762
+ };
1755
1763
  }
1756
- function addProject(rosterPath, project) {
1757
- return editManifest(rosterPath, (current) => {
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 removeProject(rosterPath, projectName) {
1768
- return editManifest(rosterPath, (current) => {
1769
- const exists = current.projects.some((p) => p.name === projectName);
1770
- if (!exists) {
1771
- const known = current.projects.map((p) => p.name);
1772
- return {
1773
- ok: false,
1774
- 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)`
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 updateProject(rosterPath, projectName, patch) {
1784
- return editManifest(rosterPath, (current) => {
1785
- const index = current.projects.findIndex((p) => p.name === projectName);
1786
- if (index === -1) {
1787
- const known = current.projects.map((p) => p.name);
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
- ok: false,
1790
- 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)`
1786
+ name: p.name,
1787
+ path: p.expandedPath,
1788
+ description: p.description,
1789
+ pathExists: false
1791
1790
  };
1792
1791
  }
1793
- if (patch.name !== undefined && patch.name !== projectName && current.projects.some((p) => p.name === patch.name)) {
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
- ok: false,
1796
- error: `space-bus: cannot rename project "${projectName}" to "${patch.name}" in ${rosterPath} — a project with that name already exists`
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
- ok: false,
1804
- error: `space-bus: internal error locating project "${projectName}"`
1821
+ name: p.name,
1822
+ path: p.expandedPath,
1823
+ description: p.description,
1824
+ pathExists: true,
1825
+ statusError: e.message
1805
1826
  };
1806
1827
  }
1807
- projects[index] = { ...existing, ...patch };
1808
- return { ...current, projects };
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
- function editServer(rosterPath, server) {
1812
- if (attachLive(rosterPath) !== null) {
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: false,
1815
- error: `space-bus: a managed daemon is running for roster ${rosterPath} — run \`space-bus stop\` first before editing its server block`
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 editManifest(rosterPath, (current) => ({ ...current, server }));
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
- // src/tools/bus_registry.ts
1822
- 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.";
1823
- var projectInputSchema = z4.object({
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
- rosters: read.registry.rosters.map((r) => ({
1943
- name: r.name,
1944
- path: r.path,
1945
- default: read.registry.default === r.name,
1946
- active: active === r.name
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 formatList(rosters) {
1951
- if (rosters.length === 0)
1952
- return "no rosters registered";
1953
- return rosters.map((r) => {
1954
- const flags = [
1955
- r.default ? "default" : null,
1956
- r.active ? "active" : null
1957
- ].filter((f) => f !== null);
1958
- const suffix = flags.length > 0 ? ` (${flags.join(", ")})` : "";
1959
- return `${r.name}: ${r.path}${suffix}`;
1960
- }).join(`
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 runList(session) {
1964
- const listed = registryListMetadata(session);
1965
- if (!listed.ok)
1966
- throw new Error(`bus_registry list: ${listed.error}`);
1967
- return { text: formatList(listed.rosters), listMetadata: listed.rosters };
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 runUse(args, session) {
1970
- if (!session) {
1971
- throw new Error("bus_registry use: roster selection is a connector-session concept — plugin calls resolve by workspace directory; pass roster per call instead");
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 runCreate(args) {
1982
- const result = createRoster({
1983
- name: args.name,
1984
- rosterPath: args.path,
1985
- server: args.server
1986
- });
1987
- if (!result.ok)
1988
- throw new Error(`bus_registry create: ${result.error}`);
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
- text: `bus_registry create: ${formatRosterHeader({ name: args.name, path: args.path })} created and registered`
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 runRegister(args) {
1994
- const result = registerRoster(args.name, args.path);
1995
- if (!result.ok)
1996
- throw new Error(`bus_registry register: ${result.error}`);
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
- text: `bus_registry register: ${formatRosterHeader({ name: args.name, path: args.path })} registered`
2078
+ ok: true,
2079
+ pending: pendingList.find((q) => q.sessionID === sessionId)
1999
2080
  };
2000
2081
  }
2001
- function runUnregister(args, session) {
2002
- const result = unregisterRoster(args.name);
2003
- if (!result.ok)
2004
- throw new Error(`bus_registry unregister: ${result.error}`);
2005
- const active = session?.getActive();
2006
- if (active !== undefined && active.toLowerCase() === args.name.toLowerCase()) {
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
- text: `bus_registry unregister: "${args.name}" unregistered — session-active roster cleared — omitted-roster calls fall back to ambient`
2089
+ ok: true,
2090
+ sessionId,
2091
+ project,
2092
+ mode: "blocked",
2093
+ requestId: pending.id
2010
2094
  };
2011
2095
  }
2012
- return { text: `bus_registry unregister: "${args.name}" unregistered` };
2013
- }
2014
- function runSetDefault(args) {
2015
- const result = setDefaultRoster(args.name);
2016
- if (!result.ok)
2017
- throw new Error(`bus_registry set-default: ${result.error}`);
2018
- return {
2019
- text: `bus_registry set-default: "${args.name}" is now the default roster`
2020
- };
2021
- }
2022
- function runAddProject(args) {
2023
- const resolved = resolveRosterByName(args.roster);
2024
- if (!resolved.ok)
2025
- throw new Error(`bus_registry add-project: ${resolved.error}`);
2026
- const result = addProject(resolved.path, args.project);
2027
- if (!result.ok)
2028
- throw new Error(`bus_registry add-project: ${result.error}`);
2029
- return {
2030
- text: `bus_registry add-project: added "${args.project.name}" to ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
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
- text: `bus_registry update-project: updated "${args.projectName}" on ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2117
+ ok: true,
2118
+ sessionId,
2119
+ project,
2120
+ mode: "follow-up",
2121
+ ...messageId !== undefined ? { messageId } : {}
2053
2122
  };
2054
2123
  }
2055
- async function runBusRegistryAction(rawArgs, session) {
2056
- const parsed = ACTION_SCHEMA.safeParse(rawArgs);
2057
- if (!parsed.success) {
2058
- const issue = parsed.error.issues[0];
2059
- const detail = issue ? `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}` : parsed.error.message;
2060
- throw new Error(`bus_registry ${rawArgs.action}: invalid input — ${detail}`);
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 args = parsed.data;
2063
- switch (args.action) {
2064
- case "list":
2065
- return runList(session);
2066
- case "use":
2067
- return runUse(args, session);
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 makeBusRegistry(session) {
2085
- return tool({
2086
- description: BUS_REGISTRY_DESCRIPTION,
2087
- args: BUS_REGISTRY_ARGS,
2088
- async execute(args) {
2089
- const { text, listMetadata } = await runBusRegistryAction(args, session);
2090
- if (listMetadata)
2091
- return { output: text, metadata: { rosters: listMetadata } };
2092
- return text;
2093
- }
2094
- });
2095
- }
2096
-
2097
- // src/tools/bus_result.ts
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
- function authHeader(credentials) {
2115
- if (!credentials.password)
2116
- return {};
2117
- const username = credentials.username ?? "opencode";
2118
- const token = toBase64(`${username}:${credentials.password}`);
2119
- return { Authorization: `Basic ${token}` };
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 api(baseUrl, credentials, directory, path, init) {
2122
- try {
2123
- const res = await fetch(`${baseUrl}${path}`, {
2124
- ...init,
2125
- headers: {
2126
- "content-type": "application/json",
2127
- "x-opencode-directory": directory,
2128
- ...authHeader(credentials),
2129
- ...init?.headers
2130
- },
2131
- redirect: "error",
2132
- signal: AbortSignal.timeout(30000)
2133
- });
2134
- const bodyText = await res.text().catch(() => "<unreadable body>");
2135
- return { res, bodyText };
2136
- } catch (e) {
2137
- const message = e.message;
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 fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
2148
- const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
2149
- if (!res.ok)
2150
- return [];
2151
- let messages;
2152
- try {
2153
- messages = turnMessageListSchema.parse(JSON.parse(bodyText));
2154
- } catch {
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 byFile = new Map;
2158
- for (const m of messages) {
2159
- if (m.info.role !== "user")
2160
- continue;
2161
- const diffs = m.info.summary?.diffs;
2162
- if (!diffs || diffs.length === 0)
2163
- continue;
2164
- for (const d of diffs) {
2165
- const key = d.file ?? `<unknown:${byFile.size}>`;
2166
- byFile.set(key, d);
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
- return Array.from(byFile.values());
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
- async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
2172
- const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
2173
- let diff = [];
2281
+ function parsePendingQuestions(questionRes) {
2282
+ if (!questionRes.res.ok)
2283
+ return new Map;
2174
2284
  try {
2175
- diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
2285
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
2286
+ return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
2176
2287
  } catch {
2177
- diff = [];
2288
+ return new Map;
2178
2289
  }
2179
- if (diff.length > 0) {
2180
- return { diff, diffSource: "session" };
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
- const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
2184
- if (sessionRes.res.ok) {
2185
- const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
2186
- const summaryDiffs = parsed.summary?.diffs;
2187
- if (summaryDiffs && summaryDiffs.length > 0) {
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
- } catch {}
2350
+ }
2192
2351
  try {
2193
- const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
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
- const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
2200
- if (vcsRes.res.ok) {
2201
- const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
2202
- if (vcsStatus.length > 0) {
2203
- return {
2204
- diff: vcsStatus.map((v) => ({
2205
- file: v.file,
2206
- additions: v.additions,
2207
- deletions: v.deletions,
2208
- status: v.status
2209
- })),
2210
- diffSource: "working-tree"
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 validateContext(context) {
2218
- const parsed = busContextSchema.safeParse(context);
2219
- if (!parsed.success) {
2220
- return err(`space-bus: invalid context: ${parsed.error.message}`);
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 { roster, credentials } = parsed.data;
2223
- let hostname;
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
- hostname = new URL(roster.server.baseUrl).hostname;
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 err("space-bus: context roster server.baseUrl is not a valid URL");
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 resolveProjectOrErr(projects, name) {
2243
- const project = findProject(projects, name);
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 roster(opts) {
2254
- const ctx = validateContext(opts.context);
2255
- if (!ctx.ok)
2256
- return ctx;
2257
- const { baseUrl, projects, credentials } = ctx;
2258
- const results = await Promise.all(projects.map(async (p) => {
2259
- if (!p.exists) {
2260
- return {
2261
- name: p.name,
2262
- path: p.expandedPath,
2263
- description: p.description,
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
- return { ok: true, projects: results };
2428
+ await sleep2(POLL_INTERVAL_MS);
2429
+ }
2430
+ return null;
2305
2431
  }
2306
- async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
2307
- const resolved = resolveProjectOrErr(projects, project);
2308
- if (!resolved.ok)
2309
- return resolved;
2310
- const directory = resolved.project.expandedPath;
2311
- const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
2312
- const createRes = await api(baseUrl, credentials, directory, "/session", {
2313
- method: "POST",
2314
- body: JSON.stringify({ title: sessionTitle })
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
- let session;
2320
- try {
2321
- session = sessionSchema.parse(JSON.parse(createRes.bodyText));
2322
- } catch (e) {
2323
- return err(`space-bus: unexpected /session response shape: ${e.message}`);
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 promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
2326
- method: "POST",
2327
- body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
2328
- });
2329
- if (promptRes.res.status !== 204) {
2330
- return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
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
- return { ok: true, sessionId: session.id, project, directory };
2468
+ throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
2333
2469
  }
2334
- function toDispatchArgs(input) {
2335
- if (input.onPendingQuestion !== undefined && input.onPendingQuestion !== "question-reply" && input.onPendingQuestion !== "blocked") {
2336
- return err(`space-bus: onPendingQuestion must be "question-reply" or "blocked", got ${JSON.stringify(input.onPendingQuestion)}`);
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
- if (input.sessionId !== undefined && input.sessionId === "") {
2339
- return err("space-bus: sessionId must be a non-empty string");
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
- if (!input.sessionId) {
2342
- if (!input.project) {
2343
- return err("space-bus: project is required when starting a new session");
2344
- }
2345
- return {
2346
- ok: true,
2347
- prompt: input.prompt,
2348
- title: input.title,
2349
- project: input.project,
2350
- onPendingQuestion: input.onPendingQuestion
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
- ok: true,
2355
- prompt: input.prompt,
2356
- title: input.title,
2357
- sessionId: input.sessionId,
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 dispatch(args, opts) {
2363
- const ctx = validateContext(opts.context);
2364
- if (!ctx.ok)
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 loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
2386
- if (!loc.ok)
2387
- return loc;
2388
- const { directory, project } = loc;
2389
- if (args.project && args.project !== project) {
2390
- return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
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
- return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project, args.onPendingQuestion ?? "question-reply");
2393
- }
2394
- async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
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 { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
2436
- if (!res.ok)
2437
- return;
2438
- const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
2439
- const entry = entries.find((e) => e.sessionID === sessionId);
2440
- if (!entry)
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
- async function status(sessionId, opts) {
2449
- const ctx = validateContext(opts.context);
2450
- if (!ctx.ok)
2451
- return ctx;
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
- let session;
2468
- let statusMap;
2469
- let todos;
2470
- try {
2471
- session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
2472
- statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
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
- const entry = statusMap[sessionId];
2478
- const busy = isStatusBusy(entry);
2479
- const { diff, diffSource } = diffResult;
2480
- const additions = diff.reduce((sum, d) => sum + d.additions, 0);
2481
- const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
2482
- const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
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
- ok: true,
2485
- sessionId,
2486
- project,
2487
- busy,
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 resolvePendingQuestionForSteer(baseUrl, credentials, directory, sessionId, onPendingQuestion) {
2498
- const questionsRes = await api(baseUrl, credentials, directory, "/question");
2499
- if (!questionsRes.res.ok) {
2500
- if (onPendingQuestion === "blocked") {
2501
- return err(`space-bus: could not verify pending-question state for session ${sessionId} (/question ${questionsRes.res.status}) — refusing to dispatch under the blocked policy`);
2502
- }
2503
- return { ok: true, pending: undefined };
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
- let pendingList;
2630
+ const { pid } = discovery;
2631
+ let groupSignaled;
2632
+ const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
2506
2633
  try {
2507
- pendingList = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
2508
- } catch (e) {
2509
- if (onPendingQuestion === "blocked") {
2510
- return err(`space-bus: could not parse pending-question state for session ${sessionId}: ${e.message} — refusing to dispatch under the blocked policy`);
2634
+ groupSignaled = signalGroup(pid, "SIGTERM");
2635
+ } catch (err) {
2636
+ if (isEpermError(err)) {
2637
+ return { stopped: false };
2511
2638
  }
2512
- return { ok: true, pending: undefined };
2639
+ removeDiscovery(rosterPath);
2640
+ return { stopped: true };
2513
2641
  }
2514
- return {
2515
- ok: true,
2516
- pending: pendingList.find((q) => q.sessionID === sessionId)
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
- if (pending) {
2534
- const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
2535
- method: "POST",
2536
- body: JSON.stringify({ answers: [[message]] })
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
- return { ok: true, sessionId, project, mode: "question-reply" };
2652
+ removeDiscovery(rosterPath);
2653
+ return { stopped: true };
2542
2654
  }
2543
- const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
2544
- method: "POST",
2545
- body: JSON.stringify({ parts: [{ type: "text", text: message }] })
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 { ok: true, sessionId, project, mode: "follow-up" };
2659
+ return { stopped: false };
2551
2660
  }
2552
- async function result(sessionId, opts) {
2553
- const ctx = validateContext(opts.context);
2554
- if (!ctx.ok)
2555
- return ctx;
2556
- const { baseUrl, projects, credentials } = ctx;
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
- const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
2565
- const entry = statusMap[sessionId];
2566
- if (isStatusBusy(entry)) {
2567
- return err(`space-bus: session ${sessionId} is still running, use bus_status`);
2568
- }
2569
- } catch {}
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 [messageRes, diffResult] = await Promise.all([
2572
- api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
2573
- fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
2574
- ]);
2575
- if (!messageRes.res.ok) {
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
- let messages;
2579
- try {
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
- const { diff, diffSource } = diffResult;
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
- var DEFAULT_WAIT_TIMEOUT_MS = 60000;
2606
- var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
2607
- var DEFAULT_WAIT_CONCURRENCY = 4;
2608
- var NEEDS_ATTENTION_STATES = [
2609
- "complete",
2610
- "blocked",
2611
- "failed",
2612
- "not_found"
2613
- ];
2614
- function sleep2(ms) {
2615
- return new Promise((resolve) => setTimeout(resolve, ms));
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 resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
2618
- const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
2619
- const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
2620
- return { id, loc };
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
- const groups = new Map;
2627
- for (const id of sessionIds) {
2628
- const loc = locationById.get(id);
2629
- if (!loc)
2630
- continue;
2631
- const group = groups.get(loc.directory) ?? {
2632
- directory: loc.directory,
2633
- sessionIds: []
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
- const lastKnown = new Map;
2639
- for (const id of sessionIds) {
2640
- const loc = locationById.get(id);
2641
- lastKnown.set(id, {
2642
- sessionId: id,
2643
- project: loc?.project ?? "",
2644
- state: loc ? "running" : "not_found",
2645
- resultAvailable: false
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 wait(sessionIds, opts) {
2651
- const ctx = validateContext(opts.context);
2652
- if (!ctx.ok)
2653
- return ctx;
2654
- const { baseUrl, projects, credentials } = ctx;
2655
- const uniqueIds = Array.from(new Set(sessionIds));
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
- const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
2660
- const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
2661
- const deadline = Date.now() + timeoutMs;
2662
- const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
2663
- async function pollGroup(group) {
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
- statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
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
- const remaining = deadline - Date.now();
2706
- await sleep2(Math.min(pollIntervalMs, Math.max(0, remaining)));
2707
- }
2708
- }
2709
- function parsePendingQuestions(questionRes) {
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 rosterPath2 = resolved.path;
2727
- if (isManagedRosterAtPath(rosterPath2)) {
2728
- await ensure(rosterPath2);
2785
+ const rosterPath = resolved.path;
2786
+ if (isManagedRosterAtPath(rosterPath)) {
2787
+ await ensure(rosterPath);
2729
2788
  }
2730
- const context = loadContextForRosterPath(rosterPath2);
2731
- return { context, rosterName: resolved.name, rosterPath: rosterPath2 };
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) {