@fro.bot/space-bus 0.7.1 → 0.8.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/README.md CHANGED
@@ -107,12 +107,14 @@ Programmatic consumers (e.g. Mothership) that want to drive the lifecycle direct
107
107
 
108
108
  ## Library surface
109
109
 
110
- Experimental subpath exports expose the bus's semantics directly — the same functions the four tools run on — for renderers and other consumers that want structured state instead of formatted strings. Subpaths are experimental: shapes may change in minor releases; pin the version if you adopt them.
110
+ Experimental subpath exports expose the bus's internals directly — the functions the four tools run on, plus the managed-server lifecycle and the attach resolver — for renderers and other consumers that want structured state instead of formatted strings. Subpaths are experimental: shapes may change in minor releases; pin the version if you adopt them.
111
111
 
112
112
  - `@fro.bot/space-bus/core` — browser-safe; no Node builtins, no ambient env reads. Every exported function takes a `context: BusContext` (`{ roster, credentials? }`) that you build yourself and pass in — core never resolves it for you. Includes `snapshot()`, a one-call composite of roster + per-project status + pending questions with bounded fan-out.
113
113
  - `@fro.bot/space-bus/config` — Node-only. `loadContext(directory?)` reads `spacebus.json` (honoring `SPACE_BUS_CONFIG` the same as the plugin) and returns a ready-to-use `BusContext`, with per-project `exists` flags and env-derived credentials attached. Build a fresh context per call; it's per-call/short-lived by contract, not meant to be cached across filesystem changes.
114
114
  - `@fro.bot/space-bus/contract` — the zod schemas (and inferred types) behind the OpenCode API and `BusContext`, for consumers hitting the server directly and wanting the same shapes. Schemas are zod v4.
115
115
  - `@fro.bot/space-bus/format` — the pure formatters the tools use to render output, for tool-identical text.
