@fro.bot/space-bus 0.8.1 → 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/index.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(),
@@ -252,6 +269,9 @@ function validateContext(context) {
252
269
  credentials: credentials ?? {}
253
270
  };
254
271
  }
272
+ function isStatusBusy(entry) {
273
+ return entry?.type === "busy" || entry?.type === "retry" || false;
274
+ }
255
275
  function resolveProjectOrErr(projects, name) {
256
276
  const project = findProject(projects, name);
257
277
  if (!project) {
@@ -293,7 +313,7 @@ async function roster(opts) {
293
313
  }
294
314
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
295
315
  const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
296
- const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
316
+ const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
297
317
  const capped = sessions.length > 100;
298
318
  return {
299
319
  name: p.name,
@@ -420,6 +440,17 @@ async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
420
440
  }
421
441
  return err(`space-bus: no manifest project has a session with id ${sessionId}`);
422
442
  }
443
+ function deriveSessionState(input) {
444
+ if (!input.resolved)
445
+ return "not_found";
446
+ if (input.failed)
447
+ return "failed";
448
+ if (input.pendingQuestion)
449
+ return "blocked";
450
+ if (input.busy)
451
+ return "running";
452
+ return "complete";
453
+ }
423
454
  function formatQuestionEntry(entry) {
424
455
  const firstQuestion = entry.questions?.[0];
425
456
  const text = firstQuestion?.question ?? "";
@@ -472,10 +503,11 @@ async function status(sessionId, opts) {
472
503
  return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
473
504
  }
474
505
  const entry = statusMap[sessionId];
475
- const busy = entry ? entry.type === "busy" || entry.type === "retry" : false;
506
+ const busy = isStatusBusy(entry);
476
507
  const { diff, diffSource } = diffResult;
477
508
  const additions = diff.reduce((sum, d) => sum + d.additions, 0);
478
509
  const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
510
+ const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
479
511
  return {
480
512
  ok: true,
481
513
  sessionId,
@@ -485,7 +517,9 @@ async function status(sessionId, opts) {
485
517
  todos,
486
518
  diff: { files: diff.length, additions, deletions },
487
519
  diffSource,
488
- pendingQuestion
520
+ pendingQuestion,
521
+ state,
522
+ resultAvailable: state === "complete"
489
523
  };
490
524
  }
491
525
  async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
@@ -532,7 +566,7 @@ async function result(sessionId, opts) {
532
566
  try {
533
567
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
534
568
  const entry = statusMap[sessionId];
535
- if (entry && (entry.type === "busy" || entry.type === "retry")) {
569
+ if (isStatusBusy(entry)) {
536
570
  return err(`space-bus: session ${sessionId} is still running, use bus_status`);
537
571
  }
538
572
  } catch {}
@@ -575,17 +609,35 @@ async function fetchSnapshotProject(baseUrl, credentials, project) {
575
609
  }
576
610
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
577
611
  const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
578
- const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
612
+ const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
579
613
  const capped = sessions.length > 100;
580
614
  let pendingQuestions;
615
+ let pendingQuestionsBySession = new Map;
581
616
  if (questionRes.res.ok) {
582
617
  try {
583
618
  const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
584
- pendingQuestions = entries.map((e) => formatQuestionEntry(e));
619
+ const formatted = entries.map((e) => formatQuestionEntry(e));
620
+ pendingQuestions = formatted;
621
+ pendingQuestionsBySession = new Map(formatted.map((q) => [q.sessionId, q]));
585
622
  } catch {
586
623
  pendingQuestions = undefined;
587
624
  }
588
625
  }
626
+ const sessionStates = sessions.map((s) => {
627
+ const entry = statusMap[s.id];
628
+ const busy = isStatusBusy(entry);
629
+ const pendingQuestion = pendingQuestionsBySession.get(s.id);
630
+ const state = deriveSessionState({
631
+ busy,
632
+ pendingQuestion,
633
+ resolved: true
634
+ });
635
+ return {
636
+ sessionId: s.id,
637
+ state,
638
+ resultAvailable: state === "complete"
639
+ };
640
+ });
589
641
  return {
590
642
  name: project.name,
591
643
  path: directory,
@@ -594,7 +646,8 @@ async function fetchSnapshotProject(baseUrl, credentials, project) {
594
646
  busyCount,
595
647
  sessionCount: capped ? 100 : sessions.length,
596
648
  sessionCountCapped: capped,
597
- pendingQuestions
649
+ pendingQuestions,
650
+ sessions: sessionStates
598
651
  };
599
652
  } catch (e) {
600
653
  return {
@@ -640,6 +693,120 @@ async function snapshot(opts) {
640
693
  });
641
694
  return { ok: true, projects: results };
642
695
  }
696
+ var DEFAULT_WAIT_TIMEOUT_MS = 60000;
697
+ var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
698
+ var DEFAULT_WAIT_CONCURRENCY = 4;
699
+ var NEEDS_ATTENTION_STATES = [
700
+ "complete",
701
+ "blocked",
702
+ "failed",
703
+ "not_found"
704
+ ];
705
+ function sleep(ms) {
706
+ return new Promise((resolve) => setTimeout(resolve, ms));
707
+ }
708
+ async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
709
+ const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
710
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
711
+ return { id, loc };
712
+ });
713
+ const locationById = new Map;
714
+ for (const { id, loc } of locations) {
715
+ locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
716
+ }
717
+ const groups = new Map;
718
+ for (const id of sessionIds) {
719
+ const loc = locationById.get(id);
720
+ if (!loc)
721
+ continue;
722
+ const group = groups.get(loc.directory) ?? {
723
+ directory: loc.directory,
724
+ sessionIds: []
725
+ };
726
+ group.sessionIds.push(id);
727
+ groups.set(loc.directory, group);
728
+ }
729
+ const lastKnown = new Map;
730
+ for (const id of sessionIds) {
731
+ const loc = locationById.get(id);
732
+ lastKnown.set(id, {
733
+ sessionId: id,
734
+ project: loc?.project ?? "",
735
+ state: loc ? "running" : "not_found",
736
+ resultAvailable: false
737
+ });
738
+ }
739
+ return { locationById, groupList: Array.from(groups.values()), lastKnown };
740
+ }
741
+ async function wait(sessionIds, opts) {
742
+ const ctx = validateContext(opts.context);
743
+ if (!ctx.ok)
744
+ return ctx;
745
+ const { baseUrl, projects, credentials } = ctx;
746
+ const uniqueIds = Array.from(new Set(sessionIds));
747
+ if (uniqueIds.length === 0) {
748
+ return { ok: true, sessions: [], waker: [], timedOut: true };
749
+ }
750
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
751
+ const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
752
+ const deadline = Date.now() + timeoutMs;
753
+ const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
754
+ async function pollGroup(group) {
755
+ const [statusRes, questionRes] = await Promise.all([
756
+ api(baseUrl, credentials, group.directory, "/session/status"),
757
+ api(baseUrl, credentials, group.directory, "/question")
758
+ ]);
759
+ if (!statusRes.res.ok)
760
+ return;
761
+ let statusMap;
762
+ try {
763
+ statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
764
+ } catch {
765
+ return;
766
+ }
767
+ const pendingBySession = parsePendingQuestions(questionRes);
768
+ for (const id of group.sessionIds) {
769
+ const entry = statusMap[id];
770
+ const busy = isStatusBusy(entry);
771
+ const pendingQuestion = pendingBySession.get(id);
772
+ const state = deriveSessionState({
773
+ busy,
774
+ pendingQuestion,
775
+ resolved: true
776
+ });
777
+ lastKnown.set(id, {
778
+ sessionId: id,
779
+ project: locationById.get(id)?.project ?? "",
780
+ state,
781
+ resultAvailable: state === "complete",
782
+ pendingQuestion
783
+ });
784
+ }
785
+ }
786
+ while (true) {
787
+ await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
788
+ const sessions = uniqueIds.map((id) => lastKnown.get(id));
789
+ const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
790
+ if (waker.length > 0) {
791
+ return { ok: true, sessions, waker, timedOut: false };
792
+ }
793
+ if (Date.now() >= deadline) {
794
+ return { ok: true, sessions, waker: [], timedOut: true };
795
+ }
796
+ const remaining = deadline - Date.now();
797
+ await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
798
+ }
799
+ }
800
+ function parsePendingQuestions(questionRes) {
801
+ if (!questionRes.res.ok)
802
+ return new Map;
803
+ try {
804
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
805
+ return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
806
+ } catch {
807
+ return new Map;
808
+ }
809
+ }
643
810
 
644
811
  // src/format.ts
645
812
  function formatRoster(projects) {
@@ -685,6 +852,25 @@ function formatStatus(r) {
685
852
  return lines.join(`
686
853
  `);
687
854
  }
855
+ function formatWait(r) {
856
+ const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
857
+ const sessionLines = r.sessions.map((s) => {
858
+ const parts = [
859
+ ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
860
+ ];
861
+ if (s.pendingQuestion) {
862
+ parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
863
+ if (s.pendingQuestion.options.length > 0) {
864
+ parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
865
+ }
866
+ parts.push(` (answer with bus_task using sessionId)`);
867
+ }
868
+ return parts.join(`
869
+ `);
870
+ });
871
+ return [header, ...sessionLines].join(`
872
+ `);
873
+ }
688
874
  function formatResult(r) {
689
875
  const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
690
876
  `) : " (no changes)";
@@ -1099,7 +1285,7 @@ var STOP_GRACE_MS = 2000;
1099
1285
  var SUPERVISE_INTERVAL_MS = 5000;
1100
1286
  var SUPERVISE_FAILURE_THRESHOLD = 3;
1101
1287
  var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1102
- function sleep(ms) {
1288
+ function sleep2(ms) {
1103
1289
  return new Promise((resolve) => setTimeout(resolve, ms));
1104
1290
  }
1105
1291
  function readManifest(rosterPath) {
@@ -1184,7 +1370,7 @@ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1184
1370
  if (!winnerAlive) {
1185
1371
  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`);
1186
1372
  }
1187
- await sleep(POLL_INTERVAL_MS);
1373
+ await sleep2(POLL_INTERVAL_MS);
1188
1374
  }
