@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/README.md +7 -1
- package/dist/attach.js +32 -1
- package/dist/cli.js +496 -63
- package/dist/config.d.ts +53 -0
- package/dist/config.js +447 -14
- package/dist/contract.d.ts +15 -0
- package/dist/contract.js +34 -1
- package/dist/core.js +32 -1
- package/dist/format.d.ts +13 -0
- package/dist/format.js +4 -0
- package/dist/index.js +1224 -183
- package/dist/mcp.js +1262 -114
- package/dist/registry-entry.d.ts +21 -0
- package/dist/registry-entry.js +1242 -0
- package/dist/registry.d.ts +58 -0
- package/dist/roster-edit.d.ts +62 -0
- package/dist/server.js +454 -21
- package/dist/tools/bus_registry.d.ts +123 -0
- package/dist/tools/shared.d.ts +31 -1
- package/package.json +6 -2
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
|
|
6
|
-
import { homedir as
|
|
7
|
-
import { join as
|
|
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
|
|
@@ -127,13 +127,44 @@ var managedSpawnConfigSchema = z.object({
|
|
|
127
127
|
cwd: z.string().optional(),
|
|
128
128
|
port: z.number().int().nonnegative().optional()
|
|
129
129
|
});
|
|
130
|
+
var registryEntrySchema = z.object({
|
|
131
|
+
name: z.string().regex(/^[a-z0-9-]{1,64}$/, "roster name must be 1-64 lowercase letters, digits, or hyphens"),
|
|
132
|
+
path: z.string().min(1, "roster path must not be empty")
|
|
133
|
+
});
|
|
134
|
+
var registryFileSchema = z.object({
|
|
135
|
+
version: z.literal(1),
|
|
136
|
+
default: z.string().optional(),
|
|
137
|
+
rosters: z.array(registryEntrySchema)
|
|
138
|
+
}).superRefine((val, ctx) => {
|
|
139
|
+
const seen = new Set;
|
|
140
|
+
for (const entry of val.rosters) {
|
|
141
|
+
const key = entry.name.toLowerCase();
|
|
142
|
+
if (seen.has(key)) {
|
|
143
|
+
ctx.addIssue({
|
|
144
|
+
code: "custom",
|
|
145
|
+
message: `space-bus: duplicate roster name "${entry.name}" (case-insensitive) in registry`
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
seen.add(key);
|
|
149
|
+
}
|
|
150
|
+
if (val.default !== undefined) {
|
|
151
|
+
const matches = val.rosters.filter((entry) => entry.name === val.default);
|
|
152
|
+
if (matches.length !== 1) {
|
|
153
|
+
ctx.addIssue({
|
|
154
|
+
code: "custom",
|
|
155
|
+
message: `space-bus: registry's default "${val.default}" must match exactly one roster entry's name (matched ${matches.length})`
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
130
160
|
var discoveryFileSchema = z.object({
|
|
131
161
|
port: z.number().int().nonnegative(),
|
|
132
162
|
pid: z.number().int().min(2),
|
|
133
163
|
identity: z.string(),
|
|
134
164
|
password: z.string(),
|
|
135
165
|
spawnConfig: managedSpawnConfigSchema,
|
|
136
|
-
baseUrl: z.url()
|
|
166
|
+
baseUrl: z.url(),
|
|
167
|
+
rosterPath: z.string().optional()
|
|
137
168
|
});
|
|
138
169
|
|
|
139
170
|
// src/discovery.ts
|
|
@@ -402,6 +433,380 @@ function removeProvisional(rosterPath) {
|
|
|
402
433
|
} catch {}
|
|
403
434
|
}
|
|
404
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
|
+
|
|
405
810
|
// src/config.ts
|
|
406
811
|
var managedServerConfigSchema = z3.object({
|
|
407
812
|
command: z3.array(z3.string()).optional(),
|
|
@@ -435,7 +840,7 @@ var manifestSchema = z3.object({
|
|
|
435
840
|
}))
|
|
436
841
|
});
|
|
437
842
|
function expandHome(path) {
|
|
438
|
-
return path.startsWith("~") ?
|
|
843
|
+
return path.startsWith("~") ? join3(homedir3(), path.slice(1)) : path;
|
|
439
844
|
}
|
|
440
845
|
function resolveRosterPath(directory) {
|
|
441
846
|
const override = process.env["SPACE_BUS_CONFIG"];
|
|
@@ -447,19 +852,18 @@ function resolveRosterPath(directory) {
|
|
|
447
852
|
if (!expanded.startsWith("/")) {
|
|
448
853
|
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
|
|
449
854
|
}
|
|
450
|
-
return existsSync(expanded) ?
|
|
855
|
+
return existsSync(expanded) ? realpathSync2(expanded) : expanded;
|
|
451
856
|
}
|
|
452
857
|
if (directory) {
|
|
453
|
-
const candidate =
|
|
454
|
-
return existsSync(candidate) ?
|
|
858
|
+
const candidate = join3(directory, "spacebus.json");
|
|
859
|
+
return existsSync(candidate) ? realpathSync2(candidate) : candidate;
|
|
455
860
|
}
|
|
456
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");
|
|
457
862
|
}
|
|
458
|
-
function
|
|
459
|
-
const manifestPath = resolveRosterPath(directory);
|
|
863
|
+
function getRosterAtPath(manifestPath) {
|
|
460
864
|
let raw;
|
|
461
865
|
try {
|
|
462
|
-
raw =
|
|
866
|
+
raw = readFileSync3(manifestPath, "utf8");
|
|
463
867
|
} catch (err) {
|
|
464
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)`);
|
|
465
869
|
}
|
|
@@ -482,6 +886,10 @@ function getRoster(directory) {
|
|
|
482
886
|
}
|
|
483
887
|
return parsed.data;
|
|
484
888
|
}
|
|
889
|
+
function getRoster(directory) {
|
|
890
|
+
const manifestPath = resolveRosterPath(directory);
|
|
891
|
+
return getRosterAtPath(manifestPath);
|
|
892
|
+
}
|
|
485
893
|
function getProjects(manifest) {
|
|
486
894
|
return manifest.projects.map((p) => {
|
|
487
895
|
const expandedPath = expandHome(p.path);
|
|
@@ -495,9 +903,8 @@ function getCredentials() {
|
|
|
495
903
|
const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
|
|
496
904
|
return { username, password };
|
|
497
905
|
}
|
|
498
|
-
function
|
|
499
|
-
const
|
|
500
|
-
const manifest = getRoster(directory);
|
|
906
|
+
function loadContextAtPath(rosterPath) {
|
|
907
|
+
const manifest = getRosterAtPath(rosterPath);
|
|
501
908
|
const projects = getProjects(manifest);
|
|
502
909
|
if (manifest.server.baseUrl === undefined) {
|
|
503
910
|
const live = attachLive(rosterPath);
|
|
@@ -514,6 +921,28 @@ function loadContext(directory) {
|
|
|
514
921
|
credentials: getCredentials()
|
|
515
922
|
};
|
|
516
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
|
+
}
|
|
517
946
|
function isManagedRoster(directory) {
|
|
518
947
|
const manifest = getRoster(directory);
|
|
519
948
|
return manifest.server.managed !== undefined;
|
|
@@ -521,8 +950,8 @@ function isManagedRoster(directory) {
|
|
|
521
950
|
|
|
522
951
|
// src/server.ts
|
|
523
952
|
import { spawn } from "node:child_process";
|
|
524
|
-
import { randomBytes as
|
|
525
|
-
import { openSync as
|
|
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";
|
|
526
955
|
import { dirname } from "node:path";
|
|
527
956
|
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
528
957
|
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
@@ -537,13 +966,13 @@ function sleep(ms) {
|
|
|
537
966
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
538
967
|
}
|
|
539
968
|
function readManifest(rosterPath) {
|
|
540
|
-
const raw =
|
|
969
|
+
const raw = readFileSync4(rosterPath, "utf8");
|
|
541
970
|
const json = JSON.parse(raw);
|
|
542
971
|
return manifestSchema.parse(json);
|
|
543
972
|
}
|
|
544
973
|
function readLogTail(logPath, maxChars = 4000) {
|
|
545
974
|
try {
|
|
546
|
-
const content =
|
|
975
|
+
const content = readFileSync4(logPath, "utf8");
|
|
547
976
|
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
548
977
|
} catch {
|
|
549
978
|
return "";
|
|
@@ -716,12 +1145,12 @@ function reapOrphanedProvisional(rosterPath) {
|
|
|
716
1145
|
}
|
|
717
1146
|
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
718
1147
|
reapOrphanedProvisional(rosterPath);
|
|
719
|
-
const password =
|
|
1148
|
+
const password = randomBytes3(32).toString("base64url");
|
|
720
1149
|
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
721
1150
|
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
722
1151
|
const requestedPort = managedConfig.port ?? 0;
|
|
723
1152
|
const logPath = logFilePath(rosterPath);
|
|
724
|
-
const logFd =
|
|
1153
|
+
const logFd = openSync3(logPath, "w", 384);
|
|
725
1154
|
let child;
|
|
726
1155
|
let pid;
|
|
727
1156
|
let spawnError;
|
|
@@ -776,7 +1205,8 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
|
776
1205
|
identity: finalIdentity,
|
|
777
1206
|
password,
|
|
778
1207
|
spawnConfig: { command, cwd, port: requestedPort },
|
|
779
|
-
baseUrl
|
|
1208
|
+
baseUrl,
|
|
1209
|
+
rosterPath
|
|
780
1210
|
});
|
|
781
1211
|
return {
|
|
782
1212
|
baseUrl,
|
|
@@ -786,6 +1216,9 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
|
786
1216
|
};
|
|
787
1217
|
}
|
|
788
1218
|
async function ensureServer(rosterPath, options = {}) {
|
|
1219
|
+
if (existsSync2(rosterPath)) {
|
|
1220
|
+
rosterPath = realpathSync3(rosterPath);
|
|
1221
|
+
}
|
|
789
1222
|
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
790
1223
|
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
791
1224
|
const fastPath = attachServer(rosterPath);
|
|
@@ -1002,50 +1435,691 @@ async function waitForGroupDeath(pid, budgetMs) {
|
|
|
1002
1435
|
return !groupAlive();
|
|
1003
1436
|
}
|
|
1004
1437
|
|
|
1005
|
-
// src/tools/
|
|
1438
|
+
// src/tools/bus_registry.ts
|
|
1439
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
1006
1440
|
import { tool } from "@opencode-ai/plugin";
|
|
1441
|
+
import { z as z4 } from "zod";
|
|
1007
1442
|
|
|
1008
|
-
// src/
|
|
1009
|
-
function
|
|
1010
|
-
return
|
|
1443
|
+
// src/format.ts
|
|
1444
|
+
function formatRosterHeader(source) {
|
|
1445
|
+
return `roster: ${source.name ?? source.path}`;
|
|
1011
1446
|
}
|
|
1012
|
-
function
|
|
1013
|
-
return
|
|
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
|
+
`);
|
|
1014
1457
|
}
|
|
1015
|
-
function
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
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}).`;
|
|
1466
|
+
}
|
|
1021
1467
|
}
|
|
1022
|
-
function
|
|
1023
|
-
|
|
1024
|
-
return {};
|
|
1025
|
-
const username = credentials.username ?? "opencode";
|
|
1026
|
-
const token = toBase64(`${username}:${credentials.password}`);
|
|
1027
|
-
return { Authorization: `Basic ${token}` };
|
|
1468
|
+
function dispatchMetadata(r) {
|
|
1469
|
+
return { sessionId: r.sessionId, project: r.project, mode: r.mode };
|
|
1028
1470
|
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
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,
|
|
1049
2123
|
statusText: "space-bus: request failed"
|
|
1050
2124
|
}),
|
|
1051
2125
|
bodyText: `space-bus: request failed: ${message}`
|
|
@@ -1595,221 +2669,187 @@ function parsePendingQuestions(questionRes) {
|
|
|
1595
2669
|
}
|
|
1596
2670
|
}
|
|
1597
2671
|
|
|
1598
|
-
// src/
|
|
1599
|
-
function
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
}).join(`
|
|
1608
|
-
`);
|
|
1609
|
-
}
|
|
1610
|
-
function formatDispatch(r) {
|
|
1611
|
-
switch (r.mode) {
|
|
1612
|
-
case "new":
|
|
1613
|
-
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
1614
|
-
case "question-reply":
|
|
1615
|
-
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
1616
|
-
case "follow-up":
|
|
1617
|
-
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
function dispatchMetadata(r) {
|
|
1621
|
-
return { sessionId: r.sessionId, project: r.project, mode: r.mode };
|
|
1622
|
-
}
|
|
1623
|
-
function formatStatus(r) {
|
|
1624
|
-
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
1625
|
-
`) : " (none)";
|
|
1626
|
-
const lines = [
|
|
1627
|
-
`session: ${r.sessionId} (${r.project})`,
|
|
1628
|
-
`title: ${r.title ?? "(untitled)"}`,
|
|
1629
|
-
`busy: ${r.busy}`
|
|
1630
|
-
];
|
|
1631
|
-
if (r.pendingQuestion) {
|
|
1632
|
-
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
1633
|
-
if (r.pendingQuestion.options.length > 0) {
|
|
1634
|
-
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);
|
|
1635
2681
|
}
|
|
1636
|
-
|
|
2682
|
+
const context = loadContextForRosterPath(rosterPath2);
|
|
2683
|
+
return { context, rosterName: resolved.name, rosterPath: rosterPath2 };
|
|
1637
2684
|
}
|
|
1638
|
-
|
|
1639
|
-
return lines.join(`
|
|
1640
|
-
`);
|
|
1641
|
-
}
|
|
1642
|
-
function formatWait(r) {
|
|
1643
|
-
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
1644
|
-
const sessionLines = r.sessions.map((s) => {
|
|
1645
|
-
const parts = [
|
|
1646
|
-
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
1647
|
-
];
|
|
1648
|
-
if (s.pendingQuestion) {
|
|
1649
|
-
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
1650
|
-
if (s.pendingQuestion.options.length > 0) {
|
|
1651
|
-
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
1652
|
-
}
|
|
1653
|
-
parts.push(` (answer with bus_task using sessionId)`);
|
|
1654
|
-
}
|
|
1655
|
-
return parts.join(`
|
|
1656
|
-
`);
|
|
1657
|
-
});
|
|
1658
|
-
return [header, ...sessionLines].join(`
|
|
1659
|
-
`);
|
|
1660
|
-
}
|
|
1661
|
-
function formatResult(r) {
|
|
1662
|
-
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
1663
|
-
`) : " (no changes)";
|
|
1664
|
-
return [
|
|
1665
|
-
`session: ${r.sessionId} (${r.project})`,
|
|
1666
|
-
`--- reply ---`,
|
|
1667
|
-
r.text || "(empty)",
|
|
1668
|
-
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
1669
|
-
diffLines
|
|
1670
|
-
].join(`
|
|
1671
|
-
`);
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1674
|
-
// src/tools/shared.ts
|
|
1675
|
-
async function ensureAndLoadContext(directory) {
|
|
2685
|
+
const rosterPath = resolveRosterPath(directory);
|
|
1676
2686
|
if (isManagedRoster(directory)) {
|
|
1677
|
-
|
|
1678
|
-
await ensureServer(rosterPath);
|
|
2687
|
+
await ensure(rosterPath);
|
|
1679
2688
|
}
|
|
1680
|
-
return loadContext(directory);
|
|
2689
|
+
return { context: loadContext(directory), rosterPath };
|
|
2690
|
+
}
|
|
2691
|
+
function withRosterHeader(source, text) {
|
|
2692
|
+
return `${formatRosterHeader(source)}
|
|
2693
|
+
${text}`;
|
|
1681
2694
|
}
|
|
1682
2695
|
|
|
1683
2696
|
// src/tools/bus_result.ts
|
|
1684
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.";
|
|
1685
2698
|
function makeBusResult(defaultDirectory) {
|
|
1686
|
-
return
|
|
2699
|
+
return tool2({
|
|
1687
2700
|
description: BUS_RESULT_DESCRIPTION,
|
|
1688
2701
|
args: {
|
|
1689
|
-
sessionId:
|
|
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)")
|
|
1690
2704
|
},
|
|
1691
2705
|
async execute(args, ctx) {
|
|
1692
2706
|
const directory = ctx.directory ?? defaultDirectory;
|
|
1693
|
-
let
|
|
2707
|
+
let resolved;
|
|
1694
2708
|
try {
|
|
1695
|
-
|
|
2709
|
+
resolved = await ensureAndLoadContext(directory, args.roster);
|
|
1696
2710
|
} catch (e) {
|
|
1697
2711
|
throw new Error(e.message);
|
|
1698
2712
|
}
|
|
1699
|
-
const
|
|
2713
|
+
const source = { name: resolved.rosterName, path: resolved.rosterPath };
|
|
2714
|
+
const r = await result(args.sessionId, { context: resolved.context });
|
|
1700
2715
|
if (!r.ok)
|
|
1701
|
-
throw new Error(r.error);
|
|
1702
|
-
|
|
2716
|
+
throw new Error(withRosterHeader(source, r.error));
|
|
2717
|
+
const header = formatRosterHeader(source);
|
|
2718
|
+
return `${header}
|
|
2719
|
+
${formatResult(r)}`;
|
|
1703
2720
|
}
|
|
1704
2721
|
});
|
|
1705
2722
|
}
|
|
1706
2723
|
|
|
1707
2724
|
// src/tools/bus_roster.ts
|
|
1708
|
-
import { tool as
|
|
2725
|
+
import { tool as tool3 } from "@opencode-ai/plugin";
|
|
1709
2726
|
var BUS_ROSTER_DESCRIPTION = "List the space-bus manifest projects with live session status per project.";
|
|
1710
2727
|
function makeBusRoster(defaultDirectory) {
|
|
1711
|
-
return
|
|
2728
|
+
return tool3({
|
|
1712
2729
|
description: BUS_ROSTER_DESCRIPTION,
|
|
1713
|
-
args: {
|
|
1714
|
-
|
|
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) {
|
|
1715
2734
|
const directory = ctx.directory ?? defaultDirectory;
|
|
1716
|
-
let
|
|
2735
|
+
let resolved;
|
|
1717
2736
|
try {
|
|
1718
|
-
|
|
2737
|
+
resolved = await ensureAndLoadContext(directory, args.roster);
|
|
1719
2738
|
} catch (e) {
|
|
1720
2739
|
throw new Error(e.message);
|
|
1721
2740
|
}
|
|
1722
|
-
const
|
|
2741
|
+
const source = { name: resolved.rosterName, path: resolved.rosterPath };
|
|
2742
|
+
const r = await roster({ context: resolved.context });
|
|
1723
2743
|
if (!r.ok)
|
|
1724
|
-
throw new Error(r.error);
|
|
1725
|
-
|
|
2744
|
+
throw new Error(withRosterHeader(source, r.error));
|
|
2745
|
+
const header = formatRosterHeader(source);
|
|
2746
|
+
return `${header}
|
|
2747
|
+
${formatRoster(r.projects)}`;
|
|
1726
2748
|
}
|
|
1727
2749
|
});
|
|
1728
2750
|
}
|
|
1729
2751
|
|
|
1730
2752
|
// src/tools/bus_status.ts
|
|
1731
|
-
import { tool as
|
|
2753
|
+
import { tool as tool4 } from "@opencode-ai/plugin";
|
|
1732
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.";
|
|
1733
2755
|
function makeBusStatus(defaultDirectory) {
|
|
1734
|
-
return
|
|
2756
|
+
return tool4({
|
|
1735
2757
|
description: BUS_STATUS_DESCRIPTION,
|
|
1736
2758
|
args: {
|
|
1737
|
-
sessionId:
|
|
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)")
|
|
1738
2761
|
},
|
|
1739
2762
|
async execute(args, ctx) {
|
|
1740
2763
|
const directory = ctx.directory ?? defaultDirectory;
|
|
1741
|
-
let
|
|
2764
|
+
let resolved;
|
|
1742
2765
|
try {
|
|
1743
|
-
|
|
2766
|
+
resolved = await ensureAndLoadContext(directory, args.roster);
|
|
1744
2767
|
} catch (e) {
|
|
1745
2768
|
throw new Error(e.message);
|
|
1746
2769
|
}
|
|
1747
|
-
const
|
|
2770
|
+
const source = { name: resolved.rosterName, path: resolved.rosterPath };
|
|
2771
|
+
const r = await status(args.sessionId, { context: resolved.context });
|
|
1748
2772
|
if (!r.ok)
|
|
1749
|
-
throw new Error(r.error);
|
|
1750
|
-
|
|
2773
|
+
throw new Error(withRosterHeader(source, r.error));
|
|
2774
|
+
const header = formatRosterHeader(source);
|
|
2775
|
+
return `${header}
|
|
2776
|
+
${formatStatus(r)}`;
|
|
1751
2777
|
}
|
|
1752
2778
|
});
|
|
1753
2779
|
}
|
|
1754
2780
|
|
|
1755
2781
|
// src/tools/bus_task.ts
|
|
1756
|
-
import { tool as
|
|
2782
|
+
import { tool as tool5 } from "@opencode-ai/plugin";
|
|
1757
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.";
|
|
1758
2784
|
function makeBusTask(defaultDirectory) {
|
|
1759
|
-
return
|
|
2785
|
+
return tool5({
|
|
1760
2786
|
description: BUS_TASK_DESCRIPTION,
|
|
1761
2787
|
args: {
|
|
1762
|
-
project:
|
|
1763
|
-
prompt:
|
|
1764
|
-
title:
|
|
1765
|
-
sessionId:
|
|
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)")
|
|
1766
2793
|
},
|
|
1767
2794
|
async execute(args, ctx) {
|
|
1768
2795
|
const dispatchArgs = toDispatchArgs(args);
|
|
1769
2796
|
if (!dispatchArgs.ok)
|
|
1770
2797
|
throw new Error(dispatchArgs.error);
|
|
1771
2798
|
const directory = ctx.directory ?? defaultDirectory;
|
|
1772
|
-
let
|
|
2799
|
+
let resolved;
|
|
1773
2800
|
try {
|
|
1774
|
-
|
|
2801
|
+
resolved = await ensureAndLoadContext(directory, args.roster);
|
|
1775
2802
|
} catch (e) {
|
|
1776
2803
|
throw new Error(e.message);
|
|
1777
2804
|
}
|
|
1778
|
-
const
|
|
2805
|
+
const source = { name: resolved.rosterName, path: resolved.rosterPath };
|
|
2806
|
+
const r = await dispatch(dispatchArgs, { context: resolved.context });
|
|
1779
2807
|
if (!r.ok)
|
|
1780
|
-
throw new Error(r.error);
|
|
1781
|
-
|
|
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
|
+
};
|
|
1782
2815
|
}
|
|
1783
2816
|
});
|
|
1784
2817
|
}
|
|
1785
2818
|
|
|
1786
2819
|
// src/tools/bus_wait.ts
|
|
1787
|
-
import { tool as
|
|
2820
|
+
import { tool as tool6 } from "@opencode-ai/plugin";
|
|
1788
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.";
|
|
1789
2822
|
var MAX_WAIT_TIMEOUT_MS = 5 * 60000;
|
|
1790
2823
|
function makeBusWait(defaultDirectory) {
|
|
1791
|
-
return
|
|
2824
|
+
return tool6({
|
|
1792
2825
|
description: BUS_WAIT_DESCRIPTION,
|
|
1793
2826
|
args: {
|
|
1794
|
-
sessionIds:
|
|
1795
|
-
timeoutMs:
|
|
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)")
|
|
1796
2830
|
},
|
|
1797
2831
|
async execute(args, ctx) {
|
|
1798
2832
|
if (!args.sessionIds || args.sessionIds.length === 0) {
|
|
1799
2833
|
throw new Error("bus_wait requires at least one sessionId");
|
|
1800
2834
|
}
|
|
1801
2835
|
const directory = ctx.directory ?? defaultDirectory;
|
|
1802
|
-
let
|
|
2836
|
+
let resolved;
|
|
1803
2837
|
try {
|
|
1804
|
-
|
|
2838
|
+
resolved = await ensureAndLoadContext(directory, args.roster);
|
|
1805
2839
|
} catch (e) {
|
|
1806
2840
|
throw new Error(e.message);
|
|
1807
2841
|
}
|
|
1808
2842
|
const timeoutMs = args.timeoutMs !== undefined ? Math.min(args.timeoutMs, MAX_WAIT_TIMEOUT_MS) : undefined;
|
|
1809
|
-
const
|
|
2843
|
+
const source = { name: resolved.rosterName, path: resolved.rosterPath };
|
|
2844
|
+
const r = await wait(args.sessionIds, {
|
|
2845
|
+
context: resolved.context,
|
|
2846
|
+
timeoutMs
|
|
2847
|
+
});
|
|
1810
2848
|
if (!r.ok)
|
|
1811
|
-
throw new Error(r.error);
|
|
1812
|
-
|
|
2849
|
+
throw new Error(withRosterHeader(source, r.error));
|
|
2850
|
+
const header = formatRosterHeader(source);
|
|
2851
|
+
return `${header}
|
|
2852
|
+
${formatWait(r)}`;
|
|
1813
2853
|
}
|
|
1814
2854
|
});
|
|
1815
2855
|
}
|
|
@@ -1821,7 +2861,8 @@ var SpaceBusPlugin = async (input) => ({
|
|
|
1821
2861
|
bus_task: makeBusTask(input.directory),
|
|
1822
2862
|
bus_status: makeBusStatus(input.directory),
|
|
1823
2863
|
bus_result: makeBusResult(input.directory),
|
|
1824
|
-
bus_wait: makeBusWait(input.directory)
|
|
2864
|
+
bus_wait: makeBusWait(input.directory),
|
|
2865
|
+
bus_registry: makeBusRegistry()
|
|
1825
2866
|
}
|
|
1826
2867
|
});
|
|
1827
2868
|
var src_default = SpaceBusPlugin;
|