@fro.bot/space-bus 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,13 +1,4 @@
1
1
  #!/usr/bin/env node
2
- // src/mcp.ts
3
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
- import { z as z3 } from "zod";
6
-
7
- // src/core.ts
8
- import { existsSync as existsSync2 } from "node:fs";
9
- import { z as z2 } from "zod";
10
-
11
2
  // src/config.ts
12
3
  import { existsSync, readFileSync, realpathSync } from "node:fs";
13
4
  import { homedir } from "node:os";
@@ -69,53 +60,29 @@ function getRoster(directory) {
69
60
  return parsed.data;
70
61
  }
71
62
  function getProjects(manifest) {
72
- return manifest.projects.map((p) => ({
73
- ...p,
74
- expandedPath: expandHome(p.path)
75
- }));
76
- }
77
-
78
- // src/core.ts
79
- function findProject(projects, name) {
80
- return projects.find((p) => p.name === name);
81
- }
82
- function err(error) {
83
- return { ok: false, error };
63
+ return manifest.projects.map((p) => {
64
+ const expandedPath = expandHome(p.path);
65
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
66
+ });
84
67
  }
85
- function authHeader() {
68
+ function getCredentials() {
86
69
  const password = process.env["OPENCODE_SERVER_PASSWORD"];
87
70
  if (!password)
88
71
  return {};
89
72
  const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
90
- const token = Buffer.from(`${username}:${password}`).toString("base64");
91
- return { Authorization: `Basic ${token}` };
73
+ return { username, password };
92
74
  }
93
- async function api(baseUrl, directory, path, init) {
94
- try {
95
- const res = await fetch(`${baseUrl}${path}`, {
96
- ...init,
97
- headers: {
98
- "content-type": "application/json",
99
- "x-opencode-directory": directory,
100
- ...authHeader(),
101
- ...init?.headers
102
- },
103
- redirect: "error",
104
- signal: AbortSignal.timeout(30000)
105
- });
106
- const bodyText = await res.text().catch(() => "<unreadable body>");
107
- return { res, bodyText };
108
- } catch (e) {
109
- const message = e.message;
110
- return {
111
- res: new Response(null, {
112
- status: 599,
113
- statusText: "space-bus: request failed"
114
- }),
115
- bodyText: `space-bus: request failed: ${message}`
116
- };
117
- }
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
+ };
118
82
  }
83
+
84
+ // src/contract.ts
85
+ import { z as z2 } from "zod";
119
86
  var sessionSchema = z2.object({
120
87
  id: z2.string(),
121
88
  directory: z2.string().optional(),
@@ -153,8 +120,92 @@ var sessionSummarySchema = z2.object({
153
120
  diffs: z2.array(turnDiffEntrySchema).optional()
154
121
  }).passthrough().optional()
155
122
  }).passthrough();
