@fro.bot/space-bus 0.8.1 → 0.10.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) {
@@ -1185,7 +1371,7 @@ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1185
1371
  if (!winnerAlive) {
1186
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`);
1187
1373
  }
1188
- await sleep(POLL_INTERVAL_MS);
1374
+ await sleep2(POLL_INTERVAL_MS);
1189
1375
  }
1190
1376
  const lockInfo = readLockFile(lockPath);
1191
1377
  const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
@@ -1222,7 +1408,7 @@ async function waitForReadinessLine(logPath, child, pid, deadline) {
1222
1408
  return { port, baseUrl: `http://127.0.0.1:${port}` };
1223
1409
  }
1224
1410
  }
1225
- await sleep(POLL_INTERVAL_MS);
1411
+ await sleep2(POLL_INTERVAL_MS);
1226
1412
  }
1227
1413
  return null;
1228
1414
  }
@@ -1235,7 +1421,7 @@ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1235
1421
  return "ready";
1236
1422
  if (outcome === "auth-failure")
1237
1423
  return "auth-failure";
1238
- await sleep(POLL_INTERVAL_MS);
1424
+ await sleep2(POLL_INTERVAL_MS);
1239
1425
  }
1240
1426
  return "timeout";
1241
1427
  }
@@ -1527,7 +1713,7 @@ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1527
1713
  async function superviseServer(rosterPath, handle, opts = {}) {
1528
1714
  const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1529
1715
  const tick = makeSuperviseTick(rosterPath, handle, opts);
1530
- const doSleep = opts.sleep ?? sleep;
1716
+ const doSleep = opts.sleep ?? sleep2;
1531
1717
  const shouldStop = opts.shouldStop ?? (() => false);
1532
1718
  let state = { failures: 0, lastReadyAt: tick.now() };
1533
1719
  for (;; ) {
@@ -1547,7 +1733,7 @@ async function waitForDeath(pid, budgetMs) {
1547
1733
  while (Date.now() < deadline) {
1548
1734
  if (!isAlive(pid))
1549
1735
  return true;
1550
- await sleep(POLL_INTERVAL_MS);
1736
+ await sleep2(POLL_INTERVAL_MS);
1551
1737
  }
1552
1738
  return !isAlive(pid);
1553
1739
  }
@@ -1564,7 +1750,7 @@ async function waitForGroupDeath(pid, budgetMs) {
1564
1750
  while (Date.now() < deadline) {
1565
1751
  if (!groupAlive())
1566
1752
  return true;
1567
- await sleep(POLL_INTERVAL_MS);
1753
+ await sleep2(POLL_INTERVAL_MS);
1568
1754
  }
1569
1755
  return !groupAlive();
1570
1756
  }
@@ -1689,6 +1875,37 @@ function makeBusTask(defaultDirectory) {
1689
1875
  });
1690
1876
  }
1691
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
+
1692
1909
  // src/mcp.ts
1693
1910
  async function mcpLoadContext() {
1694
1911
  if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRoster()) {
@@ -1697,7 +1914,7 @@ async function mcpLoadContext() {
1697
1914
  }
1698
1915
  return loadContext();
1699
1916
  }
1700
- var version = "0.8.1";
1917
+ var version = "0.10.0";
1701
1918
  var server = new McpServer({
1702
1919
  name: "space-bus",
1703
1920
  version
@@ -1797,6 +2014,28 @@ server.registerTool("bus_result", {
1797
2014
  return { content: [{ type: "text", text: r.error }], isError: true };
1798
2015
  return { content: [{ type: "text", text: formatResult(r) }] };
1799
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
+ });
1800
2039
  async function main() {
1801
2040
  const transport = new StdioServerTransport;
1802
2041
  await server.connect(transport);
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(),
@@ -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.1",
3
+ "version": "0.10.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",
@@ -29,6 +29,10 @@
29
29
  "import": "./dist/format.js"
30
30
  },
31
31
  "./server": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ },
35
+ "./managed-server": {
32
36
  "types": "./dist/server.d.ts",
33
37
  "import": "./dist/server.js"
34
38
  },