@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/index.js CHANGED
@@ -1,10 +1,3 @@
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
1
  // src/config.ts
9
2
  import { existsSync, readFileSync, realpathSync } from "node:fs";
10
3
  import { homedir } from "node:os";
@@ -66,53 +59,29 @@ function getRoster(directory) {
66
59
  return parsed.data;
67
60
  }
68
61
  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 };
62
+ return manifest.projects.map((p) => {
63
+ const expandedPath = expandHome(p.path);
64
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
65
+ });
81
66
  }
82
- function authHeader() {
67
+ function getCredentials() {
83
68
  const password = process.env["OPENCODE_SERVER_PASSWORD"];
84
69
  if (!password)
85
70
  return {};
86
71
  const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
87
- const token = Buffer.from(`${username}:${password}`).toString("base64");
88
- return { Authorization: `Basic ${token}` };
72
+ return { username, password };
89
73
  }
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
- }
74
+ function loadContext(directory) {
75
+ const manifest = getRoster(directory);
76
+ const projects = getProjects(manifest);
77
+ return {
78
+ roster: { server: manifest.server, projects },
79
+ credentials: getCredentials()
80
+ };
115
81
  }
82
+
83
+ // src/contract.ts
84
+ import { z as z2 } from "zod";
116
85
  var sessionSchema = z2.object({
117
86
  id: z2.string(),
118
87
  directory: z2.string().optional(),
@@ -150,8 +119,92 @@ var sessionSummarySchema = z2.object({
150
119
  diffs: z2.array(turnDiffEntrySchema).optional()
151
120
  }).passthrough().optional()
152
121
  }).passthrough();
153
- async function fetchTurnDiffs(baseUrl, directory, sessionId) {
154
- const { res, bodyText } = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
122
+ var messagePartSchema = z2.object({ type: z2.string(), text: z2.string().optional() }).passthrough();
123
+ var messageEnvelopeSchema = z2.object({
124
+ info: z2.object({ role: z2.string() }).passthrough(),
125
+ parts: z2.array(messagePartSchema)
126
+ }).passthrough();
127
+ var messageListSchema = z2.array(messageEnvelopeSchema);
128
+ var pendingQuestionEntrySchema = z2.object({
129
+ id: z2.string(),
130
+ sessionID: z2.string(),
131
+ questions: z2.array(z2.object({
132
+ question: z2.string().optional(),
133
+ options: z2.array(z2.object({ label: z2.string().optional() }).passthrough()).optional()
134
+ }).passthrough()).optional()
135
+ }).passthrough();
136
+ var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
137
+ var questionEntrySchema = z2.object({ id: z2.string(), sessionID: z2.string() }).passthrough();
138
+ var questionListSchema = z2.array(questionEntrySchema);
139
+ var projectSchema = z2.object({
140
+ name: z2.string(),
141
+ path: z2.string(),
142
+ description: z2.string(),
143
+ expandedPath: z2.string(),
144
+ exists: z2.boolean()
145
+ }).passthrough();
146
+ var rosterSchema = z2.object({
147
+ server: z2.object({ baseUrl: z2.string().url() }),
148
+ projects: z2.array(projectSchema)
149
+ });
150
+ var credentialsSchema = z2.object({
151
+ username: z2.string().optional(),
152
+ password: z2.string().optional()
153
+ });
154
+ var busContextSchema = z2.object({
155
+ roster: rosterSchema,
156
+ credentials: credentialsSchema.optional()
157
+ });
158
+
159
+ // src/core.ts
160
+ function findProject(projects, name) {
161
+ return projects.find((p) => p.name === name);
162
+ }
163
+ function err(error) {
164
+ return { ok: false, error };
165
+ }
166
+ function toBase64(s) {
167
+ const bytes = new TextEncoder().encode(s);
168
+ let bin = "";
169
+ for (const b of bytes)
170
+ bin += String.fromCharCode(b);
171
+ return btoa(bin);
172
+ }
173
+ function authHeader(credentials) {
174
+ if (!credentials.password)
175
+ return {};
176
+ const username = credentials.username ?? "opencode";
177
+ const token = toBase64(`${username}:${credentials.password}`);
178
+ return { Authorization: `Basic ${token}` };
179
+ }
180
+ async function api(baseUrl, credentials, directory, path, init) {
181
+ try {
182
+ const res = await fetch(`${baseUrl}${path}`, {
183
+ ...init,
184
+ headers: {
185
+ "content-type": "application/json",
186
+ "x-opencode-directory": directory,
187
+ ...authHeader(credentials),
188
+ ...init?.headers
189
+ },
190
+ redirect: "error",
191
+ signal: AbortSignal.timeout(30000)
192
+ });
193
+ const bodyText = await res.text().catch(() => "<unreadable body>");
194
+ return { res, bodyText };
195
+ } catch (e) {
196
+ const message = e.message;
197
+ return {
198
+ res: new Response(null, {
199
+ status: 599,
200
+ statusText: "space-bus: request failed"
201
+ }),
202
+ bodyText: `space-bus: request failed: ${message}`
203
+ };
204
+ }
205
+ }
206
+ async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
207
+ const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
155
208
  if (!res.ok)
156
209
  return [];
157
210
  let messages;
@@ -174,8 +227,8 @@ async function fetchTurnDiffs(baseUrl, directory, sessionId) {
174
227
  }
175
228
  return Array.from(byFile.values());
176
229
  }