156
- async function fetchTurnDiffs(baseUrl, directory, sessionId) {
157
- const { res, bodyText } = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
123
+ var messagePartSchema = z2.object({ type: z2.string(), text: z2.string().optional() }).passthrough();
124
+ var messageEnvelopeSchema = z2.object({
125
+ info: z2.object({ role: z2.string() }).passthrough(),
126
+ parts: z2.array(messagePartSchema)
127
+ }).passthrough();
128
+ var messageListSchema = z2.array(messageEnvelopeSchema);
129
+ var pendingQuestionEntrySchema = z2.object({
130
+ id: z2.string(),
131
+ sessionID: z2.string(),
132
+ questions: z2.array(z2.object({
133
+ question: z2.string().optional(),
134
+ options: z2.array(z2.object({ label: z2.string().optional() }).passthrough()).optional()
135
+ }).passthrough()).optional()
136
+ }).passthrough();
137
+ var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
138
+ var questionEntrySchema = z2.object({ id: z2.string(), sessionID: z2.string() }).passthrough();
139
+ var questionListSchema = z2.array(questionEntrySchema);
140
+ var projectSchema = z2.object({
141
+ name: z2.string(),
142
+ path: z2.string(),
143
+ description: z2.string(),
144
+ expandedPath: z2.string(),
145
+ exists: z2.boolean()
146
+ }).passthrough();
147
+ var rosterSchema = z2.object({
148
+ server: z2.object({ baseUrl: z2.string().url() }),
149
+ projects: z2.array(projectSchema)
150
+ });
151
+ var credentialsSchema = z2.object({
152
+ username: z2.string().optional(),
153
+ password: z2.string().optional()
154
+ });
155
+ var busContextSchema = z2.object({
156
+ roster: rosterSchema,
157
+ credentials: credentialsSchema.optional()
158
+ });
159
+
160
+ // src/core.ts
161
+ function findProject(projects, name) {
162
+ return projects.find((p) => p.name === name);
163
+ }
164
+ function err(error) {
165
+ return { ok: false, error };
166
+ }
167
+ function toBase64(s) {
168
+ const bytes = new TextEncoder().encode(s);
169
+ let bin = "";
170
+ for (const b of bytes)
171
+ bin += String.fromCharCode(b);
172
+ return btoa(bin);
173
+ }
174
+ function authHeader(credentials) {
175
+ if (!credentials.password)
176
+ return {};
177
+ const username = credentials.username ?? "opencode";
178
+ const token = toBase64(`${username}:${credentials.password}`);
179
+ return { Authorization: `Basic ${token}` };
180
+ }
181
+ async function api(baseUrl, credentials, directory, path, init) {
182
+ try {
183
+ const res = await fetch(`${baseUrl}${path}`, {
184
+ ...init,
185
+ headers: {
186
+ "content-type": "application/json",
187
+ "x-opencode-directory": directory,
188
+ ...authHeader(credentials),
189
+ ...init?.headers
190
+ },
191
+ redirect: "error",
192
+ signal: AbortSignal.timeout(30000)
193
+ });
194
+ const bodyText = await res.text().catch(() => "<unreadable body>");
195
+ return { res, bodyText };
196
+ } catch (e) {
197
+ const message = e.message;
198
+ return {
199
+ res: new Response(null, {
200
+ status: 599,
201
+ statusText: "space-bus: request failed"
202
+ }),
203
+ bodyText: `space-bus: request failed: ${message}`
204
+ };
205
+ }
206
+ }
207
+ async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
208
+ const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
158
209
  if (!res.ok)
159
210
  return [];
160
211
  let messages;
@@ -177,8 +228,8 @@ async function fetchTurnDiffs(baseUrl, directory, sessionId) {
177
228
  }
178
229
  return Array.from(byFile.values());
179
230
  }
180
- async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
181
- const diffRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
231
+ async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
232
+ const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
182
233
  let diff = [];
183
234
  try {
184
235
  diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
@@ -189,7 +240,7 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
189
240
  return { diff, diffSource: "session" };
190
241
  }
