@fro.bot/space-bus 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -3,9 +3,9 @@ import { createRequire } from "node:module";
3
3
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
4
 
5
5
  // src/config.ts
6
- import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
7
- import { homedir as homedir2 } from "node:os";
8
- import { join as join2 } from "node:path";
6
+ import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
7
+ import { homedir as homedir3 } from "node:os";
8
+ import { join as join3 } from "node:path";
9
9
  import { z as z3 } from "zod";
10
10
 
11
11
  // src/contract.ts
@@ -128,13 +128,44 @@ var managedSpawnConfigSchema = z.object({
128
128
  cwd: z.string().optional(),
129
129
  port: z.number().int().nonnegative().optional()
130
130
  });
131
+ var registryEntrySchema = z.object({
132
+ name: z.string().regex(/^[a-z0-9-]{1,64}$/, "roster name must be 1-64 lowercase letters, digits, or hyphens"),
133
+ path: z.string().min(1, "roster path must not be empty")
134
+ });
135
+ var registryFileSchema = z.object({
136
+ version: z.literal(1),
137
+ default: z.string().optional(),
138
+ rosters: z.array(registryEntrySchema)
139
+ }).superRefine((val, ctx) => {
140
+ const seen = new Set;
141
+ for (const entry of val.rosters) {
142
+ const key = entry.name.toLowerCase();
143
+ if (seen.has(key)) {
144
+ ctx.addIssue({
145
+ code: "custom",
146
+ message: `space-bus: duplicate roster name "${entry.name}" (case-insensitive) in registry`
147
+ });
148
+ }
149
+ seen.add(key);
150
+ }
151
+ if (val.default !== undefined) {
152
+ const matches = val.rosters.filter((entry) => entry.name === val.default);
153
+ if (matches.length !== 1) {
154
+ ctx.addIssue({
155
+ code: "custom",
156
+ message: `space-bus: registry's default "${val.default}" must match exactly one roster entry's name (matched ${matches.length})`
157
+ });
158
+ }
159
+ }
160
+ });
131
161
  var discoveryFileSchema = z.object({
132
162
  port: z.number().int().nonnegative(),
133
163
  pid: z.number().int().min(2),
134
164
  identity: z.string(),
135
165
  password: z.string(),
136
166
  spawnConfig: managedSpawnConfigSchema,
137
- baseUrl: z.url()
167
+ baseUrl: z.url(),
168
+ rosterPath: z.string().optional()
138
169
  });
139
170
 
140
171
  // src/discovery.ts
@@ -403,6 +434,380 @@ function removeProvisional(rosterPath) {
403
434
  } catch {}
404
435
  }
405
436
 