177
- async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
178
- const diffRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
230
+ async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
231
+ const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
179
232
  let diff = [];
180
233
  try {
181
234
  diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
@@ -186,7 +239,7 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
186
239
  return { diff, diffSource: "session" };
187
240
  }
188
241
  try {
189
- const sessionRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`);
242
+ const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
190
243
  if (sessionRes.res.ok) {
191
244
  const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
192
245
  const summaryDiffs = parsed.summary?.diffs;
@@ -196,13 +249,13 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
196
249
  }
197
250
  } catch {}
198
251
  try {
199
- const turnDiffs = await fetchTurnDiffs(baseUrl, directory, sessionId);
252
+ const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
200
253
  if (turnDiffs.length > 0) {
201
254
  return { diff: turnDiffs, diffSource: "turns" };
202
255
  }
203
256
  } catch {}
204
257
  try {
205
- const vcsRes = await api(baseUrl, directory, "/vcs/status");
258
+ const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
206
259
  if (vcsRes.res.ok) {
207
260
  const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
208
261
  if (vcsStatus.length > 0) {
@@ -220,20 +273,28 @@ async function fetchDiffWithFallback(baseUrl, directory, sessionId) {
220
273
  } catch {}
221
274
  return { diff, diffSource: "session" };
222
275
  }
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) {
276
+ var ALLOWED_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
277
+ function validateContext(context) {
278
+ const parsed = busContextSchema.safeParse(context);
279
+ if (!parsed.success) {
280
+ return err(`space-bus: invalid context: ${parsed.error.message}`);
281
+ }
282
+ const { roster, credentials } = parsed.data;
283
+ let hostname;
230
284
  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);
285
+ hostname = new URL(roster.server.baseUrl).hostname;
286
+ } catch {
287
+ return err("space-bus: context roster server.baseUrl is not a valid URL");
288
+ }
289
+ if (!ALLOWED_HOSTS.has(hostname)) {
290
+ return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
236
291
  }
292
+ return {
293
+ ok: true,
294
+ baseUrl: roster.server.baseUrl,
295
+ projects: roster.projects,
296
+ credentials: credentials ?? {}
297
+ };
237
298
  }
238
299
  function resolveProjectOrErr(projects, name) {
239
300
  const project = findProject(projects, name);
@@ -241,19 +302,18 @@ function resolveProjectOrErr(projects, name) {
241
302
  const valid = projects.map((p) => p.name).join(", ");
242
303
  return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
243
304
  }
244
- if (!existsSync2(project.expandedPath)) {
305
+ if (!project.exists) {
245
306
  return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
246
307
  }
247
308
  return { ok: true, project };
248
309
  }
249
310
  async function roster(opts) {
250
- const ctx = resolveContext(opts?.directory);
311
+ const ctx = validateContext(opts.context);
251
312
  if (!ctx.ok)
252
313
  return ctx;
253
- const { baseUrl, projects } = ctx;
314
+ const { baseUrl, projects, credentials } = ctx;
254
315
  const results = await Promise.all(projects.map(async (p) => {
255
- const pathExists = existsSync2(p.expandedPath);
256
- if (!pathExists) {
316
+ if (!p.exists) {
257
317
  return {
258
318
  name: p.name,
259
319
  path: p.expandedPath,
@@ -263,8 +323,8 @@ async function roster(opts) {
263
323
  }
264
324
  try {
265
325
  const [statusRes, listRes] = await Promise.all([
266
- api(baseUrl, p.expandedPath, "/session/status"),
267
- api(baseUrl, p.expandedPath, "/session?limit=101")
326
+ api(baseUrl, credentials, p.expandedPath, "/session/status"),
327
+ api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
268
328
  ]);
269
329
  if (!statusRes.res.ok || !listRes.res.ok) {
270
330
  return {
@@ -300,13 +360,13 @@ async function roster(opts) {
300
360
  }));
301
361
  return { ok: true, projects: results };
302
362
  }
303
- async function dispatchNew(baseUrl, projects, project, prompt, title) {
363
+ async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
304
364
  const resolved = resolveProjectOrErr(projects, project);
305
365
  if (!resolved.ok)
306
366
  return resolved;
307
367
  const directory = resolved.project.expandedPath;
308
368
  const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
309
- const createRes = await api(baseUrl, directory, "/session", {
369
+ const createRes = await api(baseUrl, credentials, directory, "/session", {
310
370
  method: "POST",
311
371
  body: JSON.stringify({ title: sessionTitle })
312
372
  });
@@ -319,7 +379,7 @@ async function dispatchNew(baseUrl, projects, project, prompt, title) {
319
379
  } catch (e) {
320
380
  return err(`space-bus: unexpected /session response shape: ${e.message}`);
321
381
  }
322
- const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
382
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
323
383
  method: "POST",
324
384
  body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
325
385
  });
@@ -328,11 +388,34 @@ async function dispatchNew(baseUrl, projects, project, prompt, title) {
328
388
  }
329
389
  return { ok: true, sessionId: session.id, project, directory };
330
390
  }
331
- async function dispatch(args) {
332
- const ctx = resolveContext(args.directory);
391
+ function toDispatchArgs(input) {
392
+ if (input.sessionId !== undefined && input.sessionId === "") {
393
+ return err("space-bus: sessionId must be a non-empty string");
394
+ }
395
+ if (!input.sessionId) {
396
+ if (!input.project) {
397
+ return err("space-bus: project is required when starting a new session");
398
+ }
399
+ return {
400
+ ok: true,
401
+ prompt: input.prompt,
402
+ title: input.title,
403
+ project: input.project
404
+ };
405
+ }
406
+ return {
407
+ ok: true,
408
+ prompt: input.prompt,
409
+ title: input.title,
410
+ sessionId: input.sessionId,
411
+ project: input.project
412
+ };
413
+ }
414
+ async function dispatch(args, opts) {
415
+ const ctx = validateContext(opts.context);
333
416
  if (!ctx.ok)
334
417
  return ctx;
335
- const { baseUrl, projects } = ctx;
418
+ const { baseUrl, projects, credentials } = ctx;
336
419
  if (args.sessionId !== undefined && args.sessionId === "") {
337
420
  return err("space-bus: sessionId must be a non-empty string");
338
421
  }
@@ -340,7 +423,7 @@ async function dispatch(args) {
340
423
  if (!args.project) {
341
424
  return err("space-bus: project is required when starting a new session");
342
425
  }
343
- const r = await dispatchNew(baseUrl, projects, args.project, args.prompt, args.title);
426
+ const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
344
427
  if (!r.ok)
345
428
  return r;
346
429
  return {
@@ -351,20 +434,20 @@ async function dispatch(args) {
351
434
  directory: r.directory
352
435
  };
353
436
  }
354
- const loc = await findSessionDirectory(baseUrl, projects, args.sessionId);
437
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
355
438
  if (!loc.ok)
356
439
  return loc;
357
440
  const { directory, project } = loc;
358
441
  if (args.project && args.project !== project) {
359
442
  return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
360
443
  }
361
- return steerSession(baseUrl, args.sessionId, args.prompt, directory, project);
444
+ return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project);
362
445
  }
363
- async function findSessionDirectory(baseUrl, projects, sessionId) {
446
+ async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
364
447
  for (const p of projects) {
365
- if (!existsSync2(p.expandedPath))
448
+ if (!p.exists)
366
449
  continue;
367
- const { res, bodyText } = await api(baseUrl, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
450
+ const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
368
451
  if (!res.ok)
369
452
  continue;
370
453
  let session;
@@ -381,48 +464,43 @@ async function findSessionDirectory(baseUrl, projects, sessionId) {
381
464
  }
382
465
  return err(`space-bus: no manifest project has a session with id ${sessionId}`);
383
466
  }
384
- var pendingQuestionEntrySchema = z2.object({
385
- id: z2.string(),
386
- sessionID: z2.string(),
387
- questions: z2.array(z2.object({
388
- question: z2.string().optional(),
389
- options: z2.array(z2.object({ label: z2.string().optional() }).passthrough()).optional()
390
- }).passthrough()).optional()
391
- }).passthrough();
392
- var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
393
- async function fetchPendingQuestion(baseUrl, directory, sessionId) {
467
+ function formatQuestionEntry(entry) {
468
+ const firstQuestion = entry.questions?.[0];
469
+ const text = firstQuestion?.question ?? "";
470
+ const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
471
+ const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
472
+ return { sessionId: entry.sessionID, preview, options };
473
+ }
474
+ async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
394
475
  try {
395
- const { res, bodyText } = await api(baseUrl, directory, "/question");
476
+ const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
396
477
  if (!res.ok)
397
478
  return;
398
479
  const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
399
480
  const entry = entries.find((e) => e.sessionID === sessionId);
400
481
  if (!entry)
401
482
  return;
402
- const firstQuestion = entry.questions?.[0];
403
- const text = firstQuestion?.question ?? "";
404
- const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
405
- const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
483
+ const { preview, options } = formatQuestionEntry(entry);
406
484
  return { preview, options };
407
485
  } catch {
408
486
  return;
409
487
  }
410
488
  }
411
489
  async function status(sessionId, opts) {
412
- const ctx = resolveContext(opts?.directory);
490
+ const ctx = validateContext(opts.context);
413
491
  if (!ctx.ok)
414
492
  return ctx;
415
- const { baseUrl, projects } = ctx;
416
- const loc = await findSessionDirectory(baseUrl, projects, sessionId);
493
+ const { baseUrl, projects, credentials } = ctx;
494
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
417
495
  if (!loc.ok)
418
496
  return loc;
419
497
  const { directory, project } = loc;
420
498
  const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
421
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}`),
422
- api(baseUrl, directory, "/session/status"),
423
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
424
- fetchDiffWithFallback(baseUrl, directory, sessionId),
425
- fetchPendingQuestion(baseUrl, directory, sessionId)
499
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
500
+ api(baseUrl, credentials, directory, "/session/status"),
501
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
502
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
503
+ fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
426
504
  ]);