191
242
  try {
192
- const sessionRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`);
243
+ const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
193
244
  if (sessionRes.res.ok) {
194
245
  const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
195
246
  const summaryDiffs = parsed.summary?.diffs;
@@ -199,13 +250,13 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
199
250
  }
200
251
  } catch {}
201
252
  try {
202
- const turnDiffs = await fetchTurnDiffs(baseUrl, directory, sessionId);
253
+ const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
203
254
  if (turnDiffs.length > 0) {
204
255
  return { diff: turnDiffs, diffSource: "turns" };
205
256
  }
206
257
  } catch {}
207
258
  try {
208
- const vcsRes = await api(baseUrl, directory, "/vcs/status");
259
+ const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
209
260
  if (vcsRes.res.ok) {
210
261
  const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
211
262
  if (vcsStatus.length > 0) {
@@ -223,20 +274,28 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
223
274
  } catch {}
224
275
  return { diff, diffSource: "session" };
225
276
  }
226
- var messagePartSchema = z2.object({ type: z2.string(), text: z2.string().optional() }).passthrough();
227
- var messageEnvelopeSchema = z2.object({
228
- info: z2.object({ role: z2.string() }).passthrough(),
229
- parts: z2.array(messagePartSchema)
230
- }).passthrough();
231
- var messageListSchema = z2.array(messageEnvelopeSchema);
232
- function resolveContext(directory) {
277
+ var ALLOWED_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
278
+ function validateContext(context) {
279
+ const parsed = busContextSchema.safeParse(context);
280
+ if (!parsed.success) {
281
+ return err(`space-bus: invalid context: ${parsed.error.message}`);
282
+ }
283
+ const { roster, credentials } = parsed.data;
284
+ let hostname;
233
285
  try {
234
- const manifest = getRoster(directory);
235
- const projects = getProjects(manifest);
236
- return { ok: true, baseUrl: manifest.server.baseUrl, projects };
237
- } catch (e) {
238
- return err(e.message);
286
+ hostname = new URL(roster.server.baseUrl).hostname;
287
+ } catch {
288
+ return err("space-bus: context roster server.baseUrl is not a valid URL");
289
+ }
290
+ if (!ALLOWED_HOSTS.has(hostname)) {
291
+ return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
239
292
  }
293
+ return {
294
+ ok: true,
295
+ baseUrl: roster.server.baseUrl,
296
+ projects: roster.projects,
297
+ credentials: credentials ?? {}
298
+ };
240
299
  }
241
300
  function resolveProjectOrErr(projects, name) {
242
301
  const project = findProject(projects, name);
@@ -244,19 +303,18 @@ function resolveProjectOrErr(projects, name) {
244
303
  const valid = projects.map((p) => p.name).join(", ");
245
304
  return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
246
305
  }
247
- if (!existsSync2(project.expandedPath)) {
306
+ if (!project.exists) {
248
307
  return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
249
308
  }
250
309
  return { ok: true, project };
251
310
  }
252
311
  async function roster(opts) {
253
- const ctx = resolveContext(opts?.directory);
312
+ const ctx = validateContext(opts.context);
254
313
  if (!ctx.ok)
255
314
  return ctx;
256
- const { baseUrl, projects } = ctx;
315
+ const { baseUrl, projects, credentials } = ctx;
257
316
  const results = await Promise.all(projects.map(async (p) => {
258
- const pathExists = existsSync2(p.expandedPath);
259
- if (!pathExists) {
317
+ if (!p.exists) {
260
318
  return {
261
319
  name: p.name,
262
320
  path: p.expandedPath,
@@ -266,8 +324,8 @@ async function roster(opts) {
266
324
  }
267
325
  try {
268
326
  const [statusRes, listRes] = await Promise.all([
269
- api(baseUrl, p.expandedPath, "/session/status"),
270
- api(baseUrl, p.expandedPath, "/session?limit=101")
327
+ api(baseUrl, credentials, p.expandedPath, "/session/status"),
328
+ api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
271
329
  ]);
272
330
  if (!statusRes.res.ok || !listRes.res.ok) {
273
331
  return {
@@ -303,13 +361,13 @@ async function roster(opts) {
303
361
  }));
304
362
  return { ok: true, projects: results };
305
363
  }
306
- async function dispatchNew(baseUrl, projects, project, prompt, title) {
364
+ async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
307
365
  const resolved = resolveProjectOrErr(projects, project);
308
366
  if (!resolved.ok)
309
367
  return resolved;
310
368
  const directory = resolved.project.expandedPath;
311
369
  const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
312
- const createRes = await api(baseUrl, directory, "/session", {
370
+ const createRes = await api(baseUrl, credentials, directory, "/session", {
313
371
  method: "POST",
314
372
  body: JSON.stringify({ title: sessionTitle })
315
373
  });
@@ -322,7 +380,7 @@ async function dispatchNew(baseUrl, projects, project, prompt, title) {
322
380
  } catch (e) {
323
381
  return err(`space-bus: unexpected /session response shape: ${e.message}`);
324
382
  }
325
- const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
383
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
326
384
  method: "POST",
327
385
  body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
328
386
  });
@@ -331,11 +389,34 @@ async function dispatchNew(baseUrl, projects, project, prompt, title) {
331
389
  }
332
390
  return { ok: true, sessionId: session.id, project, directory };
333
391
  }
334
- async function dispatch(args) {
335
- const ctx = resolveContext(args.directory);
392
+ function toDispatchArgs(input) {
393
+ if (input.sessionId !== undefined && input.sessionId === "") {
394
+ return err("space-bus: sessionId must be a non-empty string");
395
+ }
396
+ if (!input.sessionId) {
397
+ if (!input.project) {
398
+ return err("space-bus: project is required when starting a new session");
399
+ }
400
+ return {
401
+ ok: true,
402
+ prompt: input.prompt,
403
+ title: input.title,
404
+ project: input.project
405
+ };
406
+ }
407
+ return {
408
+ ok: true,
409
+ prompt: input.prompt,
410
+ title: input.title,
411
+ sessionId: input.sessionId,
412
+ project: input.project
413
+ };
414
+ }
415
+ async function dispatch(args, opts) {
416
+ const ctx = validateContext(opts.context);
336
417
  if (!ctx.ok)
337
418
  return ctx;
338
- const { baseUrl, projects } = ctx;
419
+ const { baseUrl, projects, credentials } = ctx;
339
420
  if (args.sessionId !== undefined && args.sessionId === "") {
340
421
  return err("space-bus: sessionId must be a non-empty string");
341
422
  }
@@ -343,7 +424,7 @@ async function dispatch(args) {
343
424
  if (!args.project) {
344
425
  return err("space-bus: project is required when starting a new session");
345
426
  }
346
- const r = await dispatchNew(baseUrl, projects, args.project, args.prompt, args.title);
427
+ const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
347
428
  if (!r.ok)
348
429
  return r;
349
430
  return {
@@ -354,20 +435,20 @@ async function dispatch(args) {
354
435
  directory: r.directory
355
436
  };
356
437
  }
357
- const loc = await findSessionDirectory(baseUrl, projects, args.sessionId);
438
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
358
439
  if (!loc.ok)
359
440
  return loc;
360
441
  const { directory, project } = loc;
361
442
  if (args.project && args.project !== project) {
362
443
  return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
363
444
  }
364
- return steerSession(baseUrl, args.sessionId, args.prompt, directory, project);
445
+ return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project);
365
446
  }
366
- async function findSessionDirectory(baseUrl, projects, sessionId) {
447
+ async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
367
448
  for (const p of projects) {
368
- if (!existsSync2(p.expandedPath))
449
+ if (!p.exists)
369
450
  continue;
370
- const { res, bodyText } = await api(baseUrl, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
451
+ const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
371
452
  if (!res.ok)
372
453
  continue;
373
454
  let session;
@@ -384,48 +465,43 @@ async function findSessionDirectory(baseUrl, projects, sessionId) {
384
465
  }
385
466
  return err(`space-bus: no manifest project has a session with id ${sessionId}`);
386
467
  }
387
- var pendingQuestionEntrySchema = z2.object({
388
- id: z2.string(),
389
- sessionID: z2.string(),
390
- questions: z2.array(z2.object({
391
- question: z2.string().optional(),
392
- options: z2.array(z2.object({ label: z2.string().optional() }).passthrough()).optional()
393
- }).passthrough()).optional()
394
- }).passthrough();
395
- var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
396
- async function fetchPendingQuestion(baseUrl, directory, sessionId) {
468
+ function formatQuestionEntry(entry) {
469
+ const firstQuestion = entry.questions?.[0];
470
+ const text = firstQuestion?.question ?? "";
471
+ const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
472
+ const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
473
+ return { sessionId: entry.sessionID, preview, options };
474
+ }
475
+ async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
397
476
  try {
398
- const { res, bodyText } = await api(baseUrl, directory, "/question");
477
+ const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
399
478
  if (!res.ok)
400
479
  return;
401
480
  const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
402
481
  const entry = entries.find((e) => e.sessionID === sessionId);
403
482
  if (!entry)
404
483
  return;
405
- const firstQuestion = entry.questions?.[0];
406
- const text = firstQuestion?.question ?? "";
407
- const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
408
- const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
484
+ const { preview, options } = formatQuestionEntry(entry);
409
485
  return { preview, options };
410
486
  } catch {
411
487
  return;
412
488
  }
413
489
  }
414
490
  async function status(sessionId, opts) {
415
- const ctx = resolveContext(opts?.directory);
491
+ const ctx = validateContext(opts.context);
416
492
  if (!ctx.ok)
417
493
  return ctx;
418
- const { baseUrl, projects } = ctx;
419
- const loc = await findSessionDirectory(baseUrl, projects, sessionId);
494
+ const { baseUrl, projects, credentials } = ctx;
495
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
420
496
  if (!loc.ok)
421
497
  return loc;
422
498
  const { directory, project } = loc;
423
499
  const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
424
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`),
425
- api(baseUrl, directory, "/session/status"),
426
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
427
- fetchDiffWithFallback(baseUrl, directory, sessionId),
428
- fetchPendingQuestion(baseUrl, directory, sessionId)
500
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
501
+ api(baseUrl, credentials, directory, "/session/status"),
502
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
503
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
504
+ fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
429
505
  ]);