1189
1375
  const lockInfo = readLockFile(lockPath);
1190
1376
  const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
@@ -1221,7 +1407,7 @@ async function waitForReadinessLine(logPath, child, pid, deadline) {
1221
1407
  return { port, baseUrl: `http://127.0.0.1:${port}` };
1222
1408
  }
1223
1409
  }
1224
- await sleep(POLL_INTERVAL_MS);
1410
+ await sleep2(POLL_INTERVAL_MS);
1225
1411
  }
1226
1412
  return null;
1227
1413
  }
@@ -1234,7 +1420,7 @@ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1234
1420
  return "ready";
1235
1421
  if (outcome === "auth-failure")
1236
1422
  return "auth-failure";
1237
- await sleep(POLL_INTERVAL_MS);
1423
+ await sleep2(POLL_INTERVAL_MS);
1238
1424
  }
1239
1425
  return "timeout";
1240
1426
  }
@@ -1526,7 +1712,7 @@ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1526
1712
  async function superviseServer(rosterPath, handle, opts = {}) {
1527
1713
  const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1528
1714
  const tick = makeSuperviseTick(rosterPath, handle, opts);
1529
- const doSleep = opts.sleep ?? sleep;
1715
+ const doSleep = opts.sleep ?? sleep2;
1530
1716
  const shouldStop = opts.shouldStop ?? (() => false);
1531
1717
  let state = { failures: 0, lastReadyAt: tick.now() };
1532
1718
  for (;; ) {
@@ -1546,7 +1732,7 @@ async function waitForDeath(pid, budgetMs) {
1546
1732
  while (Date.now() < deadline) {
1547
1733
  if (!isAlive(pid))
1548
1734
  return true;
1549
- await sleep(POLL_INTERVAL_MS);
1735
+ await sleep2(POLL_INTERVAL_MS);
1550
1736
  }
1551
1737
  return !isAlive(pid);
1552
1738
  }
@@ -1563,7 +1749,7 @@ async function waitForGroupDeath(pid, budgetMs) {
1563
1749
  while (Date.now() < deadline) {
1564
1750
  if (!groupAlive())
1565
1751
  return true;
1566
- await sleep(POLL_INTERVAL_MS);
1752
+ await sleep2(POLL_INTERVAL_MS);
1567
1753
  }
1568
1754
  return !groupAlive();
1569
1755
  }
@@ -1683,13 +1869,45 @@ function makeBusTask(defaultDirectory) {
1683
1869
  });
1684
1870
  }