427
505
  if (!sessionRes.res.ok) {
428
506
  return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
@@ -454,10 +532,8 @@ async function status(sessionId, opts) {
454
532
  pendingQuestion
455
533
  };
456
534
  }
457
- var questionEntrySchema = z2.object({ id: z2.string(), sessionID: z2.string() }).passthrough();
458
- var questionListSchema = z2.array(questionEntrySchema);
459
- async function steerSession(baseUrl, sessionId, message, directory, project) {
460
- const questionsRes = await api(baseUrl, directory, "/question");
535
+ async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
536
+ const questionsRes = await api(baseUrl, credentials, directory, "/question");
461
537
  if (questionsRes.res.ok) {
462
538
  let questions;
463
539
  try {
@@ -467,7 +543,7 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
467
543
  }
468
544
  const pending = questions.find((q) => q.sessionID === sessionId);
469
545
  if (pending) {
470
- const replyRes = await api(baseUrl, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
546
+ const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
471
547
  method: "POST",
472
548
  body: JSON.stringify({ answers: [[message]] })
473
549
  });
@@ -477,7 +553,7 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
477
553
  return { ok: true, sessionId, project, mode: "question-reply" };
478
554
  }
479
555
  }
480
- const promptRes = await api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
556
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
481
557
  method: "POST",
