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