@fro.bot/space-bus 0.4.0 → 0.6.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 +39 -1
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +961 -0
- package/dist/config.d.ts +37 -34
- package/dist/config.js +425 -17
- package/dist/contract.d.ts +72 -1671
- package/dist/contract.js +49 -32
- package/dist/core.js +48 -33
- package/dist/discovery.d.ts +126 -0
- package/dist/index.js +817 -155
- package/dist/mcp.js +839 -170
- package/dist/server.d.ts +65 -0
- package/dist/server.js +816 -0
- package/dist/tools/shared.d.ts +2 -0
- package/package.json +9 -4
package/dist/mcp.js
CHANGED
|
@@ -1,158 +1,92 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// src/
|
|
3
|
-
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
-
import { homedir } from "node:os";
|
|
5
|
-
import { join } from "node:path";
|
|
2
|
+
// src/contract.ts
|
|
6
3
|
import { z } from "zod";
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
path: z.string(),
|
|
12
|
-
description: z.string()
|
|
13
|
-
}))
|
|
4
|
+
var sessionSchema = z.looseObject({
|
|
5
|
+
id: z.string(),
|
|
6
|
+
directory: z.string().optional(),
|
|
7
|
+
title: z.string().optional()
|
|
14
8
|
});
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
function getRoster(directory) {
|
|
37
|
-
const manifestPath = resolveRosterPath(directory);
|
|
38
|
-
let raw;
|
|
39
|
-
try {
|
|
40
|
-
raw = readFileSync(manifestPath, "utf8");
|
|
41
|
-
} catch (err) {
|
|
42
|
-
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)`);
|
|
43
|
-
}
|
|
44
|
-
let json;
|
|
45
|
-
try {
|
|
46
|
-
json = JSON.parse(raw);
|
|
47
|
-
} catch (err) {
|
|
48
|
-
throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
|
|
49
|
-
}
|
|
50
|
-
const parsed = manifestSchema.safeParse(json);
|
|
51
|
-
if (!parsed.success) {
|
|
52
|
-
throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
|
|
53
|
-
}
|
|
54
|
-
const url = new URL(parsed.data.server.baseUrl);
|
|
55
|
-
const hostname = url.hostname;
|
|
56
|
-
const allowedHosts = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
|
|
57
|
-
if (!allowedHosts.has(hostname)) {
|
|
58
|
-
throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
59
|
-
}
|
|
60
|
-
return parsed.data;
|
|
61
|
-
}
|
|
62
|
-
function getProjects(manifest) {
|
|
63
|
-
return manifest.projects.map((p) => {
|
|
64
|
-
const expandedPath = expandHome(p.path);
|
|
65
|
-
return { ...p, expandedPath, exists: existsSync(expandedPath) };
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
function getCredentials() {
|
|
69
|
-
const password = process.env["OPENCODE_SERVER_PASSWORD"];
|
|
70
|
-
if (!password)
|
|
71
|
-
return {};
|
|
72
|
-
const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
|
|
73
|
-
return { username, password };
|
|
74
|
-
}
|
|
75
|
-
function loadContext(directory) {
|
|
76
|
-
const manifest = getRoster(directory);
|
|
77
|
-
const projects = getProjects(manifest);
|
|
78
|
-
return {
|
|
79
|
-
roster: { server: manifest.server, projects },
|
|
80
|
-
credentials: getCredentials()
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// src/contract.ts
|
|
85
|
-
import { z as z2 } from "zod";
|
|
86
|
-
var sessionSchema = z2.object({
|
|
87
|
-
id: z2.string(),
|
|
88
|
-
directory: z2.string().optional(),
|
|
89
|
-
title: z2.string().optional()
|
|
90
|
-
}).passthrough();
|
|
91
|
-
var sessionListSchema = z2.array(sessionSchema);
|
|
92
|
-
var sessionStatusMapSchema = z2.record(z2.string(), z2.object({ type: z2.string() }).passthrough());
|
|
93
|
-
var todoSchema = z2.array(z2.object({ content: z2.string(), status: z2.string(), priority: z2.string() }).passthrough()).default([]);
|
|
94
|
-
var diffEntrySchema = z2.object({
|
|
95
|
-
file: z2.string().optional(),
|
|
96
|
-
additions: z2.number(),
|
|
97
|
-
deletions: z2.number(),
|
|
98
|
-
status: z2.string().optional()
|
|
99
|
-
}).passthrough();
|
|
100
|
-
var diffSchema = z2.array(diffEntrySchema).default([]);
|
|
101
|
-
var vcsStatusEntrySchema = z2.object({
|
|
102
|
-
file: z2.string(),
|
|
103
|
-
additions: z2.number(),
|
|
104
|
-
deletions: z2.number(),
|
|
105
|
-
status: z2.string().optional()
|
|
106
|
-
}).passthrough();
|
|
107
|
-
var vcsStatusSchema = z2.array(vcsStatusEntrySchema).default([]);
|
|
9
|
+
var sessionListSchema = z.array(sessionSchema);
|
|
10
|
+
var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
|
|
11
|
+
var todoSchema = z.array(z.looseObject({
|
|
12
|
+
content: z.string(),
|
|
13
|
+
status: z.string(),
|
|
14
|
+
priority: z.string()
|
|
15
|
+
})).default([]);
|
|
16
|
+
var diffEntrySchema = z.looseObject({
|
|
17
|
+
file: z.string().optional(),
|
|
18
|
+
additions: z.number(),
|
|
19
|
+
deletions: z.number(),
|
|
20
|
+
status: z.string().optional()
|
|
21
|
+
});
|
|
22
|
+
var diffSchema = z.array(diffEntrySchema).default([]);
|
|
23
|
+
var vcsStatusEntrySchema = z.looseObject({
|
|
24
|
+
file: z.string(),
|
|
25
|
+
additions: z.number(),
|
|
26
|
+
deletions: z.number(),
|
|
27
|
+
status: z.string().optional()
|
|
28
|
+
});
|
|
29
|
+
var vcsStatusSchema = z.array(vcsStatusEntrySchema).default([]);
|
|
108
30
|
var turnDiffEntrySchema = diffEntrySchema;
|
|
109
|
-
var turnMessageSchema =
|
|
110
|
-
info:
|
|
111
|
-
role:
|
|
112
|
-
summary:
|
|
113
|
-
diffs:
|
|
114
|
-
}).
|
|
115
|
-
})
|
|
116
|
-
})
|
|
117
|
-
var turnMessageListSchema =
|
|
118
|
-
var sessionSummarySchema =
|
|
119
|
-
summary:
|
|
120
|
-
diffs:
|
|
121
|
-
}).
|
|
122
|
-
})
|
|
123
|
-
var messagePartSchema =
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
var
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
31
|
+
var turnMessageSchema = z.looseObject({
|
|
32
|
+
info: z.looseObject({
|
|
33
|
+
role: z.string(),
|
|
34
|
+
summary: z.looseObject({
|
|
35
|
+
diffs: z.array(turnDiffEntrySchema).optional()
|
|
36
|
+
}).optional()
|
|
37
|
+
})
|
|
38
|
+
});
|
|
39
|
+
var turnMessageListSchema = z.array(turnMessageSchema);
|
|
40
|
+
var sessionSummarySchema = z.looseObject({
|
|
41
|
+
summary: z.looseObject({
|
|
42
|
+
diffs: z.array(turnDiffEntrySchema).optional()
|
|
43
|
+
}).optional()
|
|
44
|
+
});
|
|
45
|
+
var messagePartSchema = z.looseObject({
|
|
46
|
+
type: z.string(),
|
|
47
|
+
text: z.string().optional()
|
|
48
|
+
});
|
|
49
|
+
var messageEnvelopeSchema = z.looseObject({
|
|
50
|
+
info: z.looseObject({ role: z.string() }),
|
|
51
|
+
parts: z.array(messagePartSchema)
|
|
52
|
+
});
|
|
53
|
+
var messageListSchema = z.array(messageEnvelopeSchema);
|
|
54
|
+
var pendingQuestionEntrySchema = z.looseObject({
|
|
55
|
+
id: z.string(),
|
|
56
|
+
sessionID: z.string(),
|
|
57
|
+
questions: z.array(z.looseObject({
|
|
58
|
+
question: z.string().optional(),
|
|
59
|
+
options: z.array(z.looseObject({ label: z.string().optional() })).optional()
|
|
60
|
+
})).optional()
|
|
61
|
+
});
|
|
62
|
+
var pendingQuestionListSchema = z.array(pendingQuestionEntrySchema);
|
|
63
|
+
var questionEntrySchema = z.looseObject({
|
|
64
|
+
id: z.string(),
|
|
65
|
+
sessionID: z.string()
|
|
66
|
+
});
|
|
67
|
+
var questionListSchema = z.array(questionEntrySchema);
|
|
68
|
+
var LOOPBACK_HOSTS = new Set([
|
|
69
|
+
"127.0.0.1",
|
|
70
|
+
"::1",
|
|
71
|
+
"[::1]",
|
|
72
|
+
"localhost"
|
|
73
|
+
]);
|
|
74
|
+
var projectSchema = z.looseObject({
|
|
75
|
+
name: z.string(),
|
|
76
|
+
path: z.string(),
|
|
77
|
+
description: z.string(),
|
|
78
|
+
expandedPath: z.string(),
|
|
79
|
+
exists: z.boolean()
|
|
80
|
+
});
|
|
81
|
+
var rosterSchema = z.object({
|
|
82
|
+
server: z.object({ baseUrl: z.url() }),
|
|
83
|
+
projects: z.array(projectSchema)
|
|
150
84
|
});
|
|
151
|
-
var credentialsSchema =
|
|
152
|
-
username:
|
|
153
|
-
password:
|
|
85
|
+
var credentialsSchema = z.object({
|
|
86
|
+
username: z.string().optional(),
|
|
87
|
+
password: z.string().optional()
|
|
154
88
|
});
|
|
155
|
-
var busContextSchema =
|
|
89
|
+
var busContextSchema = z.object({
|
|
156
90
|
roster: rosterSchema,
|
|
157
91
|
credentials: credentialsSchema.optional()
|
|
158
92
|
});
|
|
@@ -274,7 +208,6 @@ async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
|
|
|
274
208
|
} catch {}
|
|
275
209
|
return { diff, diffSource: "session" };
|
|
276
210
|
}
|
|
277
|
-
var ALLOWED_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
|
|
278
211
|
function validateContext(context) {
|
|
279
212
|
const parsed = busContextSchema.safeParse(context);
|
|
280
213
|
if (!parsed.success) {
|
|
@@ -287,7 +220,7 @@ function validateContext(context) {
|
|
|
287
220
|
} catch {
|
|
288
221
|
return err("space-bus: context roster server.baseUrl is not a valid URL");
|
|
289
222
|
}
|
|
290
|
-
if (!
|
|
223
|
+
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
291
224
|
return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
292
225
|
}
|
|
293
226
|
return {
|
|
@@ -743,13 +676,742 @@ function formatResult(r) {
|
|
|
743
676
|
`);
|
|
744
677
|
}
|
|
745
678
|
|
|
679
|
+
// src/config.ts
|
|
680
|
+
import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
681
|
+
import { homedir as homedir2 } from "node:os";
|
|
682
|
+
import { join as join2 } from "node:path";
|
|
683
|
+
import { z as z3 } from "zod";
|
|
684
|
+
|
|
685
|
+
// src/discovery.ts
|
|
686
|
+
import { execFileSync } from "node:child_process";
|
|
687
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
688
|
+
import {
|
|
689
|
+
chmodSync,
|
|
690
|
+
closeSync,
|
|
691
|
+
constants as fsConstants,
|
|
692
|
+
mkdirSync,
|
|
693
|
+
openSync,
|
|
694
|
+
readFileSync,
|
|
695
|
+
renameSync,
|
|
696
|
+
statSync,
|
|
697
|
+
unlinkSync,
|
|
698
|
+
writeFileSync
|
|
699
|
+
} from "node:fs";
|
|
700
|
+
import { homedir } from "node:os";
|
|
701
|
+
import { join } from "node:path";
|
|
702
|
+
import { z as z2 } from "zod";
|
|
703
|
+
function stateDirFor(rosterPath) {
|
|
704
|
+
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
705
|
+
const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
706
|
+
return join(base, "space-bus", hash);
|
|
707
|
+
}
|
|
708
|
+
function discoveryFilePath(rosterPath) {
|
|
709
|
+
return join(stateDirFor(rosterPath), "discovery.json");
|
|
710
|
+
}
|
|
711
|
+
function lockFilePath(rosterPath) {
|
|
712
|
+
return join(stateDirFor(rosterPath), "spawn.lock");
|
|
713
|
+
}
|
|
714
|
+
function logFilePath(rosterPath) {
|
|
715
|
+
return join(stateDirFor(rosterPath), "server.log");
|
|
716
|
+
}
|
|
717
|
+
var managedSpawnConfigSchema = z2.object({
|
|
718
|
+
command: z2.array(z2.string()).optional(),
|
|
719
|
+
cwd: z2.string().optional(),
|
|
720
|
+
port: z2.number().int().nonnegative().optional()
|
|
721
|
+
});
|
|
722
|
+
var discoveryFileSchema = z2.object({
|
|
723
|
+
port: z2.number().int().nonnegative(),
|
|
724
|
+
pid: z2.number().int().positive(),
|
|
725
|
+
identity: z2.string(),
|
|
726
|
+
password: z2.string(),
|
|
727
|
+
spawnConfig: managedSpawnConfigSchema,
|
|
728
|
+
baseUrl: z2.url()
|
|
729
|
+
});
|
|
730
|
+
function writeDiscovery(rosterPath, data) {
|
|
731
|
+
const dir = stateDirFor(rosterPath);
|
|
732
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
733
|
+
chmodSync(dir, 448);
|
|
734
|
+
const target = discoveryFilePath(rosterPath);
|
|
735
|
+
const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
|
|
736
|
+
const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
737
|
+
try {
|
|
738
|
+
writeFileSync(fd, JSON.stringify(data));
|
|
739
|
+
} finally {
|
|
740
|
+
closeQuietly(fd);
|
|
741
|
+
}
|
|
742
|
+
renameSync(tempPath, target);
|
|
743
|
+
chmodSync(target, 384);
|
|
744
|
+
}
|
|
745
|
+
function readDiscovery(rosterPath) {
|
|
746
|
+
const target = discoveryFilePath(rosterPath);
|
|
747
|
+
let raw;
|
|
748
|
+
try {
|
|
749
|
+
raw = readFileSync(target, "utf8");
|
|
750
|
+
} catch {
|
|
751
|
+
return null;
|
|
752
|
+
}
|
|
753
|
+
let json;
|
|
754
|
+
try {
|
|
755
|
+
json = JSON.parse(raw);
|
|
756
|
+
} catch {
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
const parsed = discoveryFileSchema.safeParse(json);
|
|
760
|
+
return parsed.success ? parsed.data : null;
|
|
761
|
+
}
|
|
762
|
+
function removeDiscovery(rosterPath) {
|
|
763
|
+
try {
|
|
764
|
+
unlinkSync(discoveryFilePath(rosterPath));
|
|
765
|
+
} catch (err2) {
|
|
766
|
+
if (!isEnoent(err2))
|
|
767
|
+
throw err2;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
function loopbackOk(baseUrl) {
|
|
771
|
+
try {
|
|
772
|
+
const url = new URL(baseUrl);
|
|
773
|
+
return LOOPBACK_HOSTS.has(url.hostname);
|
|
774
|
+
} catch {
|
|
775
|
+
return false;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
function attachLive(rosterPath) {
|
|
779
|
+
const discovery = readDiscovery(rosterPath);
|
|
780
|
+
if (!discovery)
|
|
781
|
+
return null;
|
|
782
|
+
if (!loopbackOk(discovery.baseUrl))
|
|
783
|
+
return null;
|
|
784
|
+
if (!verifyIdentity(discovery.pid, discovery.identity))
|
|
785
|
+
return null;
|
|
786
|
+
return {
|
|
787
|
+
baseUrl: discovery.baseUrl,
|
|
788
|
+
credentials: { username: "opencode", password: discovery.password },
|
|
789
|
+
pid: discovery.pid,
|
|
790
|
+
port: discovery.port
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
function captureIdentity(pid) {
|
|
794
|
+
try {
|
|
795
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
|
|
796
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
797
|
+
encoding: "utf8"
|
|
798
|
+
});
|
|
799
|
+
const trimmed = out.trim();
|
|
800
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
801
|
+
} catch {
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
function isAlive(pid) {
|
|
806
|
+
try {
|
|
807
|
+
process.kill(pid, 0);
|
|
808
|
+
return true;
|
|
809
|
+
} catch {
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
function verifyIdentity(pid, storedIdentity) {
|
|
814
|
+
if (!isAlive(pid))
|
|
815
|
+
return false;
|
|
816
|
+
const current = captureIdentity(pid);
|
|
817
|
+
return current !== null && current === storedIdentity;
|
|
818
|
+
}
|
|
819
|
+
var lockFileSchema = z2.object({
|
|
820
|
+
pid: z2.number().int().positive(),
|
|
821
|
+
startTime: z2.string(),
|
|
822
|
+
since: z2.number()
|
|
823
|
+
});
|
|
824
|
+
var CORRUPT_LOCK_GRACE_MS = 2000;
|
|
825
|
+
function acquireLock(rosterPath) {
|
|
826
|
+
const dir = stateDirFor(rosterPath);
|
|
827
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
828
|
+
chmodSync(dir, 448);
|
|
829
|
+
const target = lockFilePath(rosterPath);
|
|
830
|
+
const identity = captureIdentity(process.pid) ?? "";
|
|
831
|
+
const lock = {
|
|
832
|
+
pid: process.pid,
|
|
833
|
+
startTime: identity,
|
|
834
|
+
since: Date.now()
|
|
835
|
+
};
|
|
836
|
+
if (tryCreateLockFile(target, lock)) {
|
|
837
|
+
return { rosterPath };
|
|
838
|
+
}
|
|
839
|
+
const existing = readLockFile(target);
|
|
840
|
+
if (existing) {
|
|
841
|
+
if (verifyIdentity(existing.pid, existing.startTime))
|
|
842
|
+
return null;
|
|
843
|
+
} else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
|
|
844
|
+
return null;
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
unlinkSync(target);
|
|
848
|
+
} catch (err2) {
|
|
849
|
+
if (!isEnoent(err2))
|
|
850
|
+
throw err2;
|
|
851
|
+
}
|
|
852
|
+
if (tryCreateLockFile(target, lock)) {
|
|
853
|
+
return { rosterPath };
|
|
854
|
+
}
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
function isOlderThan(path, ageMs) {
|
|
858
|
+
try {
|
|
859
|
+
return Date.now() - statSync(path).mtimeMs > ageMs;
|
|
860
|
+
} catch {
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
function releaseLock(handle) {
|
|
865
|
+
try {
|
|
866
|
+
unlinkSync(lockFilePath(handle.rosterPath));
|
|
867
|
+
} catch {}
|
|
868
|
+
}
|
|
869
|
+
function readLockFile(target) {
|
|
870
|
+
let raw;
|
|
871
|
+
try {
|
|
872
|
+
raw = readFileSync(target, "utf8");
|
|
873
|
+
} catch {
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
let json;
|
|
877
|
+
try {
|
|
878
|
+
json = JSON.parse(raw);
|
|
879
|
+
} catch {
|
|
880
|
+
return null;
|
|
881
|
+
}
|
|
882
|
+
const parsed = lockFileSchema.safeParse(json);
|
|
883
|
+
return parsed.success ? parsed.data : null;
|
|
884
|
+
}
|
|
885
|
+
function tryCreateLockFile(target, lock) {
|
|
886
|
+
let fd;
|
|
887
|
+
try {
|
|
888
|
+
fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
889
|
+
} catch (err2) {
|
|
890
|
+
if (isErrnoCode(err2, "EEXIST"))
|
|
891
|
+
return false;
|
|
892
|
+
throw err2;
|
|
893
|
+
}
|
|
894
|
+
try {
|
|
895
|
+
writeFileSync(fd, JSON.stringify(lock));
|
|
896
|
+
} finally {
|
|
897
|
+
closeQuietly(fd);
|
|
898
|
+
}
|
|
899
|
+
return true;
|
|
900
|
+
}
|
|
901
|
+
function isEnoent(err2) {
|
|
902
|
+
return isErrnoCode(err2, "ENOENT");
|
|
903
|
+
}
|
|
904
|
+
function isErrnoCode(err2, code) {
|
|
905
|
+
return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === code;
|
|
906
|
+
}
|
|
907
|
+
function closeQuietly(fd) {
|
|
908
|
+
try {
|
|
909
|
+
closeSync(fd);
|
|
910
|
+
} catch {}
|
|
911
|
+
}
|
|
912
|
+
function provisionalFilePath(rosterPath) {
|
|
913
|
+
return join(stateDirFor(rosterPath), "spawn.provisional.json");
|
|
914
|
+
}
|
|
915
|
+
var provisionalFileSchema = z2.object({
|
|
916
|
+
pid: z2.number().int().positive(),
|
|
917
|
+
identity: z2.string(),
|
|
918
|
+
password: z2.string(),
|
|
919
|
+
since: z2.number()
|
|
920
|
+
});
|
|
921
|
+
function writeProvisional(rosterPath, data) {
|
|
922
|
+
const dir = stateDirFor(rosterPath);
|
|
923
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
924
|
+
chmodSync(dir, 448);
|
|
925
|
+
const target = provisionalFilePath(rosterPath);
|
|
926
|
+
const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
|
|
927
|
+
try {
|
|
928
|
+
writeFileSync(fd, JSON.stringify(data));
|
|
929
|
+
} finally {
|
|
930
|
+
closeQuietly(fd);
|
|
931
|
+
}
|
|
932
|
+
chmodSync(target, 384);
|
|
933
|
+
}
|
|
934
|
+
function readProvisional(rosterPath) {
|
|
935
|
+
const target = provisionalFilePath(rosterPath);
|
|
936
|
+
let raw;
|
|
937
|
+
try {
|
|
938
|
+
raw = readFileSync(target, "utf8");
|
|
939
|
+
} catch {
|
|
940
|
+
return null;
|
|
941
|
+
}
|
|
942
|
+
let json;
|
|
943
|
+
try {
|
|
944
|
+
json = JSON.parse(raw);
|
|
945
|
+
} catch {
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
const parsed = provisionalFileSchema.safeParse(json);
|
|
949
|
+
return parsed.success ? parsed.data : null;
|
|
950
|
+
}
|
|
951
|
+
function removeProvisional(rosterPath) {
|
|
952
|
+
try {
|
|
953
|
+
unlinkSync(provisionalFilePath(rosterPath));
|
|
954
|
+
} catch {}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// src/config.ts
|
|
958
|
+
var managedServerConfigSchema = z3.object({
|
|
959
|
+
command: z3.array(z3.string()).optional(),
|
|
960
|
+
cwd: z3.string().optional(),
|
|
961
|
+
port: z3.number().int().nonnegative().optional()
|
|
962
|
+
});
|
|
963
|
+
var serverConfigSchema = z3.object({
|
|
964
|
+
baseUrl: z3.url().optional(),
|
|
965
|
+
managed: managedServerConfigSchema.optional()
|
|
966
|
+
}).superRefine((val, ctx) => {
|
|
967
|
+
const hasBaseUrl = val.baseUrl !== undefined;
|
|
968
|
+
const hasManaged = val.managed !== undefined;
|
|
969
|
+
if (hasBaseUrl && hasManaged) {
|
|
970
|
+
ctx.addIssue({
|
|
971
|
+
code: "custom",
|
|
972
|
+
message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
|
|
973
|
+
});
|
|
974
|
+
} else if (!hasBaseUrl && !hasManaged) {
|
|
975
|
+
ctx.addIssue({
|
|
976
|
+
code: "custom",
|
|
977
|
+
message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
});
|
|
981
|
+
var manifestSchema = z3.object({
|
|
982
|
+
server: serverConfigSchema,
|
|
983
|
+
projects: z3.array(z3.object({
|
|
984
|
+
name: z3.string(),
|
|
985
|
+
path: z3.string(),
|
|
986
|
+
description: z3.string()
|
|
987
|
+
}))
|
|
988
|
+
});
|
|
989
|
+
function expandHome(path) {
|
|
990
|
+
return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
|
|
991
|
+
}
|
|
992
|
+
function resolveRosterPath(directory) {
|
|
993
|
+
const override = process.env["SPACE_BUS_CONFIG"];
|
|
994
|
+
if (override) {
|
|
995
|
+
if (override.includes("://")) {
|
|
996
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
|
|
997
|
+
}
|
|
998
|
+
const expanded = expandHome(override);
|
|
999
|
+
if (!expanded.startsWith("/")) {
|
|
1000
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
|
|
1001
|
+
}
|
|
1002
|
+
return existsSync(expanded) ? realpathSync(expanded) : expanded;
|
|
1003
|
+
}
|
|
1004
|
+
if (directory) {
|
|
1005
|
+
const candidate = join2(directory, "spacebus.json");
|
|
1006
|
+
return existsSync(candidate) ? realpathSync(candidate) : candidate;
|
|
1007
|
+
}
|
|
1008
|
+
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");
|
|
1009
|
+
}
|
|
1010
|
+
function getRoster(directory) {
|
|
1011
|
+
const manifestPath = resolveRosterPath(directory);
|
|
1012
|
+
let raw;
|
|
1013
|
+
try {
|
|
1014
|
+
raw = readFileSync2(manifestPath, "utf8");
|
|
1015
|
+
} catch (err2) {
|
|
1016
|
+
throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err2.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
|
|
1017
|
+
}
|
|
1018
|
+
let json;
|
|
1019
|
+
try {
|
|
1020
|
+
json = JSON.parse(raw);
|
|
1021
|
+
} catch (err2) {
|
|
1022
|
+
throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err2.message}`);
|
|
1023
|
+
}
|
|
1024
|
+
const parsed = manifestSchema.safeParse(json);
|
|
1025
|
+
if (!parsed.success) {
|
|
1026
|
+
throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
|
|
1027
|
+
}
|
|
1028
|
+
if (parsed.data.server.baseUrl !== undefined) {
|
|
1029
|
+
const url = new URL(parsed.data.server.baseUrl);
|
|
1030
|
+
const hostname = url.hostname;
|
|
1031
|
+
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
1032
|
+
throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
return parsed.data;
|
|
1036
|
+
}
|
|
1037
|
+
function getProjects(manifest) {
|
|
1038
|
+
return manifest.projects.map((p) => {
|
|
1039
|
+
const expandedPath = expandHome(p.path);
|
|
1040
|
+
return { ...p, expandedPath, exists: existsSync(expandedPath) };
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
function getCredentials() {
|
|
1044
|
+
const password = process.env["OPENCODE_SERVER_PASSWORD"];
|
|
1045
|
+
if (!password)
|
|
1046
|
+
return {};
|
|
1047
|
+
const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
|
|
1048
|
+
return { username, password };
|
|
1049
|
+
}
|
|
1050
|
+
function loadContext(directory) {
|
|
1051
|
+
const rosterPath = resolveRosterPath(directory);
|
|
1052
|
+
const manifest = getRoster(directory);
|
|
1053
|
+
const projects = getProjects(manifest);
|
|
1054
|
+
if (manifest.server.baseUrl === undefined) {
|
|
1055
|
+
const live = attachLive(rosterPath);
|
|
1056
|
+
if (!live) {
|
|
1057
|
+
throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
|
|
1058
|
+
}
|
|
1059
|
+
return {
|
|
1060
|
+
roster: { server: { baseUrl: live.baseUrl }, projects },
|
|
1061
|
+
credentials: live.credentials
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
return {
|
|
1065
|
+
roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
|
|
1066
|
+
credentials: getCredentials()
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
function isManagedRoster(directory) {
|
|
1070
|
+
const manifest = getRoster(directory);
|
|
1071
|
+
return manifest.server.managed !== undefined;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/server.ts
|
|
1075
|
+
import { spawn } from "node:child_process";
|
|
1076
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1077
|
+
import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
1078
|
+
import { dirname } from "node:path";
|
|
1079
|
+
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
1080
|
+
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
1081
|
+
var POLL_INTERVAL_MS = 50;
|
|
1082
|
+
var MIN_PROBE_PHASE_MS = 3000;
|
|
1083
|
+
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
1084
|
+
var STOP_GRACE_MS = 2000;
|
|
1085
|
+
function sleep(ms) {
|
|
1086
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1087
|
+
}
|
|
1088
|
+
function readManifest(rosterPath) {
|
|
1089
|
+
const raw = readFileSync3(rosterPath, "utf8");
|
|
1090
|
+
const json = JSON.parse(raw);
|
|
1091
|
+
return manifestSchema.parse(json);
|
|
1092
|
+
}
|
|
1093
|
+
function readLogTail(logPath, maxChars = 4000) {
|
|
1094
|
+
try {
|
|
1095
|
+
const content = readFileSync3(logPath, "utf8");
|
|
1096
|
+
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
1097
|
+
} catch {
|
|
1098
|
+
return "";
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
function basicAuthToken(password) {
|
|
1102
|
+
return Buffer.from(`opencode:${password}`).toString("base64");
|
|
1103
|
+
}
|
|
1104
|
+
function redactSensitive(tail, password) {
|
|
1105
|
+
return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
|
|
1106
|
+
}
|
|
1107
|
+
function redactedReadinessError(rosterPath, password, reason) {
|
|
1108
|
+
const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
|
|
1109
|
+
return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
|
|
1110
|
+
${tail}`);
|
|
1111
|
+
}
|
|
1112
|
+
function killIdentifiedProcess(pid, identity) {
|
|
1113
|
+
try {
|
|
1114
|
+
if (identity !== null && identity !== undefined && identity !== "") {
|
|
1115
|
+
if (verifyIdentity(pid, identity))
|
|
1116
|
+
process.kill(pid, "SIGTERM");
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
process.kill(pid, "SIGTERM");
|
|
1120
|
+
} catch {}
|
|
1121
|
+
}
|
|
1122
|
+
function attachServer(rosterPath) {
|
|
1123
|
+
return attachLive(rosterPath);
|
|
1124
|
+
}
|
|
1125
|
+
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
1126
|
+
const deadline = Date.now() + budgetMs;
|
|
1127
|
+
const lockPath = lockFilePath(rosterPath);
|
|
1128
|
+
while (Date.now() < deadline) {
|
|
1129
|
+
const handle = attachServer(rosterPath);
|
|
1130
|
+
if (handle)
|
|
1131
|
+
return handle;
|
|
1132
|
+
const lockInfo2 = readLockFile(lockPath);
|
|
1133
|
+
const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
|
|
1134
|
+
if (!winnerAlive) {
|
|
1135
|
+
throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
|
|
1136
|
+
}
|
|
1137
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1138
|
+
}
|
|
1139
|
+
const lockInfo = readLockFile(lockPath);
|
|
1140
|
+
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
1141
|
+
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
1142
|
+
}
|
|
1143
|
+
async function probe(baseUrl, password) {
|
|
1144
|
+
try {
|
|
1145
|
+
const res = await fetch(`${baseUrl}/session?limit=1`, {
|
|
1146
|
+
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
1147
|
+
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
1148
|
+
});
|
|
1149
|
+
if (res.status === 200)
|
|
1150
|
+
return "ready";
|
|
1151
|
+
if (res.status === 401 || res.status === 403)
|
|
1152
|
+
return "auth-failure";
|
|
1153
|
+
return "retry";
|
|
1154
|
+
} catch {
|
|
1155
|
+
return "retry";
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
function childDied(child, pid) {
|
|
1159
|
+
return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
|
|
1160
|
+
}
|
|
1161
|
+
async function waitForReadinessLine(logPath, child, pid, deadline) {
|
|
1162
|
+
const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
|
|
1163
|
+
while (Date.now() < deadline) {
|
|
1164
|
+
if (childDied(child, pid))
|
|
1165
|
+
return null;
|
|
1166
|
+
const tail = readLogTail(logPath);
|
|
1167
|
+
const match = readinessLine.exec(tail);
|
|
1168
|
+
if (match?.[1]) {
|
|
1169
|
+
const port = Number.parseInt(match[1], 10);
|
|
1170
|
+
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
1171
|
+
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1175
|
+
}
|
|
1176
|
+
return null;
|
|
1177
|
+
}
|
|
1178
|
+
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
1179
|
+
while (Date.now() < deadline) {
|
|
1180
|
+
if (childDied(child, pid))
|
|
1181
|
+
return "died";
|
|
1182
|
+
const outcome = await probe(baseUrl, password);
|
|
1183
|
+
if (outcome === "ready")
|
|
1184
|
+
return "ready";
|
|
1185
|
+
if (outcome === "auth-failure")
|
|
1186
|
+
return "auth-failure";
|
|
1187
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1188
|
+
}
|
|
1189
|
+
return "timeout";
|
|
1190
|
+
}
|
|
1191
|
+
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
1192
|
+
const deadline = Date.now() + budgetMs;
|
|
1193
|
+
const logPath = logFilePath(rosterPath);
|
|
1194
|
+
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
1195
|
+
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
1196
|
+
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
1197
|
+
if (lineResult === null) {
|
|
1198
|
+
const diedEarly = childDied(child, pid);
|
|
1199
|
+
killIdentifiedProcess(pid, identity);
|
|
1200
|
+
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
1201
|
+
}
|
|
1202
|
+
const { port, baseUrl } = lineResult;
|
|
1203
|
+
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
1204
|
+
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
1205
|
+
if (outcome === "ready")
|
|
1206
|
+
return { port, baseUrl };
|
|
1207
|
+
killIdentifiedProcess(pid, identity);
|
|
1208
|
+
if (outcome === "died") {
|
|
1209
|
+
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
1210
|
+
}
|
|
1211
|
+
if (outcome === "auth-failure") {
|
|
1212
|
+
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
1213
|
+
}
|
|
1214
|
+
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
1215
|
+
}
|
|
1216
|
+
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
1217
|
+
function reapOrphanedProvisional(rosterPath) {
|
|
1218
|
+
const provisional = readProvisional(rosterPath);
|
|
1219
|
+
if (!provisional)
|
|
1220
|
+
return;
|
|
1221
|
+
const discovery = readDiscovery(rosterPath);
|
|
1222
|
+
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1223
|
+
removeProvisional(rosterPath);
|
|
1224
|
+
return;
|
|
1225
|
+
}
|
|
1226
|
+
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
1227
|
+
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
1228
|
+
if (hasIdentity || isFresh) {
|
|
1229
|
+
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
1230
|
+
}
|
|
1231
|
+
removeProvisional(rosterPath);
|
|
1232
|
+
}
|
|
1233
|
+
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
1234
|
+
reapOrphanedProvisional(rosterPath);
|
|
1235
|
+
const password = randomBytes2(32).toString("base64url");
|
|
1236
|
+
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
1237
|
+
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
1238
|
+
const requestedPort = managedConfig.port ?? 0;
|
|
1239
|
+
const logPath = logFilePath(rosterPath);
|
|
1240
|
+
const logFd = openSync2(logPath, "w", 384);
|
|
1241
|
+
let child;
|
|
1242
|
+
let pid;
|
|
1243
|
+
let spawnError;
|
|
1244
|
+
try {
|
|
1245
|
+
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
1246
|
+
cwd,
|
|
1247
|
+
detached: true,
|
|
1248
|
+
stdio: ["ignore", logFd, logFd],
|
|
1249
|
+
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
1250
|
+
});
|
|
1251
|
+
child.on("error", (err2) => {
|
|
1252
|
+
spawnError = err2;
|
|
1253
|
+
});
|
|
1254
|
+
child.unref();
|
|
1255
|
+
pid = child.pid;
|
|
1256
|
+
} finally {
|
|
1257
|
+
closeQuietly(logFd);
|
|
1258
|
+
}
|
|
1259
|
+
if (pid === undefined) {
|
|
1260
|
+
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
1261
|
+
}
|
|
1262
|
+
const identity = captureIdentity(pid);
|
|
1263
|
+
writeProvisional(rosterPath, {
|
|
1264
|
+
pid,
|
|
1265
|
+
identity: identity ?? "",
|
|
1266
|
+
password,
|
|
1267
|
+
since: Date.now()
|
|
1268
|
+
});
|
|
1269
|
+
let port;
|
|
1270
|
+
let baseUrl;
|
|
1271
|
+
try {
|
|
1272
|
+
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
1273
|
+
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
1274
|
+
const check = setInterval(() => {
|
|
1275
|
+
if (spawnError) {
|
|
1276
|
+
clearInterval(check);
|
|
1277
|
+
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
1278
|
+
}
|
|
1279
|
+
}, POLL_INTERVAL_MS);
|
|
1280
|
+
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
1281
|
+
});
|
|
1282
|
+
const result2 = await Promise.race([readiness, spawnErrorWatch]);
|
|
1283
|
+
port = result2.port;
|
|
1284
|
+
baseUrl = result2.baseUrl;
|
|
1285
|
+
} finally {
|
|
1286
|
+
removeProvisional(rosterPath);
|
|
1287
|
+
}
|
|
1288
|
+
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
1289
|
+
writeDiscovery(rosterPath, {
|
|
1290
|
+
port,
|
|
1291
|
+
pid,
|
|
1292
|
+
identity: finalIdentity,
|
|
1293
|
+
password,
|
|
1294
|
+
spawnConfig: { command, cwd, port: requestedPort },
|
|
1295
|
+
baseUrl
|
|
1296
|
+
});
|
|
1297
|
+
return {
|
|
1298
|
+
baseUrl,
|
|
1299
|
+
credentials: { username: "opencode", password },
|
|
1300
|
+
pid,
|
|
1301
|
+
port
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
async function ensureServer(rosterPath, options = {}) {
|
|
1305
|
+
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
1306
|
+
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
1307
|
+
const fastPath = attachServer(rosterPath);
|
|
1308
|
+
if (fastPath)
|
|
1309
|
+
return fastPath;
|
|
1310
|
+
const manifest = readManifest(rosterPath);
|
|
1311
|
+
if (manifest.server.managed === undefined) {
|
|
1312
|
+
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
1313
|
+
}
|
|
1314
|
+
const lock = acquireLock(rosterPath);
|
|
1315
|
+
if (lock === null) {
|
|
1316
|
+
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
1317
|
+
}
|
|
1318
|
+
try {
|
|
1319
|
+
const attached = attachServer(rosterPath);
|
|
1320
|
+
if (attached)
|
|
1321
|
+
return attached;
|
|
1322
|
+
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
1323
|
+
} finally {
|
|
1324
|
+
releaseLock(lock);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
function serverStatus(rosterPath) {
|
|
1328
|
+
const discovery = readDiscovery(rosterPath);
|
|
1329
|
+
if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1330
|
+
return { running: false };
|
|
1331
|
+
}
|
|
1332
|
+
let configDrift;
|
|
1333
|
+
try {
|
|
1334
|
+
const manifest = readManifest(rosterPath);
|
|
1335
|
+
if (manifest.server.managed) {
|
|
1336
|
+
const current = manifest.server.managed;
|
|
1337
|
+
const currentCommand = current.command ?? ["harness", "serve"];
|
|
1338
|
+
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
1339
|
+
const currentPort = current.port ?? 0;
|
|
1340
|
+
const storedCommand = discovery.spawnConfig.command ?? [
|
|
1341
|
+
"harness",
|
|
1342
|
+
"serve"
|
|
1343
|
+
];
|
|
1344
|
+
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
1345
|
+
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
1346
|
+
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
1347
|
+
}
|
|
1348
|
+
} catch {}
|
|
1349
|
+
return {
|
|
1350
|
+
running: true,
|
|
1351
|
+
port: discovery.port,
|
|
1352
|
+
pid: discovery.pid,
|
|
1353
|
+
configDrift
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
async function stopServer(rosterPath) {
|
|
1357
|
+
const discovery = readDiscovery(rosterPath);
|
|
1358
|
+
if (!discovery)
|
|
1359
|
+
return { stopped: false };
|
|
1360
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1361
|
+
removeDiscovery(rosterPath);
|
|
1362
|
+
return { stopped: false };
|
|
1363
|
+
}
|
|
1364
|
+
const { pid } = discovery;
|
|
1365
|
+
try {
|
|
1366
|
+
process.kill(pid, "SIGTERM");
|
|
1367
|
+
} catch {
|
|
1368
|
+
removeDiscovery(rosterPath);
|
|
1369
|
+
return { stopped: true };
|
|
1370
|
+
}
|
|
1371
|
+
if (await waitForDeath(pid, STOP_GRACE_MS)) {
|
|
1372
|
+
removeDiscovery(rosterPath);
|
|
1373
|
+
return { stopped: true };
|
|
1374
|
+
}
|
|
1375
|
+
try {
|
|
1376
|
+
process.kill(pid, "SIGKILL");
|
|
1377
|
+
} catch {
|
|
1378
|
+
removeDiscovery(rosterPath);
|
|
1379
|
+
return { stopped: true };
|
|
1380
|
+
}
|
|
1381
|
+
if (await waitForDeath(pid, STOP_GRACE_MS)) {
|
|
1382
|
+
removeDiscovery(rosterPath);
|
|
1383
|
+
return { stopped: true };
|
|
1384
|
+
}
|
|
1385
|
+
return { stopped: false };
|
|
1386
|
+
}
|
|
1387
|
+
async function waitForDeath(pid, budgetMs) {
|
|
1388
|
+
const deadline = Date.now() + budgetMs;
|
|
1389
|
+
while (Date.now() < deadline) {
|
|
1390
|
+
if (!isAlive(pid))
|
|
1391
|
+
return true;
|
|
1392
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1393
|
+
}
|
|
1394
|
+
return !isAlive(pid);
|
|
1395
|
+
}
|
|
1396
|
+
|
|
746
1397
|
// src/mcp.ts
|
|
747
1398
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
748
1399
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
749
|
-
import { z as
|
|
1400
|
+
import { z as z4 } from "zod";
|
|
750
1401
|
|
|
751
1402
|
// src/tools/bus_result.ts
|
|
752
1403
|
import { tool } from "@opencode-ai/plugin";
|
|
1404
|
+
|
|
1405
|
+
// src/tools/shared.ts
|
|
1406
|
+
async function ensureAndLoadContext(directory) {
|
|
1407
|
+
if (isManagedRoster(directory)) {
|
|
1408
|
+
const rosterPath = resolveRosterPath(directory);
|
|
1409
|
+
await ensureServer(rosterPath);
|
|
1410
|
+
}
|
|
1411
|
+
return loadContext(directory);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// src/tools/bus_result.ts
|
|
753
1415
|
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.";
|
|
754
1416
|
function makeBusResult(defaultDirectory) {
|
|
755
1417
|
return tool({
|
|
@@ -761,7 +1423,7 @@ function makeBusResult(defaultDirectory) {
|
|
|
761
1423
|
const directory = ctx.directory ?? defaultDirectory;
|
|
762
1424
|
let context;
|
|
763
1425
|
try {
|
|
764
|
-
context =
|
|
1426
|
+
context = await ensureAndLoadContext(directory);
|
|
765
1427
|
} catch (e) {
|
|
766
1428
|
throw new Error(e.message);
|
|
767
1429
|
}
|
|
@@ -784,7 +1446,7 @@ function makeBusRoster(defaultDirectory) {
|
|
|
784
1446
|
const directory = ctx.directory ?? defaultDirectory;
|
|
785
1447
|
let context;
|
|
786
1448
|
try {
|
|
787
|
-
context =
|
|
1449
|
+
context = await ensureAndLoadContext(directory);
|
|
788
1450
|
} catch (e) {
|
|
789
1451
|
throw new Error(e.message);
|
|
790
1452
|
}
|
|
@@ -809,7 +1471,7 @@ function makeBusStatus(defaultDirectory) {
|
|
|
809
1471
|
const directory = ctx.directory ?? defaultDirectory;
|
|
810
1472
|
let context;
|
|
811
1473
|
try {
|
|
812
|
-
context =
|
|
1474
|
+
context = await ensureAndLoadContext(directory);
|
|
813
1475
|
} catch (e) {
|
|
814
1476
|
throw new Error(e.message);
|
|
815
1477
|
}
|
|
@@ -840,7 +1502,7 @@ function makeBusTask(defaultDirectory) {
|
|
|
840
1502
|
const directory = ctx.directory ?? defaultDirectory;
|
|
841
1503
|
let context;
|
|
842
1504
|
try {
|
|
843
|
-
context =
|
|
1505
|
+
context = await ensureAndLoadContext(directory);
|
|
844
1506
|
} catch (e) {
|
|
845
1507
|
throw new Error(e.message);
|
|
846
1508
|
}
|
|
@@ -853,7 +1515,14 @@ function makeBusTask(defaultDirectory) {
|
|
|
853
1515
|
}
|
|
854
1516
|
|
|
855
1517
|
// src/mcp.ts
|
|
856
|
-
|
|
1518
|
+
async function mcpLoadContext() {
|
|
1519
|
+
if (process.env["SPACE_BUS_MCP_SPAWN"] && isManagedRoster()) {
|
|
1520
|
+
const rosterPath = resolveRosterPath();
|
|
1521
|
+
await ensureServer(rosterPath);
|
|
1522
|
+
}
|
|
1523
|
+
return loadContext();
|
|
1524
|
+
}
|
|
1525
|
+
var version = "0.6.0";
|
|
857
1526
|
var server = new McpServer({
|
|
858
1527
|
name: "space-bus",
|
|
859
1528
|
version
|
|
@@ -864,7 +1533,7 @@ server.registerTool("bus_roster", {
|
|
|
864
1533
|
}, async () => {
|
|
865
1534
|
let context;
|
|
866
1535
|
try {
|
|
867
|
-
context =
|
|
1536
|
+
context = await mcpLoadContext();
|
|
868
1537
|
} catch (e) {
|
|
869
1538
|
return {
|
|
870
1539
|
content: [{ type: "text", text: e.message }],
|
|
@@ -879,15 +1548,15 @@ server.registerTool("bus_roster", {
|
|
|
879
1548
|
server.registerTool("bus_task", {
|
|
880
1549
|
description: BUS_TASK_DESCRIPTION,
|
|
881
1550
|
inputSchema: {
|
|
882
|
-
project:
|
|
883
|
-
prompt:
|
|
884
|
-
title:
|
|
885
|
-
sessionId:
|
|
1551
|
+
project: z4.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
|
|
1552
|
+
prompt: z4.string().describe("The prompt to send to the delegated agent"),
|
|
1553
|
+
title: z4.string().optional().describe("Optional session title (only used when starting a new session)"),
|
|
1554
|
+
sessionId: z4.string().optional().describe("Existing session ID to steer instead of starting a new session")
|
|
886
1555
|
},
|
|
887
1556
|
outputSchema: {
|
|
888
|
-
sessionId:
|
|
889
|
-
project:
|
|
890
|
-
mode:
|
|
1557
|
+
sessionId: z4.string().describe("The dispatched or steered session ID"),
|
|
1558
|
+
project: z4.string().describe("Manifest project name that owns the session"),
|
|
1559
|
+
mode: z4.enum(["new", "question-reply", "follow-up"]).describe("How the prompt was delivered")
|
|
891
1560
|
}
|
|
892
1561
|
}, async (args) => {
|
|
893
1562
|
const dispatchArgs = toDispatchArgs(args);
|
|
@@ -898,7 +1567,7 @@ server.registerTool("bus_task", {
|
|
|
898
1567
|
};
|
|
899
1568
|
let context;
|
|
900
1569
|
try {
|
|
901
|
-
context =
|
|
1570
|
+
context = await mcpLoadContext();
|
|
902
1571
|
} catch (e) {
|
|
903
1572
|
return {
|
|
904
1573
|
content: [{ type: "text", text: e.message }],
|
|
@@ -916,12 +1585,12 @@ server.registerTool("bus_task", {
|
|
|
916
1585
|
server.registerTool("bus_status", {
|
|
917
1586
|
description: BUS_STATUS_DESCRIPTION,
|
|
918
1587
|
inputSchema: {
|
|
919
|
-
sessionId:
|
|
1588
|
+
sessionId: z4.string().describe("Session ID returned by bus_task")
|
|
920
1589
|
}
|
|
921
1590
|
}, async (args) => {
|
|
922
1591
|
let context;
|
|
923
1592
|
try {
|
|
924
|
-
context =
|
|
1593
|
+
context = await mcpLoadContext();
|
|
925
1594
|
} catch (e) {
|
|
926
1595
|
return {
|
|
927
1596
|
content: [{ type: "text", text: e.message }],
|
|
@@ -936,12 +1605,12 @@ server.registerTool("bus_status", {
|
|
|
936
1605
|
server.registerTool("bus_result", {
|
|
937
1606
|
description: BUS_RESULT_DESCRIPTION,
|
|
938
1607
|
inputSchema: {
|
|
939
|
-
sessionId:
|
|
1608
|
+
sessionId: z4.string().describe("Session ID returned by bus_task")
|
|
940
1609
|
}
|
|
941
1610
|
}, async (args) => {
|
|
942
1611
|
let context;
|
|
943
1612
|
try {
|
|
944
|
-
context =
|
|
1613
|
+
context = await mcpLoadContext();
|
|
945
1614
|
} catch (e) {
|
|
946
1615
|
return {
|
|
947
1616
|
content: [{ type: "text", text: e.message }],
|