@fro.bot/space-bus 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
  }
@@ -546,6 +565,16 @@ function signalGroup(pid, sig) {
546
565
  } catch {}
547
566
  return false;
548
567
  }
568
+ function signalGroupOnly(pid, sig) {
569
+ if (pid <= 1)
570
+ return false;
571
+ try {
572
+ process.kill(-pid, sig);
573
+ return true;
574
+ } catch {
575
+ return false;
576
+ }
577
+ }
549
578
  function killIdentifiedProcess(pid, identity) {
550
579
  try {
551
580
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -763,7 +792,14 @@ async function ensureServer(rosterPath, options = {}) {
763
792
  }
764
793
  function serverStatus(rosterPath) {
765
794
  const discovery = readDiscovery(rosterPath);
766
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
795
+ if (!discovery) {
796
+ return { running: false };
797
+ }
798
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
799
+ removeDiscoveryIfMatches(rosterPath, {
800
+ pid: discovery.pid,
801
+ identity: discovery.identity
802
+ });
767
803
  return { running: false };
768
804
  }
769
805
  let configDrift;
@@ -795,6 +831,7 @@ async function stopServer(rosterPath) {
795
831
  if (!discovery)
796
832
  return { stopped: false };
797
833
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
834
+ await reapSurvivingGroup(discovery.pid);
798
835
  removeDiscovery(rosterPath);
799
836
  return { stopped: false };
800
837
  }
@@ -829,6 +866,97 @@ async function stopServer(rosterPath) {
829
866
  }
830
867
  return { stopped: false };
831
868
  }
869
+ async function reapSurvivingGroup(pid) {
870
+ try {
871
+ if (isAlive(pid))
872
+ return;
873
+ let groupAlive;
874
+ try {
875
+ process.kill(-pid, 0);
876
+ groupAlive = true;
877
+ } catch {
878
+ groupAlive = false;
879
+ }
880
+ if (!groupAlive)
881
+ return;
882
+ if (!signalGroupOnly(pid, "SIGTERM"))
883
+ return;
884
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
885
+ return;
886
+ signalGroupOnly(pid, "SIGKILL");
887
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
888
+ } catch {}
889
+ }
890
+ async function stopForHung(tick) {
891
+ try {
892
+ await tick.stop(tick.rosterPath);
893
+ } catch {}
894
+ return { kind: "outcome", outcome: { reason: "hung" } };
895
+ }
896
+ async function superviseTick(tick, state) {
897
+ const st = tick.status(tick.rosterPath);
898
+ if (!st.running) {
899
+ await reapSurvivingGroup(tick.handle.pid);
900
+ return { kind: "outcome", outcome: { reason: "died" } };
901
+ }
902
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
903
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
904
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
905
+ if (failures >= tick.threshold) {
906
+ return stopForHung(tick);
907
+ }
908
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
909
+ return stopForHung(tick);
910
+ }
911
+ return { kind: "tick", failures, lastReadyAt };
912
+ }
913
+ function makeSuperviseTick(rosterPath, handle, opts) {
914
+ return {
915
+ rosterPath,
916
+ handle,
917
+ password: handle.credentials.password ?? "",
918
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
919
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
920
+ now: opts.now ?? Date.now,
921
+ status: opts.status ?? serverStatus,
922
+ probe: opts.probe ?? probe,
923
+ stop: opts.stop ?? stopServer
924
+ };
925
+ }
926
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
927
+ if (!interrupt) {
928
+ await doSleep(intervalMs);
929
+ return;
930
+ }
931
+ let timer;
932
+ const timed = new Promise((resolve) => {
933
+ timer = setTimeout(resolve, intervalMs);
934
+ });
935
+ try {
936
+ await Promise.race([timed, interrupt]);
937
+ } finally {
938
+ if (timer !== undefined)
939
+ clearTimeout(timer);
940
+ }
941
+ }
942
+ async function superviseServer(rosterPath, handle, opts = {}) {
943
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
944
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
945
+ const doSleep = opts.sleep ?? sleep;
946
+ const shouldStop = opts.shouldStop ?? (() => false);
947
+ let state = { failures: 0, lastReadyAt: tick.now() };
948
+ for (;; ) {
949
+ if (shouldStop())
950
+ return { reason: "signal" };
951
+ const result = await superviseTick(tick, state);
952
+ if (result.kind === "outcome")
953
+ return result.outcome;
954
+ state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
955
+ if (shouldStop())
956
+ return { reason: "signal" };
957
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
958
+ }
959
+ }
832
960
  async function waitForDeath(pid, budgetMs) {
833
961
  const deadline = Date.now() + budgetMs;
834
962
  while (Date.now() < deadline) {
@@ -920,9 +1048,12 @@ function printJson(json, data, plain) {
920
1048
  `);
921
1049
  }
922
1050
  }
923
- async function runServe(args) {
1051
+ async function runServe(args, deps = {}) {
1052
+ const doEnsureServer = deps.ensureServer ?? ensureServer;
1053
+ const doStopServer = deps.stopServer ?? stopServer;
1054
+ const doSuperviseServer = deps.superviseServer ?? ((rosterPath2, handle2, shouldStop, interrupt) => superviseServer(rosterPath2, handle2, { shouldStop, interrupt }));
924
1055
  const rosterPath = resolveRoster(args.config);
925
- const handle = await ensureServer(rosterPath);
1056
+ const handle = await doEnsureServer(rosterPath);
926
1057
  const data = {
927
1058
  running: true,
928
1059
  port: handle.port,
@@ -933,17 +1064,45 @@ async function runServe(args) {
933
1064
  if (!args.foreground)
934
1065
  return 0;
935
1066
  return await new Promise((resolve) => {
936
- let stopping = false;
937
- const shutdown = (signal) => {
938
- if (stopping)
1067
+ let stopRequested = false;
1068
+ let wake = () => {};
1069
+ const interrupt = new Promise((r) => {
1070
+ wake = r;
1071
+ });
1072
+ const sigintHandler = () => onSignal("SIGINT");
1073
+ const sigtermHandler = () => onSignal("SIGTERM");
1074
+ const removeSignalHandlers = () => {
1075
+ process.off("SIGINT", sigintHandler);
1076
+ process.off("SIGTERM", sigtermHandler);
1077
+ };
1078
+ const onSignal = (signal) => {
1079
+ if (stopRequested)
939
1080
  return;
940
- stopping = true;
1081
+ stopRequested = true;
941
1082
  process.stderr.write(`space-bus: received ${signal}, stopping...
942
1083
  `);
943
- stopServer(rosterPath).finally(() => resolve(0));
1084
+ wake();
944
1085
  };
945
- process.on("SIGINT", () => shutdown("SIGINT"));
946
- process.on("SIGTERM", () => shutdown("SIGTERM"));
1086
+ process.on("SIGINT", sigintHandler);
1087
+ process.on("SIGTERM", sigtermHandler);
1088
+ doSuperviseServer(rosterPath, handle, () => stopRequested, interrupt).then((outcome) => {
1089
+ if (outcome.reason === "signal") {
1090
+ doStopServer(rosterPath).finally(() => {
1091
+ removeSignalHandlers();
1092
+ resolve(0);
1093
+ });
1094
+ return;
1095
+ }
1096
+ removeSignalHandlers();
1097
+ process.stderr.write(`space-bus: managed daemon ${outcome.reason}; exiting for supervisor restart
1098
+ `);
1099
+ resolve(1);
1100
+ }).catch((err) => {
1101
+ removeSignalHandlers();
1102
+ process.stderr.write(`space-bus: supervision failed unexpectedly: ${err.message}
1103
+ `);
1104
+ resolve(1);
1105
+ });
947
1106
  });
948
1107
  }
949
1108
  function runStatus(args) {
@@ -999,10 +1158,15 @@ async function main() {
999
1158
  return 1;
1000
1159
  }
1001
1160
  }
1002
- main().then((code) => {
1003
- process.exitCode = code;
1004
- }).catch((err) => {
1005
- process.stderr.write(`space-bus: ${err.message}
1161
+ if (__require.main == __require.module) {
1162
+ main().then((code) => {
1163
+ process.exitCode = code;
1164
+ }).catch((err) => {
1165
+ process.stderr.write(`space-bus: ${err.message}
1006
1166
  `);
1007
- process.exitCode = 1;
1008
- });
1167
+ process.exitCode = 1;
1168
+ });
1169
+ }
1170
+ export {
1171
+ runServe
1172
+ };
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
  }