430
506
  if (!sessionRes.res.ok) {
431
507
  return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
@@ -457,10 +533,8 @@ async function status(sessionId, opts) {
457
533
  pendingQuestion
458
534
  };
459
535
  }
460
- var questionEntrySchema = z2.object({ id: z2.string(), sessionID: z2.string() }).passthrough();
461
- var questionListSchema = z2.array(questionEntrySchema);
462
- async function steerSession(baseUrl, sessionId, message, directory, project) {
463
- const questionsRes = await api(baseUrl, directory, "/question");
536
+ async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
537
+ const questionsRes = await api(baseUrl, credentials, directory, "/question");
464
538
  if (questionsRes.res.ok) {
465
539
  let questions;
466
540
  try {
@@ -470,7 +544,7 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
470
544
  }
471
545
  const pending = questions.find((q) => q.sessionID === sessionId);
472
546
  if (pending) {
473
- const replyRes = await api(baseUrl, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
547
+ const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
474
548
  method: "POST",
475
549
  body: JSON.stringify({ answers: [[message]] })
476
550
  });
@@ -480,7 +554,7 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
480
554
  return { ok: true, sessionId, project, mode: "question-reply" };
481
555
  }
482
556
  }
483
- const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
557
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
484
558
  method: "POST",
485
559
  body: JSON.stringify({ parts: [{ type: "text", text: message }] })
