@fro.bot/space-bus 0.12.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/index.js CHANGED
@@ -2,9 +2,9 @@ import { createRequire } from "node:module";
2
2
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
3
 
4
4
  // src/config.ts
5
- import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
6
- import { homedir as homedir2 } from "node:os";
7
- import { join as join2 } from "node:path";
5
+ import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
6
+ import { homedir as homedir3 } from "node:os";
7
+ import { join as join3 } from "node:path";
8
8
  import { z as z3 } from "zod";
9
9
 
10
10
  // src/contract.ts
@@ -433,6 +433,380 @@ function removeProvisional(rosterPath) {
433
433
  } catch {}
434
434
  }
435
435
 
436
+ // src/registry.ts
437
+ import { randomBytes as randomBytes2 } from "node:crypto";
438
+ import {
439
+ closeSync as closeSync2,
440
+ constants as fsConstants2,
441
+ fstatSync,
442
+ lstatSync,
443
+ mkdirSync as mkdirSync2,
444
+ openSync as openSync2,
445
+ readFileSync as readFileSync2,
446
+ realpathSync,
447
+ renameSync as renameSync2,
448
+ statSync as statSync2,
449
+ unlinkSync as unlinkSync2,
450
+ writeSync
451
+ } from "node:fs";
452
+ import { homedir as homedir2 } from "node:os";
453
+ import { isAbsolute, join as join2 } from "node:path";
454
+ var EMPTY_REGISTRY = { version: 1, rosters: [] };
455
+ function registryPath() {
456
+ const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir2(), ".config");
457
+ return join2(base, "space-bus", "rosters.json");
458
+ }
459
+ function isEnoent2(err) {
460
+ return isErrnoCode2(err, "ENOENT");
461
+ }
462
+ function isErrnoCode2(err, code) {
463
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
464
+ }
465
+ function closeQuietly2(fd) {
466
+ try {
467
+ closeSync2(fd);
468
+ } catch {}
469
+ }
470
+ function readRegistry() {
471
+ const target = registryPath();
472
+ let raw;
473
+ try {
474
+ raw = readFileSync2(target, "utf8");
475
+ } catch (err) {
476
+ if (isEnoent2(err)) {
477
+ return { ok: true, registry: EMPTY_REGISTRY };
478
+ }
479
+ return {
480
+ ok: false,
481
+ error: `space-bus: cannot read registry at ${target}: ${String(err)}`
482
+ };
483
+ }
484
+ let json;
485
+ try {
486
+ json = JSON.parse(raw);
487
+ } catch (err) {
488
+ return {
489
+ ok: false,
490
+ error: `space-bus: registry at ${target} is not valid JSON: ${String(err)}`
491
+ };
492
+ }
493
+ const parsed = registryFileSchema.safeParse(json);
494
+ if (!parsed.success) {
495
+ return {
496
+ ok: false,
497
+ error: `space-bus: registry at ${target} failed schema validation: ${parsed.error.message}`
498
+ };
499
+ }
500
+ const nonAbsolute = parsed.data.rosters.find((entry) => !isAbsolute(entry.path));
501
+ if (nonAbsolute) {
502
+ return {
503
+ ok: false,
504
+ error: `space-bus: registry at ${target} contains a non-absolute path for roster "${nonAbsolute.name}": ${nonAbsolute.path}`
505
+ };
506
+ }
507
+ return { ok: true, registry: parsed.data };
508
+ }
509
+ function writeRegistryAtomic(data) {
510
+ const target = registryPath();
511
+ const dir = join2(target, "..");
512
+ try {
513
+ mkdirSync2(dir, { recursive: true, mode: 448 });
514
+ } catch (err) {
515
+ return {
516
+ ok: false,
517
+ error: `space-bus: failed to create registry dir ${dir}: ${String(err)}`
518
+ };
519
+ }
520
+ const tempPath = join2(dir, `.rosters.${randomBytes2(8).toString("hex")}.tmp`);
521
+ let fd;
522
+ try {
523
+ fd = openSync2(tempPath, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
524
+ writeSync(fd, JSON.stringify(data, null, 2));
525
+ closeSync2(fd);
526
+ fd = undefined;
527
+ renameSync2(tempPath, target);
528
+ } catch (err) {
529
+ if (fd !== undefined)
530
+ closeQuietly2(fd);
531
+ try {
532
+ unlinkSync2(tempPath);
533
+ } catch {}
534
+ return {
535
+ ok: false,
536
+ error: `space-bus: failed to write registry at ${target}: ${String(err)}`
537
+ };
538
+ }
539
+ return { ok: true };
540
+ }
541
+ function registryLockPath() {
542
+ return join2(registryPath(), "..", "rosters.lock");
543
+ }
544
+ var LOCK_RETRY_COUNT = 10;
545
+ var LOCK_RETRY_DELAY_MS = 50;
546
+ var LOCK_STALE_MS = 1e4;
547
+ function sleepSync(ms) {
548
+ const buf = new Int32Array(new SharedArrayBuffer(4));
549
+ Atomics.wait(buf, 0, 0, ms);
550
+ }
551
+ function tryCreateRegistryLock(target) {
552
+ let fd;
553
+ try {
554
+ fd = openSync2(target, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
555
+ } catch (err) {
556
+ if (isErrnoCode2(err, "EEXIST"))
557
+ return false;
558
+ throw err;
559
+ }
560
+ try {
561
+ writeSync(fd, String(process.pid));
562
+ } finally {
563
+ closeQuietly2(fd);
564
+ }
565
+ return true;
566
+ }
567
+ function isRegistryLockStale(target) {
568
+ try {
569
+ return Date.now() - statSync2(target).mtimeMs > LOCK_STALE_MS;
570
+ } catch {
571
+ return false;
572
+ }
573
+ }
574
+ function breakStaleAndRetry(target) {
575
+ if (!isRegistryLockStale(target))
576
+ return false;
577
+ try {
578
+ unlinkSync2(target);
579
+ } catch (err) {
580
+ if (!isEnoent2(err))
581
+ throw err;
582
+ }
583
+ return tryCreateRegistryLock(target);
584
+ }
585
+ function acquireRegistryLock() {
586
+ const dir = join2(registryPath(), "..");
587
+ mkdirSync2(dir, { recursive: true, mode: 448 });
588
+ const target = registryLockPath();
589
+ for (let attempt = 0;attempt <= LOCK_RETRY_COUNT; attempt++) {
590
+ if (tryCreateRegistryLock(target))
591
+ return true;
592
+ if (breakStaleAndRetry(target))
593
+ return true;
594
+ if (attempt < LOCK_RETRY_COUNT)
595
+ sleepSync(LOCK_RETRY_DELAY_MS);
596
+ }
597
+ return false;
598
+ }
599
+ function releaseRegistryLock() {
600
+ try {
601
+ unlinkSync2(registryLockPath());
602
+ } catch {}
603
+ }
604
+ function withRegistryLock(mutate) {
605
+ if (!acquireRegistryLock()) {
606
+ return {
607
+ ok: false,
608
+ error: "space-bus: timed out waiting for the registry lock (another process is mutating rosters.json) — try again"
609
+ };
610
+ }
611
+ try {
612
+ return mutate();
613
+ } finally {
614
+ releaseRegistryLock();
615
+ }
616
+ }
617
+ function openAndValidateRosterFile(rosterPath) {
618
+ let fd;
619
+ try {
620
+ fd = openSync2(rosterPath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
621
+ } catch (err) {
622
+ if (isErrnoCode2(err, "ELOOP")) {
623
+ return {
624
+ ok: false,
625
+ error: `space-bus: roster path ${rosterPath} is a symlink — refusing to register a symlinked roster file`
626
+ };
627
+ }
628
+ if (isEnoent2(err)) {
629
+ return {
630
+ ok: false,
631
+ error: `space-bus: roster path ${rosterPath} does not exist: ${String(err)}`
632
+ };
633
+ }
634
+ return {
635
+ ok: false,
636
+ error: `space-bus: failed to open roster path ${rosterPath}: ${String(err)}`
637
+ };
638
+ }
639
+ try {
640
+ let stat;
641
+ try {
642
+ stat = fstatSync(fd);
643
+ } catch (err) {
644
+ return {
645
+ ok: false,
646
+ error: `space-bus: failed to stat roster path ${rosterPath}: ${String(err)}`
647
+ };
648
+ }
649
+ if (!stat.isFile()) {
650
+ return {
651
+ ok: false,
652
+ error: `space-bus: roster path ${rosterPath} is not a regular file — refusing to register`
653
+ };
654
+ }
655
+ let raw;
656
+ try {
657
+ raw = readFileSync2(fd, "utf8");
658
+ } catch (err) {
659
+ return {
660
+ ok: false,
661
+ error: `space-bus: failed to read roster path ${rosterPath}: ${String(err)}`
662
+ };
663
+ }
664
+ let json;
665
+ try {
666
+ json = JSON.parse(raw);
667
+ } catch (err) {
668
+ return {
669
+ ok: false,
670
+ error: `space-bus: roster path ${rosterPath} is not valid JSON: ${String(err)}`
671
+ };
672
+ }
673
+ const parsed = manifestSchema.safeParse(json);
674
+ if (!parsed.success) {
675
+ return {
676
+ ok: false,
677
+ error: `space-bus: roster path ${rosterPath} is not a valid spacebus.json — refusing to register: ${parsed.error.message}`
678
+ };
679
+ }
680
+ } finally {
681
+ closeQuietly2(fd);
682
+ }
683
+ return { ok: true };
684
+ }
685
+ function registerRoster(name, rosterPath) {
686
+ const nameCheck = registryEntrySchema.shape.name.safeParse(name);
687
+ if (!nameCheck.success) {
688
+ return {
689
+ ok: false,
690
+ error: `space-bus: invalid roster name "${name}": ${nameCheck.error.issues[0]?.message ?? "must be 1-64 lowercase letters, digits, or hyphens"}`
691
+ };
692
+ }
693
+ const validated = openAndValidateRosterFile(rosterPath);
694
+ if (!validated.ok)
695
+ return validated;
696
+ let canonicalPath;
697
+ try {
698
+ canonicalPath = realpathSync(rosterPath);
699
+ } catch (err) {
700
+ return {
701
+ ok: false,
702
+ error: `space-bus: failed to canonicalize roster path ${rosterPath}: ${String(err)}`
703
+ };
704
+ }
705
+ return withRegistryLock(() => {
706
+ const readResult = readRegistry();
707
+ if (!readResult.ok)
708
+ return readResult;
709
+ const registry = readResult.registry;
710
+ const collision = registry.rosters.find((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
711
+ if (collision) {
712
+ return {
713
+ ok: false,
714
+ error: `space-bus: a roster named "${collision.name}" is already registered`
715
+ };
716
+ }
717
+ const entry = { name, path: canonicalPath };
718
+ const next = {
719
+ ...registry,
720
+ rosters: [...registry.rosters, entry]
721
+ };
722
+ return writeRegistryAtomic(next);
723
+ });
724
+ }
725
+ function unregisterRoster(name) {
726
+ return withRegistryLock(() => {
727
+ const readResult = readRegistry();
728
+ if (!readResult.ok)
729
+ return readResult;
730
+ const registry = readResult.registry;
731
+ const exists = registry.rosters.some((entry) => entry.name.toLowerCase() === name.toLowerCase());
732
+ if (!exists) {
733
+ return {
734
+ ok: false,
735
+ error: `space-bus: no roster named "${name}" is registered`
736
+ };
737
+ }
738
+ const rosters = registry.rosters.filter((entry) => entry.name.toLowerCase() !== name.toLowerCase());
739
+ const next = {
740
+ ...registry,
741
+ rosters,
742
+ default: registry.default !== undefined && registry.default.toLowerCase() === name.toLowerCase() ? undefined : registry.default
743
+ };
744
+ return writeRegistryAtomic(next);
745
+ });
746
+ }
747
+ function setDefaultRoster(name) {
748
+ return withRegistryLock(() => {
749
+ const readResult = readRegistry();
750
+ if (!readResult.ok)
751
+ return readResult;
752
+ const registry = readResult.registry;
753
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
754
+ if (!entry) {
755
+ return {
756
+ ok: false,
757
+ error: `space-bus: no roster named "${name}" is registered`
758
+ };
759
+ }
760
+ const next = { ...registry, default: entry.name };
761
+ return writeRegistryAtomic(next);
762
+ });
763
+ }
764
+ function resolveRosterByName(name) {
765
+ const readResult = readRegistry();
766
+ if (!readResult.ok)
767
+ return readResult;
768
+ const registry = readResult.registry;
769
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
770
+ if (!entry) {
771
+ const known = registry.rosters.map((r) => r.name);
772
+ return {
773
+ ok: false,
774
+ 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)`
775
+ };
776
+ }
777
+ let stat;
778
+ try {
779
+ stat = lstatSync(entry.path);
780
+ } catch {
781
+ return {
782
+ ok: false,
783
+ error: `space-bus: registered roster file no longer exists at ${entry.path} (name "${entry.name}") — was it moved or deleted?`
784
+ };
785
+ }
786
+ if (stat.isSymbolicLink()) {
787
+ return {
788
+ ok: false,
789
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is now a symlink — refusing to resolve a symlinked roster file`
790
+ };
791
+ }
792
+ if (!stat.isFile()) {
793
+ return {
794
+ ok: false,
795
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is no longer a regular file`
796
+ };
797
+ }
798
+ let canonicalPath;
799
+ try {
800
+ canonicalPath = realpathSync(entry.path);
801
+ } catch (err) {
802
+ return {
803
+ ok: false,
804
+ error: `space-bus: failed to canonicalize registered roster path ${entry.path} (name "${entry.name}"): ${String(err)}`
805
+ };
806
+ }
807
+ return { ok: true, path: canonicalPath, name: entry.name };
808
+ }
809
+
436
810
  // src/config.ts
437
811
  var managedServerConfigSchema = z3.object({
438
812
  command: z3.array(z3.string()).optional(),
@@ -466,7 +840,7 @@ var manifestSchema = z3.object({
466
840
  }))
467
841
  });
468
842
  function expandHome(path) {
469
- return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
843
+ return path.startsWith("~") ? join3(homedir3(), path.slice(1)) : path;
470
844
  }
471
845
  function resolveRosterPath(directory) {
472
846
  const override = process.env["SPACE_BUS_CONFIG"];
@@ -478,19 +852,18 @@ function resolveRosterPath(directory) {
478
852
  if (!expanded.startsWith("/")) {
479
853
  throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
480
854
  }
481
- return existsSync(expanded) ? realpathSync(expanded) : expanded;
855
+ return existsSync(expanded) ? realpathSync2(expanded) : expanded;
482
856
  }
483
857
  if (directory) {
484
- const candidate = join2(directory, "spacebus.json");
485
- return existsSync(candidate) ? realpathSync(candidate) : candidate;
858
+ const candidate = join3(directory, "spacebus.json");
859
+ return existsSync(candidate) ? realpathSync2(candidate) : candidate;
486
860
  }
487
861
  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");
488
862
  }
489
- function getRoster(directory) {
490
- const manifestPath = resolveRosterPath(directory);
863
+ function getRosterAtPath(manifestPath) {
491
864
  let raw;
492
865
  try {
493
- raw = readFileSync2(manifestPath, "utf8");
866
+ raw = readFileSync3(manifestPath, "utf8");
494
867
  } catch (err) {
495
868
  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)`);
496
869
  }
@@ -513,6 +886,10 @@ function getRoster(directory) {
513
886
  }
514
887
  return parsed.data;
515
888
  }
889
+ function getRoster(directory) {
890
+ const manifestPath = resolveRosterPath(directory);
891
+ return getRosterAtPath(manifestPath);
892
+ }
516
893
  function getProjects(manifest) {
517
894
  return manifest.projects.map((p) => {
518
895
  const expandedPath = expandHome(p.path);
@@ -526,9 +903,8 @@ function getCredentials() {
526
903
  const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
527
904
  return { username, password };
528
905
  }
529
- function loadContext(directory) {
530
- const rosterPath = resolveRosterPath(directory);
531
- const manifest = getRoster(directory);
906
+ function loadContextAtPath(rosterPath) {
907
+ const manifest = getRosterAtPath(rosterPath);
532
908
  const projects = getProjects(manifest);
533
909
  if (manifest.server.baseUrl === undefined) {
534
910
  const live = attachLive(rosterPath);
@@ -545,6 +921,28 @@ function loadContext(directory) {
545
921
  credentials: getCredentials()
546
922
  };
547
923
  }
924
+ function loadContext(directory) {
925
+ const rosterPath = resolveRosterPath(directory);
926
+ return loadContextAtPath(rosterPath);
927
+ }
928
+ function loadContextForRoster(rosterName) {
929
+ const resolved = resolveRosterByName(rosterName);
930
+ if (!resolved.ok) {
931
+ throw new Error(resolved.error);
932
+ }
933
+ return {
934
+ context: loadContextAtPath(resolved.path),
935
+ rosterPath: resolved.path,
936
+ rosterName: resolved.name
937
+ };
938
+ }
939
+ function loadContextForRosterPath(rosterPath) {
940
+ return loadContextAtPath(rosterPath);
941
+ }
942
+ function isManagedRosterAtPath(rosterPath) {
943
+ const manifest = getRosterAtPath(rosterPath);
944
+ return manifest.server.managed !== undefined;
945
+ }
548
946
  function isManagedRoster(directory) {
549
947
  const manifest = getRoster(directory);
550
948
  return manifest.server.managed !== undefined;
@@ -552,8 +950,8 @@ function isManagedRoster(directory) {
552
950
 
553
951
  // src/server.ts
554
952
  import { spawn } from "node:child_process";
555
- import { randomBytes as randomBytes2 } from "node:crypto";
556
- import { existsSync as existsSync2, openSync as openSync2, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
953
+ import { randomBytes as randomBytes3 } from "node:crypto";
954
+ import { existsSync as existsSync2, openSync as openSync3, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
557
955
  import { dirname } from "node:path";
558
956
  var DEFAULT_READINESS_BUDGET_MS = 15000;
559
957
  var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
@@ -568,13 +966,13 @@ function sleep(ms) {
568
966
  return new Promise((resolve) => setTimeout(resolve, ms));
569
967
  }
570
968
  function readManifest(rosterPath) {
571
- const raw = readFileSync3(rosterPath, "utf8");
969
+ const raw = readFileSync4(rosterPath, "utf8");
572
970
  const json = JSON.parse(raw);
573
971
  return manifestSchema.parse(json);
574
972
  }
575
973
  function readLogTail(logPath, maxChars = 4000) {
576
974
  try {
577
- const content = readFileSync3(logPath, "utf8");
975
+ const content = readFileSync4(logPath, "utf8");
578
976
  return content.length > maxChars ? content.slice(-maxChars) : content;
579
977
  } catch {
580
978
  return "";
@@ -747,12 +1145,12 @@ function reapOrphanedProvisional(rosterPath) {
747
1145
  }
748
1146
  async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
749
1147
  reapOrphanedProvisional(rosterPath);
750
- const password = randomBytes2(32).toString("base64url");
1148
+ const password = randomBytes3(32).toString("base64url");
751
1149
  const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
752
1150
  const cwd = managedConfig.cwd ?? dirname(rosterPath);
753
1151
  const requestedPort = managedConfig.port ?? 0;
754
1152
  const logPath = logFilePath(rosterPath);
755
- const logFd = openSync2(logPath, "w", 384);
1153
+ const logFd = openSync3(logPath, "w", 384);
756
1154
  let child;
757
1155
  let pid;
758
1156
  let spawnError;
@@ -819,7 +1217,7 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
819
1217
  }
820
1218
  async function ensureServer(rosterPath, options = {}) {
821
1219
  if (existsSync2(rosterPath)) {
822
- rosterPath = realpathSync2(rosterPath);
1220
+ rosterPath = realpathSync3(rosterPath);
823
1221
  }
824
1222
  const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
825
1223
  const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
@@ -1037,63 +1435,704 @@ async function waitForGroupDeath(pid, budgetMs) {
1037
1435
  return !groupAlive();
1038
1436
  }
1039
1437
 
1040
- // src/tools/bus_result.ts
1438
+ // src/tools/bus_registry.ts
1439
+ import { isAbsolute as isAbsolute2 } from "node:path";
1041
1440
  import { tool } from "@opencode-ai/plugin";
1441
+ import { z as z4 } from "zod";
1042
1442
 
1043
- // src/core.ts
1044
- function findProject(projects, name) {
1045
- return projects.find((p) => p.name === name);
1046
- }
1047
- function err(error) {
1048
- return { ok: false, error };
1049
- }
1050
- function toBase64(s) {
1051
- const bytes = new TextEncoder().encode(s);
1052
- let bin = "";
1053
- for (const b of bytes)
1054
- bin += String.fromCharCode(b);
1055
- return btoa(bin);
1443
+ // src/format.ts
1444
+ function formatRosterHeader(source) {
1445
+ return `roster: ${source.name ?? source.path}`;
1056
1446
  }
1057
- function authHeader(credentials) {
1058
- if (!credentials.password)
1059
- return {};
1060
- const username = credentials.username ?? "opencode";
1061
- const token = toBase64(`${username}:${credentials.password}`);
1062
- return { Authorization: `Basic ${token}` };
1447
+ function formatRoster(projects) {
1448
+ return projects.map((p) => {
1449
+ if (!p.pathExists)
1450
+ return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
1451
+ if (p.statusError)
1452
+ return `${p.name}: status error (${p.statusError}) — ${p.description}`;
1453
+ const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
1454
+ return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
1455
+ }).join(`
1456
+ `);
1063
1457
  }
1064
- async function api(baseUrl, credentials, directory, path, init) {
1065
- try {
1066
- const res = await fetch(`${baseUrl}${path}`, {
1067
- ...init,
1068
- headers: {
1069
- "content-type": "application/json",
1070
- "x-opencode-directory": directory,
1071
- ...authHeader(credentials),
1072
- ...init?.headers
1073
- },
1074
- redirect: "error",
1075
- signal: AbortSignal.timeout(30000)
1076
- });
1077
- const bodyText = await res.text().catch(() => "<unreadable body>");
1078
- return { res, bodyText };
1079
- } catch (e) {
1080
- const message = e.message;
1081
- return {
1082
- res: new Response(null, {
1083
- status: 599,
1084
- statusText: "space-bus: request failed"
1085
- }),
1086
- bodyText: `space-bus: request failed: ${message}`
1087
- };
1458
+ function formatDispatch(r) {
1459
+ switch (r.mode) {
1460
+ case "new":
1461
+ return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
1462
+ case "question-reply":
1463
+ return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
1464
+ case "follow-up":
1465
+ return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
1088
1466
  }
1089
1467
  }
1090
- async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
1091
- const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
1092
- if (!res.ok)
1093
- return [];
1094
- let messages;
1095
- try {
1096
- messages = turnMessageListSchema.parse(JSON.parse(bodyText));
1468
+ function dispatchMetadata(r) {
1469
+ return { sessionId: r.sessionId, project: r.project, mode: r.mode };
1470
+ }
1471
+ function formatStatus(r) {
1472
+ const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
1473
+ `) : " (none)";
1474
+ const lines = [
1475
+ `session: ${r.sessionId} (${r.project})`,
1476
+ `title: ${r.title ?? "(untitled)"}`,
1477
+ `busy: ${r.busy}`
1478
+ ];
1479
+ if (r.pendingQuestion) {
1480
+ lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
1481
+ if (r.pendingQuestion.options.length > 0) {
1482
+ lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
1483
+ }
1484
+ lines.push(` (answer with bus_task using sessionId)`);
1485
+ }
1486
+ lines.push(r.diffSource === "working-tree" ? `diff (working tree — repo-wide, may include changes from other sessions): ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}` : `diff: ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}`, `todos:`, todoLines);
1487
+ return lines.join(`
1488
+ `);
1489
+ }
1490
+ function formatWait(r) {
1491
+ const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
1492
+ const sessionLines = r.sessions.map((s) => {
1493
+ const parts = [
1494
+ ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
1495
+ ];
1496
+ if (s.pendingQuestion) {
1497
+ parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
1498
+ if (s.pendingQuestion.options.length > 0) {
1499
+ parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
1500
+ }
1501
+ parts.push(` (answer with bus_task using sessionId)`);
1502
+ }
1503
+ return parts.join(`
1504
+ `);
1505
+ });
1506
+ return [header, ...sessionLines].join(`
1507
+ `);
1508
+ }
1509
+ function formatResult(r) {
1510
+ const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
1511
+ `) : " (no changes)";
1512
+ return [
1513
+ `session: ${r.sessionId} (${r.project})`,
1514
+ `--- reply ---`,
1515
+ r.text || "(empty)",
1516
+ r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
1517
+ diffLines
1518
+ ].join(`
1519
+ `);
1520
+ }
1521
+
1522
+ // src/roster-edit.ts
1523
+ import { randomBytes as randomBytes4 } from "node:crypto";
1524
+ import {
1525
+ chmodSync as chmodSync2,
1526
+ closeSync as closeSync3,
1527
+ constants as fsConstants3,
1528
+ lstatSync as lstatSync2,
1529
+ mkdirSync as mkdirSync3,
1530
+ openSync as openSync4,
1531
+ readFileSync as readFileSync5,
1532
+ renameSync as renameSync3,
1533
+ statSync as statSync3,
1534
+ unlinkSync as unlinkSync3,
1535
+ writeSync as writeSync2
1536
+ } from "node:fs";
1537
+ import { join as join4 } from "node:path";
1538
+ function closeQuietly3(fd) {
1539
+ try {
1540
+ closeSync3(fd);
1541
+ } catch {}
1542
+ }
1543
+ function isErrnoCode3(err, code) {
1544
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
1545
+ }
1546
+ function duplicateProjectName(projects) {
1547
+ const seen = new Set;
1548
+ for (const p of projects) {
1549
+ if (seen.has(p.name))
1550
+ return p.name;
1551
+ seen.add(p.name);
1552
+ }
1553
+ return null;
1554
+ }
1555
+ function validateManifest(data) {
1556
+ const parsed = manifestSchema.safeParse(data);
1557
+ if (!parsed.success) {
1558
+ return {
1559
+ ok: false,
1560
+ error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
1561
+ };
1562
+ }
1563
+ const baseUrl = parsed.data.server.baseUrl;
1564
+ if (baseUrl !== undefined && !loopbackOk(baseUrl)) {
1565
+ return {
1566
+ ok: false,
1567
+ error: `space-bus: roster's server.baseUrl must point to localhost (got ${baseUrl}) — refusing to send credentials off-machine`
1568
+ };
1569
+ }
1570
+ const dup = duplicateProjectName(parsed.data.projects);
1571
+ if (dup !== null) {
1572
+ return {
1573
+ ok: false,
1574
+ error: `space-bus: roster document has duplicate project name "${dup}"`
1575
+ };
1576
+ }
1577
+ return { ok: true, manifest: parsed.data };
1578
+ }
1579
+ function readManifest2(rosterPath) {
1580
+ let raw;
1581
+ try {
1582
+ raw = readFileSync5(rosterPath, "utf8");
1583
+ } catch (err) {
1584
+ return {
1585
+ ok: false,
1586
+ error: `space-bus: cannot read roster at ${rosterPath}: ${String(err)}`
1587
+ };
1588
+ }
1589
+ let json;
1590
+ try {
1591
+ json = JSON.parse(raw);
1592
+ } catch (err) {
1593
+ return {
1594
+ ok: false,
1595
+ error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
1596
+ };
1597
+ }
1598
+ return validateManifest(json);
1599
+ }
1600
+ function writeManifestAtomic(rosterPath, data) {
1601
+ const dir = join4(rosterPath, "..");
1602
+ try {
1603
+ mkdirSync3(dir, { recursive: true });
1604
+ } catch (err) {
1605
+ return {
1606
+ ok: false,
1607
+ error: `space-bus: failed to create directory ${dir}: ${String(err)}`
1608
+ };
1609
+ }
1610
+ let existingMode;
1611
+ try {
1612
+ existingMode = statSync3(rosterPath).mode & 511;
1613
+ } catch {
1614
+ existingMode = undefined;
1615
+ }
1616
+ const tempPath = join4(dir, `.spacebus.${randomBytes4(8).toString("hex")}.tmp`);
1617
+ let fd;
1618
+ try {
1619
+ fd = openSync4(tempPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY, 420);
1620
+ writeSync2(fd, JSON.stringify(data, null, 2));
1621
+ if (existingMode !== undefined) {
1622
+ chmodSync2(tempPath, existingMode);
1623
+ }
1624
+ closeSync3(fd);
1625
+ fd = undefined;
1626
+ renameSync3(tempPath, rosterPath);
1627
+ } catch (err) {
1628
+ if (fd !== undefined)
1629
+ closeQuietly3(fd);
1630
+ try {
1631
+ unlinkSync3(tempPath);
1632
+ } catch {}
1633
+ return {
1634
+ ok: false,
1635
+ error: `space-bus: failed to write roster at ${rosterPath}: ${String(err)}`
1636
+ };
1637
+ }
1638
+ return { ok: true };
1639
+ }
1640
+ function writeRosterExclusive(rosterPath, data) {
1641
+ const dir = join4(rosterPath, "..");
1642
+ try {
1643
+ mkdirSync3(dir, { recursive: true });
1644
+ } catch (err) {
1645
+ return {
1646
+ ok: false,
1647
+ error: `space-bus: failed to create directory ${dir}: ${String(err)}`
1648
+ };
1649
+ }
1650
+ let fd;
1651
+ try {
1652
+ fd = openSync4(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
1653
+ } catch (err) {
1654
+ if (isErrnoCode3(err, "EEXIST")) {
1655
+ return {
1656
+ ok: false,
1657
+ error: `space-bus: refusing to overwrite existing roster file at ${rosterPath}`
1658
+ };
1659
+ }
1660
+ return {
1661
+ ok: false,
1662
+ error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err)}`
1663
+ };
1664
+ }
1665
+ try {
1666
+ writeSync2(fd, JSON.stringify(data, null, 2));
1667
+ } catch (err) {
1668
+ closeQuietly3(fd);
1669
+ try {
1670
+ unlinkSync3(rosterPath);
1671
+ } catch {}
1672
+ return {
1673
+ ok: false,
1674
+ error: `space-bus: failed to write roster file at ${rosterPath}: ${String(err)}`
1675
+ };
1676
+ }
1677
+ closeQuietly3(fd);
1678
+ return { ok: true };
1679
+ }
1680
+ function editManifest(rosterPath, mutate) {
1681
+ try {
1682
+ if (lstatSync2(rosterPath).isSymbolicLink()) {
1683
+ return {
1684
+ ok: false,
1685
+ error: `space-bus: refusing to edit a symlinked roster file at ${rosterPath}`
1686
+ };
1687
+ }
1688
+ } catch {}
1689
+ const current = readManifest2(rosterPath);
1690
+ if (!current.ok)
1691
+ return current;
1692
+ const mutated = mutate(current.manifest);
1693
+ if ("ok" in mutated)
1694
+ return mutated;
1695
+ const revalidated = validateManifest(mutated);
1696
+ if (!revalidated.ok)
1697
+ return revalidated;
1698
+ return writeManifestAtomic(rosterPath, revalidated.manifest);
1699
+ }
1700
+ function createRoster(opts) {
1701
+ const nameCheck = /^[a-z0-9-]{1,64}$/.test(opts.name);
1702
+ if (!nameCheck) {
1703
+ return {
1704
+ ok: false,
1705
+ error: `space-bus: invalid roster name "${opts.name}": must be 1-64 lowercase letters, digits, or hyphens`
1706
+ };
1707
+ }
1708
+ const readResult = readRegistry();
1709
+ if (!readResult.ok)
1710
+ return readResult;
1711
+ const collision = readResult.registry.rosters.find((entry) => entry.name.toLowerCase() === opts.name.toLowerCase());
1712
+ if (collision) {
1713
+ return {
1714
+ ok: false,
1715
+ error: `space-bus: a roster named "${collision.name}" is already registered — refusing to create "${opts.name}"`
1716
+ };
1717
+ }
1718
+ const candidate = {
1719
+ server: opts.server ?? { managed: {} },
1720
+ projects: []
1721
+ };
1722
+ const validated = validateManifest(candidate);
1723
+ if (!validated.ok)
1724
+ return validated;
1725
+ const written = writeRosterExclusive(opts.rosterPath, validated.manifest);
1726
+ if (!written.ok)
1727
+ return written;
1728
+ const registered = registerRoster(opts.name, opts.rosterPath);
1729
+ if (!registered.ok) {
1730
+ return {
1731
+ ok: false,
1732
+ fileCreated: true,
1733
+ 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`
1734
+ };
1735
+ }
1736
+ return { ok: true };
1737
+ }
1738
+ function addProject(rosterPath, project) {
1739
+ return editManifest(rosterPath, (current) => {
1740
+ if (current.projects.some((p) => p.name === project.name)) {
1741
+ return {
1742
+ ok: false,
1743
+ error: `space-bus: a project named "${project.name}" already exists in ${rosterPath}`
1744
+ };
1745
+ }
1746
+ return { ...current, projects: [...current.projects, project] };
1747
+ });
1748
+ }
1749
+ function removeProject(rosterPath, projectName) {
1750
+ return editManifest(rosterPath, (current) => {
1751
+ const exists = current.projects.some((p) => p.name === projectName);
1752
+ if (!exists) {
1753
+ const known = current.projects.map((p) => p.name);
1754
+ return {
1755
+ ok: false,
1756
+ 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)`
1757
+ };
1758
+ }
1759
+ return {
1760
+ ...current,
1761
+ projects: current.projects.filter((p) => p.name !== projectName)
1762
+ };
1763
+ });
1764
+ }
1765
+ function updateProject(rosterPath, projectName, patch) {
1766
+ return editManifest(rosterPath, (current) => {
1767
+ const index = current.projects.findIndex((p) => p.name === projectName);
1768
+ if (index === -1) {
1769
+ const known = current.projects.map((p) => p.name);
1770
+ return {
1771
+ ok: false,
1772
+ 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)`
1773
+ };
1774
+ }
1775
+ if (patch.name !== undefined && patch.name !== projectName && current.projects.some((p) => p.name === patch.name)) {
1776
+ return {
1777
+ ok: false,
1778
+ error: `space-bus: cannot rename project "${projectName}" to "${patch.name}" in ${rosterPath} — a project with that name already exists`
1779
+ };
1780
+ }
1781
+ const projects = [...current.projects];
1782
+ const existing = projects[index];
1783
+ if (!existing) {
1784
+ return {
1785
+ ok: false,
1786
+ error: `space-bus: internal error locating project "${projectName}"`
1787
+ };
1788
+ }
1789
+ projects[index] = { ...existing, ...patch };
1790
+ return { ...current, projects };
1791
+ });
1792
+ }
1793
+ function editServer(rosterPath, server) {
1794
+ if (attachLive(rosterPath) !== null) {
1795
+ return {
1796
+ ok: false,
1797
+ error: `space-bus: a managed daemon is running for roster ${rosterPath} — run \`space-bus stop\` first before editing its server block`
1798
+ };
1799
+ }
1800
+ return editManifest(rosterPath, (current) => ({ ...current, server }));
1801
+ }
1802
+
1803
+ // src/tools/bus_registry.ts
1804
+ 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.";
1805
+ var projectInputSchema = z4.object({
1806
+ name: z4.string().min(1),
1807
+ path: z4.string().min(1),
1808
+ description: z4.string()
1809
+ });
1810
+ var PATCH_NONEMPTY_MESSAGE = "patch must include at least one field (name, path, or description)";
1811
+ var projectPatchSchema = z4.object({
1812
+ name: z4.string().min(1).optional(),
1813
+ path: z4.string().min(1).optional(),
1814
+ description: z4.string().optional()
1815
+ }).refine((patch) => Object.keys(patch).length > 0, {
1816
+ message: PATCH_NONEMPTY_MESSAGE
1817
+ });
1818
+ var ROSTER_FIELD_DESCRIPTION = "Registry roster name — required by use/add-project/remove-project/update-project";
1819
+ var NAME_FIELD_DESCRIPTION = "Roster name to create/register/unregister/set-default — required by those actions";
1820
+ var PATH_FIELD_DESCRIPTION = "Absolute path to a spacebus.json — required by create/register";
1821
+ var SERVER_FIELD_DESCRIPTION = "Server block for create (baseUrl XOR managed; defaults to managed {})";
1822
+ var PROJECT_FIELD_DESCRIPTION = "{name, path, description} — required by add-project";
1823
+ var PROJECT_NAME_FIELD_DESCRIPTION = "Existing project name — required by remove-project/update-project";
1824
+ var PATCH_FIELD_DESCRIPTION = "Partial project fields to apply — required by update-project";
1825
+ var pluginManagedServerConfigSchema = tool.schema.object({
1826
+ command: tool.schema.array(tool.schema.string()).optional(),
1827
+ cwd: tool.schema.string().optional(),
1828
+ port: tool.schema.number().int().nonnegative().optional()
1829
+ });
1830
+ var pluginServerConfigSchema = tool.schema.object({
1831
+ baseUrl: tool.schema.url().optional(),
1832
+ managed: pluginManagedServerConfigSchema.optional()
1833
+ }).superRefine((val, ctx) => {
1834
+ const hasBaseUrl = val.baseUrl !== undefined;
1835
+ const hasManaged = val.managed !== undefined;
1836
+ if (hasBaseUrl && hasManaged) {
1837
+ ctx.addIssue({
1838
+ code: "custom",
1839
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
1840
+ });
1841
+ } else if (!hasBaseUrl && !hasManaged) {
1842
+ ctx.addIssue({
1843
+ code: "custom",
1844
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
1845
+ });
1846
+ }
1847
+ });
1848
+ var pluginProjectInputSchema = tool.schema.object({
1849
+ name: tool.schema.string().min(1),
1850
+ path: tool.schema.string().min(1),
1851
+ description: tool.schema.string()
1852
+ });
1853
+ var pluginProjectPatchSchema = tool.schema.object({
1854
+ name: tool.schema.string().min(1).optional(),
1855
+ path: tool.schema.string().min(1).optional(),
1856
+ description: tool.schema.string().optional()
1857
+ }).refine((patch) => Object.keys(patch).length > 0, {
1858
+ message: PATCH_NONEMPTY_MESSAGE
1859
+ });
1860
+ var BUS_REGISTRY_ARGS = {
1861
+ action: tool.schema.enum([
1862
+ "list",
1863
+ "use",
1864
+ "create",
1865
+ "register",
1866
+ "unregister",
1867
+ "set-default",
1868
+ "add-project",
1869
+ "remove-project",
1870
+ "update-project"
1871
+ ]),
1872
+ roster: tool.schema.string().optional().describe(ROSTER_FIELD_DESCRIPTION),
1873
+ name: tool.schema.string().optional().describe(NAME_FIELD_DESCRIPTION),
1874
+ path: tool.schema.string().optional().describe(PATH_FIELD_DESCRIPTION),
1875
+ server: pluginServerConfigSchema.optional().describe(SERVER_FIELD_DESCRIPTION),
1876
+ project: pluginProjectInputSchema.optional().describe(PROJECT_FIELD_DESCRIPTION),
1877
+ projectName: tool.schema.string().optional().describe(PROJECT_NAME_FIELD_DESCRIPTION),
1878
+ patch: pluginProjectPatchSchema.optional().describe(PATCH_FIELD_DESCRIPTION)
1879
+ };
1880
+ var ACTION_SCHEMA = z4.discriminatedUnion("action", [
1881
+ z4.strictObject({ action: z4.literal("list") }),
1882
+ z4.strictObject({ action: z4.literal("use"), roster: z4.string().min(1) }),
1883
+ z4.strictObject({
1884
+ action: z4.literal("create"),
1885
+ name: z4.string().min(1),
1886
+ path: z4.string().min(1).refine(isAbsolute2, {
1887
+ message: "path must be an absolute filesystem path"
1888
+ }),
1889
+ server: serverConfigSchema.optional()
1890
+ }),
1891
+ z4.strictObject({
1892
+ action: z4.literal("register"),
1893
+ name: z4.string().min(1),
1894
+ path: z4.string().min(1).refine(isAbsolute2, {
1895
+ message: "path must be an absolute filesystem path"
1896
+ })
1897
+ }),
1898
+ z4.strictObject({ action: z4.literal("unregister"), name: z4.string().min(1) }),
1899
+ z4.strictObject({ action: z4.literal("set-default"), name: z4.string().min(1) }),
1900
+ z4.strictObject({
1901
+ action: z4.literal("add-project"),
1902
+ roster: z4.string().min(1),
1903
+ project: projectInputSchema
1904
+ }),
1905
+ z4.strictObject({
1906
+ action: z4.literal("remove-project"),
1907
+ roster: z4.string().min(1),
1908
+ projectName: z4.string().min(1)
1909
+ }),
1910
+ z4.strictObject({
1911
+ action: z4.literal("update-project"),
1912
+ roster: z4.string().min(1),
1913
+ projectName: z4.string().min(1),
1914
+ patch: projectPatchSchema
1915
+ })
1916
+ ]);
1917
+ function registryListMetadata(session) {
1918
+ const read = readRegistry();
1919
+ if (!read.ok)
1920
+ return { ok: false, error: read.error };
1921
+ const active = session?.getActive();
1922
+ return {
1923
+ ok: true,
1924
+ rosters: read.registry.rosters.map((r) => ({
1925
+ name: r.name,
1926
+ path: r.path,
1927
+ default: read.registry.default === r.name,
1928
+ active: active === r.name
1929
+ }))
1930
+ };
1931
+ }
1932
+ function formatList(rosters) {
1933
+ if (rosters.length === 0)
1934
+ return "no rosters registered";
1935
+ return rosters.map((r) => {
1936
+ const flags = [
1937
+ r.default ? "default" : null,
1938
+ r.active ? "active" : null
1939
+ ].filter((f) => f !== null);
1940
+ const suffix = flags.length > 0 ? ` (${flags.join(", ")})` : "";
1941
+ return `${r.name}: ${r.path}${suffix}`;
1942
+ }).join(`
1943
+ `);
1944
+ }
1945
+ function runList(session) {
1946
+ const listed = registryListMetadata(session);
1947
+ if (!listed.ok)
1948
+ throw new Error(`bus_registry list: ${listed.error}`);
1949
+ return { text: formatList(listed.rosters), listMetadata: listed.rosters };
1950
+ }
1951
+ function runUse(args, session) {
1952
+ if (!session) {
1953
+ throw new Error("bus_registry use: roster selection is a connector-session concept — plugin calls resolve by workspace directory; pass roster per call instead");
1954
+ }
1955
+ const resolved = resolveRosterByName(args.roster);
1956
+ if (!resolved.ok)
1957
+ throw new Error(`bus_registry use: ${resolved.error}`);
1958
+ session.setActive(resolved.name);
1959
+ return {
1960
+ text: `bus_registry use: active roster set to "${resolved.name}" (${resolved.path})`
1961
+ };
1962
+ }
1963
+ function runCreate(args) {
1964
+ const result = createRoster({
1965
+ name: args.name,
1966
+ rosterPath: args.path,
1967
+ server: args.server
1968
+ });
1969
+ if (!result.ok)
1970
+ throw new Error(`bus_registry create: ${result.error}`);
1971
+ return {
1972
+ text: `bus_registry create: ${formatRosterHeader({ name: args.name, path: args.path })} created and registered`
1973
+ };
1974
+ }
1975
+ function runRegister(args) {
1976
+ const result = registerRoster(args.name, args.path);
1977
+ if (!result.ok)
1978
+ throw new Error(`bus_registry register: ${result.error}`);
1979
+ return {
1980
+ text: `bus_registry register: ${formatRosterHeader({ name: args.name, path: args.path })} registered`
1981
+ };
1982
+ }
1983
+ function runUnregister(args, session) {
1984
+ const result = unregisterRoster(args.name);
1985
+ if (!result.ok)
1986
+ throw new Error(`bus_registry unregister: ${result.error}`);
1987
+ const active = session?.getActive();
1988
+ if (active !== undefined && active.toLowerCase() === args.name.toLowerCase()) {
1989
+ session?.clearActive();
1990
+ return {
1991
+ text: `bus_registry unregister: "${args.name}" unregistered — session-active roster cleared — omitted-roster calls fall back to ambient`
1992
+ };
1993
+ }
1994
+ return { text: `bus_registry unregister: "${args.name}" unregistered` };
1995
+ }
1996
+ function runSetDefault(args) {
1997
+ const result = setDefaultRoster(args.name);
1998
+ if (!result.ok)
1999
+ throw new Error(`bus_registry set-default: ${result.error}`);
2000
+ return {
2001
+ text: `bus_registry set-default: "${args.name}" is now the default roster`
2002
+ };
2003
+ }
2004
+ function runAddProject(args) {
2005
+ const resolved = resolveRosterByName(args.roster);
2006
+ if (!resolved.ok)
2007
+ throw new Error(`bus_registry add-project: ${resolved.error}`);
2008
+ const result = addProject(resolved.path, args.project);
2009
+ if (!result.ok)
2010
+ throw new Error(`bus_registry add-project: ${result.error}`);
2011
+ return {
2012
+ text: `bus_registry add-project: added "${args.project.name}" to ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2013
+ };
2014
+ }
2015
+ function runRemoveProject(args) {
2016
+ const resolved = resolveRosterByName(args.roster);
2017
+ if (!resolved.ok)
2018
+ throw new Error(`bus_registry remove-project: ${resolved.error}`);
2019
+ const result = removeProject(resolved.path, args.projectName);
2020
+ if (!result.ok)
2021
+ throw new Error(`bus_registry remove-project: ${result.error}`);
2022
+ return {
2023
+ text: `bus_registry remove-project: removed "${args.projectName}" from ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2024
+ };
2025
+ }
2026
+ function runUpdateProject(args) {
2027
+ const resolved = resolveRosterByName(args.roster);
2028
+ if (!resolved.ok)
2029
+ throw new Error(`bus_registry update-project: ${resolved.error}`);
2030
+ const result = updateProject(resolved.path, args.projectName, args.patch);
2031
+ if (!result.ok)
2032
+ throw new Error(`bus_registry update-project: ${result.error}`);
2033
+ return {
2034
+ text: `bus_registry update-project: updated "${args.projectName}" on ${formatRosterHeader({ name: args.roster, path: resolved.path })}`
2035
+ };
2036
+ }
2037
+ async function runBusRegistryAction(rawArgs, session) {
2038
+ const parsed = ACTION_SCHEMA.safeParse(rawArgs);
2039
+ if (!parsed.success) {
2040
+ const issue = parsed.error.issues[0];
2041
+ const detail = issue ? `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}` : parsed.error.message;
2042
+ throw new Error(`bus_registry ${rawArgs.action}: invalid input — ${detail}`);
2043
+ }
2044
+ const args = parsed.data;
2045
+ switch (args.action) {
2046
+ case "list":
2047
+ return runList(session);
2048
+ case "use":
2049
+ return runUse(args, session);
2050
+ case "create":
2051
+ return runCreate(args);
2052
+ case "register":
2053
+ return runRegister(args);
2054
+ case "unregister":
2055
+ return runUnregister(args, session);
2056
+ case "set-default":
2057
+ return runSetDefault(args);
2058
+ case "add-project":
2059
+ return runAddProject(args);
2060
+ case "remove-project":
2061
+ return runRemoveProject(args);
2062
+ case "update-project":
2063
+ return runUpdateProject(args);
2064
+ }
2065
+ }
2066
+ function makeBusRegistry(session) {
2067
+ return tool({
2068
+ description: BUS_REGISTRY_DESCRIPTION,
2069
+ args: BUS_REGISTRY_ARGS,
2070
+ async execute(args) {
2071
+ const { text, listMetadata } = await runBusRegistryAction(args, session);
2072
+ if (listMetadata)
2073
+ return { output: text, metadata: { rosters: listMetadata } };
2074
+ return text;
2075
+ }
2076
+ });
2077
+ }
2078
+
2079
+ // src/tools/bus_result.ts
2080
+ import { tool as tool2 } from "@opencode-ai/plugin";
2081
+
2082
+ // src/core.ts
2083
+ function findProject(projects, name) {
2084
+ return projects.find((p) => p.name === name);
2085
+ }
2086
+ function err(error) {
2087
+ return { ok: false, error };
2088
+ }
2089
+ function toBase64(s) {
2090
+ const bytes = new TextEncoder().encode(s);
2091
+ let bin = "";
2092
+ for (const b of bytes)
2093
+ bin += String.fromCharCode(b);
2094
+ return btoa(bin);
2095
+ }
2096
+ function authHeader(credentials) {
2097
+ if (!credentials.password)
2098
+ return {};
2099
+ const username = credentials.username ?? "opencode";
2100
+ const token = toBase64(`${username}:${credentials.password}`);
2101
+ return { Authorization: `Basic ${token}` };
2102
+ }
2103
+ async function api(baseUrl, credentials, directory, path, init) {
2104
+ try {
2105
+ const res = await fetch(`${baseUrl}${path}`, {
2106
+ ...init,
2107
+ headers: {
2108
+ "content-type": "application/json",
2109
+ "x-opencode-directory": directory,
2110
+ ...authHeader(credentials),
2111
+ ...init?.headers
2112
+ },
2113
+ redirect: "error",
2114
+ signal: AbortSignal.timeout(30000)
2115
+ });
2116
+ const bodyText = await res.text().catch(() => "<unreadable body>");
2117
+ return { res, bodyText };
2118
+ } catch (e) {
2119
+ const message = e.message;
2120
+ return {
2121
+ res: new Response(null, {
2122
+ status: 599,
2123
+ statusText: "space-bus: request failed"
2124
+ }),
2125
+ bodyText: `space-bus: request failed: ${message}`
2126
+ };
2127
+ }
2128
+ }
2129
+ async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
2130
+ const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
2131
+ if (!res.ok)
2132
+ return [];
2133
+ let messages;
2134
+ try {
2135
+ messages = turnMessageListSchema.parse(JSON.parse(bodyText));
1097
2136
  } catch {
1098
2137
  return [];
1099
2138
  }
@@ -1630,221 +2669,187 @@ function parsePendingQuestions(questionRes) {
1630
2669
  }
1631
2670
  }
1632
2671
 
1633
- // src/format.ts
1634
- function formatRoster(projects) {
1635
- return projects.map((p) => {
1636
- if (!p.pathExists)
1637
- return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
1638
- if (p.statusError)
1639
- return `${p.name}: status error (${p.statusError}) — ${p.description}`;
1640
- const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
1641
- return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
1642
- }).join(`
1643
- `);
1644
- }
1645
- function formatDispatch(r) {
1646
- switch (r.mode) {
1647
- case "new":
1648
- return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
1649
- case "question-reply":
1650
- return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
1651
- case "follow-up":
1652
- return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
1653
- }
1654
- }
1655
- function dispatchMetadata(r) {
1656
- return { sessionId: r.sessionId, project: r.project, mode: r.mode };
1657
- }
1658
- function formatStatus(r) {
1659
- const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
1660
- `) : " (none)";
1661
- const lines = [
1662
- `session: ${r.sessionId} (${r.project})`,
1663
- `title: ${r.title ?? "(untitled)"}`,
1664
- `busy: ${r.busy}`
1665
- ];
1666
- if (r.pendingQuestion) {
1667
- lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
1668
- if (r.pendingQuestion.options.length > 0) {
1669
- lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
2672
+ // src/tools/shared.ts
2673
+ async function ensureAndLoadContext(directory, rosterName, ensure = ensureServer) {
2674
+ if (rosterName !== undefined) {
2675
+ const resolved = resolveRosterByName(rosterName);
2676
+ if (!resolved.ok)
2677
+ throw new Error(resolved.error);
2678
+ const rosterPath2 = resolved.path;
2679
+ if (isManagedRosterAtPath(rosterPath2)) {
2680
+ await ensure(rosterPath2);
1670
2681
  }
1671
- lines.push(` (answer with bus_task using sessionId)`);
2682
+ const context = loadContextForRosterPath(rosterPath2);
2683
+ return { context, rosterName: resolved.name, rosterPath: rosterPath2 };
1672
2684
  }
1673
- lines.push(r.diffSource === "working-tree" ? `diff (working tree — repo-wide, may include changes from other sessions): ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}` : `diff: ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}`, `todos:`, todoLines);
1674
- return lines.join(`
1675
- `);
1676
- }
1677
- function formatWait(r) {
1678
- const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
1679
- const sessionLines = r.sessions.map((s) => {
1680
- const parts = [
1681
- ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
1682
- ];
1683
- if (s.pendingQuestion) {
1684
- parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
1685
- if (s.pendingQuestion.options.length > 0) {
1686
- parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
1687
- }
1688
- parts.push(` (answer with bus_task using sessionId)`);
1689
- }
1690
- return parts.join(`
1691
- `);
1692
- });
1693
- return [header, ...sessionLines].join(`
1694
- `);
1695
- }
1696
- function formatResult(r) {
1697
- const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
1698
- `) : " (no changes)";
1699
- return [
1700
- `session: ${r.sessionId} (${r.project})`,
1701
- `--- reply ---`,
1702
- r.text || "(empty)",
1703
- r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
1704
- diffLines
1705
- ].join(`
1706
- `);
1707
- }
1708
-
1709
- // src/tools/shared.ts
1710
- async function ensureAndLoadContext(directory) {
2685
+ const rosterPath = resolveRosterPath(directory);
1711
2686
  if (isManagedRoster(directory)) {
1712
- const rosterPath = resolveRosterPath(directory);
1713
- await ensureServer(rosterPath);
2687
+ await ensure(rosterPath);
1714
2688
  }
1715
- return loadContext(directory);
2689
+ return { context: loadContext(directory), rosterPath };
2690
+ }
2691
+ function withRosterHeader(source, text) {
2692
+ return `${formatRosterHeader(source)}
2693
+ ${text}`;
1716
2694
  }
1717
2695
 
1718
2696
  // src/tools/bus_result.ts
1719
2697
  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.";
1720
2698
  function makeBusResult(defaultDirectory) {
1721
- return tool({
2699
+ return tool2({
1722
2700
  description: BUS_RESULT_DESCRIPTION,
1723
2701
  args: {
1724
- sessionId: tool.schema.string().describe("Session ID returned by bus_task")
2702
+ sessionId: tool2.schema.string().describe("Session ID returned by bus_task"),
2703
+ roster: tool2.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1725
2704
  },
1726
2705
  async execute(args, ctx) {
1727
2706
  const directory = ctx.directory ?? defaultDirectory;
1728
- let context;
2707
+ let resolved;
1729
2708
  try {
1730
- context = await ensureAndLoadContext(directory);
2709
+ resolved = await ensureAndLoadContext(directory, args.roster);
1731
2710
  } catch (e) {
1732
2711
  throw new Error(e.message);
1733
2712
  }
1734
- const r = await result(args.sessionId, { context });
2713
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2714
+ const r = await result(args.sessionId, { context: resolved.context });
1735
2715
  if (!r.ok)
1736
- throw new Error(r.error);
1737
- return formatResult(r);
2716
+ throw new Error(withRosterHeader(source, r.error));
2717
+ const header = formatRosterHeader(source);
2718
+ return `${header}
2719
+ ${formatResult(r)}`;
1738
2720
  }
1739
2721
  });
1740
2722
  }
1741
2723
 
1742
2724
  // src/tools/bus_roster.ts
1743
- import { tool as tool2 } from "@opencode-ai/plugin";
2725
+ import { tool as tool3 } from "@opencode-ai/plugin";
1744
2726
  var BUS_ROSTER_DESCRIPTION = "List the space-bus manifest projects with live session status per project.";
1745
2727
  function makeBusRoster(defaultDirectory) {
1746
- return tool2({
2728
+ return tool3({
1747
2729
  description: BUS_ROSTER_DESCRIPTION,
1748
- args: {},
1749
- async execute(_args, ctx) {
2730
+ args: {
2731
+ roster: tool3.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
2732
+ },
2733
+ async execute(args, ctx) {
1750
2734
  const directory = ctx.directory ?? defaultDirectory;
1751
- let context;
2735
+ let resolved;
1752
2736
  try {
1753
- context = await ensureAndLoadContext(directory);
2737
+ resolved = await ensureAndLoadContext(directory, args.roster);
1754
2738
  } catch (e) {
1755
2739
  throw new Error(e.message);
1756
2740
  }
1757
- const r = await roster({ context });
2741
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2742
+ const r = await roster({ context: resolved.context });
1758
2743
  if (!r.ok)
1759
- throw new Error(r.error);
1760
- return formatRoster(r.projects);
2744
+ throw new Error(withRosterHeader(source, r.error));
2745
+ const header = formatRosterHeader(source);
2746
+ return `${header}
2747
+ ${formatRoster(r.projects)}`;
1761
2748
  }
1762
2749
  });
1763
2750
  }
1764
2751
 
1765
2752
  // src/tools/bus_status.ts
1766
- import { tool as tool3 } from "@opencode-ai/plugin";
2753
+ import { tool as tool4 } from "@opencode-ai/plugin";
1767
2754
  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.";
1768
2755
  function makeBusStatus(defaultDirectory) {
1769
- return tool3({
2756
+ return tool4({
1770
2757
  description: BUS_STATUS_DESCRIPTION,
1771
2758
  args: {
1772
- sessionId: tool3.schema.string().describe("Session ID returned by bus_task")
2759
+ sessionId: tool4.schema.string().describe("Session ID returned by bus_task"),
2760
+ roster: tool4.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1773
2761
  },
1774
2762
  async execute(args, ctx) {
1775
2763
  const directory = ctx.directory ?? defaultDirectory;
1776
- let context;
2764
+ let resolved;
1777
2765
  try {
1778
- context = await ensureAndLoadContext(directory);
2766
+ resolved = await ensureAndLoadContext(directory, args.roster);
1779
2767
  } catch (e) {
1780
2768
  throw new Error(e.message);
1781
2769
  }
1782
- const r = await status(args.sessionId, { context });
2770
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2771
+ const r = await status(args.sessionId, { context: resolved.context });
1783
2772
  if (!r.ok)
1784
- throw new Error(r.error);
1785
- return formatStatus(r);
2773
+ throw new Error(withRosterHeader(source, r.error));
2774
+ const header = formatRosterHeader(source);
2775
+ return `${header}
2776
+ ${formatStatus(r)}`;
1786
2777
  }
1787
2778
  });
1788
2779
  }
1789
2780
 
1790
2781
  // src/tools/bus_task.ts
1791
- import { tool as tool4 } from "@opencode-ai/plugin";
2782
+ import { tool as tool5 } from "@opencode-ai/plugin";
1792
2783
  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.";
1793
2784
  function makeBusTask(defaultDirectory) {
1794
- return tool4({
2785
+ return tool5({
1795
2786
  description: BUS_TASK_DESCRIPTION,
1796
2787
  args: {
1797
- project: tool4.schema.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
1798
- prompt: tool4.schema.string().describe("The prompt to send to the delegated agent"),
1799
- title: tool4.schema.string().optional().describe("Optional session title (only used when starting a new session)"),
1800
- sessionId: tool4.schema.string().optional().describe("Existing session ID to steer instead of starting a new session")
2788
+ project: tool5.schema.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
2789
+ prompt: tool5.schema.string().describe("The prompt to send to the delegated agent"),
2790
+ title: tool5.schema.string().optional().describe("Optional session title (only used when starting a new session)"),
2791
+ sessionId: tool5.schema.string().optional().describe("Existing session ID to steer instead of starting a new session"),
2792
+ roster: tool5.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1801
2793
  },
1802
2794
  async execute(args, ctx) {
1803
2795
  const dispatchArgs = toDispatchArgs(args);
1804
2796
  if (!dispatchArgs.ok)
1805
2797
  throw new Error(dispatchArgs.error);
1806
2798
  const directory = ctx.directory ?? defaultDirectory;
1807
- let context;
2799
+ let resolved;
1808
2800
  try {
1809
- context = await ensureAndLoadContext(directory);
2801
+ resolved = await ensureAndLoadContext(directory, args.roster);
1810
2802
  } catch (e) {
1811
2803
  throw new Error(e.message);
1812
2804
  }
1813
- const r = await dispatch(dispatchArgs, { context });
2805
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2806
+ const r = await dispatch(dispatchArgs, { context: resolved.context });
1814
2807
  if (!r.ok)
1815
- throw new Error(r.error);
1816
- return { output: formatDispatch(r), metadata: dispatchMetadata(r) };
2808
+ throw new Error(withRosterHeader(source, r.error));
2809
+ const header = formatRosterHeader(source);
2810
+ return {
2811
+ output: `${header}
2812
+ ${formatDispatch(r)}`,
2813
+ metadata: dispatchMetadata(r)
2814
+ };
1817
2815
  }
1818
2816
  });
1819
2817
  }
1820
2818
 
1821
2819
  // src/tools/bus_wait.ts
1822
- import { tool as tool5 } from "@opencode-ai/plugin";
2820
+ import { tool as tool6 } from "@opencode-ai/plugin";
1823
2821
  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.";
1824
2822
  var MAX_WAIT_TIMEOUT_MS = 5 * 60000;
1825
2823
  function makeBusWait(defaultDirectory) {
1826
- return tool5({
2824
+ return tool6({
1827
2825
  description: BUS_WAIT_DESCRIPTION,
1828
2826
  args: {
1829
- 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)"),
1830
- 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)`)
2827
+ 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)"),
2828
+ 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)`),
2829
+ roster: tool6.schema.string().optional().describe("Registry roster name to target. Resolution precedence: this param > workspace directory (see bus_registry to list)")
1831
2830
  },
1832
2831
  async execute(args, ctx) {
1833
2832
  if (!args.sessionIds || args.sessionIds.length === 0) {
1834
2833
  throw new Error("bus_wait requires at least one sessionId");
1835
2834
  }
1836
2835
  const directory = ctx.directory ?? defaultDirectory;
1837
- let context;
2836
+ let resolved;
1838
2837
  try {
1839
- context = await ensureAndLoadContext(directory);
2838
+ resolved = await ensureAndLoadContext(directory, args.roster);
1840
2839
  } catch (e) {
1841
2840
  throw new Error(e.message);
1842
2841
  }
1843
2842
  const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
1844
- const r = await wait(args.sessionIds, { context, timeoutMs });
2843
+ const source = { name: resolved.rosterName, path: resolved.rosterPath };
2844
+ const r = await wait(args.sessionIds, {
2845
+ context: resolved.context,
2846
+ timeoutMs
2847
+ });
1845
2848
  if (!r.ok)
1846
- throw new Error(r.error);
1847
- return formatWait(r);
2849
+ throw new Error(withRosterHeader(source, r.error));
2850
+ const header = formatRosterHeader(source);
2851
+ return `${header}
2852
+ ${formatWait(r)}`;
1848
2853
  }
1849
2854
  });
1850
2855
  }
@@ -1856,7 +2861,8 @@ var SpaceBusPlugin = async (input) => ({
1856
2861
  bus_task: makeBusTask(input.directory),
1857
2862
  bus_status: makeBusStatus(input.directory),
1858
2863
  bus_result: makeBusResult(input.directory),
1859
- bus_wait: makeBusWait(input.directory)
2864
+ bus_wait: makeBusWait(input.directory),
2865
+ bus_registry: makeBusRegistry()
1860
2866
  }
1861
2867
  });
1862
2868
  var src_default = SpaceBusPlugin;