@@ -1130,6 +1149,16 @@ function signalGroup(pid, sig) {
1130
1149
  } catch {}
1131
1150
  return false;
1132
1151
  }
1152
+ function signalGroupOnly(pid, sig) {
1153
+ if (pid <= 1)
1154
+ return false;
1155
+ try {
1156
+ process.kill(-pid, sig);
1157
+ return true;
1158
+ } catch {
1159
+ return false;
1160
+ }
1161
+ }
1133
1162
  function killIdentifiedProcess(pid, identity) {
1134
1163
  try {
1135
1164
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -1347,7 +1376,14 @@ async function ensureServer(rosterPath, options = {}) {
1347
1376
  }
1348
1377
  function serverStatus(rosterPath) {
1349
1378
  const discovery = readDiscovery(rosterPath);
1350
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
1379
+ if (!discovery) {
1380
+ return { running: false };
1381
+ }
1382
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
1383
+ removeDiscoveryIfMatches(rosterPath, {
1384
+ pid: discovery.pid,
1385
+ identity: discovery.identity
1386
+ });
1351
1387
  return { running: false };
1352
1388
  }
1353
1389
  let configDrift;
@@ -1379,6 +1415,7 @@ async function stopServer(rosterPath) {
1379
1415
  if (!discovery)
1380
1416
  return { stopped: false };
1381
1417
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
1418
+ await reapSurvivingGroup(discovery.pid);
1382
1419
  removeDiscovery(rosterPath);
1383
1420
  return { stopped: false };
1384
1421
  }
@@ -1413,6 +1450,97 @@ async function stopServer(rosterPath) {
1413
1450
  }
1414
1451
  return { stopped: false };
1415
1452
  }
1453
+ async function reapSurvivingGroup(pid) {
1454
+ try {
1455
+ if (isAlive(pid))
1456
+ return;
1457
+ let groupAlive;
1458
+ try {
1459
+ process.kill(-pid, 0);
1460
+ groupAlive = true;
1461
+ } catch {
1462
+ groupAlive = false;
1463
+ }
1464
+ if (!groupAlive)
1465
+ return;
1466
+ if (!signalGroupOnly(pid, "SIGTERM"))
1467
+ return;
1468
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
1469
+ return;
1470
+ signalGroupOnly(pid, "SIGKILL");
1471
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
1472
+ } catch {}
1473
+ }
1474
+ async function stopForHung(tick) {
1475
+ try {
1476
+ await tick.stop(tick.rosterPath);
1477
+ } catch {}
1478
+ return { kind: "outcome", outcome: { reason: "hung" } };
1479
+ }
1480
+ async function superviseTick(tick, state) {
1481
+ const st = tick.status(tick.rosterPath);
1482
+ if (!st.running) {
1483
+ await reapSurvivingGroup(tick.handle.pid);
1484
+ return { kind: "outcome", outcome: { reason: "died" } };
1485
+ }
1486
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1487
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1488
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1489
+ if (failures >= tick.threshold) {
1490
+ return stopForHung(tick);
1491
+ }
1492
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1493
+ return stopForHung(tick);
1494
+ }
1495
+ return { kind: "tick", failures, lastReadyAt };
1496
+ }
1497
+ function makeSuperviseTick(rosterPath, handle, opts) {
1498
+ return {
1499
+ rosterPath,
1500
+ handle,
1501
+ password: handle.credentials.password ?? "",
1502
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1503
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1504
+ now: opts.now ?? Date.now,
1505
+ status: opts.status ?? serverStatus,
1506
+ probe: opts.probe ?? probe,
1507
+ stop: opts.stop ?? stopServer
1508
+ };
1509
+ }
1510
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1511
+ if (!interrupt) {
1512
+ await doSleep(intervalMs);
1513
+ return;
1514
+ }
1515
+ let timer;
1516
+ const timed = new Promise((resolve) => {
1517
+ timer = setTimeout(resolve, intervalMs);
1518
+ });
1519
+ try {
1520
+ await Promise.race([timed, interrupt]);
1521
+ } finally {
1522
+ if (timer !== undefined)
1523
+ clearTimeout(timer);
1524
+ }
1525
+ }
1526
+ async function superviseServer(rosterPath, handle, opts = {}) {
1527
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1528
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
1529
+ const doSleep = opts.sleep ?? sleep;
1530
+ const shouldStop = opts.shouldStop ?? (() => false);
1531
+ let state = { failures: 0, lastReadyAt: tick.now() };
1532
+ for (;; ) {
1533
+ if (shouldStop())
1534
+ return { reason: "signal" };
1535
+ const result2 = await superviseTick(tick, state);
1536
+ if (result2.kind === "outcome")
1537
+ return result2.outcome;
1538
+ state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
1539
+ if (shouldStop())
1540
+ return { reason: "signal" };
1541
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1542
+ }
1543
+ }
1416
1544
  async function waitForDeath(pid, budgetMs) {
1417
1545
  const deadline = Date.now() + budgetMs;
1418
1546
  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
  }
