@fro.bot/space-bus 0.8.0 → 0.9.0

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
@@ -11,6 +11,23 @@ var sessionSchema = z.looseObject({
11
11
  });
12
12
  var sessionListSchema = z.array(sessionSchema);
13
13
  var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
14
+ var sessionStateSchema = z.enum([
15
+ "running",
16
+ "blocked",
17
+ "complete",
18
+ "failed",
19
+ "not_found"
20
+ ]);
21
+ var sessionStateInfoSchema = z.object({
22
+ sessionId: z.string(),
23
+ project: z.string(),
24
+ state: sessionStateSchema,
25
+ resultAvailable: z.boolean(),
26
+ pendingQuestion: z.object({
27
+ preview: z.string(),
28
+ options: z.array(z.string())
29
+ }).optional()
30
+ });
14
31
  var todoSchema = z.array(z.looseObject({
15
32
  content: z.string(),
16
33
  status: z.string(),
@@ -253,6 +270,9 @@ function validateContext(context) {
253
270
  credentials: credentials ?? {}
254
271
  };
255
272
  }
273
+ function isStatusBusy(entry) {
274
+ return entry?.type === "busy" || entry?.type === "retry" || false;
275
+ }
256
276
  function resolveProjectOrErr(projects, name) {
257
277
  const project = findProject(projects, name);
258
278
  if (!project) {
@@ -294,7 +314,7 @@ async function roster(opts) {
294
314
  }
295
315
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
296
316
  const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
297
- const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
317
+ const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
298
318
  const capped = sessions.length > 100;
299
319
  return {
300
320
  name: p.name,
@@ -421,6 +441,17 @@ async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
421
441
  }
422
442
  return err(`space-bus: no manifest project has a session with id ${sessionId}`);
423
443
  }
444
+ function deriveSessionState(input) {
445
+ if (!input.resolved)
446
+ return "not_found";
447
+ if (input.failed)
448
+ return "failed";
449
+ if (input.pendingQuestion)
450
+ return "blocked";
451
+ if (input.busy)
452
+ return "running";
453
+ return "complete";
454
+ }
424
455
  function formatQuestionEntry(entry) {
425
456
  const firstQuestion = entry.questions?.[0];
426
457
  const text = firstQuestion?.question ?? "";
@@ -473,10 +504,11 @@ async function status(sessionId, opts) {
473
504
  return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
474
505
  }
475
506
  const entry = statusMap[sessionId];
476
- const busy = entry ? entry.type === "busy" || entry.type === "retry" : false;
507
+ const busy = isStatusBusy(entry);
477
508
  const { diff, diffSource } = diffResult;
478
509
  const additions = diff.reduce((sum, d) => sum + d.additions, 0);
479
510
  const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
511
+ const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
480
512
  return {
481
513
  ok: true,
482
514
  sessionId,
@@ -486,7 +518,9 @@ async function status(sessionId, opts) {
486
518
  todos,
487
519
  diff: { files: diff.length, additions, deletions },
488
520
  diffSource,
489
- pendingQuestion
521
+ pendingQuestion,
522
+ state,
523
+ resultAvailable: state === "complete"
490
524
  };
491
525
  }
492
526
  async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
@@ -533,7 +567,7 @@ async function result(sessionId, opts) {
533
567
  try {
534
568
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
535
569
  const entry = statusMap[sessionId];
536
- if (entry && (entry.type === "busy" || entry.type === "retry")) {
570
+ if (isStatusBusy(entry)) {
537
571
  return err(`space-bus: session ${sessionId} is still running, use bus_status`);
538
572
  }
539
573
  } catch {}
@@ -576,17 +610,35 @@ async function fetchSnapshotProject(baseUrl, credentials, project) {
576
610
  }
577
611
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
578
612
  const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
579
- const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
613
+ const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
580
614
  const capped = sessions.length > 100;
581
615
  let pendingQuestions;
616
+ let pendingQuestionsBySession = new Map;
582
617
  if (questionRes.res.ok) {
583
618
  try {
584
619
  const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
585
- pendingQuestions = entries.map((e) => formatQuestionEntry(e));
620
+ const formatted = entries.map((e) => formatQuestionEntry(e));
621
+ pendingQuestions = formatted;
622
+ pendingQuestionsBySession = new Map(formatted.map((q) => [q.sessionId, q]));
586
623
  } catch {
587
624
  pendingQuestions = undefined;
588
625
  }
589
626
  }
627
+ const sessionStates = sessions.map((s) => {
628
+ const entry = statusMap[s.id];
629
+ const busy = isStatusBusy(entry);
630
+ const pendingQuestion = pendingQuestionsBySession.get(s.id);
631
+ const state = deriveSessionState({
632
+ busy,
633
+ pendingQuestion,
634
+ resolved: true
635
+ });
636
+ return {
637
+ sessionId: s.id,
638
+ state,
639
+ resultAvailable: state === "complete"
640
+ };
641
+ });
590
642
  return {
591
643
  name: project.name,
592
644
  path: directory,
@@ -595,7 +647,8 @@ async function fetchSnapshotProject(baseUrl, credentials, project) {
595
647
  busyCount,
596
648
  sessionCount: capped ? 100 : sessions.length,
597
649
  sessionCountCapped: capped,
598
- pendingQuestions
650
+ pendingQuestions,
651
+ sessions: sessionStates
599
652
  };
600
653
  } catch (e) {
601
654
  return {
@@ -641,6 +694,120 @@ async function snapshot(opts) {
641
694
  });
642
695
  return { ok: true, projects: results };
643
696
  }
697
+ var DEFAULT_WAIT_TIMEOUT_MS = 60000;
698
+ var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
699
+ var DEFAULT_WAIT_CONCURRENCY = 4;
700
+ var NEEDS_ATTENTION_STATES = [
701
+ "complete",
702
+ "blocked",
703
+ "failed",
704
+ "not_found"
705
+ ];
706
+ function sleep(ms) {
707
+ return new Promise((resolve) => setTimeout(resolve, ms));
708
+ }
709
+ async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
710
+ const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
711
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
712
+ return { id, loc };
713
+ });
714
+ const locationById = new Map;
715
+ for (const { id, loc } of locations) {
716
+ locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
717
+ }
718
+ const groups = new Map;
719
+ for (const id of sessionIds) {
720
+ const loc = locationById.get(id);
721
+ if (!loc)
722
+ continue;
723
+ const group = groups.get(loc.directory) ?? {
724
+ directory: loc.directory,
725
+ sessionIds: []
726
+ };
727
+ group.sessionIds.push(id);
728
+ groups.set(loc.directory, group);
729
+ }
730
+ const lastKnown = new Map;
731
+ for (const id of sessionIds) {
732
+ const loc = locationById.get(id);
733
+ lastKnown.set(id, {
734
+ sessionId: id,
735
+ project: loc?.project ?? "",
736
+ state: loc ? "running" : "not_found",
737
+ resultAvailable: false
738
+ });
739
+ }
740
+ return { locationById, groupList: Array.from(groups.values()), lastKnown };
741
+ }
742
+ async function wait(sessionIds, opts) {
743
+ const ctx = validateContext(opts.context);
744
+ if (!ctx.ok)
745
+ return ctx;
746
+ const { baseUrl, projects, credentials } = ctx;
747
+ const uniqueIds = Array.from(new Set(sessionIds));
748
+ if (uniqueIds.length === 0) {
749
+ return { ok: true, sessions: [], waker: [], timedOut: true };
750
+ }
751
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
752
+ const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
753
+ const deadline = Date.now() + timeoutMs;
754
+ const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
755
+ async function pollGroup(group) {
756
+ const [statusRes, questionRes] = await Promise.all([
757
+ api(baseUrl, credentials, group.directory, "/session/status"),
758
+ api(baseUrl, credentials, group.directory, "/question")
759
+ ]);
760
+ if (!statusRes.res.ok)
761
+ return;
762
+ let statusMap;
763
+ try {
764
+ statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
765
+ } catch {
766
+ return;
767
+ }
768
+ const pendingBySession = parsePendingQuestions(questionRes);
769
+ for (const id of group.sessionIds) {
770
+ const entry = statusMap[id];
771
+ const busy = isStatusBusy(entry);
772
+ const pendingQuestion = pendingBySession.get(id);
773
+ const state = deriveSessionState({
774
+ busy,
775
+ pendingQuestion,
776
+ resolved: true
777
+ });
778
+ lastKnown.set(id, {
779
+ sessionId: id,
780
+ project: locationById.get(id)?.project ?? "",
781
+ state,
782
+ resultAvailable: state === "complete",
783
+ pendingQuestion
784
+ });
785
+ }
786
+ }
787
+ while (true) {
788
+ await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
789
+ const sessions = uniqueIds.map((id) => lastKnown.get(id));
790
+ const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
791
+ if (waker.length > 0) {
792
+ return { ok: true, sessions, waker, timedOut: false };
793
+ }
794
+ if (Date.now() >= deadline) {
795
+ return { ok: true, sessions, waker: [], timedOut: true };
796
+ }
797
+ const remaining = deadline - Date.now();
798
+ await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
799
+ }
800
+ }
801
+ function parsePendingQuestions(questionRes) {
802
+ if (!questionRes.res.ok)
803
+ return new Map;
804
+ try {
805
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
806
+ return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
807
+ } catch {
808
+ return new Map;
809
+ }
810
+ }
644
811
 
645
812
  // src/format.ts
646
813
  function formatRoster(projects) {
@@ -686,6 +853,25 @@ function formatStatus(r) {
686
853
  return lines.join(`
687
854
  `);
688
855
  }
856
+ function formatWait(r) {
857
+ const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
858
+ const sessionLines = r.sessions.map((s) => {
859
+ const parts = [
860
+ ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
861
+ ];
862
+ if (s.pendingQuestion) {
863
+ parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
864
+ if (s.pendingQuestion.options.length > 0) {
865
+ parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
866
+ }
867
+ parts.push(` (answer with bus_task using sessionId)`);
868
+ }
869
+ return parts.join(`
870
+ `);
871
+ });
872
+ return [header, ...sessionLines].join(`
873
+ `);
874
+ }
689
875
  function formatResult(r) {
690
876
  const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
691
877
  `) : " (no changes)";
@@ -1100,7 +1286,7 @@ var STOP_GRACE_MS = 2000;
1100
1286
  var SUPERVISE_INTERVAL_MS = 5000;
1101
1287
  var SUPERVISE_FAILURE_THRESHOLD = 3;
1102
1288
  var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1103
- function sleep(ms) {
1289
+ function sleep2(ms) {
1104
1290
  return new Promise((resolve) => setTimeout(resolve, ms));
1105
1291
  }
1106
1292
  function readManifest(rosterPath) {
@@ -1150,6 +1336,16 @@ function signalGroup(pid, sig) {
1150
1336
  } catch {}
1151
1337
  return false;
1152
1338
  }
1339
+ function signalGroupOnly(pid, sig) {
1340
+ if (pid <= 1)
1341
+ return false;
1342
+ try {
1343
+ process.kill(-pid, sig);
1344
+ return true;
1345
+ } catch {
1346
+ return false;
1347
+ }
1348
+ }
1153
1349
  function killIdentifiedProcess(pid, identity) {
1154
1350
  try {
1155
1351
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -1175,7 +1371,7 @@ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1175
1371
  if (!winnerAlive) {
1176
1372
  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`);
1177
1373
  }
1178
- await sleep(POLL_INTERVAL_MS);
1374
+ await sleep2(POLL_INTERVAL_MS);
1179
1375
  }
1180
1376
  const lockInfo = readLockFile(lockPath);
1181
1377
  const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
@@ -1212,7 +1408,7 @@ async function waitForReadinessLine(logPath, child, pid, deadline) {
1212
1408
  return { port, baseUrl: `http://127.0.0.1:${port}` };
1213
1409
  }
1214
1410
  }
1215
- await sleep(POLL_INTERVAL_MS);
1411
+ await sleep2(POLL_INTERVAL_MS);
1216
1412
  }