1685
1871
 
1872
+ // src/tools/bus_wait.ts
1873
+ import { tool as tool5 } from "@opencode-ai/plugin";
1874
+ 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.";
1875
+ var MAX_WAIT_TIMEOUT_MS = 5 * 60000;
1876
+ function makeBusWait(defaultDirectory) {
1877
+ return tool5({
1878
+ description: BUS_WAIT_DESCRIPTION,
1879
+ args: {
1880
+ 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)"),
1881
+ 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)`)
1882
+ },
1883
+ async execute(args, ctx) {
1884
+ if (!args.sessionIds || args.sessionIds.length === 0) {
1885
+ throw new Error("bus_wait requires at least one sessionId");
1886
+ }
1887
+ const directory = ctx.directory ?? defaultDirectory;
1888
+ let context;
1889
+ try {
1890
+ context = await ensureAndLoadContext(directory);
1891
+ } catch (e) {
1892
+ throw new Error(e.message);
1893
+ }
1894
+ const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
1895
+ const r = await wait(args.sessionIds, { context, timeoutMs });
1896
+ if (!r.ok)
1897
+ throw new Error(r.error);
1898
+ return formatWait(r);
1899
+ }
1900
+ });
1901
+ }
1902
+
1686
1903
  // src/index.ts
1687
1904
  var SpaceBusPlugin = async (input) => ({
1688
1905
  tool: {
1689
1906
  bus_roster: makeBusRoster(input.directory),
1690
1907
  bus_task: makeBusTask(input.directory),
1691
1908
  bus_status: makeBusStatus(input.directory),
1692
- bus_result: makeBusResult(input.directory)
1909
+ bus_result: makeBusResult(input.directory),
1910
+ bus_wait: makeBusWait(input.directory)
1693
1911
  }
1694
1912
  });
1695
1913
  var src_default = SpaceBusPlugin;