482
558
  body: JSON.stringify({ parts: [{ type: "text", text: message }] })
483
559
  });
@@ -487,15 +563,15 @@ async function steerSession(baseUrl, sessionId, message, directory, project) {
487
563
  return { ok: true, sessionId, project, mode: "follow-up" };
488
564
  }
489
565
  async function result(sessionId, opts) {
490
- const ctx = resolveContext(opts?.directory);
566
+ const ctx = validateContext(opts.context);
491
567
  if (!ctx.ok)
492
568
  return ctx;
493
- const { baseUrl, projects } = ctx;
494
- const loc = await findSessionDirectory(baseUrl, projects, sessionId);
569
+ const { baseUrl, projects, credentials } = ctx;
570
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
495
571
  if (!loc.ok)
496
572
  return loc;
497
573
  const { directory, project } = loc;
498
- const statusMapRes = await api(baseUrl, directory, "/session/status");
574
+ const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
499
575
  if (statusMapRes.res.ok) {
500
576
  try {
501
577
  const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
@@ -506,8 +582,8 @@ async function result(sessionId, opts) {
506
582
  } catch {}
507
583
  }
508
584
  const [messageRes, diffResult] = await Promise.all([
509
- api(baseUrl, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
510
- fetchDiffWithFallback(baseUrl, directory, sessionId)
585
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
586
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
511
587
  ]);
512
588
  if (!messageRes.res.ok) {
513
589
  return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
@@ -524,6 +600,90 @@ async function result(sessionId, opts) {
524
600
  `).trim() : "";
525
601
  return { ok: true, sessionId, project, text, diff, diffSource };
526
602
  }
603
+ async function fetchSnapshotProject(baseUrl, credentials, project) {
604
+ const directory = project.expandedPath;
605
+ try {
606
+ const [statusRes, listRes, questionRes] = await Promise.all([
607
+ api(baseUrl, credentials, directory, "/session/status"),
608
+ api(baseUrl, credentials, directory, "/session?limit=101"),
609
+ api(baseUrl, credentials, directory, "/question")
610
+ ]);
611
+ if (!statusRes.res.ok || !listRes.res.ok) {
612
+ return {
613
+ name: project.name,
614
+ path: directory,
615
+ exists: true,
616
+ description: project.description,
617
+ error: `status=${statusRes.res.status}/${listRes.res.status}`
618
+ };
619
+ }
620
+ const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
621
+ const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
622
+ const busyCount = Object.values(statusMap).filter((s) => s.type === "busy" || s.type === "retry").length;
623
+ const capped = sessions.length > 100;
624
+ let pendingQuestions;
625
+ if (questionRes.res.ok) {
626
+ try {
627
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
628
+ pendingQuestions = entries.map((e) => formatQuestionEntry(e));
629
+ } catch {
630
+ pendingQuestions = undefined;
631
+ }
632
+ }
633
+ return {
634
+ name: project.name,
635
+ path: directory,
636
+ exists: true,
637
+ description: project.description,
638
+ busyCount,
639
+ sessionCount: capped ? 100 : sessions.length,
640
+ sessionCountCapped: capped,
641
+ pendingQuestions
642
+ };
643
+ } catch (e) {
644
+ return {
645
+ name: project.name,
646
+ path: directory,
647
+ exists: true,
648
+ description: project.description,
649
+ error: e.message
650
+ };
651
+ }
652
+ }
653
+ async function mapWithConcurrency(items, concurrency, fn) {
654
+ const results = new Array(items.length);
655
+ let next = 0;
656
+ const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
657
+ const workers = Array.from({ length: limit }, async () => {
658
+ while (true) {
659
+ const i = next++;
660
+ if (i >= items.length)
661
+ return;
662
+ results[i] = await fn(items[i]);
663
+ }
664
+ });
665
+ await Promise.all(workers);
666
+ return results;
667
+ }
668
+ async function snapshot(opts) {
669
+ const ctx = validateContext(opts.context);
670
+ if (!ctx.ok)
671
+ return ctx;
672
+ const { baseUrl, projects, credentials } = ctx;
673
+ const concurrency = opts.concurrency ?? 4;
674
+ const results = await mapWithConcurrency(projects, concurrency, async (p) => {
675
+ if (!p.exists) {
676
+ return {
677
+ name: p.name,
678
+ path: p.expandedPath,
679
+ exists: false,
680
+ description: p.description
681
+ };
682
+ }
683
+ return fetchSnapshotProject(baseUrl, credentials, p);
684
+ });
685
+ return { ok: true, projects: results };
686
+ }
527
687
 
528
688
  // src/format.ts
529
689
  function formatRoster(projects) {
@@ -580,6 +740,7 @@ function formatResult(r) {
580
740
  }
581
741
 
582
742
  // src/tools/bus_result.ts
743
+ import { tool } from "@opencode-ai/plugin";
583
744
  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.";
584
745
  function makeBusResult(defaultDirectory) {
585
746
  return tool({
@@ -588,9 +749,14 @@ function makeBusResult(defaultDirectory) {
588
749
  sessionId: tool.schema.string().describe("Session ID returned by bus_task")
589
750
  },
590
751
  async execute(args, ctx) {
591
- const r = await result(args.sessionId, {
592
- directory: ctx.directory ?? defaultDirectory
593
- });
752
+ const directory = ctx.directory ?? defaultDirectory;
753
+ let context;
754
+ try {
755
+ context = loadContext(directory);
756
+ } catch (e) {
757
+ throw new Error(e.message);
758
+ }
759
+ const r = await result(args.sessionId, { context });
594
760
  if (!r.ok)
595
761
  throw new Error(r.error);
596
762
  return formatResult(r);
@@ -606,7 +772,14 @@ function makeBusRoster(defaultDirectory) {
606
772
  description: BUS_ROSTER_DESCRIPTION,
607
773
  args: {},
608
774
  async execute(_args, ctx) {
609
- const r = await roster({ directory: ctx.directory ?? defaultDirectory });
775
+ const directory = ctx.directory ?? defaultDirectory;
776
+ let context;
777
+ try {
778
+ context = loadContext(directory);
779
+ } catch (e) {
780
+ throw new Error(e.message);
781
+ }
782
+ const r = await roster({ context });
610
783
  if (!r.ok)
611
784
  throw new Error(r.error);
612
785
  return formatRoster(r.projects);
@@ -624,9 +797,14 @@ function makeBusStatus(defaultDirectory) {
624
797
  sessionId: tool3.schema.string().describe("Session ID returned by bus_task")
625
798
  },
626
799
  async execute(args, ctx) {
627
- const r = await status(args.sessionId, {
628
- directory: ctx.directory ?? defaultDirectory
629
- });
800
+ const directory = ctx.directory ?? defaultDirectory;
801
+ let context;
802
+ try {
803
+ context = loadContext(directory);
804
+ } catch (e) {
805
+ throw new Error(e.message);
806
+ }
807
+ const r = await status(args.sessionId, { context });
630
808
  if (!r.ok)
631
809
  throw new Error(r.error);
632
810
  return formatStatus(r);
@@ -647,10 +825,17 @@ function makeBusTask(defaultDirectory) {
647
825
  sessionId: tool4.schema.string().optional().describe("Existing session ID to steer instead of starting a new session")
648
826
  },
649
827
  async execute(args, ctx) {
650
- const r = await dispatch({
651
- ...args,
652
- directory: ctx.directory ?? defaultDirectory
653
- });
828
+ const dispatchArgs = toDispatchArgs(args);
829
+ if (!dispatchArgs.ok)
830
+ throw new Error(dispatchArgs.error);
831
+ const directory = ctx.directory ?? defaultDirectory;
832
+ let context;
833
+ try {
834
+ context = loadContext(directory);
835
+ } catch (e) {
836
+ throw new Error(e.message);
837
+ }
838
+ const r = await dispatch(dispatchArgs, { context });
654
839
  if (!r.ok)
655
840
  throw new Error(r.error);
656
841
  return formatDispatch(r);