116
+ - `@fro.bot/space-bus/server` — Node-only. The managed-server lifecycle (`ensureServer`/`serverStatus`/`stopServer`) for consumers driving spawn/attach/stop directly — see [Managed server](#managed-server).
117
+ - `@fro.bot/space-bus/attach` — browser-safe. `resolveManagedServer(workspaceDir, seams)` resolves a managed roster's running endpoint by reading the discovery file through injected filesystem/env/crypto seams — re-checking the localhost guard and probing liveness — so an external attacher such as a Tauri webview can attach without any `node:*` imports or reimplementing the discovery contract. Returns `{ baseUrl, credentials, alive }` or an actionable error.
116
118
 
117
119
  Node example (`/config` + `/core`):
118
120
 
@@ -129,7 +131,7 @@ if (result.ok) {
129
131
  }
130
132
  ```
131
133
 
132
- Browser consumers: `/core`, `/contract`, and `/format` are browser-safe (their module graphs are bundle-tested in CI to exclude `node:*` imports and never reach `/config`). `/config` is Node-only — browser code can't call `loadContext`, so credentials must be injected explicitly by whatever server-side process builds the `BusContext` (never read ambiently by core). The localhost guard travels with the context: it's re-checked at core's single validation gate on every call, so a context built from a non-local `baseUrl` is rejected there, not just at config's load time.
134
+ Browser consumers: `/core`, `/contract`, `/format`, and `/attach` are browser-safe (their module graphs are bundle-tested in CI to exclude `node:*` imports and never reach `/config`). `/config` is Node-only — browser code can't call `loadContext`, so credentials must be injected explicitly by whatever server-side process builds the `BusContext` (never read ambiently by core). The localhost guard travels with the context: it's re-checked at core's single validation gate on every call, so a context built from a non-local `baseUrl` is rejected there, not just at config's load time.
133
135
 
134
136
  ## Claude Desktop
135
137
 
package/dist/cli.d.ts CHANGED
@@ -1 +1,26 @@
1
+ import { ensureServer, type ServerHandle, type SuperviseOutcome, stopServer } from "./server";
2
+ interface ParsedArgs {
3
+ command: string | undefined;
4
+ json: boolean;
5
+ foreground: boolean;
6
+ config: string | undefined;
7
+ help: boolean;
8
+ unknownFlags: string[];
9
+ /** --config was the last arg with no following value. */
10
+ configMissingValue: boolean;
11
+ }
12
+ /** Injectable dependencies for `runServe`'s foreground supervision — lets
13
+ * tests drive the signal/died/hung outcomes deterministically without a
14
+ * real daemon or real timers. Defaults to the real implementations. */
15
+ export interface RunServeDeps {
16
+ ensureServer?: typeof ensureServer;
17
+ stopServer?: typeof stopServer;
18
+ /** Receives a `shouldStop` seam wired to the process signal handlers —
19
+ * when a signal fires, `shouldStop()` starts returning true so the loop
20
+ * (real or injected) can break with `{ reason: "signal" }` — plus an
21
+ * `interrupt` promise that resolves immediately on signal, so the
22
+ * inter-tick sleep doesn't have to wait out the full interval. */
23
+ superviseServer?: (rosterPath: string, handle: ServerHandle, shouldStop: () => boolean, interrupt: Promise<void>) => Promise<SuperviseOutcome>;
24
+ }
25
+ export declare function runServe(args: ParsedArgs, deps?: RunServeDeps): Promise<number>;
1
26
  export {};
package/dist/cli.js CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
+
2
5
  // src/contract.ts
3
6
  import { z } from "zod";
4
7
  var sessionSchema = z.looseObject({
@@ -189,14 +192,27 @@ function removeDiscovery(rosterPath) {
189
192
  throw err;
190
193
  }
191
194
  }
195
+ function removeDiscoveryIfMatches(rosterPath, expected) {
196
+ try {
197
+ const current = readDiscovery(rosterPath);
198
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
199
+ removeDiscovery(rosterPath);
200
+ }
201
+ } catch {}
202
+ }
192
203
  function attachLive(rosterPath) {
193
204
  const discovery = readDiscovery(rosterPath);
194
205
  if (!discovery)
195
206
  return null;
196
207
  if (!loopbackOk(discovery.baseUrl))
197
208
  return null;
198
- if (!verifyIdentity(discovery.pid, discovery.identity))
209
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
210
+ removeDiscoveryIfMatches(rosterPath, {
211
+ pid: discovery.pid,
212
+ identity: discovery.identity
213
+ });
199
214
  return null;
215
+ }
200
216
  return {
201
217
  baseUrl: discovery.baseUrl,
202
218
  credentials: { username: "opencode", password: discovery.password },
@@ -496,6 +512,9 @@ var POLL_INTERVAL_MS = 50;
496
512
  var MIN_PROBE_PHASE_MS = 3000;
497
513
  var PROBE_FETCH_TIMEOUT_MS = 2000;
498
514
  var STOP_GRACE_MS = 2000;
515
+ var SUPERVISE_INTERVAL_MS = 5000;
516
+ var SUPERVISE_FAILURE_THRESHOLD = 3;
517
+ var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
499
518
  function sleep(ms) {
500
519
  return new Promise((resolve) => setTimeout(resolve, ms));
501
520
  }
@@ -763,7 +782,14 @@ async function ensureServer(rosterPath, options = {}) {
763
782
  }
764
783
  function serverStatus(rosterPath) {
765
784
  const discovery = readDiscovery(rosterPath);
766
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
785
+ if (!discovery) {
786
+ return { running: false };
787
+ }
788
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
789
+ removeDiscoveryIfMatches(rosterPath, {
790
+ pid: discovery.pid,
791
+ identity: discovery.identity
792
+ });
767
793
  return { running: false };
768
794
  }
769
795
  let configDrift;
@@ -829,6 +855,75 @@ async function stopServer(rosterPath) {
829
855
  }
830
856
  return { stopped: false };
831
857
  }
858
+ async function stopForHung(tick) {
859
+ try {
860
+ await tick.stop(tick.rosterPath);
861
+ } catch {}
862
+ return { kind: "outcome", outcome: { reason: "hung" } };
863
+ }
864
+ async function superviseTick(tick, state) {
865
+ const st = tick.status(tick.rosterPath);
866
+ if (!st.running) {
867
+ return { kind: "outcome", outcome: { reason: "died" } };
868
+ }
869
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
870
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
871
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
872
+ if (failures >= tick.threshold) {
873
+ return stopForHung(tick);
874
+ }
875
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
876
+ return stopForHung(tick);
877
+ }
878
+ return { kind: "tick", failures, lastReadyAt };
879
+ }
880
+ function makeSuperviseTick(rosterPath, handle, opts) {
881
+ return {
882
+ rosterPath,
883
+ handle,
884
+ password: handle.credentials.password ?? "",
885
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
886
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
887
+ now: opts.now ?? Date.now,
888
+ status: opts.status ?? serverStatus,
889
+ probe: opts.probe ?? probe,
890
+ stop: opts.stop ?? stopServer
891
+ };
892
+ }
893
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
894
+ if (!interrupt) {
895
+ await doSleep(intervalMs);
896
+ return;
897
+ }
898
+ let timer;
899
+ const timed = new Promise((resolve) => {
900
+ timer = setTimeout(resolve, intervalMs);
901
+ });
902
+ try {
903
+ await Promise.race([timed, interrupt]);
904
+ } finally {
905
+ if (timer !== undefined)
906
+ clearTimeout(timer);
907
+ }
908
+ }
909
+ async function superviseServer(rosterPath, handle, opts = {}) {
910
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
911
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
912
+ const doSleep = opts.sleep ?? sleep;
913
+ const shouldStop = opts.shouldStop ?? (() => false);
914
+ let state = { failures: 0, lastReadyAt: tick.now() };
915
+ for (;; ) {
916
+ if (shouldStop())
917
+ return { reason: "signal" };
918
+ const result = await superviseTick(tick, state);
919
+ if (result.kind === "outcome")
920
+ return result.outcome;
921
+ state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
922
+ if (shouldStop())
923
+ return { reason: "signal" };
924
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
925
+ }
926
+ }
832
927
  async function waitForDeath(pid, budgetMs) {
833
928
  const deadline = Date.now() + budgetMs;
834
929
  while (Date.now() < deadline) {
@@ -920,9 +1015,12 @@ function printJson(json, data, plain) {
920
1015
  `);