1217
1413
  return null;
1218
1414
  }
@@ -1225,7 +1421,7 @@ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1225
1421
  return "ready";
1226
1422
  if (outcome === "auth-failure")
1227
1423
  return "auth-failure";
1228
- await sleep(POLL_INTERVAL_MS);
1424
+ await sleep2(POLL_INTERVAL_MS);
1229
1425
  }
1230
1426
  return "timeout";
1231
1427
  }
@@ -1406,6 +1602,7 @@ async function stopServer(rosterPath) {
1406
1602
  if (!discovery)
1407
1603
  return { stopped: false };
1408
1604
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
1605
+ await reapSurvivingGroup(discovery.pid);
1409
1606
  removeDiscovery(rosterPath);
1410
1607
  return { stopped: false };
1411
1608
  }
@@ -1440,6 +1637,27 @@ async function stopServer(rosterPath) {
1440
1637
  }
1441
1638
  return { stopped: false };
1442
1639
  }
1640
+ async function reapSurvivingGroup(pid) {
1641
+ try {
1642
+ if (isAlive(pid))
1643
+ return;
1644
+ let groupAlive;
1645
+ try {
1646
+ process.kill(-pid, 0);
1647
+ groupAlive = true;
1648
+ } catch {
1649
+ groupAlive = false;
1650
+ }
1651
+ if (!groupAlive)
1652
+ return;
1653
+ if (!signalGroupOnly(pid, "SIGTERM"))
1654
+ return;
1655
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
1656
+ return;
1657
+ signalGroupOnly(pid, "SIGKILL");
1658
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
1659
+ } catch {}
1660
+ }
1443
1661
  async function stopForHung(tick) {
1444
1662
  try {
1445
1663
  await tick.stop(tick.rosterPath);
@@ -1449,6 +1667,7 @@ async function stopForHung(tick) {
1449
1667
  async function superviseTick(tick, state) {
1450
1668
  const st = tick.status(tick.rosterPath);
1451
1669
  if (!st.running) {
1670
+ await reapSurvivingGroup(tick.handle.pid);
1452
1671
  return { kind: "outcome", outcome: { reason: "died" } };
1453
1672
  }
1454
1673
  const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
@@ -1494,7 +1713,7 @@ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1494
1713
  async function superviseServer(rosterPath, handle, opts = {}) {
1495
1714
  const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1496
1715
  const tick = makeSuperviseTick(rosterPath, handle, opts);
1497
- const doSleep = opts.sleep ?? sleep;
1716
+ const doSleep = opts.sleep ?? sleep2;
1498
1717
  const shouldStop = opts.shouldStop ?? (() => false);
1499
1718
  let state = { failures: 0, lastReadyAt: tick.now() };
1500
1719
  for (;; ) {
@@ -1514,7 +1733,7 @@ async function waitForDeath(pid, budgetMs) {
1514
1733
  while (Date.now() < deadline) {
1515
1734
  if (!isAlive(pid))
1516
1735
  return true;
1517
- await sleep(POLL_INTERVAL_MS);
1736
+ await sleep2(POLL_INTERVAL_MS);
1518
1737
  }
1519
1738
  return !isAlive(pid);
1520
1739
  }
@@ -1531,7 +1750,7 @@ async function waitForGroupDeath(pid, budgetMs) {
1531
1750
  while (Date.now() < deadline) {
1532
1751
  if (!groupAlive())
1533
1752
  return true;
1534
- await sleep(POLL_INTERVAL_MS);
1753
+ await sleep2(POLL_INTERVAL_MS);
1535
1754
  }
1536
1755
  return !groupAlive();
1537
1756
  }
@@ -1656,6 +1875,37 @@ function makeBusTask(defaultDirectory) {
1656
1875
  });
1657
1876
  }
1658
1877
 
1878
+ // src/tools/bus_wait.ts
1879
+ import { tool as tool5 } from "@opencode-ai/plugin";
1880
+ var BUS_WAIT_DESCRIPTION = "Block until any of the given space-bus sessions needs attention (completes, blocks on a question, fails, or is not found) or a timeout elapses. Returns every watched session's normalized state and which session(s) woke the wait. A bounded, level-triggered long-poll — an already-done session wakes immediately; on timeout it returns the current snapshot, not an error.";
1881
+ var MAX_WAIT_TIMEOUT_MS = 5 * 60000;
1882
+ function makeBusWait(defaultDirectory) {
1883
+ return tool5({
1884
+ description: BUS_WAIT_DESCRIPTION,
1885
+ args: {
1886
+ sessionIds: tool5.schema.array(tool5.schema.string()).min(1, "bus_wait requires at least one sessionId").max(100, "bus_wait accepts at most 100 sessionIds").describe("Session IDs to watch (returned by bus_task)"),
1887
+ timeoutMs: tool5.schema.number().positive().optional().describe(`Max time to wait in milliseconds before returning a timeout snapshot (default 60s, capped at ${MAX_WAIT_TIMEOUT_MS}ms; soft deadline, may overshoot by up to ~30s if a request is slow)`)
1888
+ },
1889
+ async execute(args, ctx) {
1890
+ if (!args.sessionIds || args.sessionIds.length === 0) {
1891
+ throw new Error("bus_wait requires at least one sessionId");
1892
+ }
1893
+ const directory = ctx.directory ?? defaultDirectory;
1894
+ let context;
1895
+ try {
1896
+ context = await ensureAndLoadContext(directory);
1897
+ } catch (e) {
1898
+ throw new Error(e.message);
1899
+ }
1900
+ const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
1901
+ const r = await wait(args.sessionIds, { context, timeoutMs });
1902
+ if (!r.ok)
1903
+ throw new Error(r.error);
1904
+ return formatWait(r);
1905
+ }
1906
+ });
1907
+ }
1908
+
1659
1909
  // src/mcp.ts
1660
1910
  async function mcpLoadContext() {
1661
1911
  if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRoster()) {
@@ -1664,7 +1914,7 @@ async function mcpLoadContext() {
1664
1914
  }
1665
1915
  return loadContext();
1666
1916
  }
1667
- var version = "0.8.0";
1917
+ var version = "0.9.0";
1668
1918
  var server = new McpServer({
1669
1919
  name: "space-bus",
1670
1920
  version
@@ -1764,6 +2014,28 @@ server.registerTool("bus_result", {
1764
2014
  return { content: [{ type: "text", text: r.error }], isError: true };
1765
2015
  return { content: [{ type: "text", text: formatResult(r) }] };
1766
2016
  });
2017
+ server.registerTool("bus_wait", {
2018
+ description: BUS_WAIT_DESCRIPTION,
2019
+ inputSchema: {
2020
+ sessionIds: z4.array(z4.string()).min(1, "bus_wait requires at least one sessionId").max(100, "bus_wait accepts at most 100 sessionIds").describe("Session IDs to watch (returned by bus_task)"),
2021
+ timeoutMs: z4.number().positive().optional().describe(`Max time to wait in milliseconds before returning a timeout snapshot (default 60s, capped at ${MAX_WAIT_TIMEOUT_MS}ms; soft deadline, may overshoot by up to ~30s if a request is slow)`)
2022
+ }
2023
+ }, async (args) => {
2024
+ let context;
2025
+ try {
2026
+ context = await mcpLoadContext();
2027
+ } catch (e) {
2028
+ return {
2029
+ content: [{ type: "text", text: e.message }],
2030
+ isError: true
2031
+ };
2032
+ }
2033
+ const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
2034
+ const r = await wait(args.sessionIds, { context, timeoutMs });
2035
+ if (!r.ok)
2036
+ return { content: [{ type: "text", text: r.error }], isError: true };
2037
+ return { content: [{ type: "text", text: formatWait(r) }] };
2038
+ });
1767
2039
  async function main() {
1768
2040
  const transport = new StdioServerTransport;
1769
2041
  await server.connect(transport);
package/dist/server.d.ts CHANGED
@@ -69,6 +69,42 @@ export declare function serverStatus(rosterPath: string): ServerStatus;
69
69
  export declare function stopServer(rosterPath: string): Promise<{
70
70
  stopped: boolean;
71
71
  }>;
72
+ /**
73
+ * Best-effort reap of a surviving process group whose leader has died —
74
+ * the died-path fix for the wrapper-only-death orphan (issue #49 Layer B
75
+ * follow-up). Guarded so it can NEVER signal a process that recycled the
76
+ * leader's pid:
77
+ *
78
+ * - If `pid` is still alive, do nothing. Either it's still our (running)
79
+ * wrapper — shouldn't happen on the died path — or it's an unrelated
80
+ * process that recycled the pid. Never signal a live leader here.
81
+ * - If `pid` is dead, check group liveness (`process.kill(-pid, 0)`). If
82
+ * the whole group is already gone (ESRCH), it's a clean crash — no-op.
83
+ * - If the leader is dead but the group still has live members, so this
84
+ * is, in practice, still our group (a live group's pgid is not reused
85
+ * while any member holds it — a strong practical guard, not an absolute
86
+ * proof: a narrow TOCTOU remains if the whole original group exits and
87
+ * the pgid is recycled between this check and the signal, the same
88
+ * residual race stopServer's verify→signal path carries): SIGTERM the
89
+ * group via `signalGroupOnly` (never falls back to a bare-pid signal —
90
+ * the recycled bare pid could be a stranger), wait a bounded grace,
91
+ * escalate to SIGKILL if members survive.
92
+ *
93
+ * Known limitation (zombie leader): the `isAlive(pid)` guard above is
94
+ * deliberately safe-biased — it errs toward NOT reaping. On Linux, a
95
+ * freshly-exited-but-unreaped ZOMBIE leader still passes `isAlive`
96
+ * (`kill(pid, 0)` succeeds for a zombie until reaped by its parent), so if
97
+ * the died path is ever reached while our wrapper is a zombie with a
98
+ * still-live child, the reap is skipped and the child leaks until a later
99
+ * tick observes the pid absent. This is a narrow race — normally the
100
+ * zombie's identity still matches, so `serverStatus` reports running and
101
+ * the died path isn't reached at all — accepted as a known limitation
102
+ * under the same-user trust boundary; tracked as a follow-up.
103
+ *
104
+ * Never throws — this runs on the fail-closed exit path and must not break
105
+ * it (mirrors the swallow style of `stopForHung`/`removeDiscoveryIfMatches`).
106
+ */
107
+ export declare function reapSurvivingGroup(pid: number): Promise<void>;
72
108
  export type SuperviseOutcome = {
73
109
  reason: "signal";
74
110
  } | {
package/dist/server.js CHANGED
@@ -10,6 +10,23 @@ var sessionSchema = z.looseObject({
10
10
  });
11
11
  var sessionListSchema = z.array(sessionSchema);
12
12
  var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
13
+ var sessionStateSchema = z.enum([
14
+ "running",
15
+ "blocked",
16
+ "complete",
17
+ "failed",
18
+ "not_found"
19
+ ]);
20
+ var sessionStateInfoSchema = z.object({
21
+ sessionId: z.string(),
22
+ project: z.string(),
23
+ state: sessionStateSchema,
24
+ resultAvailable: z.boolean(),
25
+ pendingQuestion: z.object({
26
+ preview: z.string(),
27
+ options: z.array(z.string())
28
+ }).optional()
29
+ });
13
30
  var todoSchema = z.array(z.looseObject({
14
31
  content: z.string(),
15
32
  status: z.string(),
@@ -564,6 +581,16 @@ function signalGroup(pid, sig) {
564
581
  } catch {}
565
582
  return false;
566
583
  }
584
+ function signalGroupOnly(pid, sig) {
585
+ if (pid <= 1)
586
+ return false;
587
+ try {
588
+ process.kill(-pid, sig);
589
+ return true;
590
+ } catch {
591
+ return false;
592
+ }
593
+ }
567
594
  function killIdentifiedProcess(pid, identity) {
568
595
  try {
569
596
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -820,6 +847,7 @@ async function stopServer(rosterPath) {
820
847
  if (!discovery)
821
848
  return { stopped: false };
822
849
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
850
+ await reapSurvivingGroup(discovery.pid);
823
851
  removeDiscovery(rosterPath);
824
852
  return { stopped: false };
825
853
  }
@@ -854,6 +882,27 @@ async function stopServer(rosterPath) {
854
882
  }
855
883
  return { stopped: false };
856
884
  }
885
+ async function reapSurvivingGroup(pid) {
886
+ try {
887
+ if (isAlive(pid))
888
+ return;
889
+ let groupAlive;
890
+ try {
891
+ process.kill(-pid, 0);
892
+ groupAlive = true;
893
+ } catch {
894
+ groupAlive = false;
895
+ }
896
+ if (!groupAlive)
897
+ return;
898
+ if (!signalGroupOnly(pid, "SIGTERM"))
899
+ return;
900
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
901
+ return;
902
+ signalGroupOnly(pid, "SIGKILL");
903
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
904
+ } catch {}
905
+ }
857
906
  async function stopForHung(tick) {
858
907
  try {
859
908
  await tick.stop(tick.rosterPath);
@@ -863,6 +912,7 @@ async function stopForHung(tick) {
863
912
  async function superviseTick(tick, state) {
864
913
  const st = tick.status(tick.rosterPath);
865
914
  if (!st.running) {
915
+ await reapSurvivingGroup(tick.handle.pid);
866
916
  return { kind: "outcome", outcome: { reason: "died" } };
867
917
  }
868
918
  const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
@@ -954,6 +1004,7 @@ export {
954
1004
  stopServer,
955
1005
  serverStatus,
956
1006
  redactSensitive,
1007
+ reapSurvivingGroup,
957
1008
  probe,
958
1009
  ensureServer,
959
1010
  attachServer,
@@ -0,0 +1,4 @@
1
+ import { type ToolDefinition } from "@opencode-ai/plugin";
2
+ export declare const BUS_WAIT_DESCRIPTION = "Block until any of the given space-bus sessions needs attention (completes, blocks on a question, fails, or is not found) or a timeout elapses. Returns every watched session's normalized state and which session(s) woke the wait. A bounded, level-triggered long-poll \u2014 an already-done session wakes immediately; on timeout it returns the current snapshot, not an error.";
3
+ export declare const MAX_WAIT_TIMEOUT_MS: number;
4
+ export declare function makeBusWait(defaultDirectory?: string): ToolDefinition;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fro.bot/space-bus",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Space Bus — workspace agent bus for OpenCode. One control agent tasking per-project agents over the OpenCode server API, with an MCP facade for Claude Desktop.",
5
5
  "type": "module",
6
6
  "license": "MIT",