486
560
  });
@@ -490,15 +564,15 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
490
564
  return { ok: true, sessionId, project, mode: "follow-up" };
491
565
  }
492
566
  async function result(sessionId, opts) {
493
- const ctx = resolveContext(opts?.directory);
567
+ const ctx = validateContext(opts.context);
494
568
  if (!ctx.ok)
495
569
  return ctx;
496
- const { baseUrl, projects } = ctx;
497
- const loc = await findSessionDirectory(baseUrl, projects, sessionId);
570
+ const { baseUrl, projects, credentials } = ctx;
571
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
498
572
  if (!loc.ok)
499
573
  return loc;
500
574
  const { directory, project } = loc;
501
- const statusMapRes = await api(baseUrl, directory, "/session/status");
575
+ const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
502
576
  if (statusMapRes.res.ok) {
503
577
  try {
504
578
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
@@ -509,8 +583,8 @@ async function result(sessionId, opts) {
509
583
  } catch {}
510
584
  }
511
585
  const [messageRes, diffResult] = await Promise.all([
512
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
513
- fetchDiffWithFallback(baseUrl, directory, sessionId)
586
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
587
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
514
588
  ]);
515
589
  if (!messageRes.res.ok) {
516
590
  return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
@@ -527,6 +601,90 @@ async function result(sessionId, opts) {
527
601
  `).trim() : "";
528
602
  return { ok: true, sessionId, project, text, diff, diffSource };
529
603
  }
604
+ async function fetchSnapshotProject(baseUrl, credentials, project) {
605
+ const directory = project.expandedPath;
606
+ try {
607
+ const [statusRes, listRes, questionRes] = await Promise.all([
608
+ api(baseUrl, credentials, directory, "/session/status"),
609
+ api(baseUrl, credentials, directory, "/session?limit=101"),
610
+ api(baseUrl, credentials, directory, "/question")
611
+ ]);
612
+ if (!statusRes.res.ok || !listRes.res.ok) {
613
+ return {
614
+ name: project.name,
615
+ path: directory,
616
+ exists: true,
617
+ description: project.description,
618
+ error: `status=${statusRes.res.status}/${listRes.res.status}`
619
+ };
620
+ }
621
+ const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
622
+ const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
623
+ const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
624
+ const capped = sessions.length > 100;
625
+ let pendingQuestions;
626
+ if (questionRes.res.ok) {
627
+ try {
628
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
629
+ pendingQuestions = entries.map((e) => formatQuestionEntry(e));
630
+ } catch {
631
+ pendingQuestions = undefined;
632
+ }
633
+ }
634
+ return {
635
+ name: project.name,
636
+ path: directory,
637
+ exists: true,
638
+ description: project.description,
639
+ busyCount,
640
+ sessionCount: capped ? 100 : sessions.length,
641
+ sessionCountCapped: capped,
642
+ pendingQuestions
643
+ };
644
+ } catch (e) {
645
+ return {
646
+ name: project.name,
647
+ path: directory,
648
+ exists: true,
649
+ description: project.description,
650
+ error: e.message
651
+ };
652
+ }
653
+ }
654
+ async function mapWithConcurrency(items, concurrency, fn) {
655
+ const results = new Array(items.length);
656
+ let next = 0;
657
+ const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
658
+ const workers = Array.from({ length: limit }, async () => {
659
+ while (true) {
660
+ const i = next++;
661
+ if (i >= items.length)
662
+ return;
663
+ results[i] = await fn(items[i]);
664
+ }
665
+ });
666
+ await Promise.all(workers);
667
+ return results;
668
+ }
669
+ async function snapshot(opts) {
670
+ const ctx = validateContext(opts.context);
671
+ if (!ctx.ok)
672
+ return ctx;
673
+ const { baseUrl, projects, credentials } = ctx;
674
+ const concurrency = opts.concurrency ?? 4;
675
+ const results = await mapWithConcurrency(projects, concurrency, async (p) => {
676
+ if (!p.exists) {
677
+ return {
678
+ name: p.name,
679
+ path: p.expandedPath,
680
+ exists: false,
681
+ description: p.description
682
+ };
683
+ }
684
+ return fetchSnapshotProject(baseUrl, credentials, p);
685
+ });
686
+ return { ok: true, projects: results };
687
+ }
530
688
 
531
689
  // src/format.ts
532
690
  function formatRoster(projects) {
@@ -582,6 +740,11 @@ function formatResult(r) {
582
740
  `);
583
741
  }
584
742
 
743
+ // src/mcp.ts
744
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
745
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
746
+ import { z as z3 } from "zod";
747
+
585
748
  // src/tools/bus_result.ts
586
749
  import { tool } from "@opencode-ai/plugin";
587
750
  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.";
@@ -592,9 +755,14 @@ function makeBusResult(defaultDirectory) {
592
755
  sessionId: tool.schema.string().describe("Session ID returned by bus_task")
593
756
  },
594
757
  async execute(args, ctx) {
595
- const r = await result(args.sessionId, {
596
- directory: ctx.directory ?? defaultDirectory
597
- });
758
+ const directory = ctx.directory ?? defaultDirectory;
759
+ let context;
760
+ try {
761
+ context = loadContext(directory);
762
+ } catch (e) {
763
+ throw new Error(e.message);
764
+ }
765
+ const r = await result(args.sessionId, { context });
598
766
  if (!r.ok)
599
767
  throw new Error(r.error);
600
768
  return formatResult(r);
@@ -610,7 +778,14 @@ function makeBusRoster(defaultDirectory) {
610
778
  description: BUS_ROSTER_DESCRIPTION,
611
779
  args: {},
612
780
  async execute(_args, ctx) {
613
- const r = await roster({ directory: ctx.directory ?? defaultDirectory });
781
+ const directory = ctx.directory ?? defaultDirectory;
782
+ let context;
783
+ try {
784
+ context = loadContext(directory);
785
+ } catch (e) {
786
+ throw new Error(e.message);
787
+ }
788
+ const r = await roster({ context });
614
789
  if (!r.ok)
615
790
  throw new Error(r.error);
616
791
  return formatRoster(r.projects);
@@ -628,9 +803,14 @@ function makeBusStatus(defaultDirectory) {
628
803
  sessionId: tool3.schema.string().describe("Session ID returned by bus_task")
629
804
  },
630
805
  async execute(args, ctx) {
631
- const r = await status(args.sessionId, {
632
- directory: ctx.directory ?? defaultDirectory
633
- });
806
+ const directory = ctx.directory ?? defaultDirectory;
807
+ let context;
808
+ try {
809
+ context = loadContext(directory);
810
+ } catch (e) {
811
+ throw new Error(e.message);
812
+ }
813
+ const r = await status(args.sessionId, { context });
634
814
  if (!r.ok)
635
815
  throw new Error(r.error);
636
816
  return formatStatus(r);
@@ -651,10 +831,17 @@ function makeBusTask(defaultDirectory) {
651
831
  sessionId: tool4.schema.string().optional().describe("Existing session ID to steer instead of starting a new session")
652
832
  },
653
833
  async execute(args, ctx) {
654
- const r = await dispatch({
655
- ...args,
656
- directory: ctx.directory ?? defaultDirectory
657
- });
834
+ const dispatchArgs = toDispatchArgs(args);
835
+ if (!dispatchArgs.ok)
836
+ throw new Error(dispatchArgs.error);
837
+ const directory = ctx.directory ?? defaultDirectory;
838
+ let context;
839
+ try {
840
+ context = loadContext(directory);
841
+ } catch (e) {
842
+ throw new Error(e.message);
843
+ }
844
+ const r = await dispatch(dispatchArgs, { context });
658
845
  if (!r.ok)
659
846
  throw new Error(r.error);
660
847
  return formatDispatch(r);
@@ -663,7 +850,7 @@ function makeBusTask(defaultDirectory) {
663
850
  }
664
851
 
665
852
  // src/mcp.ts
666
- var version = "0.2.0";
853
+ var version = "0.3.0";
667
854
  var server = new McpServer({
668
855
  name: "space-bus",
669
856
  version
@@ -672,7 +859,16 @@ server.registerTool("bus_roster", {
672
859
  description: BUS_ROSTER_DESCRIPTION,
673
860
  inputSchema: {}
674
861
  }, async () => {
675
- const r = await roster({});
862
+ let context;
863
+ try {
864
+ context = loadContext();
865
+ } catch (e) {
866
+ return {
867
+ content: [{ type: "text", text: e.message }],
868
+ isError: true
869
+ };
870
+ }
871
+ const r = await roster({ context });
676
872
  if (!r.ok)
677
873
  return { content: [{ type: "text", text: r.error }], isError: true };
678
874
  return { content: [{ type: "text", text: formatRoster(r.projects) }] };
@@ -686,7 +882,22 @@ server.registerTool("bus_task", {
686
882
  sessionId: z3.string().optional().describe("Existing session ID to steer instead of starting a new session")
687
883
  }
688
884
  }, async (args) => {
689
- const r = await dispatch(args);
885
+ const dispatchArgs = toDispatchArgs(args);
886
+ if (!dispatchArgs.ok)
887
+ return {
888
+ content: [{ type: "text", text: dispatchArgs.error }],
889
+ isError: true
890
+ };
891
+ let context;
892
+ try {
893
+ context = loadContext();
894
+ } catch (e) {
895
+ return {
896
+ content: [{ type: "text", text: e.message }],
897
+ isError: true
898
+ };
899
+ }
900
+ const r = await dispatch(dispatchArgs, { context });
690
901
  if (!r.ok)
691
902
  return { content: [{ type: "text", text: r.error }], isError: true };
692
903
  return { content: [{ type: "text", text: formatDispatch(r) }] };
@@ -697,7 +908,16 @@ server.registerTool("bus_status", {
697
908
  sessionId: z3.string().describe("Session ID returned by bus_task")
698
909
  }
699
910
  }, async (args) => {
700
- const r = await status(args.sessionId, {});
911
+ let context;
912
+ try {
913
+ context = loadContext();
914
+ } catch (e) {
915
+ return {
916
+ content: [{ type: "text", text: e.message }],
917
+ isError: true
918
+ };
919
+ }
920
+ const r = await status(args.sessionId, { context });
701
921
  if (!r.ok)
702
922
  return { content: [{ type: "text", text: r.error }], isError: true };
703
923
  return { content: [{ type: "text", text: formatStatus(r) }] };
@@ -708,7 +928,16 @@ server.registerTool("bus_result", {
708
928
  sessionId: z3.string().describe("Session ID returned by bus_task")
709
929
  }
710
930
  }, async (args) => {
711
- const r = await result(args.sessionId, {});
931
+ let context;
932
+ try {
933
+ context = loadContext();
934
+ } catch (e) {
935
+ return {
936
+ content: [{ type: "text", text: e.message }],
937
+ isError: true
938
+ };
939
+ }
940
+ const r = await result(args.sessionId, { context });
712
941
  if (!r.ok)
713
942
  return { content: [{ type: "text", text: r.error }], isError: true };
714
943
  return { content: [{ type: "text", text: formatResult(r) }] };