@fro.bot/space-bus 0.0.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/LICENSE +20 -0
- package/README.md +94 -0
- package/dist/config.d.ts +64 -0
- package/dist/core.d.ts +81 -0
- package/dist/format.d.ts +5 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +670 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +719 -0
- package/dist/tools/bus_result.d.ts +3 -0
- package/dist/tools/bus_roster.d.ts +3 -0
- package/dist/tools/bus_status.d.ts +3 -0
- package/dist/tools/bus_task.d.ts +3 -0
- package/package.json +56 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
// src/tools/bus_result.ts
|
|
2
|
+
import { tool } from "@opencode-ai/plugin";
|
|
3
|
+
|
|
4
|
+
// src/core.ts
|
|
5
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
6
|
+
import { z as z2 } from "zod";
|
|
7
|
+
|
|
8
|
+
// src/config.ts
|
|
9
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
var manifestSchema = z.object({
|
|
14
|
+
server: z.object({ baseUrl: z.string().url() }),
|
|
15
|
+
projects: z.array(z.object({
|
|
16
|
+
name: z.string(),
|
|
17
|
+
path: z.string(),
|
|
18
|
+
description: z.string()
|
|
19
|
+
}))
|
|
20
|
+
});
|
|
21
|
+
function expandHome(path) {
|
|
22
|
+
return path.startsWith("~") ? join(homedir(), path.slice(1)) : path;
|
|
23
|
+
}
|
|
24
|
+
function resolveRosterPath(directory) {
|
|
25
|
+
const override = process.env["SPACE_BUS_CONFIG"];
|
|
26
|
+
if (override) {
|
|
27
|
+
if (override.includes("://")) {
|
|
28
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
|
|
29
|
+
}
|
|
30
|
+
const expanded = expandHome(override);
|
|
31
|
+
if (!expanded.startsWith("/")) {
|
|
32
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
|
|
33
|
+
}
|
|
34
|
+
return existsSync(expanded) ? realpathSync(expanded) : expanded;
|
|
35
|
+
}
|
|
36
|
+
if (directory) {
|
|
37
|
+
const candidate = join(directory, "spacebus.json");
|
|
38
|
+
return existsSync(candidate) ? realpathSync(candidate) : candidate;
|
|
39
|
+
}
|
|
40
|
+
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");
|
|
41
|
+
}
|
|
42
|
+
function getRoster(directory) {
|
|
43
|
+
const manifestPath = resolveRosterPath(directory);
|
|
44
|
+
let raw;
|
|
45
|
+
try {
|
|
46
|
+
raw = readFileSync(manifestPath, "utf8");
|
|
47
|
+
} catch (err) {
|
|
48
|
+
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)`);
|
|
49
|
+
}
|
|
50
|
+
let json;
|
|
51
|
+
try {
|
|
52
|
+
json = JSON.parse(raw);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
|
|
55
|
+
}
|
|
56
|
+
const parsed = manifestSchema.safeParse(json);
|
|
57
|
+
if (!parsed.success) {
|
|
58
|
+
throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
|
|
59
|
+
}
|
|
60
|
+
const url = new URL(parsed.data.server.baseUrl);
|
|
61
|
+
const hostname = url.hostname;
|
|
62
|
+
const allowedHosts = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
|
|
63
|
+
if (!allowedHosts.has(hostname)) {
|
|
64
|
+
throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
65
|
+
}
|
|
66
|
+
return parsed.data;
|
|
67
|
+
}
|
|
68
|
+
function getProjects(manifest) {
|
|
69
|
+
return manifest.projects.map((p) => ({
|
|
70
|
+
...p,
|
|
71
|
+
expandedPath: expandHome(p.path)
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/core.ts
|
|
76
|
+
function findProject(projects, name) {
|
|
77
|
+
return projects.find((p) => p.name === name);
|
|
78
|
+
}
|
|
79
|
+
function err(error) {
|
|
80
|
+
return { ok: false, error };
|
|
81
|
+
}
|
|
82
|
+
function authHeader() {
|
|
83
|
+
const password = process.env["OPENCODE_SERVER_PASSWORD"];
|
|
84
|
+
if (!password)
|
|
85
|
+
return {};
|
|
86
|
+
const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
|
|
87
|
+
const token = Buffer.from(`${username}:${password}`).toString("base64");
|
|
88
|
+
return { Authorization: `Basic ${token}` };
|
|
89
|
+
}
|
|
90
|
+
async function api(baseUrl, directory, path, init) {
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(`${baseUrl}${path}`, {
|
|
93
|
+
...init,
|
|
94
|
+
headers: {
|
|
95
|
+
"content-type": "application/json",
|
|
96
|
+
"x-opencode-directory": directory,
|
|
97
|
+
...authHeader(),
|
|
98
|
+
...init?.headers
|
|
99
|
+
},
|
|
100
|
+
redirect: "error",
|
|
101
|
+
signal: AbortSignal.timeout(30000)
|
|
102
|
+
});
|
|
103
|
+
const bodyText = await res.text().catch(() => "<unreadable body>");
|
|
104
|
+
return { res, bodyText };
|
|
105
|
+
} catch (e) {
|
|
106
|
+
const message = e.message;
|
|
107
|
+
return {
|
|
108
|
+
res: new Response(null, {
|
|
109
|
+
status: 599,
|
|
110
|
+
statusText: "space-bus: request failed"
|
|
111
|
+
}),
|
|
112
|
+
bodyText: `space-bus: request failed: ${message}`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
var sessionSchema = z2.object({
|
|
117
|
+
id: z2.string(),
|
|
118
|
+
directory: z2.string().optional(),
|
|
119
|
+
title: z2.string().optional()
|
|
120
|
+
}).passthrough();
|
|
121
|
+
var sessionListSchema = z2.array(sessionSchema);
|
|
122
|
+
var sessionStatusMapSchema = z2.record(z2.string(), z2.object({ type: z2.string() }).passthrough());
|
|
123
|
+
var todoSchema = z2.array(z2.object({ content: z2.string(), status: z2.string(), priority: z2.string() }).passthrough()).default([]);
|
|
124
|
+
var diffEntrySchema = z2.object({
|
|
125
|
+
file: z2.string().optional(),
|
|
126
|
+
additions: z2.number(),
|
|
127
|
+
deletions: z2.number(),
|
|
128
|
+
status: z2.string().optional()
|
|
129
|
+
}).passthrough();
|
|
130
|
+
var diffSchema = z2.array(diffEntrySchema).default([]);
|
|
131
|
+
var vcsStatusEntrySchema = z2.object({
|
|
132
|
+
file: z2.string(),
|
|
133
|
+
additions: z2.number(),
|
|
134
|
+
deletions: z2.number(),
|
|
135
|
+
status: z2.string().optional()
|
|
136
|
+
}).passthrough();
|
|
137
|
+
var vcsStatusSchema = z2.array(vcsStatusEntrySchema).default([]);
|
|
138
|
+
var turnDiffEntrySchema = diffEntrySchema;
|
|
139
|
+
var turnMessageSchema = z2.object({
|
|
140
|
+
info: z2.object({
|
|
141
|
+
role: z2.string(),
|
|
142
|
+
summary: z2.object({
|
|
143
|
+
diffs: z2.array(turnDiffEntrySchema).optional()
|
|
144
|
+
}).passthrough().optional()
|
|
145
|
+
}).passthrough()
|
|
146
|
+
}).passthrough();
|
|
147
|
+
var turnMessageListSchema = z2.array(turnMessageSchema);
|
|
148
|
+
var sessionSummarySchema = z2.object({
|
|
149
|
+
summary: z2.object({
|
|
150
|
+
diffs: z2.array(turnDiffEntrySchema).optional()
|
|
151
|
+
}).passthrough().optional()
|
|
152
|
+
}).passthrough();
|
|
153
|
+
async function fetchTurnDiffs(baseUrl, directory, sessionId) {
|
|
154
|
+
const { res, bodyText } = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
|
|
155
|
+
if (!res.ok)
|
|
156
|
+
return [];
|
|
157
|
+
let messages;
|
|
158
|
+
try {
|
|
159
|
+
messages = turnMessageListSchema.parse(JSON.parse(bodyText));
|
|
160
|
+
} catch {
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
const byFile = new Map;
|
|
164
|
+
for (const m of messages) {
|
|
165
|
+
if (m.info.role !== "user")
|
|
166
|
+
continue;
|
|
167
|
+
const diffs = m.info.summary?.diffs;
|
|
168
|
+
if (!diffs || diffs.length === 0)
|
|
169
|
+
continue;
|
|
170
|
+
for (const d of diffs) {
|
|
171
|
+
const key = d.file ?? `<unknown:${byFile.size}>`;
|
|
172
|
+
byFile.set(key, d);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return Array.from(byFile.values());
|
|
176
|
+
}
|
|
177
|
+
async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
|
|
178
|
+
const diffRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
|
|
179
|
+
let diff = [];
|
|
180
|
+
try {
|
|
181
|
+
diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
|
|
182
|
+
} catch {
|
|
183
|
+
diff = [];
|
|
184
|
+
}
|
|
185
|
+
if (diff.length > 0) {
|
|
186
|
+
return { diff, diffSource: "session" };
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const sessionRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`);
|
|
190
|
+
if (sessionRes.res.ok) {
|
|
191
|
+
const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
|
|
192
|
+
const summaryDiffs = parsed.summary?.diffs;
|
|
193
|
+
if (summaryDiffs && summaryDiffs.length > 0) {
|
|
194
|
+
return { diff: summaryDiffs, diffSource: "session" };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} catch {}
|
|
198
|
+
try {
|
|
199
|
+
const turnDiffs = await fetchTurnDiffs(baseUrl, directory, sessionId);
|
|
200
|
+
if (turnDiffs.length > 0) {
|
|
201
|
+
return { diff: turnDiffs, diffSource: "turns" };
|
|
202
|
+
}
|
|
203
|
+
} catch {}
|
|
204
|
+
try {
|
|
205
|
+
const vcsRes = await api(baseUrl, directory, "/vcs/status");
|
|
206
|
+
if (vcsRes.res.ok) {
|
|
207
|
+
const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
|
|
208
|
+
if (vcsStatus.length > 0) {
|
|
209
|
+
return {
|
|
210
|
+
diff: vcsStatus.map((v) => ({
|
|
211
|
+
file: v.file,
|
|
212
|
+
additions: v.additions,
|
|
213
|
+
deletions: v.deletions,
|
|
214
|
+
status: v.status
|
|
215
|
+
})),
|
|
216
|
+
diffSource: "working-tree"
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
} catch {}
|
|
221
|
+
return { diff, diffSource: "session" };
|
|
222
|
+
}
|
|
223
|
+
var messagePartSchema = z2.object({ type: z2.string(), text: z2.string().optional() }).passthrough();
|
|
224
|
+
var messageEnvelopeSchema = z2.object({
|
|
225
|
+
info: z2.object({ role: z2.string() }).passthrough(),
|
|
226
|
+
parts: z2.array(messagePartSchema)
|
|
227
|
+
}).passthrough();
|
|
228
|
+
var messageListSchema = z2.array(messageEnvelopeSchema);
|
|
229
|
+
function resolveContext(directory) {
|
|
230
|
+
try {
|
|
231
|
+
const manifest = getRoster(directory);
|
|
232
|
+
const projects = getProjects(manifest);
|
|
233
|
+
return { ok: true, baseUrl: manifest.server.baseUrl, projects };
|
|
234
|
+
} catch (e) {
|
|
235
|
+
return err(e.message);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function resolveProjectOrErr(projects, name) {
|
|
239
|
+
const project = findProject(projects, name);
|
|
240
|
+
if (!project) {
|
|
241
|
+
const valid = projects.map((p) => p.name).join(", ");
|
|
242
|
+
return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
|
|
243
|
+
}
|
|
244
|
+
if (!existsSync2(project.expandedPath)) {
|
|
245
|
+
return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
|
|
246
|
+
}
|
|
247
|
+
return { ok: true, project };
|
|
248
|
+
}
|
|
249
|
+
async function roster(opts) {
|
|
250
|
+
const ctx = resolveContext(opts?.directory);
|
|
251
|
+
if (!ctx.ok)
|
|
252
|
+
return ctx;
|
|
253
|
+
const { baseUrl, projects } = ctx;
|
|
254
|
+
const results = await Promise.all(projects.map(async (p) => {
|
|
255
|
+
const pathExists = existsSync2(p.expandedPath);
|
|
256
|
+
if (!pathExists) {
|
|
257
|
+
return {
|
|
258
|
+
name: p.name,
|
|
259
|
+
path: p.expandedPath,
|
|
260
|
+
description: p.description,
|
|
261
|
+
pathExists: false
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const [statusRes, listRes] = await Promise.all([
|
|
266
|
+
api(baseUrl, p.expandedPath, "/session/status"),
|
|
267
|
+
api(baseUrl, p.expandedPath, "/session?limit=101")
|
|
268
|
+
]);
|
|
269
|
+
if (!statusRes.res.ok || !listRes.res.ok) {
|
|
270
|
+
return {
|
|
271
|
+
name: p.name,
|
|
272
|
+
path: p.expandedPath,
|
|
273
|
+
description: p.description,
|
|
274
|
+
pathExists: true,
|
|
275
|
+
statusError: `status=${statusRes.res.status}/${listRes.res.status}`
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
279
|
+
const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
|
|
280
|
+
const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
|
|
281
|
+
const capped = sessions.length > 100;
|
|
282
|
+
return {
|
|
283
|
+
name: p.name,
|
|
284
|
+
path: p.expandedPath,
|
|
285
|
+
description: p.description,
|
|
286
|
+
pathExists: true,
|
|
287
|
+
busyCount,
|
|
288
|
+
sessionCount: capped ? 100 : sessions.length,
|
|
289
|
+
sessionCountCapped: capped
|
|
290
|
+
};
|
|
291
|
+
} catch (e) {
|
|
292
|
+
return {
|
|
293
|
+
name: p.name,
|
|
294
|
+
path: p.expandedPath,
|
|
295
|
+
description: p.description,
|
|
296
|
+
pathExists: true,
|
|
297
|
+
statusError: e.message
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
}));
|
|
301
|
+
return { ok: true, projects: results };
|
|
302
|
+
}
|
|
303
|
+
async function dispatchNew(baseUrl, projects, project, prompt, title) {
|
|
304
|
+
const resolved = resolveProjectOrErr(projects, project);
|
|
305
|
+
if (!resolved.ok)
|
|
306
|
+
return resolved;
|
|
307
|
+
const directory = resolved.project.expandedPath;
|
|
308
|
+
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
309
|
+
const createRes = await api(baseUrl, directory, "/session", {
|
|
310
|
+
method: "POST",
|
|
311
|
+
body: JSON.stringify({ title: sessionTitle })
|
|
312
|
+
});
|
|
313
|
+
if (!createRes.res.ok) {
|
|
314
|
+
return err(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`);
|
|
315
|
+
}
|
|
316
|
+
let session;
|
|
317
|
+
try {
|
|
318
|
+
session = sessionSchema.parse(JSON.parse(createRes.bodyText));
|
|
319
|
+
} catch (e) {
|
|
320
|
+
return err(`space-bus: unexpected /session response shape: ${e.message}`);
|
|
321
|
+
}
|
|
322
|
+
const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
|
|
325
|
+
});
|
|
326
|
+
if (promptRes.res.status !== 204) {
|
|
327
|
+
return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
328
|
+
}
|
|
329
|
+
return { ok: true, sessionId: session.id, project, directory };
|
|
330
|
+
}
|
|
331
|
+
async function dispatch(args) {
|
|
332
|
+
const ctx = resolveContext(args.directory);
|
|
333
|
+
if (!ctx.ok)
|
|
334
|
+
return ctx;
|
|
335
|
+
const { baseUrl, projects } = ctx;
|
|
336
|
+
if (!args.sessionId) {
|
|
337
|
+
if (!args.project) {
|
|
338
|
+
return err("space-bus: project is required when starting a new session");
|
|
339
|
+
}
|
|
340
|
+
const r = await dispatchNew(baseUrl, projects, args.project, args.prompt, args.title);
|
|
341
|
+
if (!r.ok)
|
|
342
|
+
return r;
|
|
343
|
+
return {
|
|
344
|
+
ok: true,
|
|
345
|
+
sessionId: r.sessionId,
|
|
346
|
+
project: r.project,
|
|
347
|
+
mode: "new",
|
|
348
|
+
directory: r.directory
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
const loc = await findSessionDirectory(baseUrl, projects, args.sessionId);
|
|
352
|
+
if (!loc.ok)
|
|
353
|
+
return loc;
|
|
354
|
+
const { directory, project } = loc;
|
|
355
|
+
if (args.project && args.project !== project) {
|
|
356
|
+
return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
|
|
357
|
+
}
|
|
358
|
+
return steerSession(baseUrl, args.sessionId, args.prompt, directory, project);
|
|
359
|
+
}
|
|
360
|
+
async function findSessionDirectory(baseUrl, projects, sessionId) {
|
|
361
|
+
for (const p of projects) {
|
|
362
|
+
if (!existsSync2(p.expandedPath))
|
|
363
|
+
continue;
|
|
364
|
+
const { res, bodyText } = await api(baseUrl, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
|
|
365
|
+
if (!res.ok)
|
|
366
|
+
continue;
|
|
367
|
+
let session;
|
|
368
|
+
try {
|
|
369
|
+
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
370
|
+
} catch {
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
374
|
+
if (owner) {
|
|
375
|
+
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
376
|
+
}
|
|
377
|
+
return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
|
|
378
|
+
}
|
|
379
|
+
return err(`space-bus: no manifest project has a session with id ${sessionId}`);
|
|
380
|
+
}
|
|
381
|
+
var pendingQuestionEntrySchema = z2.object({
|
|
382
|
+
id: z2.string(),
|
|
383
|
+
sessionID: z2.string(),
|
|
384
|
+
questions: z2.array(z2.object({
|
|
385
|
+
question: z2.string().optional(),
|
|
386
|
+
options: z2.array(z2.object({ label: z2.string().optional() }).passthrough()).optional()
|
|
387
|
+
}).passthrough()).optional()
|
|
388
|
+
}).passthrough();
|
|
389
|
+
var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
|
|
390
|
+
async function fetchPendingQuestion(baseUrl, directory, sessionId) {
|
|
391
|
+
try {
|
|
392
|
+
const { res, bodyText } = await api(baseUrl, directory, "/question");
|
|
393
|
+
if (!res.ok)
|
|
394
|
+
return;
|
|
395
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
|
|
396
|
+
const entry = entries.find((e) => e.sessionID === sessionId);
|
|
397
|
+
if (!entry)
|
|
398
|
+
return;
|
|
399
|
+
const firstQuestion = entry.questions?.[0];
|
|
400
|
+
const text = firstQuestion?.question ?? "";
|
|
401
|
+
const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
|
|
402
|
+
const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
|
|
403
|
+
return { preview, options };
|
|
404
|
+
} catch {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
async function status(sessionId, opts) {
|
|
409
|
+
const ctx = resolveContext(opts?.directory);
|
|
410
|
+
if (!ctx.ok)
|
|
411
|
+
return ctx;
|
|
412
|
+
const { baseUrl, projects } = ctx;
|
|
413
|
+
const loc = await findSessionDirectory(baseUrl, projects, sessionId);
|
|
414
|
+
if (!loc.ok)
|
|
415
|
+
return loc;
|
|
416
|
+
const { directory, project } = loc;
|
|
417
|
+
const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
|
|
418
|
+
api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`),
|
|
419
|
+
api(baseUrl, directory, "/session/status"),
|
|
420
|
+
api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
|
|
421
|
+
fetchDiffWithFallback(baseUrl, directory, sessionId),
|
|
422
|
+
fetchPendingQuestion(baseUrl, directory, sessionId)
|
|
423
|
+
]);
|
|
424
|
+
if (!sessionRes.res.ok) {
|
|
425
|
+
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
426
|
+
}
|
|
427
|
+
let session;
|
|
428
|
+
let statusMap;
|
|
429
|
+
let todos;
|
|
430
|
+
try {
|
|
431
|
+
session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
|
|
432
|
+
statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
|
|
433
|
+
todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
|
|
434
|
+
} catch (e) {
|
|
435
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
436
|
+
}
|
|
437
|
+
const entry = statusMap[sessionId];
|
|
438
|
+
const busy = entry ? entry.type === "busy" || entry.type === "retry" : false;
|
|
439
|
+
const { diff, diffSource } = diffResult;
|
|
440
|
+
const additions = diff.reduce((sum, d) => sum + d.additions, 0);
|
|
441
|
+
const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
|
|
442
|
+
return {
|
|
443
|
+
ok: true,
|
|
444
|
+
sessionId,
|
|
445
|
+
project,
|
|
446
|
+
busy,
|
|
447
|
+
title: session.title,
|
|
448
|
+
todos,
|
|
449
|
+
diff: { files: diff.length, additions, deletions },
|
|
450
|
+
diffSource,
|
|
451
|
+
pendingQuestion
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
var questionEntrySchema = z2.object({ id: z2.string(), sessionID: z2.string() }).passthrough();
|
|
455
|
+
var questionListSchema = z2.array(questionEntrySchema);
|
|
456
|
+
async function steerSession(baseUrl, sessionId, message, directory, project) {
|
|
457
|
+
const questionsRes = await api(baseUrl, directory, "/question");
|
|
458
|
+
if (questionsRes.res.ok) {
|
|
459
|
+
let questions;
|
|
460
|
+
try {
|
|
461
|
+
questions = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
|
|
462
|
+
} catch {
|
|
463
|
+
questions = [];
|
|
464
|
+
}
|
|
465
|
+
const pending = questions.find((q) => q.sessionID === sessionId);
|
|
466
|
+
if (pending) {
|
|
467
|
+
const replyRes = await api(baseUrl, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
|
|
468
|
+
method: "POST",
|
|
469
|
+
body: JSON.stringify({ answers: [[message]] })
|
|
470
|
+
});
|
|
471
|
+
if (!replyRes.res.ok) {
|
|
472
|
+
return err(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`);
|
|
473
|
+
}
|
|
474
|
+
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
478
|
+
method: "POST",
|
|
479
|
+
body: JSON.stringify({ parts: [{ type: "text", text: message }] })
|
|
480
|
+
});
|
|
481
|
+
if (promptRes.res.status !== 204) {
|
|
482
|
+
return err(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
483
|
+
}
|
|
484
|
+
return { ok: true, sessionId, project, mode: "follow-up" };
|
|
485
|
+
}
|
|
486
|
+
async function result(sessionId, opts) {
|
|
487
|
+
const ctx = resolveContext(opts?.directory);
|
|
488
|
+
if (!ctx.ok)
|
|
489
|
+
return ctx;
|
|
490
|
+
const { baseUrl, projects } = ctx;
|
|
491
|
+
const loc = await findSessionDirectory(baseUrl, projects, sessionId);
|
|
492
|
+
if (!loc.ok)
|
|
493
|
+
return loc;
|
|
494
|
+
const { directory, project } = loc;
|
|
495
|
+
const statusMapRes = await api(baseUrl, directory, "/session/status");
|
|
496
|
+
if (statusMapRes.res.ok) {
|
|
497
|
+
try {
|
|
498
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
499
|
+
const entry = statusMap[sessionId];
|
|
500
|
+
if (entry && (entry.type === "busy" || entry.type === "retry")) {
|
|
501
|
+
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
502
|
+
}
|
|
503
|
+
} catch {}
|
|
504
|
+
}
|
|
505
|
+
const [messageRes, diffResult] = await Promise.all([
|
|
506
|
+
api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
|
|
507
|
+
fetchDiffWithFallback(baseUrl, directory, sessionId)
|
|
508
|
+
]);
|
|
509
|
+
if (!messageRes.res.ok) {
|
|
510
|
+
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
511
|
+
}
|
|
512
|
+
let messages;
|
|
513
|
+
try {
|
|
514
|
+
messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
|
|
515
|
+
} catch (e) {
|
|
516
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
517
|
+
}
|
|
518
|
+
const { diff, diffSource } = diffResult;
|
|
519
|
+
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
520
|
+
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
521
|
+
`).trim() : "";
|
|
522
|
+
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/format.ts
|
|
526
|
+
function formatRoster(projects) {
|
|
527
|
+
return projects.map((p) => {
|
|
528
|
+
if (!p.pathExists)
|
|
529
|
+
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
530
|
+
if (p.statusError)
|
|
531
|
+
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
532
|
+
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
533
|
+
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
534
|
+
}).join(`
|
|
535
|
+
`);
|
|
536
|
+
}
|
|
537
|
+
function formatDispatch(r) {
|
|
538
|
+
switch (r.mode) {
|
|
539
|
+
case "new":
|
|
540
|
+
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
541
|
+
case "question-reply":
|
|
542
|
+
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
543
|
+
case "follow-up":
|
|
544
|
+
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function formatStatus(r) {
|
|
548
|
+
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
549
|
+
`) : " (none)";
|
|
550
|
+
const lines = [
|
|
551
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
552
|
+
`title: ${r.title ?? "(untitled)"}`,
|
|
553
|
+
`busy: ${r.busy}`
|
|
554
|
+
];
|
|
555
|
+
if (r.pendingQuestion) {
|
|
556
|
+
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
557
|
+
if (r.pendingQuestion.options.length > 0) {
|
|
558
|
+
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
559
|
+
}
|
|
560
|
+
lines.push(` (answer with bus_task using sessionId)`);
|
|
561
|
+
}
|
|
562
|
+
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);
|
|
563
|
+
return lines.join(`
|
|
564
|
+
`);
|
|
565
|
+
}
|
|
566
|
+
function formatResult(r) {
|
|
567
|
+
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
568
|
+
`) : " (no changes)";
|
|
569
|
+
return [
|
|
570
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
571
|
+
`--- reply ---`,
|
|
572
|
+
r.text || "(empty)",
|
|
573
|
+
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
574
|
+
diffLines
|
|
575
|
+
].join(`
|
|
576
|
+
`);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// src/tools/bus_result.ts
|
|
580
|
+
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.";
|
|
581
|
+
function makeBusResult(defaultDirectory) {
|
|
582
|
+
return tool({
|
|
583
|
+
description: BUS_RESULT_DESCRIPTION,
|
|
584
|
+
args: {
|
|
585
|
+
sessionId: tool.schema.string().describe("Session ID returned by bus_task")
|
|
586
|
+
},
|
|
587
|
+
async execute(args, ctx) {
|
|
588
|
+
const r = await result(args.sessionId, {
|
|
589
|
+
directory: ctx.directory ?? defaultDirectory
|
|
590
|
+
});
|
|
591
|
+
if (!r.ok)
|
|
592
|
+
throw new Error(r.error);
|
|
593
|
+
return formatResult(r);
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// src/tools/bus_roster.ts
|
|
599
|
+
import { tool as tool2 } from "@opencode-ai/plugin";
|
|
600
|
+
var BUS_ROSTER_DESCRIPTION = "List the space-bus manifest projects with live session status per project.";
|
|
601
|
+
function makeBusRoster(defaultDirectory) {
|
|
602
|
+
return tool2({
|
|
603
|
+
description: BUS_ROSTER_DESCRIPTION,
|
|
604
|
+
args: {},
|
|
605
|
+
async execute(_args, ctx) {
|
|
606
|
+
const r = await roster({ directory: ctx.directory ?? defaultDirectory });
|
|
607
|
+
if (!r.ok)
|
|
608
|
+
throw new Error(r.error);
|
|
609
|
+
return formatRoster(r.projects);
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/tools/bus_status.ts
|
|
615
|
+
import { tool as tool3 } from "@opencode-ai/plugin";
|
|
616
|
+
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.";
|
|
617
|
+
function makeBusStatus(defaultDirectory) {
|
|
618
|
+
return tool3({
|
|
619
|
+
description: BUS_STATUS_DESCRIPTION,
|
|
620
|
+
args: {
|
|
621
|
+
sessionId: tool3.schema.string().describe("Session ID returned by bus_task")
|
|
622
|
+
},
|
|
623
|
+
async execute(args, ctx) {
|
|
624
|
+
const r = await status(args.sessionId, {
|
|
625
|
+
directory: ctx.directory ?? defaultDirectory
|
|
626
|
+
});
|
|
627
|
+
if (!r.ok)
|
|
628
|
+
throw new Error(r.error);
|
|
629
|
+
return formatStatus(r);
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// src/tools/bus_task.ts
|
|
635
|
+
import { tool as tool4 } from "@opencode-ai/plugin";
|
|
636
|
+
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.";
|
|
637
|
+
function makeBusTask(defaultDirectory) {
|
|
638
|
+
return tool4({
|
|
639
|
+
description: BUS_TASK_DESCRIPTION,
|
|
640
|
+
args: {
|
|
641
|
+
project: tool4.schema.string().optional().describe("Manifest project name, e.g. dashboard, agent, control-plane, infra. Required when starting a new session."),
|
|
642
|
+
prompt: tool4.schema.string().describe("The prompt to send to the delegated agent"),
|
|
643
|
+
title: tool4.schema.string().optional().describe("Optional session title (only used when starting a new session)"),
|
|
644
|
+
sessionId: tool4.schema.string().optional().describe("Existing session ID to steer instead of starting a new session")
|
|
645
|
+
},
|
|
646
|
+
async execute(args, ctx) {
|
|
647
|
+
const r = await dispatch({
|
|
648
|
+
...args,
|
|
649
|
+
directory: ctx.directory ?? defaultDirectory
|
|
650
|
+
});
|
|
651
|
+
if (!r.ok)
|
|
652
|
+
throw new Error(r.error);
|
|
653
|
+
return formatDispatch(r);
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// src/index.ts
|
|
659
|
+
var SpaceBusPlugin = async (input) => ({
|
|
660
|
+
tool: {
|
|
661
|
+
bus_roster: makeBusRoster(input.directory),
|
|
662
|
+
bus_task: makeBusTask(input.directory),
|
|
663
|
+
bus_status: makeBusStatus(input.directory),
|
|
664
|
+
bus_result: makeBusResult(input.directory)
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
var src_default = SpaceBusPlugin;
|
|
668
|
+
export {
|
|
669
|
+
src_default as default
|
|
670
|
+
};
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|