437
+ // src/registry.ts
438
+ import { randomBytes as randomBytes2 } from "node:crypto";
439
+ import {
440
+ closeSync as closeSync2,
441
+ constants as fsConstants2,
442
+ fstatSync,
443
+ lstatSync,
444
+ mkdirSync as mkdirSync2,
445
+ openSync as openSync2,
446
+ readFileSync as readFileSync2,
447
+ realpathSync,
448
+ renameSync as renameSync2,
449
+ statSync as statSync2,
450
+ unlinkSync as unlinkSync2,
451
+ writeSync
452
+ } from "node:fs";
453
+ import { homedir as homedir2 } from "node:os";
454
+ import { isAbsolute, join as join2 } from "node:path";
455
+ var EMPTY_REGISTRY = { version: 1, rosters: [] };
456
+ function registryPath() {
457
+ const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir2(), ".config");
458
+ return join2(base, "space-bus", "rosters.json");
459
+ }
460
+ function isEnoent2(err) {
461
+ return isErrnoCode2(err, "ENOENT");
462
+ }
463
+ function isErrnoCode2(err, code) {
464
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
465
+ }
466
+ function closeQuietly2(fd) {
467
+ try {
468
+ closeSync2(fd);
469
+ } catch {}
470
+ }
471
+ function readRegistry() {
472
+ const target = registryPath();
473
+ let raw;
474
+ try {
475
+ raw = readFileSync2(target, "utf8");
476
+ } catch (err) {
477
+ if (isEnoent2(err)) {
478
+ return { ok: true, registry: EMPTY_REGISTRY };
479
+ }
480
+ return {
481
+ ok: false,
482
+ error: `space-bus: cannot read registry at ${target}: ${String(err)}`
483
+ };
484
+ }
485
+ let json;
486
+ try {
487
+ json = JSON.parse(raw);
488
+ } catch (err) {
489
+ return {
490
+ ok: false,
491
+ error: `space-bus: registry at ${target} is not valid JSON: ${String(err)}`
492
+ };
493
+ }
494
+ const parsed = registryFileSchema.safeParse(json);
495
+ if (!parsed.success) {
496
+ return {
497
+ ok: false,
498
+ error: `space-bus: registry at ${target} failed schema validation: ${parsed.error.message}`
499
+ };
500
+ }
501
+ const nonAbsolute = parsed.data.rosters.find((entry) => !isAbsolute(entry.path));
502
+ if (nonAbsolute) {
503
+ return {
504
+ ok: false,
505
+ error: `space-bus: registry at ${target} contains a non-absolute path for roster "${nonAbsolute.name}": ${nonAbsolute.path}`
506
+ };
507
+ }
508
+ return { ok: true, registry: parsed.data };
509
+ }
510
+ function writeRegistryAtomic(data) {
511
+ const target = registryPath();
512
+ const dir = join2(target, "..");
513
+ try {
514
+ mkdirSync2(dir, { recursive: true, mode: 448 });
515
+ } catch (err) {
516
+ return {
517
+ ok: false,
518
+ error: `space-bus: failed to create registry dir ${dir}: ${String(err)}`
519
+ };
520
+ }
521
+ const tempPath = join2(dir, `.rosters.${randomBytes2(8).toString("hex")}.tmp`);
522
+ let fd;
523
+ try {
524
+ fd = openSync2(tempPath, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
525
+ writeSync(fd, JSON.stringify(data, null, 2));
526
+ closeSync2(fd);
527
+ fd = undefined;
528
+ renameSync2(tempPath, target);
529
+ } catch (err) {
530
+ if (fd !== undefined)
531
+ closeQuietly2(fd);
532
+ try {
533
+ unlinkSync2(tempPath);
534
+ } catch {}
535
+ return {
536
+ ok: false,
537
+ error: `space-bus: failed to write registry at ${target}: ${String(err)}`
538
+ };
539
+ }
540
+ return { ok: true };
541
+ }
542
+ function registryLockPath() {
543
+ return join2(registryPath(), "..", "rosters.lock");
544
+ }
545
+ var LOCK_RETRY_COUNT = 10;
546
+ var LOCK_RETRY_DELAY_MS = 50;
547
+ var LOCK_STALE_MS = 1e4;
548
+ function sleepSync(ms) {
549
+ const buf = new Int32Array(new SharedArrayBuffer(4));
550
+ Atomics.wait(buf, 0, 0, ms);
551
+ }
552
+ function tryCreateRegistryLock(target) {
553
+ let fd;
554
+ try {
555
+ fd = openSync2(target, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
556
+ } catch (err) {
557
+ if (isErrnoCode2(err, "EEXIST"))
558
+ return false;
559
+ throw err;
560
+ }
561
+ try {
562
+ writeSync(fd, String(process.pid));
563
+ } finally {
564
+ closeQuietly2(fd);
565
+ }
566
+ return true;
567
+ }
568
+ function isRegistryLockStale(target) {
569
+ try {
570
+ return Date.now() - statSync2(target).mtimeMs > LOCK_STALE_MS;
571
+ } catch {
572
+ return false;
573
+ }
574
+ }
575
+ function breakStaleAndRetry(target) {
576
+ if (!isRegistryLockStale(target))
577
+ return false;
578
+ try {
579
+ unlinkSync2(target);
580
+ } catch (err) {
581
+ if (!isEnoent2(err))
582
+ throw err;
583
+ }
584
+ return tryCreateRegistryLock(target);
585
+ }
586
+ function acquireRegistryLock() {
587
+ const dir = join2(registryPath(), "..");
588
+ mkdirSync2(dir, { recursive: true, mode: 448 });
589
+ const target = registryLockPath();
590
+ for (let attempt = 0;attempt <= LOCK_RETRY_COUNT; attempt++) {
591
+ if (tryCreateRegistryLock(target))
592
+ return true;
593
+ if (breakStaleAndRetry(target))
594
+ return true;
595
+ if (attempt < LOCK_RETRY_COUNT)
596
+ sleepSync(LOCK_RETRY_DELAY_MS);
597
+ }
598
+ return false;
599
+ }
600
+ function releaseRegistryLock() {
601
+ try {
602
+ unlinkSync2(registryLockPath());
603
+ } catch {}
604
+ }
605
+ function withRegistryLock(mutate) {
606
+ if (!acquireRegistryLock()) {
607
+ return {
608
+ ok: false,
609
+ error: "space-bus: timed out waiting for the registry lock (another process is mutating rosters.json) — try again"
610
+ };
611
+ }
612
+ try {
613
+ return mutate();
614
+ } finally {
615
+ releaseRegistryLock();
616
+ }
617
+ }
618
+ function openAndValidateRosterFile(rosterPath) {
619
+ let fd;
620
+ try {
621
+ fd = openSync2(rosterPath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
622
+ } catch (err) {
623
+ if (isErrnoCode2(err, "ELOOP")) {
624
+ return {
625
+ ok: false,
626
+ error: `space-bus: roster path ${rosterPath} is a symlink — refusing to register a symlinked roster file`
627
+ };
628
+ }
629
+ if (isEnoent2(err)) {
630
+ return {
631
+ ok: false,
632
+ error: `space-bus: roster path ${rosterPath} does not exist: ${String(err)}`
633
+ };
634
+ }
635
+ return {
636
+ ok: false,
637
+ error: `space-bus: failed to open roster path ${rosterPath}: ${String(err)}`
638
+ };
639
+ }
640
+ try {
641
+ let stat;
642
+ try {
643
+ stat = fstatSync(fd);
644
+ } catch (err) {
645
+ return {
646
+ ok: false,
647
+ error: `space-bus: failed to stat roster path ${rosterPath}: ${String(err)}`
648
+ };
649
+ }
650
+ if (!stat.isFile()) {
651
+ return {
652
+ ok: false,
653
+ error: `space-bus: roster path ${rosterPath} is not a regular file — refusing to register`
654
+ };
655
+ }
656
+ let raw;
657
+ try {
658
+ raw = readFileSync2(fd, "utf8");
659
+ } catch (err) {
660
+ return {
661
+ ok: false,
662
+ error: `space-bus: failed to read roster path ${rosterPath}: ${String(err)}`
663
+ };
664
+ }
665
+ let json;
666
+ try {
667
+ json = JSON.parse(raw);
668
+ } catch (err) {
669
+ return {
670
+ ok: false,
671
+ error: `space-bus: roster path ${rosterPath} is not valid JSON: ${String(err)}`
672
+ };
673
+ }
674
+ const parsed = manifestSchema.safeParse(json);
675
+ if (!parsed.success) {
676
+ return {
677
+ ok: false,
678
+ error: `space-bus: roster path ${rosterPath} is not a valid spacebus.json — refusing to register: ${parsed.error.message}`
679
+ };
680
+ }
681
+ } finally {
682
+ closeQuietly2(fd);
683
+ }
684
+ return { ok: true };
685
+ }
686
+ function registerRoster(name, rosterPath) {
687
+ const nameCheck = registryEntrySchema.shape.name.safeParse(name);
688
+ if (!nameCheck.success) {
689
+ return {
690
+ ok: false,
691
+ error: `space-bus: invalid roster name "${name}": ${nameCheck.error.issues[0]?.message ?? "must be 1-64 lowercase letters, digits, or hyphens"}`
692
+ };
693
+ }
694
+ const validated = openAndValidateRosterFile(rosterPath);
695
+ if (!validated.ok)
696
+ return validated;
697
+ let canonicalPath;
698
+ try {
699
+ canonicalPath = realpathSync(rosterPath);
700
+ } catch (err) {
701
+ return {
702
+ ok: false,
703
+ error: `space-bus: failed to canonicalize roster path ${rosterPath}: ${String(err)}`
704
+ };
705
+ }
706
+ return withRegistryLock(() => {
707
+ const readResult = readRegistry();
708
+ if (!readResult.ok)
709
+ return readResult;
710
+ const registry = readResult.registry;
711
+ const collision = registry.rosters.find((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
712
+ if (collision) {
713
+ return {
714
+ ok: false,
715
+ error: `space-bus: a roster named "${collision.name}" is already registered`
716
+ };
717
+ }
718
+ const entry = { name, path: canonicalPath };
719
+ const next = {
720
+ ...registry,
721
+ rosters: [...registry.rosters, entry]
722
+ };
723
+ return writeRegistryAtomic(next);
724
+ });
725
+ }
726
+ function unregisterRoster(name) {
727
+ return withRegistryLock(() => {
728
+ const readResult = readRegistry();
729
+ if (!readResult.ok)
730
+ return readResult;
731
+ const registry = readResult.registry;
732
+ const exists = registry.rosters.some((entry) => entry.name.toLowerCase() === name.toLowerCase());
733
+ if (!exists) {
734
+ return {
735
+ ok: false,
736
+ error: `space-bus: no roster named "${name}" is registered`
737
+ };
738
+ }
739
+ const rosters = registry.rosters.filter((entry) => entry.name.toLowerCase() !== name.toLowerCase());
740
+ const next = {
741
+ ...registry,
742
+ rosters,
743
+ default: registry.default !== undefined && registry.default.toLowerCase() === name.toLowerCase() ? undefined : registry.default
744
+ };
745
+ return writeRegistryAtomic(next);
746
+ });
747
+ }
748
+ function setDefaultRoster(name) {
749
+ return withRegistryLock(() => {
750
+ const readResult = readRegistry();
751
+ if (!readResult.ok)
752
+ return readResult;
753
+ const registry = readResult.registry;
754
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
755
+ if (!entry) {
756
+ return {
757
+ ok: false,
758
+ error: `space-bus: no roster named "${name}" is registered`
759
+ };
760
+ }
761
+ const next = { ...registry, default: entry.name };
762
+ return writeRegistryAtomic(next);
763
+ });
764
+ }
765
+ function resolveRosterByName(name) {
766
+ const readResult = readRegistry();
767
+ if (!readResult.ok)
768
+ return readResult;
769
+ const registry = readResult.registry;
770
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
771
+ if (!entry) {
772
+ const known = registry.rosters.map((r) => r.name);
773
+ return {
774
+ ok: false,
775
+ error: known.length > 0 ? `space-bus: no roster named "${name}" is registered (known: ${known.join(", ")})` : `space-bus: no roster named "${name}" is registered (no rosters are registered)`
776
+ };
777
+ }
778
+ let stat;
779
+ try {
780
+ stat = lstatSync(entry.path);
781
+ } catch {
782
+ return {
783
+ ok: false,
784
+ error: `space-bus: registered roster file no longer exists at ${entry.path} (name "${entry.name}") — was it moved or deleted?`
785
+ };
786
+ }
787
+ if (stat.isSymbolicLink()) {
788
+ return {
789
+ ok: false,
790
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is now a symlink — refusing to resolve a symlinked roster file`
791
+ };
792
+ }
793
+ if (!stat.isFile()) {
794
+ return {
795
+ ok: false,
796
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is no longer a regular file`
797
+ };
798
+ }
799
+ let canonicalPath;
800
+ try {
801
+ canonicalPath = realpathSync(entry.path);
802
+ } catch (err) {
803
+ return {
804
+ ok: false,
805
+ error: `space-bus: failed to canonicalize registered roster path ${entry.path} (name "${entry.name}"): ${String(err)}`
806
+ };
807
+ }
808
+ return { ok: true, path: canonicalPath, name: entry.name };
809
+ }
810
+
406
811
  // src/config.ts
407
812
  var managedServerConfigSchema = z3.object({
408
813
  command: z3.array(z3.string()).optional(),
@@ -436,7 +841,7 @@ var manifestSchema = z3.object({
436
841
  }))
437
842
  });
438
843
  function expandHome(path) {
439
- return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
844
+ return path.startsWith("~") ? join3(homedir3(), path.slice(1)) : path;
440
845
  }
441
846
  function resolveRosterPath(directory) {
442
847
  const override = process.env["SPACE_BUS_CONFIG"];
@@ -448,19 +853,18 @@ function resolveRosterPath(directory) {
448
853
  if (!expanded.startsWith("/")) {
449
854
  throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
450
855
  }
451
- return existsSync(expanded) ? realpathSync(expanded) : expanded;
856
+ return existsSync(expanded) ? realpathSync2(expanded) : expanded;
452
857
  }
453
858
  if (directory) {
454
- const candidate = join2(directory, "spacebus.json");
455
- return existsSync(candidate) ? realpathSync(candidate) : candidate;
859
+ const candidate = join3(directory, "spacebus.json");
860
+ return existsSync(candidate) ? realpathSync2(candidate) : candidate;
456
861
  }
457
862
  throw new Error("space-bus: cannot locate spacebus.json — pass a directory containing spacebus.json, or set SPACE_BUS_CONFIG to an absolute path (or ~-prefixed path) to the roster file");
458
863
  }
459
- function getRoster(directory) {
460
- const manifestPath = resolveRosterPath(directory);
864
+ function getRosterAtPath(manifestPath) {
461
865
  let raw;
462
866
  try {
463
- raw = readFileSync2(manifestPath, "utf8");
867
+ raw = readFileSync3(manifestPath, "utf8");
464
868
  } catch (err) {
465
869
  throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
466
870
  }
@@ -483,6 +887,10 @@ function getRoster(directory) {
483
887
  }
484
888
  return parsed.data;
485
889
  }
890
+ function getRoster(directory) {
891
+ const manifestPath = resolveRosterPath(directory);
892
+ return getRosterAtPath(manifestPath);
893
+ }
486
894
  function getProjects(manifest) {
487
895
  return manifest.projects.map((p) => {
488
896
  const expandedPath = expandHome(p.path);
@@ -496,9 +904,8 @@ function getCredentials() {
496
904
  const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
497
905
  return { username, password };
498
906
  }
499
- function loadContext(directory) {
500
- const rosterPath = resolveRosterPath(directory);
501
- const manifest = getRoster(directory);
907
+ function loadContextAtPath(rosterPath) {
908
+ const manifest = getRosterAtPath(rosterPath);
502
909
  const projects = getProjects(manifest);
503
910
  if (manifest.server.baseUrl === undefined) {
504
911
  const live = attachLive(rosterPath);
@@ -515,6 +922,28 @@ function loadContext(directory) {
515
922
  credentials: getCredentials()
516
923
  };
517
924
  }
925
+ function loadContext(directory) {
926
+ const rosterPath = resolveRosterPath(directory);
927
+ return loadContextAtPath(rosterPath);
928
+ }
929
+ function loadContextForRoster(rosterName) {
930
+ const resolved = resolveRosterByName(rosterName);
931
+ if (!resolved.ok) {
932
+ throw new Error(resolved.error);
933
+ }
934
+ return {
935
+ context: loadContextAtPath(resolved.path),
936
+ rosterPath: resolved.path,
937
+ rosterName: resolved.name
938
+ };
939
+ }
940
+ function loadContextForRosterPath(rosterPath) {
941
+ return loadContextAtPath(rosterPath);
942
+ }
943
+ function isManagedRosterAtPath(rosterPath) {
944
+ const manifest = getRosterAtPath(rosterPath);
945
+ return manifest.server.managed !== undefined;
946
+ }
518
947
  function isManagedRoster(directory) {
519
948
  const manifest = getRoster(directory);
520
949
  return manifest.server.managed !== undefined;
@@ -522,8 +951,8 @@ function isManagedRoster(directory) {
522
951
 
523
952
  // src/server.ts
524
953
  import { spawn } from "node:child_process";
525
- import { randomBytes as randomBytes2 } from "node:crypto";
526
- import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
954
+ import { randomBytes as randomBytes3 } from "node:crypto";
955
+ import { existsSync as existsSync2, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
527
956
  import { dirname } from "node:path";
528
957
  var DEFAULT_READINESS_BUDGET_MS = 15000;
529
958
  var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
@@ -538,13 +967,13 @@ function sleep(ms) {
538
967
  return new Promise((resolve) => setTimeout(resolve, ms));
539
968
  }
540
969
  function readManifest(rosterPath) {
541
- const raw = readFileSync3(rosterPath, "utf8");
970
+ const raw = readFileSync4(rosterPath, "utf8");
542
971
  const json = JSON.parse(raw);
543
972
  return manifestSchema.parse(json);
544
973
  }
545
974
  function readLogTail(logPath, maxChars = 4000) {
546
975
  try {
547
- const content = readFileSync3(logPath, "utf8");
976
+ const content = readFileSync4(logPath, "utf8");
548
977
  return content.length > maxChars ? content.slice(-maxChars) : content;
549
978
  } catch {
550
979
  return "";
@@ -717,12 +1146,12 @@ function reapOrphanedProvisional(rosterPath) {
717
1146
  }
718
1147
  async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
719
1148
  reapOrphanedProvisional(rosterPath);
720
- const password = randomBytes2(32).toString("base64url");
1149
+ const password = randomBytes3(32).toString("base64url");
721
1150
  const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
722
1151
  const cwd = managedConfig.cwd ?? dirname(rosterPath);
723
1152
  const requestedPort = managedConfig.port ?? 0;
724
1153
  const logPath = logFilePath(rosterPath);
725
- const logFd = openSync2(logPath, "w", 384);
1154
+ const logFd = openSync3(logPath, "w", 384);
726
1155
  let child;
727
1156
  let pid;
728
1157
  let spawnError;
@@ -777,7 +1206,8 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
777
1206
  identity: finalIdentity,
778
1207
  password,
779
1208
  spawnConfig: { command, cwd, port: requestedPort },
780
- baseUrl
1209
+ baseUrl,
1210
+ rosterPath
781
1211
  });
782
1212
  return {
783
1213
  baseUrl,
@@ -787,6 +1217,9 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
787
1217
  };
788
1218
  }
789
1219
  async function ensureServer(rosterPath, options = {}) {
1220
+ if (existsSync2(rosterPath)) {
1221
+ rosterPath = realpathSync3(rosterPath);
1222
+ }
790
1223
  const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
791
1224
  const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
792
1225
  const fastPath = attachServer(rosterPath);
@@ -1006,7 +1439,7 @@ async function waitForGroupDeath(pid, budgetMs) {
1006
1439
  // src/mcp.ts
1007
1440
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1008
1441
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1009
- import { z as z4 } from "zod";
1442
+ import { z as z5 } from "zod";
1010
1443
 
1011
1444
  // src/core.ts
1012
1445
  function findProject(projects, name) {
@@ -1599,6 +2032,9 @@ function parsePendingQuestions(questionRes) {
1599
2032
  }
1600
2033
 
1601
2034
  // src/format.ts
2035
+ function formatRosterHeader(source) {
2036
+ return `roster: ${source.name ?? source.path}`;
2037
+ }
1602
2038
  function formatRoster(projects) {
1603
2039
  return projects.map((p) => {
1604
2040
  if (!p.pathExists)
@@ -1674,195 +2110,846 @@ function formatResult(r) {
1674
2110
  `);
1675
2111
  }
1676
2112
 
1677
- // src/tools/bus_result.ts
2113
+ // src/tools/bus_registry.ts
2114
+ import { isAbsolute as isAbsolute2 } from "node:path";
1678
2115
  import { tool } from "@opencode-ai/plugin";
2116
+ import { z as z4 } from "zod";
2117
+
2118
+ // src/roster-edit.ts
2119
+ import { randomBytes as randomBytes4 } from "node:crypto";
2120
+ import {
2121
+ chmodSync as chmodSync2,
2122
+ closeSync as closeSync3,
2123
+ constants as fsConstants3,
2124
+ lstatSync as lstatSync2,
2125
+ mkdirSync as mkdirSync3,
2126
+ openSync as openSync4,
2127
+ readFileSync as readFileSync5,
2128
+ renameSync as renameSync3,
2129
+ statSync as statSync3,
2130
+ unlinkSync as unlinkSync3,
2131
+ writeSync as writeSync2
2132
+ } from "node:fs";
2133
+ import { join as join4 } from "node:path";
2134
+ function closeQuietly3(fd) {
2135
+ try {
2136
+ closeSync3(fd);
2137
+ } catch {}
2138
+ }
2139
+ function isErrnoCode3(err2, code) {
2140
+ return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === code;
2141
+ }
2142
+ function duplicateProjectName(projects) {
2143
+ const seen = new Set;
2144
+ for (const p of projects) {
2145
+ if (seen.has(p.name))
2146
+ return p.name;
2147
+ seen.add(p.name);
2148
+ }
2149
+ return null;
2150
+ }
2151
+ function validateManifest(data) {
2152
+ const parsed = manifestSchema.safeParse(data);
2153
+ if (!parsed.success) {
2154
+ return {
2155
+ ok: false,
2156
+ error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
2157
+ };
2158
+ }
2159
+ const baseUrl = parsed.data.server.baseUrl;
2160
+ if (baseUrl !== undefined && !loopbackOk(baseUrl)) {
2161
+ return {
2162
+ ok: false,
2163
+ error: `space-bus: roster's server.baseUrl must point to localhost (got ${baseUrl}) — refusing to send credentials off-machine`
2164
+ };
2165
+ }
2166
+ const dup = duplicateProjectName(parsed.data.projects);
2167
+ if (dup !== null) {
2168
+ return {
2169
+ ok: false,
2170
+ error: `space-bus: roster document has duplicate project name "${dup}"`
2171
+ };
2172
+ }
2173
+ return { ok: true, manifest: parsed.data };
2174
+ }
2175
+ function readManifest2(rosterPath) {
2176
+ let raw;
2177
+ try {
2178
+ raw = readFileSync5(rosterPath, "utf8");
2179
+ } catch (err2) {
2180
+ return {
2181
+ ok: false,
2182
+ error: `space-bus: cannot read roster at ${rosterPath}: ${String(err2)}`
2183
+ };
2184
+ }
2185
+ let json;
2186
+ try {
2187
+ json = JSON.parse(raw);
2188
+ } catch (err2) {
2189
+ return {
2190
+ ok: false,
2191
+ error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err2)}`
2192
+ };
2193
+ }
2194
+ return validateManifest(json);
2195
+ }
2196
+ function writeManifestAtomic(rosterPath, data) {
2197
+ const dir = join4(rosterPath, "..");
2198
+ try {
2199
+ mkdirSync3(dir, { recursive: true });
2200
+ } catch (err2) {
2201
+ return {
2202
+ ok: false,
2203
+ error: `space-bus: failed to create directory ${dir}: ${String(err2)}`
2204
+ };
2205
+ }
2206
+ let existingMode;
2207
+ try {
2208
+ existingMode = statSync3(rosterPath).mode & 511;
2209
+ } catch {
2210
+ existingMode = undefined;
2211
+ }
2212
+ const tempPath = join4(dir, `.spacebus.${randomBytes4(8).toString("hex")}.tmp`);
2213
+ let fd;
2214
+ try {
2215
+ fd = openSync4(tempPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY, 420);
2216
+ writeSync2(fd, JSON.stringify(data, null, 2));
2217
+ if (existingMode !== undefined) {
2218
+ chmodSync2(tempPath, existingMode);
2219
+ }
2220
+ closeSync3(fd);
2221
+ fd = undefined;
2222
+ renameSync3(tempPath, rosterPath);
2223
+ } catch (err2) {
2224
+ if (fd !== undefined)
2225
+ closeQuietly3(fd);
2226
+ try {
2227
+ unlinkSync3(tempPath);
2228
+ } catch {}
2229
+ return {
2230
+ ok: false,
2231
+ error: `space-bus: failed to write roster at ${rosterPath}: ${String(err2)}`
2232
+ };
2233
+ }
2234
+ return { ok: true };
2235
+ }
2236
+ function writeRosterExclusive(rosterPath, data) {
2237
+ const dir = join4(rosterPath, "..");
2238
+ try {
2239
+ mkdirSync3(dir, { recursive: true });
2240
+ } catch (err2) {
2241
+ return {
2242
+ ok: false,
2243
+ error: `space-bus: failed to create directory ${dir}: ${String(err2)}`
2244
+ };
2245
+ }
2246
+ let fd;
2247
+ try {
2248
+ fd = openSync4(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
2249
+ } catch (err2) {
2250
+ if (isErrnoCode3(err2, "EEXIST")) {
2251
+ return {
2252
+ ok: false,
2253
+ error: `space-bus: refusing to overwrite existing roster file at ${rosterPath}`
2254
+ };
2255
+ }
2256
+ return {
2257
+ ok: false,
2258
+ error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err2)}`
2259
+ };
2260
+ }
2261
+ try {
2262
+ writeSync2(fd, JSON.stringify(data, null, 2));
2263
+ } catch (err2) {
2264
+ closeQuietly3(fd);
2265
+ try {
2266
+ unlinkSync3(rosterPath);
2267
+ } catch {}
2268
+ return {
2269
+ ok: false,
2270
+ error: `space-bus: failed to write roster file at ${rosterPath}: ${String(err2)}`
2271
+ };
2272
+ }
2273
+ closeQuietly3(fd);
2274
+ return { ok: true };
2275
+ }
2276
+ function editManifest(rosterPath, mutate) {
2277
+ try {
2278
+ if (lstatSync2(rosterPath).isSymbolicLink()) {
2279
+ return {
2280
+ ok: false,
2281
+ error: `space-bus: refusing to edit a symlinked roster file at ${rosterPath}`
2282
+ };
2283
+ }
2284
+ } catch {}
2285
+ const current = readManifest2(rosterPath);
2286
+ if (!current.ok)
2287
+ return current;
2288
+ const mutated = mutate(current.manifest);
2289
+ if ("ok" in mutated)
2290
+ return mutated;
2291
+ const revalidated = validateManifest(mutated);
2292
+ if (!revalidated.ok)
2293
+ return revalidated;
2294
+ return writeManifestAtomic(rosterPath, revalidated.manifest);
2295
+ }
2296
+ function createRoster(opts) {
2297
+ const nameCheck = /^[a-z0-9-]{1,64}$/.test(opts.name);
2298
+ if (!nameCheck) {
2299
+ return {
2300
+ ok: false,
2301
+ error: `space-bus: invalid roster name "${opts.name}": must be 1-64 lowercase letters, digits, or hyphens`
2302
+ };
2303
+ }
2304
+ const readResult = readRegistry();
2305
+ if (!readResult.ok)
2306
+ return readResult;
2307
+ const collision = readResult.registry.rosters.find((entry) => entry.name.toLowerCase() === opts.name.toLowerCase());
2308
+ if (collision) {
2309
+ return {
2310
+ ok: false,
2311
+ error: `space-bus: a roster named "${collision.name}" is already registered — refusing to create "${opts.name}"`
2312
+ };
2313
+ }
2314
+ const candidate = {
2315
+ server: opts.server ?? { managed: {} },
2316
+ projects: []
2317
+ };
2318
+ const validated = validateManifest(candidate);
2319
+ if (!validated.ok)
2320
+ return validated;
2321
+ const written = writeRosterExclusive(opts.rosterPath, validated.manifest);
2322
+ if (!written.ok)
2323
+ return written;
2324
+ const registered = registerRoster(opts.name, opts.rosterPath);
2325
+ if (!registered.ok) {
2326
+ return {
2327
+ ok: false,
2328
+ fileCreated: true,
2329
+ error: `space-bus: roster file was created at ${opts.rosterPath}, but registering it as "${opts.name}" failed: ${registered.error} — retry registerRoster("${opts.name}", "${opts.rosterPath}") to recover`
2330
+ };
2331
+ }
2332
+ return { ok: true };
2333
+ }
2334
+ function addProject(rosterPath, project) {
2335
+ return editManifest(rosterPath, (current) => {
2336
+ if (current.projects.some((p) => p.name === project.name)) {
2337
+ return {
2338
+ ok: false,
2339
+ error: `space-bus: a project named "${project.name}" already exists in ${rosterPath}`
2340
+ };
2341
+ }
2342
+ return { ...current, projects: [...current.projects, project] };
2343
+ });
2344
+ }
2345
+ function removeProject(rosterPath, projectName) {
2346
+ return editManifest(rosterPath, (current) => {
2347
+ const exists = current.projects.some((p) => p.name === projectName);
2348
+ if (!exists) {
2349
+ const known = current.projects.map((p) => p.name);
2350
+ return {
2351
+ ok: false,
2352
+ error: known.length > 0 ? `space-bus: no project named "${projectName}" in ${rosterPath} (known: ${known.join(", ")})` : `space-bus: no project named "${projectName}" in ${rosterPath} (no projects defined)`
2353
+ };
2354
+ }
2355
+ return {
2356
+ ...current,
2357
+ projects: current.projects.filter((p) => p.name !== projectName)
2358
+ };
2359
+ });
2360
+ }
2361
+ function updateProject(rosterPath, projectName, patch) {
2362
+ return editManifest(rosterPath, (current) => {
2363
+ const index = current.projects.findIndex((p) => p.name === projectName);
2364
+ if (index === -1) {
2365
+ const known = current.projects.map((p) => p.name);
2366
+ return {
2367
+ ok: false,
2368
+ error: known.length > 0 ? `space-bus: no project named "${projectName}" in ${rosterPath} (known: ${known.join(", ")})` : `space-bus: no project named "${projectName}" in ${rosterPath} (no projects defined)`
2369
+ };
2370
+ }
2371
+ if (patch.name !== undefined && patch.name !== projectName && current.projects.some((p) => p.name === patch.name)) {
2372
+ return {
2373
+ ok: false,
2374
+ error: `space-bus: cannot rename project "${projectName}" to "${patch.name}" in ${rosterPath} — a project with that name already exists`
2375
+ };
2376
+ }
2377
+ const projects = [...current.projects];
2378
+ const existing = projects[index];
2379
+ if (!existing) {
2380
+ return {
2381
+ ok: false,
2382
+ error: `space-bus: internal error locating project "${projectName}"`
2383
+ };
2384
+ }
2385
+ projects[index] = { ...existing, ...patch };
2386
+ return { ...current, projects };
2387
+ });
2388
+ }
2389
+ function editServer(rosterPath, server) {
2390
+ if (attachLive(rosterPath) !== null) {
2391
+ return {
2392
+ ok: false,
2393
+ error: `space-bus: a managed daemon is running for roster ${rosterPath} — run \`space-bus stop\` first before editing its server block`
2394
+ };
2395
+ }
2396
+ return editManifest(rosterPath, (current) => ({ ...current, server }));
2397
+ }
2398
+
2399
+ // src/tools/bus_registry.ts
2400
+ var BUS_REGISTRY_DESCRIPTION = "Manage the roster registry: list registered rosters, create/register/unregister rosters, set the default, select an active roster for this connector session (MCP only), and add/remove/update projects on a registered roster.";
2401
+ var projectInputSchema = z4.object({
2402
+ name: z4.string().min(1),
2403
+ path: z4.string().min(1),
2404
+ description: z4.string()
2405
+ });
2406
+ var PATCH_NONEMPTY_MESSAGE = "patch must include at least one field (name, path, or description)";
2407
+ var projectPatchSchema = z4.object({
2408
+ name: z4.string().min(1).optional(),
2409
+ path: z4.string().min(1).optional(),
2410
+ description: z4.string().optional()
2411
+ }).refine((patch) => Object.keys(patch).length > 0, {
2412
+ message: PATCH_NONEMPTY_MESSAGE
2413
+ });
2414
+ var ROSTER_FIELD_DESCRIPTION = "Registry roster name — required by use/add-project/remove-project/update-project";
2415
+ var NAME_FIELD_DESCRIPTION = "Roster name to create/register/unregister/set-default — required by those actions";
2416
+ var PATH_FIELD_DESCRIPTION = "Absolute path to a spacebus.json — required by create/register";
2417
+ var SERVER_FIELD_DESCRIPTION = "Server block for create (baseUrl XOR managed; defaults to managed {})";
2418
+ var PROJECT_FIELD_DESCRIPTION = "{name, path, description} — required by add-project";
2419
+ var PROJECT_NAME_FIELD_DESCRIPTION = "Existing project name — required by remove-project/update-project";
2420
+ var PATCH_FIELD_DESCRIPTION = "Partial project fields to apply — required by update-project";
2421
+ var pluginManagedServerConfigSchema = tool.schema.object({
2422
+ command: tool.schema.array(tool.schema.string()).optional(),
2423
+ cwd: tool.schema.string().optional(),
2424
+ port: tool.schema.number().int().nonnegative().optional()
2425
+ });
2426
+ var pluginServerConfigSchema = tool.schema.object({
2427
+ baseUrl: tool.schema.url().optional(),
2428
+ managed: pluginManagedServerConfigSchema.optional()
2429
+ }).superRefine((val, ctx) => {
2430
+ const hasBaseUrl = val.baseUrl !== undefined;
2431
+ const hasManaged = val.managed !== undefined;
2432
+ if (hasBaseUrl && hasManaged) {
2433
+ ctx.addIssue({
2434
+ code: "custom",
2435
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
2436
+ });
2437
+ } else if (!hasBaseUrl && !hasManaged) {
2438
+ ctx.addIssue({
2439
+ code: "custom",
2440
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
2441
+ });
2442
+ }
2443
+ });
2444
+ var pluginProjectInputSchema = tool.schema.object({
2445
+ name: tool.schema.string().min(1),
2446
+ path: tool.schema.string().min(1),
2447
+ description: tool.schema.string()
2448
+ });
2449
+ var pluginProjectPatchSchema = tool.schema.object({
2450
+ name: tool.schema.string().min(1).optional(),
2451
+ path: tool.schema.string().min(1).optional(),
2452
+ description: tool.schema.string().optional()
2453
+ }).refine((patch) => Object.keys(patch).length > 0, {
2454
+ message: PATCH_NONEMPTY_MESSAGE
2455
+ });
2456
+ var BUS_REGISTRY_ARGS = {
2457
+ action: tool.schema.enum([
2458
+ "list",
2459
+ "use",
2460
+ "create",
2461
+ "register",
2462
+ "unregister",
2463
+ "set-default",
2464
+ "add-project",
2465
+ "remove-project",
2466
+ "update-project"
2467
+ ]),
2468
+ roster: tool.schema.string().optional().describe(ROSTER_FIELD_DESCRIPTION),
2469
+ name: tool.schema.string().optional().describe(NAME_FIELD_DESCRIPTION),
2470
+ path: tool.schema.string().optional().describe(PATH_FIELD_DESCRIPTION),
2471
+ server: pluginServerConfigSchema.optional().describe(SERVER_FIELD_DESCRIPTION),
2472
+ project: pluginProjectInputSchema.optional().describe(PROJECT_FIELD_DESCRIPTION),
2473
+ projectName: tool.schema.string().optional().describe(PROJECT_NAME_FIELD_DESCRIPTION),
2474
+ patch: pluginProjectPatchSchema.optional().describe(PATCH_FIELD_DESCRIPTION)
2475
+ };
2476
+ var ACTION_SCHEMA = z4.discriminatedUnion("action", [
2477
+ z4.strictObject({ action: z4.literal("list") }),
2478
+ z4.strictObject({ action: z4.literal("use"), roster: z4.string().min(1) }),
2479
+ z4.strictObject({
2480
+ action: z4.literal("create"),
2481
+ name: z4.string().min(1),
2482
+ path: z4.string().min(1).refine(isAbsolute2, {
2483
+ message: "path must be an absolute filesystem path"
2484
+ }),
2485
+ server: serverConfigSchema.optional()
2486
+ }),
2487
+ z4.strictObject({
2488
+ action: z4.literal("register"),
2489
+ name: z4.string().min(1),
2490
+ path: z4.string().min(1).refine(isAbsolute2, {
2491
+ message: "path must be an absolute filesystem path"
2492
+ })
2493
+ }),
2494
+ z4.strictObject({ action: z4.literal("unregister"), name: z4.string().min(1) }),
2495
+ z4.strictObject({ action: z4.literal("set-default"), name: z4.string().min(1) }),
2496
+ z4.strictObject({
2497
+ action: z4.literal("add-project"),
2498
+ roster: z4.string().min(1),
2499
+ project: projectInputSchema
2500
+ }),
2501
+ z4.strictObject({
2502
+ action: z4.literal("remove-project"),
2503
+ roster: z4.string().min(1),
2504
+ projectName: z4.string().min(1)
2505
+ }),
2506
+ z4.strictObject({
2507
+ action: z4.literal("update-project"),
2508
+ roster: z4.string().min(1),
2509
+ projectName: z4.string().min(1),
2510
+ patch: projectPatchSchema
2511
+ })
2512
+ ]);
2513
+ function registryListMetadata(session) {
2514
+ const read = readRegistry();
2515
+ if (!read.ok)
2516
+ return { ok: false, error: read.error };
2517
+ const active = session?.getActive();
2518
+ return {
2519
+ ok: true,
2520
+ rosters: read.registry.rosters.map((r) => ({
2521
+ name: r.name,
2522
+ path: r.path,
2523
+ default: read.registry.default === r.name,
2524
+ active: active === r.name
2525
+ }))
2526
+ };
2527
+ }
2528
+ function formatList(rosters) {
2529
+ if (rosters.length === 0)
2530
+ return "no rosters registered";
2531
+ return rosters.map((r) => {
2532
+ const flags = [
2533
+ r.default ? "default" : null,
2534
+ r.active ? "active" : null
2535
+ ].filter((f) => f !== null);
2536
+ const suffix = flags.length > 0 ? ` (${flags.join(", ")})` : "";
2537
+ return `${r.name}: ${r.path}${suffix}`;
2538
+ }).join(`
2539
+ `);
2540
+ }
2541
+ function runList(session) {
2542
+ const listed = registryListMetadata(session);
2543
+ if (!listed.ok)
2544
+ throw new Error(`bus_registry list: ${listed.error}`);
2545
+ return { text: formatList(listed.rosters), listMetadata: listed.rosters };
2546
+ }
2547
+ function runUse(args, session) {
2548
+ if (!session) {
2549
+ throw new Error("bus_registry use: roster selection is a connector-session concept — plugin calls resolve by workspace directory; pass roster per call instead");
2550
+ }
2551
+ const resolved = resolveRosterByName(args.roster);
2552
+ if (!resolved.ok)
2553
+ throw new Error(`bus_registry use: ${resolved.error}`);
2554
+ session.setActive(resolved.name);
2555
+ return {
2556
+ text: `bus_registry use: active roster set to "${resolved.name}" (${resolved.path})`
2557
+ };
2558
+ }
2559
+ function runCreate(args) {
2560
+ const result2 = createRoster({
2561
+ name: args.name,
2562
+ rosterPath: args.path,
2563
+ server: args.server
2564
+ });
2565
+ if (!result2.ok)
2566
+ throw new Error(`bus_registry create: ${result2.error}`);
2567
+ return {
2568
+ text: `bus_registry create: ${formatRosterHeader({ name: args.name, path: args.path })} created and registered`
2569
+ };
2570
+ }
2571
+ function runRegister(args) {
2572
+ const result2 = registerRoster(args.name, args.path);
2573
+ if (!result2.ok)
2574
+ throw new Error(`bus_registry register: ${result2.error}`);
2575
+ return {
2576
+ text: `bus_registry register: ${formatRosterHeader({ name: args.name, path: args.path })} registered`
2577
+ };
2578
+ }
2579
+ function runUnregister(args, session) {
2580
+ const result2 = unregisterRoster(args.name);
2581
+ if (!result2.ok)
2582
+ throw new Error(`bus_registry unregister: ${result2.error}`);
2583
+ const active = session?.getActive();
2584
+ if (active !== undefined && active.toLowerCase() === args.name.toLowerCase()) {
2585
+ session?.clearActive();
2586
+ return {
2587
+ text: `bus_registry unregister: "${args.name}" unregistered — session-active roster cleared — omitted-roster calls fall back to ambient`
2588
+ };
2589
+ }
2590
+ return { text: `bus_registry unregister: "${args.name}" unregistered` };
2591
+ }
2592
+ function runSetDefault(args) {
2593
+ const result2 = setDefaultRoster(args.name);
2594
+ if (!result2.ok)
2595
+ throw new Error(`bus_registry set-default: ${result2.error}`);
2596
+ return {
2597
+ text: `bus_registry set-default: "${args.name}" is now the default roster`
2598
+ };
2599
+ }
2600
+ function runAddProject(args) {
2601
+ const resolved = resolveRosterByName(args.roster);
2602
+ if (!resolved.ok)
2603
+ throw new Error(`bus_registry add-project: ${resolved.error}`);
2604
+ const result2 = addProject(resolved.path, args.project);
2605
+ if (!result2.ok)
2606
+ throw new Error(`bus_registry add-project: ${result2.error}`);
2607
+ return {
2608
+ text: `bus_registry add-project: added "${args.project.name}" to ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2609
+ };
2610
+ }
2611
+ function runRemoveProject(args) {
2612
+ const resolved = resolveRosterByName(args.roster);
2613
+ if (!resolved.ok)
2614
+ throw new Error(`bus_registry remove-project: ${resolved.error}`);
2615
+ const result2 = removeProject(resolved.path, args.projectName);
2616
+ if (!result2.ok)
2617
+ throw new Error(`bus_registry remove-project: ${result2.error}`);
2618
+ return {
2619
+ text: `bus_registry remove-project: removed "${args.projectName}" from ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2620
+ };
2621
+ }
2622
+ function runUpdateProject(args) {
2623
+ const resolved = resolveRosterByName(args.roster);
2624
+ if (!resolved.ok)
2625
+ throw new Error(`bus_registry update-project: ${resolved.error}`);
2626
+ const result2 = updateProject(resolved.path, args.projectName, args.patch);
2627
+ if (!result2.ok)
2628
+ throw new Error(`bus_registry update-project: ${result2.error}`);
2629
+ return {
2630
+ text: `bus_registry update-project: updated "${args.projectName}" on ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2631
+ };
2632
+ }
2633
+ async function runBusRegistryAction(rawArgs, session) {
2634
+ const parsed = ACTION_SCHEMA.safeParse(rawArgs);
2635
+ if (!parsed.success) {
2636
+ const issue = parsed.error.issues[0];
2637
+ const detail = issue ? `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}` : parsed.error.message;
2638
+ throw new Error(`bus_registry ${rawArgs.action}: invalid input — ${detail}`);
2639
+ }
2640
+ const args = parsed.data;
2641
+ switch (args.action) {
2642
+ case "list":
2643
+ return runList(session);
2644
+ case "use":
2645
+ return runUse(args, session);
2646
+ case "create":
2647
+ return runCreate(args);
2648
+ case "register":
2649
+ return runRegister(args);
2650
+ case "unregister":
2651
+ return runUnregister(args, session);
2652
+ case "set-default":
2653
+ return runSetDefault(args);
2654
+ case "add-project":
2655
+ return runAddProject(args);
2656
+ case "remove-project":
2657
+ return runRemoveProject(args);
2658
+ case "update-project":
2659
+ return runUpdateProject(args);
2660
+ }
2661
+ }
2662
+ function makeBusRegistry(session) {
2663
+ return tool({
2664
+ description: BUS_REGISTRY_DESCRIPTION,
2665
+ args: BUS_REGISTRY_ARGS,
2666
+ async execute(args) {
2667
+ const { text, listMetadata } = await runBusRegistryAction(args, session);
2668
+ if (listMetadata)
2669
+ return { output: text, metadata: { rosters: listMetadata } };
2670
+ return text;
2671
+ }
2672
+ });
2673
+ }
2674
+
2675
+ // src/tools/bus_result.ts
2676
+ import { tool as tool2 } from "@opencode-ai/plugin";
1679
2677
 
1680
2678
  // src/tools/shared.ts
1681
- async function ensureAndLoadContext(directory) {
2679
+ async function ensureAndLoadContext(directory, rosterName, ensure = ensureServer) {
2680
+ if (rosterName !== undefined) {
2681
+ const resolved = resolveRosterByName(rosterName);
2682
+ if (!resolved.ok)
2683
+ throw new Error(resolved.error);
2684
+ const rosterPath2 = resolved.path;
2685
+ if (isManagedRosterAtPath(rosterPath2)) {
2686
+ await ensure(rosterPath2);
2687
+ }
2688
+ const context = loadContextForRosterPath(rosterPath2);
2689
+ return { context, rosterName: resolved.name, rosterPath: rosterPath2 };
2690
+ }
2691
+ const rosterPath = resolveRosterPath(directory);
1682
2692
  if (isManagedRoster(directory)) {
1683
- const rosterPath = resolveRosterPath(directory);
1684
- await ensureServer(rosterPath);
2693
+ await ensure(rosterPath);
1685
2694
  }
1686
- return loadContext(directory);
2695
+ return { context: loadContext(directory), rosterPath };
2696
+ }
2697
+ function withRosterHeader(source, text) {
2698
+ return `${formatRosterHeader(source)}
2699
+ ${text}`;
1687
2700
  }
1688
2701
 
1689
2702
  // src/tools/bus_result.ts
1690
2703
  var BUS_RESULT_DESCRIPTION = "Return a completed space-bus session's final assistant message and diff. Errors if the session is still running — use bus_status to check first.";
1691
2704
  function makeBusResult(defaultDirectory) {
1692
- return tool({
2705
+ return tool2({
1693
2706
  description: BUS_RESULT_DESCRIPTION,
1694
2707
  args: {
1695
- sessionId: tool.schema.string().describe("Session ID returned by bus_task")
2708
+ sessionId: tool2.schema.string().describe("Session ID returned by bus_task"),
2709
+ roster: tool2.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1696
2710
  },
1697
2711
  async execute(args, ctx) {
1698
2712
  const directory = ctx.directory ?? defaultDirectory;
1699
- let context;
2713
+ let resolved;
1700
2714
  try {
1701
- context = await ensureAndLoadContext(directory);
2715
+ resolved = await ensureAndLoadContext(directory, args.roster);
1702
2716
  } catch (e) {
1703
2717
  throw new Error(e.message);
1704
2718
  }
1705
- const r = await result(args.sessionId, { context });
2719
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2720
+ const r = await result(args.sessionId, { context: resolved.context });
1706
2721
  if (!r.ok)
1707
- throw new Error(r.error);
1708
- return formatResult(r);
2722
+ throw new Error(withRosterHeader(source, r.error));
2723
+ const header = formatRosterHeader(source);
2724
+ return `${header}
2725
+ ${formatResult(r)}`;
1709
2726
  }
1710
2727
  });
1711
2728
  }
1712
2729
 
1713
2730
  // src/tools/bus_roster.ts
1714
- import { tool as tool2 } from "@opencode-ai/plugin";
2731
+ import { tool as tool3 } from "@opencode-ai/plugin";
1715
2732
  var BUS_ROSTER_DESCRIPTION = "List the space-bus manifest projects with live session status per project.";
1716
2733
  function makeBusRoster(defaultDirectory) {
1717
- return tool2({
2734
+ return tool3({
1718
2735
  description: BUS_ROSTER_DESCRIPTION,
1719
- args: {},
1720
- async execute(_args, ctx) {
2736
+ args: {
2737
+ roster: tool3.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
2738
+ },
2739
+ async execute(args, ctx) {
1721
2740
  const directory = ctx.directory ?? defaultDirectory;
1722
- let context;
2741
+ let resolved;
1723
2742
  try {
1724
- context = await ensureAndLoadContext(directory);
2743
+ resolved = await ensureAndLoadContext(directory, args.roster);
1725
2744
  } catch (e) {
1726
2745
  throw new Error(e.message);
1727
2746
  }
1728
- const r = await roster({ context });
2747
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2748
+ const r = await roster({ context: resolved.context });
1729
2749
  if (!r.ok)
1730
- throw new Error(r.error);
1731
- return formatRoster(r.projects);
2750
+ throw new Error(withRosterHeader(source, r.error));
2751
+ const header = formatRosterHeader(source);
2752
+ return `${header}
2753
+ ${formatRoster(r.projects)}`;
1732
2754
  }
1733
2755
  });
1734
2756
  }
1735
2757
 
1736
2758
  // src/tools/bus_status.ts
1737
- import { tool as tool3 } from "@opencode-ai/plugin";
2759
+ import { tool as tool4 } from "@opencode-ai/plugin";
1738
2760
  var BUS_STATUS_DESCRIPTION = "Report a space-bus session's status plus a summary of its latest todo and diff. Also reports when the session is blocked on an interactive question awaiting a reply.";
1739
2761
  function makeBusStatus(defaultDirectory) {
1740
- return tool3({
2762
+ return tool4({
1741
2763
  description: BUS_STATUS_DESCRIPTION,
1742
2764
  args: {
1743
- sessionId: tool3.schema.string().describe("Session ID returned by bus_task")
2765
+ sessionId: tool4.schema.string().describe("Session ID returned by bus_task"),
2766
+ roster: tool4.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1744
2767
  },
1745
2768
  async execute(args, ctx) {
1746
2769
  const directory = ctx.directory ?? defaultDirectory;
1747
- let context;
2770
+ let resolved;
1748
2771
  try {
1749
- context = await ensureAndLoadContext(directory);
2772
+ resolved = await ensureAndLoadContext(directory, args.roster);
1750
2773
  } catch (e) {
1751
2774
  throw new Error(e.message);
1752
2775
  }
1753
- const r = await status(args.sessionId, { context });
2776
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2777
+ const r = await status(args.sessionId, { context: resolved.context });
1754
2778
  if (!r.ok)
1755
- throw new Error(r.error);
1756
- return formatStatus(r);
2779
+ throw new Error(withRosterHeader(source, r.error));
2780
+ const header = formatRosterHeader(source);
2781
+ return `${header}
2782
+ ${formatStatus(r)}`;
1757
2783
  }
1758
2784
  });
1759
2785
  }
1760
2786
 
1761
2787
  // src/tools/bus_task.ts
1762
- import { tool as tool4 } from "@opencode-ai/plugin";
2788
+ import { tool as tool5 } from "@opencode-ai/plugin";
1763
2789
  var BUS_TASK_DESCRIPTION = "Dispatch a prompt to an agent in the given space-bus manifest project, or steer an existing session by passing sessionId (answers its pending question, else sends a follow-up prompt). Returns immediately; does not wait for completion.";
1764
2790
  function makeBusTask(defaultDirectory) {
1765
- return tool4({
2791
+ return tool5({
1766
2792
  description: BUS_TASK_DESCRIPTION,
1767
2793
  args: {
1768
- project: tool4.schema.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
1769
- prompt: tool4.schema.string().describe("The prompt to send to the delegated agent"),
1770
- title: tool4.schema.string().optional().describe("Optional session title (only used when starting a new session)"),
1771
- sessionId: tool4.schema.string().optional().describe("Existing session ID to steer instead of starting a new session")
2794
+ project: tool5.schema.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
2795
+ prompt: tool5.schema.string().describe("The prompt to send to the delegated agent"),
2796
+ title: tool5.schema.string().optional().describe("Optional session title (only used when starting a new session)"),
2797
+ sessionId: tool5.schema.string().optional().describe("Existing session ID to steer instead of starting a new session"),
2798
+ roster: tool5.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1772
2799
  },
1773
2800
  async execute(args, ctx) {
1774
2801
  const dispatchArgs = toDispatchArgs(args);
1775
2802
  if (!dispatchArgs.ok)
1776
2803
  throw new Error(dispatchArgs.error);
1777
2804
  const directory = ctx.directory ?? defaultDirectory;
1778
- let context;
2805
+ let resolved;
1779
2806
  try {
1780
- context = await ensureAndLoadContext(directory);
2807
+ resolved = await ensureAndLoadContext(directory, args.roster);
1781
2808
  } catch (e) {
1782
2809
  throw new Error(e.message);
1783
2810
  }
1784
- const r = await dispatch(dispatchArgs, { context });
2811
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2812
+ const r = await dispatch(dispatchArgs, { context: resolved.context });
1785
2813
  if (!r.ok)
1786
- throw new Error(r.error);
1787
- return { output: formatDispatch(r), metadata: dispatchMetadata(r) };
2814
+ throw new Error(withRosterHeader(source, r.error));
2815
+ const header = formatRosterHeader(source);
2816
+ return {
2817
+ output: `${header}
2818
+ ${formatDispatch(r)}`,
2819
+ metadata: dispatchMetadata(r)
2820
+ };
1788
2821
  }
1789
2822
  });
1790
2823
  }
1791
2824
 
1792
2825
  // src/tools/bus_wait.ts
1793
- import { tool as tool5 } from "@opencode-ai/plugin";
2826
+ import { tool as tool6 } from "@opencode-ai/plugin";
1794
2827
  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.";
1795
2828
  var MAX_WAIT_TIMEOUT_MS = 5 * 60000;
1796
2829
  function makeBusWait(defaultDirectory) {
1797
- return tool5({
2830
+ return tool6({
1798
2831
  description: BUS_WAIT_DESCRIPTION,
1799
2832
  args: {
1800
- 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)"),
1801
- 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)`)
2833
+ sessionIds: tool6.schema.array(tool6.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)"),
2834
+ timeoutMs: tool6.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)`),
2835
+ roster: tool6.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1802
2836
  },
1803
2837
  async execute(args, ctx) {
1804
2838
  if (!args.sessionIds || args.sessionIds.length === 0) {
1805
2839
  throw new Error("bus_wait requires at least one sessionId");
1806
2840
  }
1807
2841
  const directory = ctx.directory ?? defaultDirectory;
1808
- let context;
2842
+ let resolved;
1809
2843
  try {
1810
- context = await ensureAndLoadContext(directory);
2844
+ resolved = await ensureAndLoadContext(directory, args.roster);
1811
2845
  } catch (e) {
1812
2846
  throw new Error(e.message);
1813
2847
  }
1814
2848
  const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
1815
- const r = await wait(args.sessionIds, { context, timeoutMs });
2849
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2850
+ const r = await wait(args.sessionIds, {
2851
+ context: resolved.context,
2852
+ timeoutMs
2853
+ });
1816
2854
  if (!r.ok)
1817
- throw new Error(r.error);
1818
- return formatWait(r);
2855
+ throw new Error(withRosterHeader(source, r.error));
2856
+ const header = formatRosterHeader(source);
2857
+ return `${header}
2858
+ ${formatWait(r)}`;
1819
2859
  }
1820
2860
  });
1821
2861
  }
1822
2862
 
1823
2863
  // src/mcp.ts
1824
- async function mcpLoadContext() {
1825
- if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRoster()) {
2864
+ var activeRoster;
2865
+ var registrySession = {
2866
+ getActive: () => activeRoster,
2867
+ setActive: (name) => {
2868
+ activeRoster = name;
2869
+ },
2870
+ clearActive: () => {
2871
+ activeRoster = undefined;
2872
+ }
2873
+ };
2874
+ var ROSTER_PARAM_SCHEMA = z5.string().optional().describe("Registry roster name to target. Resolution precedence: this param > " + "connector-session active roster (bus_registry use) > " + "SPACE_BUS_CONFIG > registry default (bus_registry set-default) " + "(see bus_registry to list)");
2875
+ async function resolveByName(name, ensure) {
2876
+ const resolved = resolveRosterByName(name);
2877
+ if (!resolved.ok)
2878
+ throw new Error(resolved.error);
2879
+ const rosterPath = resolved.path;
2880
+ if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRosterAtPath(rosterPath)) {
2881
+ await ensure(rosterPath);
2882
+ }
2883
+ const context = loadContextForRosterPath(rosterPath);
2884
+ return { context, rosterName: resolved.name, rosterPath };
2885
+ }
2886
+ async function mcpLoadContext(rosterName, ensure = ensureServer) {
2887
+ const effectiveRosterName = rosterName ?? activeRoster;
2888
+ if (effectiveRosterName !== undefined) {
2889
+ return resolveByName(effectiveRosterName, ensure);
2890
+ }
2891
+ let ambientError;
2892
+ try {
1826
2893
  const rosterPath = resolveRosterPath();
1827
- await ensureServer(rosterPath);
2894
+ if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRoster()) {
2895
+ await ensure(rosterPath);
2896
+ }
2897
+ return { context: loadContext(), rosterPath };
2898
+ } catch (e) {
2899
+ ambientError = e;
2900
+ }
2901
+ const read = readRegistry();
2902
+ if (read.ok && read.registry.default !== undefined) {
2903
+ return resolveByName(read.registry.default, ensure);
1828
2904
  }
1829
- return loadContext();
2905
+ throw ambientError;
1830
2906
  }
1831
- var version = "0.11.0";
2907
+ var version = "0.13.0";
1832
2908
  var server = new McpServer({
1833
2909
  name: "space-bus",
1834
2910
  version
1835
2911
  });
1836
2912
  server.registerTool("bus_roster", {
1837
2913
  description: BUS_ROSTER_DESCRIPTION,
1838
- inputSchema: {}
1839
- }, async () => {
1840
- let context;
2914
+ inputSchema: { roster: ROSTER_PARAM_SCHEMA }
2915
+ }, async (args) => {
2916
+ let loaded;
1841
2917
  try {
1842
- context = await mcpLoadContext();
2918
+ loaded = await mcpLoadContext(args.roster);
1843
2919
  } catch (e) {
1844
2920
  return {
1845
2921
  content: [{ type: "text", text: e.message }],
1846
2922
  isError: true
1847
2923
  };
1848
2924
  }
1849
- const r = await roster({ context });
2925
+ const source = { name: loaded.rosterName, path: loaded.rosterPath };
2926
+ const r = await roster({ context: loaded.context });
1850
2927
  if (!r.ok)
1851
- return { content: [{ type: "text", text: r.error }], isError: true };
1852
- return { content: [{ type: "text", text: formatRoster(r.projects) }] };
2928
+ return {
2929
+ content: [{ type: "text", text: withRosterHeader(source, r.error) }],
2930
+ isError: true
2931
+ };
2932
+ const header = formatRosterHeader(source);
2933
+ return {
2934
+ content: [
2935
+ { type: "text", text: `${header}
2936
+ ${formatRoster(r.projects)}` }
2937
+ ]
2938
+ };
1853
2939
  });
1854
2940
  server.registerTool("bus_task", {
1855
2941
  description: BUS_TASK_DESCRIPTION,
1856
2942
  inputSchema: {
1857
- project: z4.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
1858
- prompt: z4.string().describe("The prompt to send to the delegated agent"),
1859
- title: z4.string().optional().describe("Optional session title (only used when starting a new session)"),
1860
- sessionId: z4.string().optional().describe("Existing session ID to steer instead of starting a new session")
2943
+ project: z5.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
2944
+ prompt: z5.string().describe("The prompt to send to the delegated agent"),
2945
+ title: z5.string().optional().describe("Optional session title (only used when starting a new session)"),
2946
+ sessionId: z5.string().optional().describe("Existing session ID to steer instead of starting a new session"),
2947
+ roster: ROSTER_PARAM_SCHEMA
1861
2948
  },
1862
2949
  outputSchema: {
1863
- sessionId: z4.string().describe("The dispatched or steered session ID"),
1864
- project: z4.string().describe("Manifest project name that owns the session"),
1865
- mode: z4.enum(["new", "question-reply", "follow-up"]).describe("How the prompt was delivered")
2950
+ sessionId: z5.string().describe("The dispatched or steered session ID"),
2951
+ project: z5.string().describe("Manifest project name that owns the session"),
2952
+ mode: z5.enum(["new", "question-reply", "follow-up"]).describe("How the prompt was delivered")
1866
2953
  }
1867
2954
  }, async (args) => {
1868
2955
  const dispatchArgs = toDispatchArgs(args);
@@ -1871,73 +2958,98 @@ server.registerTool("bus_task", {
1871
2958
  content: [{ type: "text", text: dispatchArgs.error }],
1872
2959
  isError: true
1873
2960
  };
1874
- let context;
2961
+ let loaded;
1875
2962
  try {
1876
- context = await mcpLoadContext();
2963
+ loaded = await mcpLoadContext(args.roster);
1877
2964
  } catch (e) {
1878
2965
  return {
1879
2966
  content: [{ type: "text", text: e.message }],
1880
2967
  isError: true
1881
2968
  };
1882
2969
  }
1883
- const r = await dispatch(dispatchArgs, { context });
2970
+ const source = { name: loaded.rosterName, path: loaded.rosterPath };
2971
+ const r = await dispatch(dispatchArgs, { context: loaded.context });
1884
2972
  if (!r.ok)
1885
- return { content: [{ type: "text", text: r.error }], isError: true };
2973
+ return {
2974
+ content: [{ type: "text", text: withRosterHeader(source, r.error) }],
2975
+ isError: true
2976
+ };
2977
+ const header = formatRosterHeader(source);
1886
2978
  return {
1887
- content: [{ type: "text", text: formatDispatch(r) }],
2979
+ content: [{ type: "text", text: `${header}
2980
+ ${formatDispatch(r)}` }],
1888
2981
  structuredContent: dispatchMetadata(r)
1889
2982
  };
1890
2983
  });
1891
2984
  server.registerTool("bus_status", {
1892
2985
  description: BUS_STATUS_DESCRIPTION,
1893
2986
  inputSchema: {
1894
- sessionId: z4.string().describe("Session ID returned by bus_task")
2987
+ sessionId: z5.string().describe("Session ID returned by bus_task"),
2988
+ roster: ROSTER_PARAM_SCHEMA
1895
2989
  }
1896
2990
  }, async (args) => {
1897
- let context;
2991
+ let loaded;
1898
2992
  try {
1899
- context = await mcpLoadContext();
2993
+ loaded = await mcpLoadContext(args.roster);
1900
2994
  } catch (e) {
1901
2995
  return {
1902
2996
  content: [{ type: "text", text: e.message }],
1903
2997
  isError: true
1904
2998
  };
1905
2999
  }
1906
- const r = await status(args.sessionId, { context });
3000
+ const source = { name: loaded.rosterName, path: loaded.rosterPath };
3001
+ const r = await status(args.sessionId, { context: loaded.context });
1907
3002
  if (!r.ok)
1908
- return { content: [{ type: "text", text: r.error }], isError: true };
1909
- return { content: [{ type: "text", text: formatStatus(r) }] };
3003
+ return {
3004
+ content: [{ type: "text", text: withRosterHeader(source, r.error) }],
3005
+ isError: true
3006
+ };
3007
+ const header = formatRosterHeader(source);
3008
+ return {
3009
+ content: [{ type: "text", text: `${header}
3010
+ ${formatStatus(r)}` }]
3011
+ };
1910
3012
  });
1911
3013
  server.registerTool("bus_result", {
1912
3014
  description: BUS_RESULT_DESCRIPTION,
1913
3015
  inputSchema: {
1914
- sessionId: z4.string().describe("Session ID returned by bus_task")
3016
+ sessionId: z5.string().describe("Session ID returned by bus_task"),
3017
+ roster: ROSTER_PARAM_SCHEMA
1915
3018
  }
1916
3019
  }, async (args) => {
1917
- let context;
3020
+ let loaded;
1918
3021
  try {
1919
- context = await mcpLoadContext();
3022
+ loaded = await mcpLoadContext(args.roster);
1920
3023
  } catch (e) {
1921
3024
  return {
1922
3025
  content: [{ type: "text", text: e.message }],
1923
3026
  isError: true
1924
3027
  };
1925
3028
  }
1926
- const r = await result(args.sessionId, { context });
3029
+ const source = { name: loaded.rosterName, path: loaded.rosterPath };
3030
+ const r = await result(args.sessionId, { context: loaded.context });
1927
3031
  if (!r.ok)
1928
- return { content: [{ type: "text", text: r.error }], isError: true };
1929
- return { content: [{ type: "text", text: formatResult(r) }] };
3032
+ return {
3033
+ content: [{ type: "text", text: withRosterHeader(source, r.error) }],
3034
+ isError: true
3035
+ };
3036
+ const header = formatRosterHeader(source);
3037
+ return {
3038
+ content: [{ type: "text", text: `${header}
3039
+ ${formatResult(r)}` }]
3040
+ };
1930
3041
  });
1931
3042
  server.registerTool("bus_wait", {
1932
3043
  description: BUS_WAIT_DESCRIPTION,
1933
3044
  inputSchema: {
1934
- sessionIds: z4.array(z4.string()).min(1, "bus_wait requires at least one sessionId").max(100, "bus_wait accepts at most 100 sessionIds").describe("Session IDs to watch (returned by bus_task)"),
1935
- timeoutMs: z4.number().positive().optional().describe(`Max time to wait in milliseconds before returning a timeout snapshot (default 60s, capped at ${MAX_WAIT_TIMEOUT_MS}ms; soft deadline, may overshoot by up to ~30s if a request is slow)`)
3045
+ sessionIds: z5.array(z5.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)"),
3046
+ timeoutMs: z5.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)`),
3047
+ roster: ROSTER_PARAM_SCHEMA
1936
3048
  }
1937
3049
  }, async (args) => {
1938
- let context;
3050
+ let loaded;
1939
3051
  try {
1940
- context = await mcpLoadContext();
3052
+ loaded = await mcpLoadContext(args.roster);
1941
3053
  } catch (e) {
1942
3054
  return {
1943
3055
  content: [{ type: "text", text: e.message }],
@@ -1945,10 +3057,46 @@ server.registerTool("bus_wait", {
1945
3057
  };
1946
3058
  }
1947
3059
  const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
1948
- const r = await wait(args.sessionIds, { context, timeoutMs });
3060
+ const source = { name: loaded.rosterName, path: loaded.rosterPath };
3061
+ const r = await wait(args.sessionIds, {
3062
+ context: loaded.context,
3063
+ timeoutMs
3064
+ });
1949
3065
  if (!r.ok)
1950
- return { content: [{ type: "text", text: r.error }], isError: true };
1951
- return { content: [{ type: "text", text: formatWait(r) }] };
3066
+ return {
3067
+ content: [{ type: "text", text: withRosterHeader(source, r.error) }],
3068
+ isError: true
3069
+ };
3070
+ const header = formatRosterHeader(source);
3071
+ return {
3072
+ content: [{ type: "text", text: `${header}
3073
+ ${formatWait(r)}` }]
3074
+ };
3075
+ });
3076
+ server.registerTool("bus_registry", {
3077
+ description: BUS_REGISTRY_DESCRIPTION,
3078
+ inputSchema: ACTION_SCHEMA,
3079
+ outputSchema: {
3080
+ rosters: z5.array(z5.object({
3081
+ name: z5.string(),
3082
+ path: z5.string(),
3083
+ default: z5.boolean(),
3084
+ active: z5.boolean()
3085
+ })).optional().describe("Populated for the `list` action only")
3086
+ }
3087
+ }, async (args) => {
3088
+ try {
3089
+ const { text, listMetadata } = await runBusRegistryAction(args, registrySession);
3090
+ return listMetadata ? {
3091
+ content: [{ type: "text", text }],
3092
+ structuredContent: { rosters: listMetadata }
3093
+ } : { content: [{ type: "text", text }] };
3094
+ } catch (e) {
3095
+ return {
3096
+ content: [{ type: "text", text: e.message }],
3097
+ isError: true
3098
+ };
3099
+ }
1952
3100
  });
1953
3101
  async function main() {
1954
3102
  const transport = new StdioServerTransport;