@@ -1131,6 +1150,16 @@ function signalGroup(pid, sig) {
1131
1150
  } catch {}
1132
1151
  return false;
1133
1152
  }
1153
+ function signalGroupOnly(pid, sig) {
1154
+ if (pid <= 1)
1155
+ return false;
1156
+ try {
1157
+ process.kill(-pid, sig);
1158
+ return true;
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ }
1134
1163
  function killIdentifiedProcess(pid, identity) {
1135
1164
  try {
1136
1165
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -1348,7 +1377,14 @@ async function ensureServer(rosterPath, options = {}) {
1348
1377
  }
1349
1378
  function serverStatus(rosterPath) {
1350
1379
  const discovery = readDiscovery(rosterPath);
1351
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
1380
+ if (!discovery) {
1381
+ return { running: false };
1382
+ }
1383
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
1384
+ removeDiscoveryIfMatches(rosterPath, {
1385
+ pid: discovery.pid,
1386
+ identity: discovery.identity
1387
+ });
1352
1388
  return { running: false };
1353
1389
  }
1354
1390
  let configDrift;
@@ -1380,6 +1416,7 @@ async function stopServer(rosterPath) {
1380
1416
  if (!discovery)
1381
1417
  return { stopped: false };
1382
1418
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
1419
+ await reapSurvivingGroup(discovery.pid);
1383
1420
  removeDiscovery(rosterPath);
1384
1421
  return { stopped: false };
1385
1422
  }
@@ -1414,6 +1451,97 @@ async function stopServer(rosterPath) {
1414
1451
  }
1415
1452
  return { stopped: false };
1416
1453
  }
1454
+ async function reapSurvivingGroup(pid) {
1455
+ try {
1456
+ if (isAlive(pid))
1457
+ return;
1458
+ let groupAlive;
1459
+ try {
1460
+ process.kill(-pid, 0);
1461
+ groupAlive = true;
1462
+ } catch {
1463
+ groupAlive = false;
1464
+ }
1465
+ if (!groupAlive)
1466
+ return;
1467
+ if (!signalGroupOnly(pid, "SIGTERM"))
1468
+ return;
1469
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
1470
+ return;
1471
+ signalGroupOnly(pid, "SIGKILL");
1472
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
1473
+ } catch {}
1474
+ }
1475
+ async function stopForHung(tick) {
1476
+ try {
1477
+ await tick.stop(tick.rosterPath);
1478
+ } catch {}
1479
+ return { kind: "outcome", outcome: { reason: "hung" } };
1480
+ }
1481
+ async function superviseTick(tick, state) {
1482
+ const st = tick.status(tick.rosterPath);
1483
+ if (!st.running) {
1484
+ await reapSurvivingGroup(tick.handle.pid);
1485
+ return { kind: "outcome", outcome: { reason: "died" } };
1486
+ }
1487
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1488
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1489
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1490
+ if (failures >= tick.threshold) {
1491
+ return stopForHung(tick);
1492
+ }
1493
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1494
+ return stopForHung(tick);
1495
+ }
1496
+ return { kind: "tick", failures, lastReadyAt };
1497
+ }
1498
+ function makeSuperviseTick(rosterPath, handle, opts) {
1499
+ return {
1500
+ rosterPath,
1501
+ handle,
1502
+ password: handle.credentials.password ?? "",
1503
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1504
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1505
+ now: opts.now ?? Date.now,
1506
+ status: opts.status ?? serverStatus,
1507
+ probe: opts.probe ?? probe,
1508
+ stop: opts.stop ?? stopServer
1509
+ };
1510
+ }
1511
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1512
+ if (!interrupt) {
1513
+ await doSleep(intervalMs);
1514
+ return;
1515
+ }
1516
+ let timer;
1517
+ const timed = new Promise((resolve) => {
1518
+ timer = setTimeout(resolve, intervalMs);
1519
+ });
1520
+ try {
1521
+ await Promise.race([timed, interrupt]);
1522
+ } finally {
1523
+ if (timer !== undefined)
1524
+ clearTimeout(timer);
1525
+ }
1526
+ }
1527
+ async function superviseServer(rosterPath, handle, opts = {}) {
1528
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1529
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
1530
+ const doSleep = opts.sleep ?? sleep;
1531
+ const shouldStop = opts.shouldStop ?? (() => false);
1532
+ let state = { failures: 0, lastReadyAt: tick.now() };
1533
+ for (;; ) {
1534
+ if (shouldStop())
1535
+ return { reason: "signal" };
1536
+ const result2 = await superviseTick(tick, state);
1537
+ if (result2.kind === "outcome")
1538
+ return result2.outcome;
1539
+ state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
1540
+ if (shouldStop())
1541
+ return { reason: "signal" };
1542
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1543
+ }
1544
+ }
1417
1545
  async function waitForDeath(pid, budgetMs) {
1418
1546
  const deadline = Date.now() + budgetMs;
1419
1547
  while (Date.now() < deadline) {
@@ -1569,7 +1697,7 @@ async function mcpLoadContext() {
1569
1697
  }
1570
1698
  return loadContext();
1571
1699
  }
1572
- var version = "0.7.1";
1700
+ var version = "0.8.1";
1573
1701
  var server = new McpServer({
1574
1702
  name: "space-bus",
1575
1703
  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,74 @@ export declare function serverStatus(rosterPath: string): ServerStatus;
54
69
  export declare function stopServer(rosterPath: string): Promise<{
55
70
  stopped: boolean;
56
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>;
108
+ export type SuperviseOutcome = {
109
+ reason: "signal";
110
+ } | {
111
+ reason: "died";
112
+ } | {
113
+ reason: "hung";
114
+ };
115
+ export interface SuperviseServerOptions {
116
+ /** Interval between liveness ticks. Default `SUPERVISE_INTERVAL_MS`. */
117
+ intervalMs?: number;
118
+ /** Consecutive `retry` probes (pid alive) before declaring the daemon
119
+ * hung. Default `SUPERVISE_FAILURE_THRESHOLD`. */
120
+ threshold?: number;
121
+ /** Absolute-lifetime watchdog budget. Default
122
+ * `SUPERVISE_UNHEALTHY_BUDGET_MS`. */
123
+ unhealthyBudgetMs?: number;
124
+ /** Injectable sleep, for deterministic tests. */
125
+ sleep?: (ms: number) => Promise<void>;
126
+ /** Injectable clock, for deterministic tests. Default `Date.now`. */
127
+ now?: () => number;
128
+ /** Injectable serverStatus, for deterministic tests. */
129
+ status?: typeof serverStatus;
130
+ /** Injectable probe, for deterministic tests. */
131
+ probe?: typeof probe;
132
+ /** Injectable stopServer, for deterministic tests. */
133
+ stop?: typeof stopServer;
134
+ /** Checked at the top of every tick; returning true breaks the loop with
135
+ * `{ reason: "signal" }` before any liveness work happens on that tick. */
136
+ shouldStop?: () => boolean;
137
+ /** Resolves to break the inter-tick sleep immediately (e.g. wired to a
138
+ * signal handler) instead of waiting out the full `intervalMs`. If
139
+ * undefined, the loop just sleeps the full interval. */
140
+ interrupt?: Promise<void>;
141
+ }
142
+ 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
  }
@@ -545,6 +564,16 @@ function signalGroup(pid, sig) {
545
564
  } catch {}
546
565
  return false;
547
566
  }
567
+ function signalGroupOnly(pid, sig) {
568
+ if (pid <= 1)
569
+ return false;
570
+ try {
571
+ process.kill(-pid, sig);
572
+ return true;
573
+ } catch {
574
+ return false;
575
+ }
576
+ }
548
577
  function killIdentifiedProcess(pid, identity) {
549
578
  try {
550
579
  if (identity !== null && identity !== undefined && identity !== "") {
@@ -762,7 +791,14 @@ async function ensureServer(rosterPath, options = {}) {
762
791
  }
763
792
  function serverStatus(rosterPath) {
764
793
  const discovery = readDiscovery(rosterPath);
765
- if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
794
+ if (!discovery) {
795
+ return { running: false };
796
+ }
797
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
798
+ removeDiscoveryIfMatches(rosterPath, {
799
+ pid: discovery.pid,
800
+ identity: discovery.identity
801
+ });
766
802
  return { running: false };
767
803
  }
768
804
  let configDrift;
@@ -794,6 +830,7 @@ async function stopServer(rosterPath) {
794
830
  if (!discovery)
795
831
  return { stopped: false };
796
832
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
833
+ await reapSurvivingGroup(discovery.pid);
797
834
  removeDiscovery(rosterPath);
798
835
  return { stopped: false };
799
836
  }
@@ -828,6 +865,97 @@ async function stopServer(rosterPath) {
828
865
  }
829
866
  return { stopped: false };
830
867
  }
868
+ async function reapSurvivingGroup(pid) {
869
+ try {
870
+ if (isAlive(pid))
871
+ return;
872
+ let groupAlive;
873
+ try {
874
+ process.kill(-pid, 0);
875
+ groupAlive = true;
876
+ } catch {
877
+ groupAlive = false;
878
+ }
879
+ if (!groupAlive)
880
+ return;
881
+ if (!signalGroupOnly(pid, "SIGTERM"))
882
+ return;
883
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
884
+ return;
885
+ signalGroupOnly(pid, "SIGKILL");
886
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
887
+ } catch {}
888
+ }
889
+ async function stopForHung(tick) {
890
+ try {
891
+ await tick.stop(tick.rosterPath);
892
+ } catch {}
893
+ return { kind: "outcome", outcome: { reason: "hung" } };
894
+ }
895
+ async function superviseTick(tick, state) {
896
+ const st = tick.status(tick.rosterPath);
897
+ if (!st.running) {
898
+ await reapSurvivingGroup(tick.handle.pid);
899
+ return { kind: "outcome", outcome: { reason: "died" } };
900
+ }
901
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
902
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
903
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
904
+ if (failures >= tick.threshold) {
905
+ return stopForHung(tick);
906
+ }
907
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
908
+ return stopForHung(tick);
909
+ }
910
+ return { kind: "tick", failures, lastReadyAt };
911
+ }
912
+ function makeSuperviseTick(rosterPath, handle, opts) {
913
+ return {
914
+ rosterPath,
915
+ handle,
916
+ password: handle.credentials.password ?? "",
917
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
918
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
919
+ now: opts.now ?? Date.now,
920
+ status: opts.status ?? serverStatus,
921
+ probe: opts.probe ?? probe,
922
+ stop: opts.stop ?? stopServer
923
+ };
924
+ }
925
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
926
+ if (!interrupt) {
927
+ await doSleep(intervalMs);
928
+ return;
929
+ }
930
+ let timer;
931
+ const timed = new Promise((resolve) => {
932
+ timer = setTimeout(resolve, intervalMs);
933
+ });
934
+ try {
935
+ await Promise.race([timed, interrupt]);
936
+ } finally {
937
+ if (timer !== undefined)
938
+ clearTimeout(timer);
939
+ }
940
+ }
941
+ async function superviseServer(rosterPath, handle, opts = {}) {
942
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
943
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
944
+ const doSleep = opts.sleep ?? sleep;
945
+ const shouldStop = opts.shouldStop ?? (() => false);
946
+ let state = { failures: 0, lastReadyAt: tick.now() };
947
+ for (;; ) {
948
+ if (shouldStop())
949
+ return { reason: "signal" };
950
+ const result = await superviseTick(tick, state);
951
+ if (result.kind === "outcome")
952
+ return result.outcome;
953
+ state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
954
+ if (shouldStop())
955
+ return { reason: "signal" };
956
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
957
+ }
958
+ }
831
959
  async function waitForDeath(pid, budgetMs) {
832
960
  const deadline = Date.now() + budgetMs;
833
961
  while (Date.now() < deadline) {
@@ -855,9 +983,15 @@ async function waitForGroupDeath(pid, budgetMs) {
855
983
  return !groupAlive();
856
984
  }
857
985
  export {
986
+ superviseServer,
858
987
  stopServer,
859
988
  serverStatus,
860
989
  redactSensitive,
990
+ reapSurvivingGroup,
991
+ probe,
861
992
  ensureServer,
862
- attachServer
993
+ attachServer,
994
+ SUPERVISE_UNHEALTHY_BUDGET_MS,
995
+ SUPERVISE_INTERVAL_MS,
996
+ SUPERVISE_FAILURE_THRESHOLD
863
997
  };
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.1",
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
  }