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