921
1016
  }
922
1017
  }
923
- async function runServe(args) {
1018
+ async function runServe(args, deps = {}) {
1019
+ const doEnsureServer = deps.ensureServer ?? ensureServer;
1020
+ const doStopServer = deps.stopServer ?? stopServer;
1021
+ const doSuperviseServer = deps.superviseServer ?? ((rosterPath2, handle2, shouldStop, interrupt) => superviseServer(rosterPath2, handle2, { shouldStop, interrupt }));
924
1022
  const rosterPath = resolveRoster(args.config);
925
- const handle = await ensureServer(rosterPath);
1023
+ const handle = await doEnsureServer(rosterPath);
926
1024
  const data = {
927
1025
  running: true,
928
1026
  port: handle.port,
@@ -933,17 +1031,45 @@ async function runServe(args) {
933
1031
  if (!args.foreground)
934
1032
  return 0;
935
1033
  return await new Promise((resolve) => {
936
- let stopping = false;
937
- const shutdown = (signal) => {
938
- if (stopping)
1034
+ let stopRequested = false;
1035
+ let wake = () => {};
1036
+ const interrupt = new Promise((r) => {
1037
+ wake = r;
1038
+ });
1039
+ const sigintHandler = () => onSignal("SIGINT");
1040
+ const sigtermHandler = () => onSignal("SIGTERM");
1041
+ const removeSignalHandlers = () => {
1042
+ process.off("SIGINT", sigintHandler);
1043
+ process.off("SIGTERM", sigtermHandler);
1044
+ };
1045
+ const onSignal = (signal) => {
1046
+ if (stopRequested)
939
1047
  return;
940
- stopping = true;
1048
+ stopRequested = true;
941
1049
  process.stderr.write(`space-bus: received ${signal}, stopping...
942
1050
  `);
943
- stopServer(rosterPath).finally(() => resolve(0));
1051
+ wake();
944
1052
  };
945
- process.on("SIGINT", () => shutdown("SIGINT"));
946
- process.on("SIGTERM", () => shutdown("SIGTERM"));
1053
+ process.on("SIGINT", sigintHandler);
1054
+ process.on("SIGTERM", sigtermHandler);
1055
+ doSuperviseServer(rosterPath, handle, () => stopRequested, interrupt).then((outcome) => {
1056
+ if (outcome.reason === "signal") {
1057
+ doStopServer(rosterPath).finally(() => {
1058
+ removeSignalHandlers();
1059
+ resolve(0);
1060
+ });
1061
+ return;
1062
+ }
1063
+ removeSignalHandlers();
1064
+ process.stderr.write(`space-bus: managed daemon ${outcome.reason}; exiting for supervisor restart
1065
+ `);
1066
+ resolve(1);
1067
+ }).catch((err) => {
1068
+ removeSignalHandlers();
1069
+ process.stderr.write(`space-bus: supervision failed unexpectedly: ${err.message}
1070
+ `);
1071
+ resolve(1);
1072
+ });
947
1073
  });
948
1074
  }
949
1075
  function runStatus(args) {
@@ -999,10 +1125,15 @@ async function main() {
999
1125
  return 1;
1000
1126
  }
1001
1127
  }
1002
- main().then((code) => {
1003
- process.exitCode = code;
1004
- }).catch((err) => {
1005
- process.stderr.write(`space-bus: ${err.message}
1128
+ if (__require.main == __require.module) {
1129
+ main().then((code) => {
1130
+ process.exitCode = code;
1131
+ }).catch((err) => {
1132
+ process.stderr.write(`space-bus: ${err.message}
1006
1133
  `);
1007
- process.exitCode = 1;
1008
- });
1134
+ process.exitCode = 1;
1135
+ });
1136
+ }
1137
+ export {
1138
+ runServe
1139
+ };
package/dist/config.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contract.ts
2
5
  import { z } from "zod";
3
6
  var sessionSchema = z.looseObject({
@@ -188,14 +191,27 @@ function removeDiscovery(rosterPath) {
188
191
  throw err;
189
192
  }
190
193
  }
194
+ function removeDiscoveryIfMatches(rosterPath, expected) {
195
+ try {
196
+ const current = readDiscovery(rosterPath);
197
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
198
+ removeDiscovery(rosterPath);
199
+ }
200
+ } catch {}
201
+ }
191
202
  function attachLive(rosterPath) {
192
203
  const discovery = readDiscovery(rosterPath);
193
204
  if (!discovery)
194
205
  return null;
195
206
  if (!loopbackOk(discovery.baseUrl))
196
207
  return null;
197
- if (!verifyIdentity(discovery.pid, discovery.identity))
208
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
209
+ removeDiscoveryIfMatches(rosterPath, {
210
+ pid: discovery.pid,
211
+ identity: discovery.identity
212
+ });
198
213
  return null;
214
+ }
199
215
  return {
200
216
  baseUrl: discovery.baseUrl,
201
217
  credentials: { username: "opencode", password: discovery.password },
package/dist/contract.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contract.ts
2
5
  import { z } from "zod";
3
6
  var sessionSchema = z.looseObject({
package/dist/core.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contract.ts
2
5
  import { z } from "zod";
3
6
  var sessionSchema = z.looseObject({
@@ -22,6 +22,20 @@ export declare function writeDiscovery(rosterPath: string, data: DiscoveryFile):
22
22
  /** Reads and validates the discovery file; returns null if absent or corrupt. */
23
23
  export declare function readDiscovery(rosterPath: string): DiscoveryFile | null;
24
24
  export declare function removeDiscovery(rosterPath: string): void;
25
+ /**
26
+ * Compare-and-delete: re-reads the record and unlinks only if the on-disk
27
+ * pid+identity still match the ones passed in, so a fresh record written
28
+ * by a concurrent respawn is (practically) preserved. A vanishingly small
29
+ * window remains between the re-read and the unlink; a respawn's atomic
30
+ * rename landing in that window could still be removed — accepted as
31
+ * best-effort, consistent with the discovery layer's other best-effort
32
+ * operations, and self-heals (the orphaned daemon is reaped on the next
33
+ * ensure).
34
+ */
35
+ export declare function removeDiscoveryIfMatches(rosterPath: string, expected: {
36
+ pid: number;
37
+ identity: string;
38
+ }): void;
25
39
  export { loopbackOk };
26
40
  export interface LiveEndpoint {
27
41
  baseUrl: string;
package/dist/format.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/format.ts
2
5
  function formatRoster(projects) {
3
6
  return projects.map((p) => {
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contract.ts
2
5
  import { z } from "zod";
3
6
  var sessionSchema = z.looseObject({
@@ -773,14 +776,27 @@ function removeDiscovery(rosterPath) {
773
776
  throw err2;
774
777
  }
775
778
  }
779
+ function removeDiscoveryIfMatches(rosterPath, expected) {
780
+ try {
781
+ const current = readDiscovery(rosterPath);
782
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
783
+ removeDiscovery(rosterPath);
784
+ }
785
+ } catch {}
786
+ }
776
787
  function attachLive(rosterPath) {
777
788
  const discovery = readDiscovery(rosterPath);
778
789
  if (!discovery)
779
790
  return null;
780
791
  if (!loopbackOk(discovery.baseUrl))
781
792
  return null;
782
- if (!verifyIdentity(discovery.pid, discovery.identity))
793
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
794
+ removeDiscoveryIfMatches(rosterPath, {
795
+ pid: discovery.pid,
796
+ identity: discovery.identity
797
+ });
783
798
  return null;
799
+ }
784
800
  return {
785
801
  baseUrl: discovery.baseUrl,
786
802
  credentials: { username: "opencode", password: discovery.password },
@@ -1080,6 +1096,9 @@ var POLL_INTERVAL_MS = 50;
1080
1096
  var MIN_PROBE_PHASE_MS = 3000;
1081
1097
  var PROBE_FETCH_TIMEOUT_MS = 2000;
1082
1098
  var STOP_GRACE_MS = 2000;
1099
+ var SUPERVISE_INTERVAL_MS = 5000;
1100
+ var SUPERVISE_FAILURE_THRESHOLD = 3;
1101
+ var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1083
1102
  function sleep(ms) {
1084
1103
  return new Promise((resolve) => setTimeout(resolve, ms));
1085
1104
  }
@@ -1347,7 +1366,14 @@ async function ensureServer(rosterPath, options = {}) {
1347
1366
  }
1348
1367
  function serverStatus(rosterPath) {
1349
1368
  const discovery = readDiscovery(rosterPath);
1350
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
1369
+ if (!discovery) {
1370
+ return { running: false };
1371
+ }
1372
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
1373
+ removeDiscoveryIfMatches(rosterPath, {
1374
+ pid: discovery.pid,
1375
+ identity: discovery.identity
1376
+ });
1351
1377
  return { running: false };
1352
1378
  }
1353
1379
  let configDrift;
@@ -1413,6 +1439,75 @@ async function stopServer(rosterPath) {
1413
1439
  }
1414
1440
  return { stopped: false };
1415
1441
  }
1442
+ async function stopForHung(tick) {
1443
+ try {
1444
+ await tick.stop(tick.rosterPath);
1445
+ } catch {}
1446
+ return { kind: "outcome", outcome: { reason: "hung" } };
1447
+ }
1448
+ async function superviseTick(tick, state) {
1449
+ const st = tick.status(tick.rosterPath);
1450
+ if (!st.running) {
1451
+ return { kind: "outcome", outcome: { reason: "died" } };
1452
+ }
1453
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1454
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1455
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1456
+ if (failures >= tick.threshold) {
1457
+ return stopForHung(tick);
1458
+ }
1459
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1460
+ return stopForHung(tick);
1461
+ }
1462
+ return { kind: "tick", failures, lastReadyAt };
1463
+ }
1464
+ function makeSuperviseTick(rosterPath, handle, opts) {
1465
+ return {
1466
+ rosterPath,
1467
+ handle,
1468
+ password: handle.credentials.password ?? "",
1469
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1470
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1471
+ now: opts.now ?? Date.now,
1472
+ status: opts.status ?? serverStatus,
1473
+ probe: opts.probe ?? probe,
1474
+ stop: opts.stop ?? stopServer
1475
+ };
1476
+ }
1477
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1478
+ if (!interrupt) {
1479
+ await doSleep(intervalMs);
1480
+ return;
1481
+ }
1482
+ let timer;
1483
+ const timed = new Promise((resolve) => {
1484
+ timer = setTimeout(resolve, intervalMs);
1485
+ });
1486
+ try {
1487
+ await Promise.race([timed, interrupt]);
1488
+ } finally {
1489
+ if (timer !== undefined)
1490
+ clearTimeout(timer);
1491
+ }
1492
+ }
1493
+ async function superviseServer(rosterPath, handle, opts = {}) {
1494
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1495
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
1496
+ const doSleep = opts.sleep ?? sleep;
1497
+ const shouldStop = opts.shouldStop ?? (() => false);
1498
+ let state = { failures: 0, lastReadyAt: tick.now() };
1499
+ for (;; ) {
1500
+ if (shouldStop())
1501
+ return { reason: "signal" };
1502
+ const result2 = await superviseTick(tick, state);
1503
+ if (result2.kind === "outcome")
1504
+ return result2.outcome;
1505
+ state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
1506
+ if (shouldStop())
1507
+ return { reason: "signal" };
1508
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1509
+ }
1510
+ }
1416
1511
  async function waitForDeath(pid, budgetMs) {
1417
1512
  const deadline = Date.now() + budgetMs;
1418
1513
  while (Date.now() < deadline) {
package/dist/mcp.js CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
+
2
5
  // src/contract.ts
3
6
  import { z } from "zod";
4
7
  var sessionSchema = z.looseObject({
@@ -774,14 +777,27 @@ function removeDiscovery(rosterPath) {
774
777
  throw err2;
775
778
  }
776
779
  }
780
+ function removeDiscoveryIfMatches(rosterPath, expected) {
781
+ try {
782
+ const current = readDiscovery(rosterPath);
783
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
784
+ removeDiscovery(rosterPath);
785
+ }
786
+ } catch {}
787
+ }
777
788
  function attachLive(rosterPath) {
778
789
  const discovery = readDiscovery(rosterPath);
779
790
  if (!discovery)
780
791
  return null;
781
792
  if (!loopbackOk(discovery.baseUrl))
782
793
  return null;
783
- if (!verifyIdentity(discovery.pid, discovery.identity))
794
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
795
+ removeDiscoveryIfMatches(rosterPath, {
796
+ pid: discovery.pid,
797
+ identity: discovery.identity
798
+ });
784
799
  return null;
800
+ }
785
801
  return {
786
802
  baseUrl: discovery.baseUrl,
787
803
  credentials: { username: "opencode", password: discovery.password },
@@ -1081,6 +1097,9 @@ var POLL_INTERVAL_MS = 50;
1081
1097
  var MIN_PROBE_PHASE_MS = 3000;
1082
1098
  var PROBE_FETCH_TIMEOUT_MS = 2000;
1083
1099
  var STOP_GRACE_MS = 2000;
1100
+ var SUPERVISE_INTERVAL_MS = 5000;
1101
+ var SUPERVISE_FAILURE_THRESHOLD = 3;
1102
+ var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1084
1103
  function sleep(ms) {
1085
1104
  return new Promise((resolve) => setTimeout(resolve, ms));
1086
1105
  }
@@ -1348,7 +1367,14 @@ async function ensureServer(rosterPath, options = {}) {
1348
1367
  }
1349
1368
  function serverStatus(rosterPath) {
1350
1369
  const discovery = readDiscovery(rosterPath);
1351
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
1370
+ if (!discovery) {
1371
+ return { running: false };
1372
+ }
1373
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
1374
+ removeDiscoveryIfMatches(rosterPath, {
1375
+ pid: discovery.pid,
1376
+ identity: discovery.identity
1377
+ });
1352
1378
  return { running: false };
1353
1379
  }
1354
1380
  let configDrift;
@@ -1414,6 +1440,75 @@ async function stopServer(rosterPath) {
1414
1440
  }
1415
1441
  return { stopped: false };
1416
1442
  }
1443
+ async function stopForHung(tick) {
1444
+ try {
1445
+ await tick.stop(tick.rosterPath);
1446
+ } catch {}
1447
+ return { kind: "outcome", outcome: { reason: "hung" } };
1448
+ }
1449
+ async function superviseTick(tick, state) {
1450
+ const st = tick.status(tick.rosterPath);
1451
+ if (!st.running) {
1452
+ return { kind: "outcome", outcome: { reason: "died" } };
1453
+ }
1454
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1455
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1456
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1457
+ if (failures >= tick.threshold) {
1458
+ return stopForHung(tick);
1459
+ }
1460
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1461
+ return stopForHung(tick);
1462
+ }
1463
+ return { kind: "tick", failures, lastReadyAt };
1464
+ }
1465
+ function makeSuperviseTick(rosterPath, handle, opts) {
1466
+ return {
1467
+ rosterPath,
1468
+ handle,
1469
+ password: handle.credentials.password ?? "",
1470
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1471
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1472
+ now: opts.now ?? Date.now,
1473
+ status: opts.status ?? serverStatus,
1474
+ probe: opts.probe ?? probe,
1475
+ stop: opts.stop ?? stopServer
1476
+ };
1477
+ }
1478
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1479
+ if (!interrupt) {
1480
+ await doSleep(intervalMs);
1481
+ return;
1482
+ }
1483
+ let timer;
1484
+ const timed = new Promise((resolve) => {
1485
+ timer = setTimeout(resolve, intervalMs);
1486
+ });
1487
+ try {
1488
+ await Promise.race([timed, interrupt]);
1489
+ } finally {
1490
+ if (timer !== undefined)
1491
+ clearTimeout(timer);
1492
+ }
1493
+ }
1494
+ async function superviseServer(rosterPath, handle, opts = {}) {
1495
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1496
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
1497
+ const doSleep = opts.sleep ?? sleep;
1498
+ const shouldStop = opts.shouldStop ?? (() => false);
1499
+ let state = { failures: 0, lastReadyAt: tick.now() };
1500
+ for (;; ) {
1501
+ if (shouldStop())
1502
+ return { reason: "signal" };
1503
+ const result2 = await superviseTick(tick, state);
1504
+ if (result2.kind === "outcome")
1505
+ return result2.outcome;
1506
+ state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
1507
+ if (shouldStop())
1508
+ return { reason: "signal" };
1509
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1510
+ }
1511
+ }
1417
1512
  async function waitForDeath(pid, budgetMs) {
1418
1513
  const deadline = Date.now() + budgetMs;
1419
1514
  while (Date.now() < deadline) {
@@ -1569,7 +1664,7 @@ async function mcpLoadContext() {
1569
1664
  }
1570
1665
  return loadContext();
1571
1666
  }
1572
- var version = "0.7.1";
1667
+ var version = "0.8.0";
1573
1668
  var server = new McpServer({
1574
1669
  name: "space-bus",
1575
1670
  version
package/dist/server.d.ts CHANGED
@@ -1,3 +1,16 @@
1
+ /** Interval between supervision liveness ticks. */
2
+ export declare const SUPERVISE_INTERVAL_MS = 5000;
3
+ /** Consecutive unreachable-probe failures (pid still alive) before the
4
+ * supervisor declares the daemon hung and kills it. */
5
+ export declare const SUPERVISE_FAILURE_THRESHOLD = 3;
6
+ /** Absolute-lifetime watchdog: how long the daemon may go without a
7
+ * genuinely-"ready" probe before it's declared hung, regardless of whether
8
+ * failures ever hit 3-in-a-row. Bounds two cases the consecutive-failure
9
+ * counter can't catch: a FLAPPING daemon (retry, ready, retry, ready, ...
10
+ * never 3 consecutive) and a persistent auth-failure (server answers but
11
+ * never actually serves, looping "silently" forever). Tunable; 60s gives
12
+ * ~12 ticks at the default 5s interval to recover before being killed. */
13
+ export declare const SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1
14
  export interface EnsureServerOptions {
2
15
  /** Bounds the readiness probe loop after spawning. Default 15s. */
3
16
  readinessBudgetMs?: number;
@@ -37,6 +50,8 @@ export declare function redactSensitive(tail: string, password: string): string;
37
50
  * config->server->config cycle since server.ts imports config.ts already).
38
51
  */
39
52
  export declare function attachServer(rosterPath: string): ServerHandle | null;
53
+ export type ProbeOutcome = "ready" | "auth-failure" | "retry";
54
+ export declare function probe(baseUrl: string, password: string): Promise<ProbeOutcome>;
40
55
  /**
41
56
  * Ensures a managed server is running for the roster and returns a handle
42
57
  * to it. Fast-paths to an existing live discovery; otherwise races for the
@@ -54,3 +69,38 @@ export declare function serverStatus(rosterPath: string): ServerStatus;
54
69
  export declare function stopServer(rosterPath: string): Promise<{
55
70
  stopped: boolean;
56
71
  }>;
72
+ export type SuperviseOutcome = {
73
+ reason: "signal";
74
+ } | {
75
+ reason: "died";
76
+ } | {
77
+ reason: "hung";
78
+ };
79
+ export interface SuperviseServerOptions {
80
+ /** Interval between liveness ticks. Default `SUPERVISE_INTERVAL_MS`. */
81
+ intervalMs?: number;
82
+ /** Consecutive `retry` probes (pid alive) before declaring the daemon
83
+ * hung. Default `SUPERVISE_FAILURE_THRESHOLD`. */
84
+ threshold?: number;
85
+ /** Absolute-lifetime watchdog budget. Default
86
+ * `SUPERVISE_UNHEALTHY_BUDGET_MS`. */
87
+ unhealthyBudgetMs?: number;
88
+ /** Injectable sleep, for deterministic tests. */
89
+ sleep?: (ms: number) => Promise<void>;
90
+ /** Injectable clock, for deterministic tests. Default `Date.now`. */
91
+ now?: () => number;
92
+ /** Injectable serverStatus, for deterministic tests. */
93
+ status?: typeof serverStatus;
94
+ /** Injectable probe, for deterministic tests. */
95
+ probe?: typeof probe;
96
+ /** Injectable stopServer, for deterministic tests. */
97
+ stop?: typeof stopServer;
98
+ /** Checked at the top of every tick; returning true breaks the loop with
99
+ * `{ reason: "signal" }` before any liveness work happens on that tick. */
100
+ shouldStop?: () => boolean;
101
+ /** Resolves to break the inter-tick sleep immediately (e.g. wired to a
102
+ * signal handler) instead of waiting out the full `intervalMs`. If
103
+ * undefined, the loop just sleeps the full interval. */
104
+ interrupt?: Promise<void>;
105
+ }
106
+ export declare function superviseServer(rosterPath: string, handle: ServerHandle, opts?: SuperviseServerOptions): Promise<SuperviseOutcome>;
package/dist/server.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contract.ts
2
5
  import { z } from "zod";
3
6
  var sessionSchema = z.looseObject({
@@ -188,14 +191,27 @@ function removeDiscovery(rosterPath) {
188
191
  throw err;
189
192
  }
190
193
  }
194
+ function removeDiscoveryIfMatches(rosterPath, expected) {
195
+ try {
196
+ const current = readDiscovery(rosterPath);
197
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
198
+ removeDiscovery(rosterPath);
199
+ }
200
+ } catch {}
201
+ }
191
202
  function attachLive(rosterPath) {
192
203
  const discovery = readDiscovery(rosterPath);
193
204
  if (!discovery)
194
205
  return null;
195
206
  if (!loopbackOk(discovery.baseUrl))
196
207
  return null;
197
- if (!verifyIdentity(discovery.pid, discovery.identity))
208
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
209
+ removeDiscoveryIfMatches(rosterPath, {
210
+ pid: discovery.pid,
211
+ identity: discovery.identity
212
+ });
198
213
  return null;
214
+ }
199
215
  return {
200
216
  baseUrl: discovery.baseUrl,
201
217
  credentials: { username: "opencode", password: discovery.password },
@@ -495,6 +511,9 @@ var POLL_INTERVAL_MS = 50;
495
511
  var MIN_PROBE_PHASE_MS = 3000;
496
512
  var PROBE_FETCH_TIMEOUT_MS = 2000;
497
513
  var STOP_GRACE_MS = 2000;
514
+ var SUPERVISE_INTERVAL_MS = 5000;
515
+ var SUPERVISE_FAILURE_THRESHOLD = 3;
516
+ var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
498
517
  function sleep(ms) {
499
518
  return new Promise((resolve) => setTimeout(resolve, ms));
500
519
  }
@@ -762,7 +781,14 @@ async function ensureServer(rosterPath, options = {}) {
762
781
  }
763
782
  function serverStatus(rosterPath) {
764
783
  const discovery = readDiscovery(rosterPath);
765
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
784
+ if (!discovery) {
785
+ return { running: false };
786
+ }
787
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
788
+ removeDiscoveryIfMatches(rosterPath, {
789
+ pid: discovery.pid,
790
+ identity: discovery.identity
791
+ });
766
792
  return { running: false };
767
793
  }
768
794
  let configDrift;
@@ -828,6 +854,75 @@ async function stopServer(rosterPath) {
828
854
  }
829
855
  return { stopped: false };
830
856
  }
857
+ async function stopForHung(tick) {
858
+ try {
859
+ await tick.stop(tick.rosterPath);
860
+ } catch {}
861
+ return { kind: "outcome", outcome: { reason: "hung" } };
862
+ }
863
+ async function superviseTick(tick, state) {
864
+ const st = tick.status(tick.rosterPath);
865
+ if (!st.running) {
866
+ return { kind: "outcome", outcome: { reason: "died" } };
867
+ }
868
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
869
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
870
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
871
+ if (failures >= tick.threshold) {
872
+ return stopForHung(tick);
873
+ }
874
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
875
+ return stopForHung(tick);
876
+ }
877
+ return { kind: "tick", failures, lastReadyAt };
878
+ }
879
+ function makeSuperviseTick(rosterPath, handle, opts) {
880
+ return {
881
+ rosterPath,
882
+ handle,
883
+ password: handle.credentials.password ?? "",
884
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
885
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
886
+ now: opts.now ?? Date.now,
887
+ status: opts.status ?? serverStatus,
888
+ probe: opts.probe ?? probe,
889
+ stop: opts.stop ?? stopServer
890
+ };
891
+ }
892
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
893
+ if (!interrupt) {
894
+ await doSleep(intervalMs);
895
+ return;
896
+ }
897
+ let timer;
898
+ const timed = new Promise((resolve) => {
899
+ timer = setTimeout(resolve, intervalMs);
900
+ });
901
+ try {
902
+ await Promise.race([timed, interrupt]);
903
+ } finally {
904
+ if (timer !== undefined)
905
+ clearTimeout(timer);
906
+ }
907
+ }
908
+ async function superviseServer(rosterPath, handle, opts = {}) {
909
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
910
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
911
+ const doSleep = opts.sleep ?? sleep;
912
+ const shouldStop = opts.shouldStop ?? (() => false);
913
+ let state = { failures: 0, lastReadyAt: tick.now() };
914
+ for (;; ) {
915
+ if (shouldStop())
916
+ return { reason: "signal" };
917
+ const result = await superviseTick(tick, state);
918
+ if (result.kind === "outcome")
919
+ return result.outcome;
920
+ state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
921
+ if (shouldStop())
922
+ return { reason: "signal" };
923
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
924
+ }
925
+ }
831
926
  async function waitForDeath(pid, budgetMs) {
832
927
  const deadline = Date.now() + budgetMs;
833
928
  while (Date.now() < deadline) {
@@ -855,9 +950,14 @@ async function waitForGroupDeath(pid, budgetMs) {
855
950
  return !groupAlive();
856
951
  }
857
952
  export {
953
+ superviseServer,
858
954
  stopServer,
859
955
  serverStatus,
860
956
  redactSensitive,
957
+ probe,
861
958
  ensureServer,
862
- attachServer
959
+ attachServer,
960
+ SUPERVISE_UNHEALTHY_BUDGET_MS,
961
+ SUPERVISE_INTERVAL_MS,
962
+ SUPERVISE_FAILURE_THRESHOLD
863
963
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fro.bot/space-bus",
3
- "version": "0.7.1",
3
+ "version": "0.8.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",
@@ -74,7 +74,7 @@
74
74
  "devDependencies": {
75
75
  "@biomejs/biome": "2.5.2",
76
76
  "@changesets/cli": "2.31.0",
77
- "@opencode-ai/plugin": "1.17.13",
77
+ "@opencode-ai/plugin": "1.17.15",
78
78
  "@types/bun": "1.3.14",
79
79
  "typescript": "5.9.3"
80
80
  }