@fro.bot/space-bus 0.9.0 → 0.10.1

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
@@ -2,6 +2,12 @@
2
2
  import { createRequire } from "node:module";
3
3
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
4
 
5
+ // src/config.ts
6
+ import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
7
+ import { homedir as homedir2 } from "node:os";
8
+ import { join as join2 } from "node:path";
9
+ import { z as z3 } from "zod";
10
+
5
11
  // src/contract.ts
6
12
  import { z } from "zod";
7
13
  var sessionSchema = z.looseObject({
@@ -131,1634 +137,1540 @@ var discoveryFileSchema = z.object({
131
137
  baseUrl: z.url()
132
138
  });
133
139
 
134
- // src/core.ts
135
- function findProject(projects, name) {
136
- return projects.find((p) => p.name === name);
140
+ // src/discovery.ts
141
+ import { execFileSync } from "node:child_process";
142
+ import { createHash, randomBytes } from "node:crypto";
143
+ import {
144
+ chmodSync,
145
+ closeSync,
146
+ constants as fsConstants,
147
+ mkdirSync,
148
+ openSync,
149
+ readFileSync,
150
+ renameSync,
151
+ statSync,
152
+ unlinkSync,
153
+ writeFileSync
154
+ } from "node:fs";
155
+ import { homedir } from "node:os";
156
+ import { join } from "node:path";
157
+ import { z as z2 } from "zod";
158
+ function stateDirFor(rosterPath) {
159
+ const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
160
+ const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
161
+ return join(base, "space-bus", hash);
137
162
  }
138
- function err(error) {
139
- return { ok: false, error };
163
+ function discoveryFilePath(rosterPath) {
164
+ return join(stateDirFor(rosterPath), "discovery.json");
140
165
  }
141
- function toBase64(s) {
142
- const bytes = new TextEncoder().encode(s);
143
- let bin = "";
144
- for (const b of bytes)
145
- bin += String.fromCharCode(b);
146
- return btoa(bin);
166
+ function lockFilePath(rosterPath) {
167
+ return join(stateDirFor(rosterPath), "spawn.lock");
147
168
  }
148
- function authHeader(credentials) {
149
- if (!credentials.password)
150
- return {};
151
- const username = credentials.username ?? "opencode";
152
- const token = toBase64(`${username}:${credentials.password}`);
153
- return { Authorization: `Basic ${token}` };
169
+ function logFilePath(rosterPath) {
170
+ return join(stateDirFor(rosterPath), "server.log");
154
171
  }
155
- async function api(baseUrl, credentials, directory, path, init) {
172
+ function writeDiscovery(rosterPath, data) {
173
+ const dir = stateDirFor(rosterPath);
174
+ mkdirSync(dir, { recursive: true, mode: 448 });
175
+ chmodSync(dir, 448);
176
+ const target = discoveryFilePath(rosterPath);
177
+ const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
178
+ const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
156
179
  try {
157
- const res = await fetch(`${baseUrl}${path}`, {
158
- ...init,
159
- headers: {
160
- "content-type": "application/json",
161
- "x-opencode-directory": directory,
162
- ...authHeader(credentials),
163
- ...init?.headers
164
- },
165
- redirect: "error",
166
- signal: AbortSignal.timeout(30000)
167
- });
168
- const bodyText = await res.text().catch(() => "<unreadable body>");
169
- return { res, bodyText };
170
- } catch (e) {
171
- const message = e.message;
172
- return {
173
- res: new Response(null, {
174
- status: 599,
175
- statusText: "space-bus: request failed"
176
- }),
177
- bodyText: `space-bus: request failed: ${message}`
178
- };
180
+ writeFileSync(fd, JSON.stringify(data));
181
+ } finally {
182
+ closeQuietly(fd);
179
183
  }
184
+ renameSync(tempPath, target);
185
+ chmodSync(target, 384);
180
186
  }
181
- async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
182
- const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
183
- if (!res.ok)
184
- return [];
185
- let messages;
187
+ function readDiscovery(rosterPath) {
188
+ const target = discoveryFilePath(rosterPath);
189
+ let raw;
186
190
  try {
187
- messages = turnMessageListSchema.parse(JSON.parse(bodyText));
191
+ raw = readFileSync(target, "utf8");
188
192
  } catch {
189
- return [];
190
- }
191
- const byFile = new Map;
192
- for (const m of messages) {
193
- if (m.info.role !== "user")
194
- continue;
195
- const diffs = m.info.summary?.diffs;
196
- if (!diffs || diffs.length === 0)
197
- continue;
198
- for (const d of diffs) {
199
- const key = d.file ?? `<unknown:${byFile.size}>`;
200
- byFile.set(key, d);
201
- }
193
+ return null;
202
194
  }
203
- return Array.from(byFile.values());
204
- }
205
- async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
206
- const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
207
- let diff = [];
195
+ let json;
208
196
  try {
209
- diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
197
+ json = JSON.parse(raw);
210
198
  } catch {
211
- diff = [];
212
- }
213
- if (diff.length > 0) {
214
- return { diff, diffSource: "session" };
199
+ return null;
215
200
  }
201
+ const parsed = discoveryFileSchema.safeParse(json);
202
+ return parsed.success ? parsed.data : null;
203
+ }
204
+ function removeDiscovery(rosterPath) {
216
205
  try {
217
- const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
218
- if (sessionRes.res.ok) {
219
- const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
220
- const summaryDiffs = parsed.summary?.diffs;
221
- if (summaryDiffs && summaryDiffs.length > 0) {
222
- return { diff: summaryDiffs, diffSource: "session" };
223
- }
224
- }
225
- } catch {}
226
- try {
227
- const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
228
- if (turnDiffs.length > 0) {
229
- return { diff: turnDiffs, diffSource: "turns" };
230
- }
231
- } catch {}
206
+ unlinkSync(discoveryFilePath(rosterPath));
207
+ } catch (err) {
208
+ if (!isEnoent(err))
209
+ throw err;
210
+ }
211
+ }
212
+ function removeDiscoveryIfMatches(rosterPath, expected) {
232
213
  try {
233
- const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
234
- if (vcsRes.res.ok) {
235
- const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
236
- if (vcsStatus.length > 0) {
237
- return {
238
- diff: vcsStatus.map((v) => ({
239
- file: v.file,
240
- additions: v.additions,
241
- deletions: v.deletions,
242
- status: v.status
243
- })),
244
- diffSource: "working-tree"
245
- };
246
- }
214
+ const current = readDiscovery(rosterPath);
215
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
216
+ removeDiscovery(rosterPath);
247
217
  }
248
218
  } catch {}
249
- return { diff, diffSource: "session" };
250
219
  }
251
- function validateContext(context) {
252
- const parsed = busContextSchema.safeParse(context);
253
- if (!parsed.success) {
254
- return err(`space-bus: invalid context: ${parsed.error.message}`);
220
+ function attachLive(rosterPath) {
221
+ const discovery = readDiscovery(rosterPath);
222
+ if (!discovery)
223
+ return null;
224
+ if (!loopbackOk(discovery.baseUrl))
225
+ return null;
226
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
227
+ removeDiscoveryIfMatches(rosterPath, {
228
+ pid: discovery.pid,
229
+ identity: discovery.identity
230
+ });
231
+ return null;
255
232
  }
256
- const { roster, credentials } = parsed.data;
257
- let hostname;
233
+ return {
234
+ baseUrl: discovery.baseUrl,
235
+ credentials: { username: "opencode", password: discovery.password },
236
+ pid: discovery.pid,
237
+ port: discovery.port
238
+ };
239
+ }
240
+ function captureIdentity(pid) {
258
241
  try {
259
- hostname = new URL(roster.server.baseUrl).hostname;
242
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
243
+ env: { ...process.env, LC_ALL: "C" },
244
+ encoding: "utf8"
245
+ });
246
+ const trimmed = out.trim();
247
+ return trimmed.length > 0 ? trimmed : null;
260
248
  } catch {
261
- return err("space-bus: context roster server.baseUrl is not a valid URL");
249
+ return null;
262
250
  }
263
- if (!LOOPBACK_HOSTS.has(hostname)) {
264
- return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
251
+ }
252
+ function isAlive(pid) {
253
+ try {
254
+ process.kill(pid, 0);
255
+ return true;
256
+ } catch {
257
+ return false;
265
258
  }
266
- return {
267
- ok: true,
268
- baseUrl: roster.server.baseUrl,
269
- projects: roster.projects,
270
- credentials: credentials ?? {}
271
- };
272
259
  }
273
- function isStatusBusy(entry) {
274
- return entry?.type === "busy" || entry?.type === "retry" || false;
260
+ function verifyIdentity(pid, storedIdentity) {
261
+ if (!isAlive(pid))
262
+ return false;
263
+ const current = captureIdentity(pid);
264
+ return current !== null && current === storedIdentity;
275
265
  }
276
- function resolveProjectOrErr(projects, name) {
277
- const project = findProject(projects, name);
278
- if (!project) {
279
- const valid = projects.map((p) => p.name).join(", ");
280
- return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
266
+ var lockFileSchema = z2.object({
267
+ pid: z2.number().int().min(2),
268
+ startTime: z2.string(),
269
+ since: z2.number()
270
+ });
271
+ var CORRUPT_LOCK_GRACE_MS = 2000;
272
+ function acquireLock(rosterPath) {
273
+ const dir = stateDirFor(rosterPath);
274
+ mkdirSync(dir, { recursive: true, mode: 448 });
275
+ chmodSync(dir, 448);
276
+ const target = lockFilePath(rosterPath);
277
+ const identity = captureIdentity(process.pid) ?? "";
278
+ const lock = {
279
+ pid: process.pid,
280
+ startTime: identity,
281
+ since: Date.now()
282
+ };
283
+ if (tryCreateLockFile(target, lock)) {
284
+ return { rosterPath };
281
285
  }
282
- if (!project.exists) {
283
- return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
286
+ const existing = readLockFile(target);
287
+ if (existing) {
288
+ if (verifyIdentity(existing.pid, existing.startTime))
289
+ return null;
290
+ } else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
291
+ return null;
284
292
  }
285
- return { ok: true, project };
286
- }
287
- async function roster(opts) {
288
- const ctx = validateContext(opts.context);
289
- if (!ctx.ok)
290
- return ctx;
291
- const { baseUrl, projects, credentials } = ctx;
292
- const results = await Promise.all(projects.map(async (p) => {
293
- if (!p.exists) {
294
- return {
295
- name: p.name,
296
- path: p.expandedPath,
297
- description: p.description,
298
- pathExists: false
299
- };
300
- }
301
- try {
302
- const [statusRes, listRes] = await Promise.all([
303
- api(baseUrl, credentials, p.expandedPath, "/session/status"),
304
- api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
305
- ]);
306
- if (!statusRes.res.ok || !listRes.res.ok) {
307
- return {
308
- name: p.name,
309
- path: p.expandedPath,
310
- description: p.description,
311
- pathExists: true,
312
- statusError: `status=${statusRes.res.status}/${listRes.res.status}`
313
- };
314
- }
315
- const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
316
- const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
317
- const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
318
- const capped = sessions.length > 100;
319
- return {
320
- name: p.name,
321
- path: p.expandedPath,
322
- description: p.description,
323
- pathExists: true,
324
- busyCount,
325
- sessionCount: capped ? 100 : sessions.length,
326
- sessionCountCapped: capped
327
- };
328
- } catch (e) {
329
- return {
330
- name: p.name,
331
- path: p.expandedPath,
332
- description: p.description,
333
- pathExists: true,
334
- statusError: e.message
335
- };
336
- }
337
- }));
338
- return { ok: true, projects: results };
339
- }
340
- async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
341
- const resolved = resolveProjectOrErr(projects, project);
342
- if (!resolved.ok)
343
- return resolved;
344
- const directory = resolved.project.expandedPath;
345
- const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
346
- const createRes = await api(baseUrl, credentials, directory, "/session", {
347
- method: "POST",
348
- body: JSON.stringify({ title: sessionTitle })
349
- });
350
- if (!createRes.res.ok) {
351
- return err(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`);
352
- }
353
- let session;
354
293
  try {
355
- session = sessionSchema.parse(JSON.parse(createRes.bodyText));
356
- } catch (e) {
357
- return err(`space-bus: unexpected /session response shape: ${e.message}`);
294
+ unlinkSync(target);
295
+ } catch (err) {
296
+ if (!isEnoent(err))
297
+ throw err;
358
298
  }
359
- const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
360
- method: "POST",
361
- body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
362
- });
363
- if (promptRes.res.status !== 204) {
364
- return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
299
+ if (tryCreateLockFile(target, lock)) {
300
+ return { rosterPath };
365
301
  }
366
- return { ok: true, sessionId: session.id, project, directory };
302
+ return null;
367
303
  }
368
- function toDispatchArgs(input) {
369
- if (input.sessionId !== undefined && input.sessionId === "") {
370
- return err("space-bus: sessionId must be a non-empty string");
371
- }
372
- if (!input.sessionId) {
373
- if (!input.project) {
374
- return err("space-bus: project is required when starting a new session");
375
- }
376
- return {
377
- ok: true,
378
- prompt: input.prompt,
379
- title: input.title,
380
- project: input.project
381
- };
304
+ function isOlderThan(path, ageMs) {
305
+ try {
306
+ return Date.now() - statSync(path).mtimeMs > ageMs;
307
+ } catch {
308
+ return false;
382
309
  }
383
- return {
384
- ok: true,
385
- prompt: input.prompt,
386
- title: input.title,
387
- sessionId: input.sessionId,
388
- project: input.project
389
- };
390
310
  }
391
- async function dispatch(args, opts) {
392
- const ctx = validateContext(opts.context);
393
- if (!ctx.ok)
394
- return ctx;
395
- const { baseUrl, projects, credentials } = ctx;
396
- if (args.sessionId !== undefined && args.sessionId === "") {
397
- return err("space-bus: sessionId must be a non-empty string");
398
- }
399
- if (!args.sessionId) {
400
- if (!args.project) {
401
- return err("space-bus: project is required when starting a new session");
402
- }
403
- const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
404
- if (!r.ok)
405
- return r;
406
- return {
407
- ok: true,
408
- sessionId: r.sessionId,
409
- project: r.project,
410
- mode: "new",
411
- directory: r.directory
412
- };
311
+ function releaseLock(handle) {
312
+ try {
313
+ unlinkSync(lockFilePath(handle.rosterPath));
314
+ } catch {}
315
+ }
316
+ function readLockFile(target) {
317
+ let raw;
318
+ try {
319
+ raw = readFileSync(target, "utf8");
320
+ } catch {
321
+ return null;
413
322
  }
414
- const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
415
- if (!loc.ok)
416
- return loc;
417
- const { directory, project } = loc;
418
- if (args.project && args.project !== project) {
419
- return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
323
+ let json;
324
+ try {
325
+ json = JSON.parse(raw);
326
+ } catch {
327
+ return null;
420
328
  }
421
- return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project);
329
+ const parsed = lockFileSchema.safeParse(json);
330
+ return parsed.success ? parsed.data : null;
422
331
  }
423
- async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
424
- for (const p of projects) {
425
- if (!p.exists)
426
- continue;
427
- const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
428
- if (!res.ok)
429
- continue;
430
- let session;
431
- try {
432
- session = sessionSchema.parse(JSON.parse(bodyText));
433
- } catch {
434
- continue;
435
- }
436
- const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
437
- if (owner) {
438
- return { ok: true, directory: owner.expandedPath, project: owner.name };
439
- }
440
- return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
332
+ function tryCreateLockFile(target, lock) {
333
+ let fd;
334
+ try {
335
+ fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
336
+ } catch (err) {
337
+ if (isErrnoCode(err, "EEXIST"))
338
+ return false;
339
+ throw err;
441
340
  }
442
- return err(`space-bus: no manifest project has a session with id ${sessionId}`);
341
+ try {
342
+ writeFileSync(fd, JSON.stringify(lock));
343
+ } finally {
344
+ closeQuietly(fd);
345
+ }
346
+ return true;
443
347
  }
444
- function deriveSessionState(input) {
445
- if (!input.resolved)
446
- return "not_found";
447
- if (input.failed)
448
- return "failed";
449
- if (input.pendingQuestion)
450
- return "blocked";
451
- if (input.busy)
452
- return "running";
453
- return "complete";
348
+ function isEnoent(err) {
349
+ return isErrnoCode(err, "ENOENT");
454
350
  }
455
- function formatQuestionEntry(entry) {
456
- const firstQuestion = entry.questions?.[0];
457
- const text = firstQuestion?.question ?? "";
458
- const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
459
- const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
460
- return { sessionId: entry.sessionID, preview, options };
351
+ function isErrnoCode(err, code) {
352
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
461
353
  }
462
- async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
354
+ function closeQuietly(fd) {
463
355
  try {
464
- const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
465
- if (!res.ok)
466
- return;
467
- const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
468
- const entry = entries.find((e) => e.sessionID === sessionId);
469
- if (!entry)
470
- return;
471
- const { preview, options } = formatQuestionEntry(entry);
472
- return { preview, options };
356
+ closeSync(fd);
357
+ } catch {}
358
+ }
359
+ function provisionalFilePath(rosterPath) {
360
+ return join(stateDirFor(rosterPath), "spawn.provisional.json");
361
+ }
362
+ var provisionalFileSchema = z2.object({
363
+ pid: z2.number().int().min(2),
364
+ identity: z2.string(),
365
+ password: z2.string(),
366
+ since: z2.number()
367
+ });
368
+ function writeProvisional(rosterPath, data) {
369
+ const dir = stateDirFor(rosterPath);
370
+ mkdirSync(dir, { recursive: true, mode: 448 });
371
+ chmodSync(dir, 448);
372
+ const target = provisionalFilePath(rosterPath);
373
+ const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
374
+ try {
375
+ writeFileSync(fd, JSON.stringify(data));
376
+ } finally {
377
+ closeQuietly(fd);
378
+ }
379
+ chmodSync(target, 384);
380
+ }
381
+ function readProvisional(rosterPath) {
382
+ const target = provisionalFilePath(rosterPath);
383
+ let raw;
384
+ try {
385
+ raw = readFileSync(target, "utf8");
473
386
  } catch {
474
- return;
387
+ return null;
388
+ }
389
+ let json;
390
+ try {
391
+ json = JSON.parse(raw);
392
+ } catch {
393
+ return null;
475
394
  }
395
+ const parsed = provisionalFileSchema.safeParse(json);
396
+ return parsed.success ? parsed.data : null;
476
397
  }
477
- async function status(sessionId, opts) {
478
- const ctx = validateContext(opts.context);
479
- if (!ctx.ok)
480
- return ctx;
481
- const { baseUrl, projects, credentials } = ctx;
482
- const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
483
- if (!loc.ok)
484
- return loc;
485
- const { directory, project } = loc;
486
- const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
487
- api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
488
- api(baseUrl, credentials, directory, "/session/status"),
489
- api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
490
- fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
491
- fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
492
- ]);
493
- if (!sessionRes.res.ok) {
494
- return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
495
- }
496
- let session;
497
- let statusMap;
498
- let todos;
398
+ function removeProvisional(rosterPath) {
499
399
  try {
500
- session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
501
- statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
502
- todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
503
- } catch (e) {
504
- return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
400
+ unlinkSync(provisionalFilePath(rosterPath));
401
+ } catch {}
402
+ }
403
+
404
+ // src/config.ts
405
+ var managedServerConfigSchema = z3.object({
406
+ command: z3.array(z3.string()).optional(),
407
+ cwd: z3.string().optional(),
408
+ port: z3.number().int().nonnegative().optional()
409
+ });
410
+ var serverConfigSchema = z3.object({
411
+ baseUrl: z3.url().optional(),
412
+ managed: managedServerConfigSchema.optional()
413
+ }).superRefine((val, ctx) => {
414
+ const hasBaseUrl = val.baseUrl !== undefined;
415
+ const hasManaged = val.managed !== undefined;
416
+ if (hasBaseUrl && hasManaged) {
417
+ ctx.addIssue({
418
+ code: "custom",
419
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
420
+ });
421
+ } else if (!hasBaseUrl && !hasManaged) {
422
+ ctx.addIssue({
423
+ code: "custom",
424
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
425
+ });
505
426
  }
506
- const entry = statusMap[sessionId];
507
- const busy = isStatusBusy(entry);
508
- const { diff, diffSource } = diffResult;
509
- const additions = diff.reduce((sum, d) => sum + d.additions, 0);
510
- const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
511
- const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
512
- return {
513
- ok: true,
514
- sessionId,
515
- project,
516
- busy,
517
- title: session.title,
518
- todos,
519
- diff: { files: diff.length, additions, deletions },
520
- diffSource,
521
- pendingQuestion,
522
- state,
523
- resultAvailable: state === "complete"
524
- };
427
+ });
428
+ var manifestSchema = z3.object({
429
+ server: serverConfigSchema,
430
+ projects: z3.array(z3.object({
431
+ name: z3.string(),
432
+ path: z3.string(),
433
+ description: z3.string()
434
+ }))
435
+ });
436
+ function expandHome(path) {
437
+ return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
525
438
  }
526
- async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
527
- const questionsRes = await api(baseUrl, credentials, directory, "/question");
528
- if (questionsRes.res.ok) {
529
- let questions;
530
- try {
531
- questions = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
532
- } catch {
533
- questions = [];
439
+ function resolveRosterPath(directory) {
440
+ const override = process.env["SPACE_BUS_CONFIG"];
441
+ if (override) {
442
+ if (override.includes("://")) {
443
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
534
444
  }
535
- const pending = questions.find((q) => q.sessionID === sessionId);
536
- if (pending) {
537
- const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
538
- method: "POST",
539
- body: JSON.stringify({ answers: [[message]] })
540
- });
541
- if (!replyRes.res.ok) {
542
- return err(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`);
543
- }
544
- return { ok: true, sessionId, project, mode: "question-reply" };
445
+ const expanded = expandHome(override);
446
+ if (!expanded.startsWith("/")) {
447
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
545
448
  }
449
+ return existsSync(expanded) ? realpathSync(expanded) : expanded;
546
450
  }
547
- const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
548
- method: "POST",
549
- body: JSON.stringify({ parts: [{ type: "text", text: message }] })
550
- });
551
- if (promptRes.res.status !== 204) {
552
- return err(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`);
451
+ if (directory) {
452
+ const candidate = join2(directory, "spacebus.json");
453
+ return existsSync(candidate) ? realpathSync(candidate) : candidate;
553
454
  }
554
- return { ok: true, sessionId, project, mode: "follow-up" };
455
+ throw new Error("space-bus: cannot locate spacebus.json — pass a directory containing spacebus.json, or set SPACE_BUS_CONFIG to an absolute path (or ~-prefixed path) to the roster file");
555
456
  }
556
- async function result(sessionId, opts) {
557
- const ctx = validateContext(opts.context);
558
- if (!ctx.ok)
559
- return ctx;
560
- const { baseUrl, projects, credentials } = ctx;
561
- const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
562
- if (!loc.ok)
563
- return loc;
564
- const { directory, project } = loc;
565
- const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
566
- if (statusMapRes.res.ok) {
567
- try {
568
- const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
569
- const entry = statusMap[sessionId];
570
- if (isStatusBusy(entry)) {
571
- return err(`space-bus: session ${sessionId} is still running, use bus_status`);
572
- }
573
- } catch {}
574
- }
575
- const [messageRes, diffResult] = await Promise.all([
576
- api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
577
- fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
578
- ]);
579
- if (!messageRes.res.ok) {
580
- return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
581
- }
582
- let messages;
457
+ function getRoster(directory) {
458
+ const manifestPath = resolveRosterPath(directory);
459
+ let raw;
583
460
  try {
584
- messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
585
- } catch (e) {
586
- return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
461
+ raw = readFileSync2(manifestPath, "utf8");
462
+ } catch (err) {
463
+ throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
587
464
  }
588
- const { diff, diffSource } = diffResult;
589
- const last = messages.filter((m) => m.info.role === "assistant").at(-1);
590
- const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
591
- `).trim() : "";
592
- return { ok: true, sessionId, project, text, diff, diffSource };
593
- }
594
- async function fetchSnapshotProject(baseUrl, credentials, project) {
595
- const directory = project.expandedPath;
465
+ let json;
596
466
  try {
597
- const [statusRes, listRes, questionRes] = await Promise.all([
598
- api(baseUrl, credentials, directory, "/session/status"),
599
- api(baseUrl, credentials, directory, "/session?limit=101"),
600
- api(baseUrl, credentials, directory, "/question")
601
- ]);
602
- if (!statusRes.res.ok || !listRes.res.ok) {
603
- return {
604
- name: project.name,
605
- path: directory,
606
- exists: true,
607
- description: project.description,
608
- error: `status=${statusRes.res.status}/${listRes.res.status}`
609
- };
610
- }
611
- const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
612
- const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
613
- const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
614
- const capped = sessions.length > 100;
615
- let pendingQuestions;
616
- let pendingQuestionsBySession = new Map;
617
- if (questionRes.res.ok) {
618
- try {
619
- const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
620
- const formatted = entries.map((e) => formatQuestionEntry(e));
621
- pendingQuestions = formatted;
622
- pendingQuestionsBySession = new Map(formatted.map((q) => [q.sessionId, q]));
623
- } catch {
624
- pendingQuestions = undefined;
625
- }
467
+ json = JSON.parse(raw);
468
+ } catch (err) {
469
+ throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
470
+ }
471
+ const parsed = manifestSchema.safeParse(json);
472
+ if (!parsed.success) {
473
+ throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
474
+ }
475
+ if (parsed.data.server.baseUrl !== undefined) {
476
+ const url = new URL(parsed.data.server.baseUrl);
477
+ const hostname = url.hostname;
478
+ if (!LOOPBACK_HOSTS.has(hostname)) {
479
+ throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
626
480
  }
627
- const sessionStates = sessions.map((s) => {
628
- const entry = statusMap[s.id];
629
- const busy = isStatusBusy(entry);
630
- const pendingQuestion = pendingQuestionsBySession.get(s.id);
631
- const state = deriveSessionState({
632
- busy,
633
- pendingQuestion,
634
- resolved: true
635
- });
636
- return {
637
- sessionId: s.id,
638
- state,
639
- resultAvailable: state === "complete"
640
- };
641
- });
642
- return {
643
- name: project.name,
644
- path: directory,
645
- exists: true,
646
- description: project.description,
647
- busyCount,
648
- sessionCount: capped ? 100 : sessions.length,
649
- sessionCountCapped: capped,
650
- pendingQuestions,
651
- sessions: sessionStates
652
- };
653
- } catch (e) {
654
- return {
655
- name: project.name,
656
- path: directory,
657
- exists: true,
658
- description: project.description,
659
- error: e.message
660
- };
661
481
  }
482
+ return parsed.data;
662
483
  }
663
- async function mapWithConcurrency(items, concurrency, fn) {
664
- const results = new Array(items.length);
665
- let next = 0;
666
- const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
667
- const workers = Array.from({ length: limit }, async () => {
668
- while (true) {
669
- const i = next++;
670
- if (i >= items.length)
671
- return;
672
- results[i] = await fn(items[i]);
673
- }
484
+ function getProjects(manifest) {
485
+ return manifest.projects.map((p) => {
486
+ const expandedPath = expandHome(p.path);
487
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
674
488
  });
675
- await Promise.all(workers);
676
- return results;
677
489
  }
678
- async function snapshot(opts) {
679
- const ctx = validateContext(opts.context);
680
- if (!ctx.ok)
681
- return ctx;
682
- const { baseUrl, projects, credentials } = ctx;
683
- const concurrency = opts.concurrency ?? 4;
684
- const results = await mapWithConcurrency(projects, concurrency, async (p) => {
685
- if (!p.exists) {
686
- return {
687
- name: p.name,
688
- path: p.expandedPath,
689
- exists: false,
690
- description: p.description
691
- };
490
+ function getCredentials() {
491
+ const password = process.env["OPENCODE_SERVER_PASSWORD"];
492
+ if (!password)
493
+ return {};
494
+ const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
495
+ return { username, password };
496
+ }
497
+ function loadContext(directory) {
498
+ const rosterPath = resolveRosterPath(directory);
499
+ const manifest = getRoster(directory);
500
+ const projects = getProjects(manifest);
501
+ if (manifest.server.baseUrl === undefined) {
502
+ const live = attachLive(rosterPath);
503
+ if (!live) {
504
+ throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
692
505
  }
693
- return fetchSnapshotProject(baseUrl, credentials, p);
694
- });
695
- return { ok: true, projects: results };
506
+ return {
507
+ roster: { server: { baseUrl: live.baseUrl }, projects },
508
+ credentials: live.credentials
509
+ };
510
+ }
511
+ return {
512
+ roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
513
+ credentials: getCredentials()
514
+ };
696
515
  }
697
- var DEFAULT_WAIT_TIMEOUT_MS = 60000;
698
- var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
699
- var DEFAULT_WAIT_CONCURRENCY = 4;
700
- var NEEDS_ATTENTION_STATES = [
701
- "complete",
702
- "blocked",
703
- "failed",
704
- "not_found"
705
- ];
706
- function sleep(ms) {
707
- return new Promise((resolve) => setTimeout(resolve, ms));
516
+ function isManagedRoster(directory) {
517
+ const manifest = getRoster(directory);
518
+ return manifest.server.managed !== undefined;
708
519
  }
709
- async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
710
- const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
711
- const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
712
- return { id, loc };
713
- });
714
- const locationById = new Map;
715
- for (const { id, loc } of locations) {
716
- locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
520
+
521
+ // src/server.ts
522
+ import { spawn } from "node:child_process";
523
+ import { randomBytes as randomBytes2 } from "node:crypto";
524
+ import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
525
+ import { dirname } from "node:path";
526
+ var DEFAULT_READINESS_BUDGET_MS = 15000;
527
+ var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
528
+ var POLL_INTERVAL_MS = 50;
529
+ var MIN_PROBE_PHASE_MS = 3000;
530
+ var PROBE_FETCH_TIMEOUT_MS = 2000;
531
+ var STOP_GRACE_MS = 2000;
532
+ var SUPERVISE_INTERVAL_MS = 5000;
533
+ var SUPERVISE_FAILURE_THRESHOLD = 3;
534
+ var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
535
+ function sleep(ms) {
536
+ return new Promise((resolve) => setTimeout(resolve, ms));
537
+ }
538
+ function readManifest(rosterPath) {
539
+ const raw = readFileSync3(rosterPath, "utf8");
540
+ const json = JSON.parse(raw);
541
+ return manifestSchema.parse(json);
542
+ }
543
+ function readLogTail(logPath, maxChars = 4000) {
544
+ try {
545
+ const content = readFileSync3(logPath, "utf8");
546
+ return content.length > maxChars ? content.slice(-maxChars) : content;
547
+ } catch {
548
+ return "";
717
549
  }
718
- const groups = new Map;
719
- for (const id of sessionIds) {
720
- const loc = locationById.get(id);
721
- if (!loc)
722
- continue;
723
- const group = groups.get(loc.directory) ?? {
724
- directory: loc.directory,
725
- sessionIds: []
726
- };
727
- group.sessionIds.push(id);
728
- groups.set(loc.directory, group);
550
+ }
551
+ function basicAuthToken(password) {
552
+ return Buffer.from(`opencode:${password}`).toString("base64");
553
+ }
554
+ function redactSensitive(tail, password) {
555
+ return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
556
+ }
557
+ function redactedReadinessError(rosterPath, password, reason) {
558
+ const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
559
+ return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
560
+ ${tail}`);
561
+ }
562
+ function isEpermError(err) {
563
+ return typeof err === "object" && err !== null && "code" in err && err.code === "EPERM";
564
+ }
565
+ function signalGroup(pid, sig) {
566
+ if (pid <= 1) {
567
+ try {
568
+ process.kill(pid, sig);
569
+ } catch {}
570
+ return false;
729
571
  }
730
- const lastKnown = new Map;
731
- for (const id of sessionIds) {
732
- const loc = locationById.get(id);
733
- lastKnown.set(id, {
734
- sessionId: id,
735
- project: loc?.project ?? "",
736
- state: loc ? "running" : "not_found",
737
- resultAvailable: false
738
- });
572
+ try {
573
+ process.kill(-pid, sig);
574
+ return true;
575
+ } catch (err) {
576
+ if (err.code === "EPERM") {
577
+ throw err;
578
+ }
739
579
  }
740
- return { locationById, groupList: Array.from(groups.values()), lastKnown };
580
+ try {
581
+ process.kill(pid, sig);
582
+ } catch {}
583
+ return false;
741
584
  }
742
- async function wait(sessionIds, opts) {
743
- const ctx = validateContext(opts.context);
744
- if (!ctx.ok)
745
- return ctx;
746
- const { baseUrl, projects, credentials } = ctx;
747
- const uniqueIds = Array.from(new Set(sessionIds));
748
- if (uniqueIds.length === 0) {
749
- return { ok: true, sessions: [], waker: [], timedOut: true };
585
+ function signalGroupOnly(pid, sig) {
586
+ if (pid <= 1)
587
+ return false;
588
+ try {
589
+ process.kill(-pid, sig);
590
+ return true;
591
+ } catch {
592
+ return false;
750
593
  }
751
- const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
752
- const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
753
- const deadline = Date.now() + timeoutMs;
754
- const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
755
- async function pollGroup(group) {
756
- const [statusRes, questionRes] = await Promise.all([
757
- api(baseUrl, credentials, group.directory, "/session/status"),
758
- api(baseUrl, credentials, group.directory, "/question")
759
- ]);
760
- if (!statusRes.res.ok)
761
- return;
762
- let statusMap;
763
- try {
764
- statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
765
- } catch {
594
+ }
595
+ function killIdentifiedProcess(pid, identity) {
596
+ try {
597
+ if (identity !== null && identity !== undefined && identity !== "") {
598
+ if (verifyIdentity(pid, identity))
599
+ signalGroup(pid, "SIGTERM");
766
600
  return;
767
601
  }
768
- const pendingBySession = parsePendingQuestions(questionRes);
769
- for (const id of group.sessionIds) {
770
- const entry = statusMap[id];
771
- const busy = isStatusBusy(entry);
772
- const pendingQuestion = pendingBySession.get(id);
773
- const state = deriveSessionState({
774
- busy,
775
- pendingQuestion,
776
- resolved: true
777
- });
778
- lastKnown.set(id, {
779
- sessionId: id,
780
- project: locationById.get(id)?.project ?? "",
781
- state,
782
- resultAvailable: state === "complete",
783
- pendingQuestion
784
- });
785
- }
786
- }
787
- while (true) {
788
- await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
789
- const sessions = uniqueIds.map((id) => lastKnown.get(id));
790
- const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
791
- if (waker.length > 0) {
792
- return { ok: true, sessions, waker, timedOut: false };
793
- }
794
- if (Date.now() >= deadline) {
795
- return { ok: true, sessions, waker: [], timedOut: true };
602
+ process.kill(pid, "SIGTERM");
603
+ } catch {}
604
+ }
605
+ function attachServer(rosterPath) {
606
+ return attachLive(rosterPath);
607
+ }
608
+ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
609
+ const deadline = Date.now() + budgetMs;
610
+ const lockPath = lockFilePath(rosterPath);
611
+ while (Date.now() < deadline) {
612
+ const handle = attachServer(rosterPath);
613
+ if (handle)
614
+ return handle;
615
+ const lockInfo2 = readLockFile(lockPath);
616
+ const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
617
+ if (!winnerAlive) {
618
+ throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
796
619
  }
797
- const remaining = deadline - Date.now();
798
- await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
620
+ await sleep(POLL_INTERVAL_MS);
799
621
  }
622
+ const lockInfo = readLockFile(lockPath);
623
+ const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
624
+ throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
800
625
  }
801
- function parsePendingQuestions(questionRes) {
802
- if (!questionRes.res.ok)
803
- return new Map;
626
+ async function probe(baseUrl, password) {
804
627
  try {
805
- const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
806
- return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
628
+ const res = await fetch(`${baseUrl}/session?limit=1`, {
629
+ headers: { authorization: `Basic ${basicAuthToken(password)}` },
630
+ signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
631
+ });
632
+ if (res.status === 200)
633
+ return "ready";
634
+ if (res.status === 401 || res.status === 403)
635
+ return "auth-failure";
636
+ return "retry";
807
637
  } catch {
808
- return new Map;
638
+ return "retry";
809
639
  }
810
640
  }
811
-
812
- // src/format.ts
813
- function formatRoster(projects) {
814
- return projects.map((p) => {
815
- if (!p.pathExists)
816
- return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
817
- if (p.statusError)
818
- return `${p.name}: status error (${p.statusError}) — ${p.description}`;
819
- const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
820
- return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
821
- }).join(`
822
- `);
641
+ function childDied(child, pid) {
642
+ return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
823
643
  }
824
- function formatDispatch(r) {
825
- switch (r.mode) {
826
- case "new":
827
- return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
828
- case "question-reply":
829
- return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
830
- case "follow-up":
831
- return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
644
+ async function waitForReadinessLine(logPath, child, pid, deadline) {
645
+ const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
646
+ while (Date.now() < deadline) {
647
+ if (childDied(child, pid))
648
+ return null;
649
+ const tail = readLogTail(logPath);
650
+ const match = readinessLine.exec(tail);
651
+ if (match?.[1]) {
652
+ const port = Number.parseInt(match[1], 10);
653
+ if (Number.isInteger(port) && port > 0 && port <= 65535) {
654
+ return { port, baseUrl: `http://127.0.0.1:${port}` };
655
+ }
656
+ }
657
+ await sleep(POLL_INTERVAL_MS);
832
658
  }
659
+ return null;
833
660
  }
834
- function dispatchMetadata(r) {
835
- return { sessionId: r.sessionId, project: r.project, mode: r.mode };
836
- }
837
- function formatStatus(r) {
838
- const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
839
- `) : " (none)";
840
- const lines = [
841
- `session: ${r.sessionId} (${r.project})`,
842
- `title: ${r.title ?? "(untitled)"}`,
843
- `busy: ${r.busy}`
844
- ];
845
- if (r.pendingQuestion) {
846
- lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
847
- if (r.pendingQuestion.options.length > 0) {
848
- lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
849
- }
850
- lines.push(` (answer with bus_task using sessionId)`);
661
+ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
662
+ while (Date.now() < deadline) {
663
+ if (childDied(child, pid))
664
+ return "died";
665
+ const outcome = await probe(baseUrl, password);
666
+ if (outcome === "ready")
667
+ return "ready";
668
+ if (outcome === "auth-failure")
669
+ return "auth-failure";
670
+ await sleep(POLL_INTERVAL_MS);
851
671
  }
852
- 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);
853
- return lines.join(`
854
- `);
672
+ return "timeout";
855
673
  }
856
- function formatWait(r) {
857
- const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
858
- const sessionLines = r.sessions.map((s) => {
859
- const parts = [
860
- ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
861
- ];
862
- if (s.pendingQuestion) {
863
- parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
864
- if (s.pendingQuestion.options.length > 0) {
865
- parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
866
- }
867
- parts.push(` (answer with bus_task using sessionId)`);
868
- }
869
- return parts.join(`
870
- `);
871
- });
872
- return [header, ...sessionLines].join(`
873
- `);
874
- }
875
- function formatResult(r) {
876
- const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
877
- `) : " (no changes)";
878
- return [
879
- `session: ${r.sessionId} (${r.project})`,
880
- `--- reply ---`,
881
- r.text || "(empty)",
882
- r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
883
- diffLines
884
- ].join(`
885
- `);
886
- }
887
-
888
- // src/config.ts
889
- import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
890
- import { homedir as homedir2 } from "node:os";
891
- import { join as join2 } from "node:path";
892
- import { z as z3 } from "zod";
893
-
894
- // src/discovery.ts
895
- import { execFileSync } from "node:child_process";
896
- import { createHash, randomBytes } from "node:crypto";
897
- import {
898
- chmodSync,
899
- closeSync,
900
- constants as fsConstants,
901
- mkdirSync,
902
- openSync,
903
- readFileSync,
904
- renameSync,
905
- statSync,
906
- unlinkSync,
907
- writeFileSync
908
- } from "node:fs";
909
- import { homedir } from "node:os";
910
- import { join } from "node:path";
911
- import { z as z2 } from "zod";
912
- function stateDirFor(rosterPath) {
913
- const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
914
- const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
915
- return join(base, "space-bus", hash);
916
- }
917
- function discoveryFilePath(rosterPath) {
918
- return join(stateDirFor(rosterPath), "discovery.json");
919
- }
920
- function lockFilePath(rosterPath) {
921
- return join(stateDirFor(rosterPath), "spawn.lock");
674
+ async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
675
+ const deadline = Date.now() + budgetMs;
676
+ const logPath = logFilePath(rosterPath);
677
+ const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
678
+ const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
679
+ const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
680
+ if (lineResult === null) {
681
+ const diedEarly = childDied(child, pid);
682
+ killIdentifiedProcess(pid, identity);
683
+ throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
684
+ }
685
+ const { port, baseUrl } = lineResult;
686
+ const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
687
+ const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
688
+ if (outcome === "ready")
689
+ return { port, baseUrl };
690
+ killIdentifiedProcess(pid, identity);
691
+ if (outcome === "died") {
692
+ throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
693
+ }
694
+ if (outcome === "auth-failure") {
695
+ throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
696
+ }
697
+ throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
922
698
  }
923
- function logFilePath(rosterPath) {
924
- return join(stateDirFor(rosterPath), "server.log");
699
+ var PROVISIONAL_FRESH_WINDOW_MS = 5000;
700
+ function reapOrphanedProvisional(rosterPath) {
701
+ const provisional = readProvisional(rosterPath);
702
+ if (!provisional)
703
+ return;
704
+ const discovery = readDiscovery(rosterPath);
705
+ if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
706
+ removeProvisional(rosterPath);
707
+ return;
708
+ }
709
+ const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
710
+ const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
711
+ if (hasIdentity || isFresh) {
712
+ killIdentifiedProcess(provisional.pid, provisional.identity);
713
+ }
714
+ removeProvisional(rosterPath);
925
715
  }
926
- function writeDiscovery(rosterPath, data) {
927
- const dir = stateDirFor(rosterPath);
928
- mkdirSync(dir, { recursive: true, mode: 448 });
929
- chmodSync(dir, 448);
930
- const target = discoveryFilePath(rosterPath);
931
- const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
932
- const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
716
+ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
717
+ reapOrphanedProvisional(rosterPath);
718
+ const password = randomBytes2(32).toString("base64url");
719
+ const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
720
+ const cwd = managedConfig.cwd ?? dirname(rosterPath);
721
+ const requestedPort = managedConfig.port ?? 0;
722
+ const logPath = logFilePath(rosterPath);
723
+ const logFd = openSync2(logPath, "w", 384);
724
+ let child;
725
+ let pid;
726
+ let spawnError;
933
727
  try {
934
- writeFileSync(fd, JSON.stringify(data));
728
+ child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
729
+ cwd,
730
+ detached: true,
731
+ stdio: ["ignore", logFd, logFd],
732
+ env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
733
+ });
734
+ child.on("error", (err) => {
735
+ spawnError = err;
736
+ });
737
+ child.unref();
738
+ pid = child.pid;
935
739
  } finally {
936
- closeQuietly(fd);
740
+ closeQuietly(logFd);
937
741
  }
938
- renameSync(tempPath, target);
939
- chmodSync(target, 384);
940
- }
941
- function readDiscovery(rosterPath) {
942
- const target = discoveryFilePath(rosterPath);
943
- let raw;
944
- try {
945
- raw = readFileSync(target, "utf8");
946
- } catch {
947
- return null;
742
+ if (pid === undefined) {
743
+ throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
948
744
  }
949
- let json;
745
+ const identity = captureIdentity(pid);
746
+ writeProvisional(rosterPath, {
747
+ pid,
748
+ identity: identity ?? "",
749
+ password,
750
+ since: Date.now()
751
+ });
752
+ let port;
753
+ let baseUrl;
950
754
  try {
951
- json = JSON.parse(raw);
952
- } catch {
953
- return null;
755
+ const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
756
+ const spawnErrorWatch = new Promise((_resolve, reject) => {
757
+ const check = setInterval(() => {
758
+ if (spawnError) {
759
+ clearInterval(check);
760
+ reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
761
+ }
762
+ }, POLL_INTERVAL_MS);
763
+ readiness.finally(() => clearInterval(check)).catch(() => {});
764
+ });
765
+ const result = await Promise.race([readiness, spawnErrorWatch]);
766
+ port = result.port;
767
+ baseUrl = result.baseUrl;
768
+ } finally {
769
+ removeProvisional(rosterPath);
954
770
  }
955
- const parsed = discoveryFileSchema.safeParse(json);
956
- return parsed.success ? parsed.data : null;
771
+ const finalIdentity = identity ?? captureIdentity(pid) ?? "";
772
+ writeDiscovery(rosterPath, {
773
+ port,
774
+ pid,
775
+ identity: finalIdentity,
776
+ password,
777
+ spawnConfig: { command, cwd, port: requestedPort },
778
+ baseUrl
779
+ });
780
+ return {
781
+ baseUrl,
782
+ credentials: { username: "opencode", password },
783
+ pid,
784
+ port
785
+ };
957
786
  }
958
- function removeDiscovery(rosterPath) {
959
- try {
960
- unlinkSync(discoveryFilePath(rosterPath));
961
- } catch (err2) {
962
- if (!isEnoent(err2))
963
- throw err2;
787
+ async function ensureServer(rosterPath, options = {}) {
788
+ const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
789
+ const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
790
+ const fastPath = attachServer(rosterPath);
791
+ if (fastPath)
792
+ return fastPath;
793
+ const manifest = readManifest(rosterPath);
794
+ if (manifest.server.managed === undefined) {
795
+ throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
796
+ }
797
+ const lock = acquireLock(rosterPath);
798
+ if (lock === null) {
799
+ return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
964
800
  }
965
- }
966
- function removeDiscoveryIfMatches(rosterPath, expected) {
967
801
  try {
968
- const current = readDiscovery(rosterPath);
969
- if (current && current.pid === expected.pid && current.identity === expected.identity) {
970
- removeDiscovery(rosterPath);
971
- }
972
- } catch {}
802
+ const attached = attachServer(rosterPath);
803
+ if (attached)
804
+ return attached;
805
+ return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
806
+ } finally {
807
+ releaseLock(lock);
808
+ }
973
809
  }
974
- function attachLive(rosterPath) {
810
+ function serverStatus(rosterPath) {
975
811
  const discovery = readDiscovery(rosterPath);
976
- if (!discovery)
977
- return null;
978
- if (!loopbackOk(discovery.baseUrl))
979
- return null;
812
+ if (!discovery) {
813
+ return { running: false };
814
+ }
980
815
  if (!verifyIdentity(discovery.pid, discovery.identity)) {
981
816
  removeDiscoveryIfMatches(rosterPath, {
982
817
  pid: discovery.pid,
983
818
  identity: discovery.identity
984
819
  });
985
- return null;
820
+ return { running: false };
986
821
  }
822
+ let configDrift;
823
+ try {
824
+ const manifest = readManifest(rosterPath);
825
+ if (manifest.server.managed) {
826
+ const current = manifest.server.managed;
827
+ const currentCommand = current.command ?? ["harness", "serve"];
828
+ const currentCwd = current.cwd ?? dirname(rosterPath);
829
+ const currentPort = current.port ?? 0;
830
+ const storedCommand = discovery.spawnConfig.command ?? [
831
+ "harness",
832
+ "serve"
833
+ ];
834
+ const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
835
+ const storedPort = discovery.spawnConfig.port ?? 0;
836
+ configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
837
+ }
838
+ } catch {}
987
839
  return {
988
- baseUrl: discovery.baseUrl,
989
- credentials: { username: "opencode", password: discovery.password },
840
+ running: true,
841
+ port: discovery.port,
990
842
  pid: discovery.pid,
991
- port: discovery.port
843
+ configDrift
992
844
  };
993
845
  }
994
- function captureIdentity(pid) {
995
- try {
996
- const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
997
- env: { ...process.env, LC_ALL: "C" },
998
- encoding: "utf8"
999
- });
1000
- const trimmed = out.trim();
1001
- return trimmed.length > 0 ? trimmed : null;
1002
- } catch {
1003
- return null;
846
+ async function stopServer(rosterPath) {
847
+ const discovery = readDiscovery(rosterPath);
848
+ if (!discovery)
849
+ return { stopped: false };
850
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
851
+ await reapSurvivingGroup(discovery.pid);
852
+ removeDiscovery(rosterPath);
853
+ return { stopped: false };
1004
854
  }
1005
- }
1006
- function isAlive(pid) {
855
+ const { pid } = discovery;
856
+ let groupSignaled;
857
+ const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
1007
858
  try {
1008
- process.kill(pid, 0);
1009
- return true;
1010
- } catch {
1011
- return false;
1012
- }
1013
- }
1014
- function verifyIdentity(pid, storedIdentity) {
1015
- if (!isAlive(pid))
1016
- return false;
1017
- const current = captureIdentity(pid);
1018
- return current !== null && current === storedIdentity;
1019
- }
1020
- var lockFileSchema = z2.object({
1021
- pid: z2.number().int().min(2),
1022
- startTime: z2.string(),
1023
- since: z2.number()
1024
- });
1025
- var CORRUPT_LOCK_GRACE_MS = 2000;
1026
- function acquireLock(rosterPath) {
1027
- const dir = stateDirFor(rosterPath);
1028
- mkdirSync(dir, { recursive: true, mode: 448 });
1029
- chmodSync(dir, 448);
1030
- const target = lockFilePath(rosterPath);
1031
- const identity = captureIdentity(process.pid) ?? "";
1032
- const lock = {
1033
- pid: process.pid,
1034
- startTime: identity,
1035
- since: Date.now()
1036
- };
1037
- if (tryCreateLockFile(target, lock)) {
1038
- return { rosterPath };
859
+ groupSignaled = signalGroup(pid, "SIGTERM");
860
+ } catch (err) {
861
+ if (isEpermError(err)) {
862
+ return { stopped: false };
863
+ }
864
+ removeDiscovery(rosterPath);
865
+ return { stopped: true };
1039
866
  }
1040
- const existing = readLockFile(target);
1041
- if (existing) {
1042
- if (verifyIdentity(existing.pid, existing.startTime))
1043
- return null;
1044
- } else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
1045
- return null;
867
+ if (await waitForCompletion(STOP_GRACE_MS)) {
868
+ removeDiscovery(rosterPath);
869
+ return { stopped: true };
1046
870
  }
1047
871
  try {
1048
- unlinkSync(target);
1049
- } catch (err2) {
1050
- if (!isEnoent(err2))
1051
- throw err2;
872
+ groupSignaled = signalGroup(pid, "SIGKILL");
873
+ } catch (err) {
874
+ if (isEpermError(err)) {
875
+ return { stopped: false };
876
+ }
877
+ removeDiscovery(rosterPath);
878
+ return { stopped: true };
1052
879
  }
1053
- if (tryCreateLockFile(target, lock)) {
1054
- return { rosterPath };
880
+ if (await waitForCompletion(STOP_GRACE_MS)) {
881
+ removeDiscovery(rosterPath);
882
+ return { stopped: true };
1055
883
  }
1056
- return null;
884
+ return { stopped: false };
1057
885
  }
1058
- function isOlderThan(path, ageMs) {
886
+ async function reapSurvivingGroup(pid) {
1059
887
  try {
1060
- return Date.now() - statSync(path).mtimeMs > ageMs;
1061
- } catch {
1062
- return false;
1063
- }
888
+ if (isAlive(pid))
889
+ return;
890
+ let groupAlive;
891
+ try {
892
+ process.kill(-pid, 0);
893
+ groupAlive = true;
894
+ } catch {
895
+ groupAlive = false;
896
+ }
897
+ if (!groupAlive)
898
+ return;
899
+ if (!signalGroupOnly(pid, "SIGTERM"))
900
+ return;
901
+ if (await waitForGroupDeath(pid, STOP_GRACE_MS))
902
+ return;
903
+ signalGroupOnly(pid, "SIGKILL");
904
+ await waitForGroupDeath(pid, STOP_GRACE_MS);
905
+ } catch {}
1064
906
  }
1065
- function releaseLock(handle) {
907
+ async function stopForHung(tick) {
1066
908
  try {
1067
- unlinkSync(lockFilePath(handle.rosterPath));
909
+ await tick.stop(tick.rosterPath);
1068
910
  } catch {}
911
+ return { kind: "outcome", outcome: { reason: "hung" } };
1069
912
  }
1070
- function readLockFile(target) {
1071
- let raw;
1072
- try {
1073
- raw = readFileSync(target, "utf8");
1074
- } catch {
1075
- return null;
1076
- }
1077
- let json;
1078
- try {
1079
- json = JSON.parse(raw);
1080
- } catch {
1081
- return null;
913
+ async function superviseTick(tick, state) {
914
+ const st = tick.status(tick.rosterPath);
915
+ if (!st.running) {
916
+ await reapSurvivingGroup(tick.handle.pid);
917
+ return { kind: "outcome", outcome: { reason: "died" } };
1082
918
  }
1083
- const parsed = lockFileSchema.safeParse(json);
1084
- return parsed.success ? parsed.data : null;
1085
- }
1086
- function tryCreateLockFile(target, lock) {
1087
- let fd;
1088
- try {
1089
- fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
1090
- } catch (err2) {
1091
- if (isErrnoCode(err2, "EEXIST"))
1092
- return false;
1093
- throw err2;
919
+ const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
920
+ const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
921
+ const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
922
+ if (failures >= tick.threshold) {
923
+ return stopForHung(tick);
1094
924
  }
1095
- try {
1096
- writeFileSync(fd, JSON.stringify(lock));
1097
- } finally {
1098
- closeQuietly(fd);
925
+ if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
926
+ return stopForHung(tick);
1099
927
  }
1100
- return true;
1101
- }
1102
- function isEnoent(err2) {
1103
- return isErrnoCode(err2, "ENOENT");
1104
- }
1105
- function isErrnoCode(err2, code) {
1106
- return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === code;
1107
- }
1108
- function closeQuietly(fd) {
1109
- try {
1110
- closeSync(fd);
1111
- } catch {}
928
+ return { kind: "tick", failures, lastReadyAt };
1112
929
  }
1113
- function provisionalFilePath(rosterPath) {
1114
- return join(stateDirFor(rosterPath), "spawn.provisional.json");
930
+ function makeSuperviseTick(rosterPath, handle, opts) {
931
+ return {
932
+ rosterPath,
933
+ handle,
934
+ password: handle.credentials.password ?? "",
935
+ threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
936
+ unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
937
+ now: opts.now ?? Date.now,
938
+ status: opts.status ?? serverStatus,
939
+ probe: opts.probe ?? probe,
940
+ stop: opts.stop ?? stopServer
941
+ };
1115
942
  }
1116
- var provisionalFileSchema = z2.object({
1117
- pid: z2.number().int().min(2),
1118
- identity: z2.string(),
1119
- password: z2.string(),
1120
- since: z2.number()
1121
- });
1122
- function writeProvisional(rosterPath, data) {
1123
- const dir = stateDirFor(rosterPath);
1124
- mkdirSync(dir, { recursive: true, mode: 448 });
1125
- chmodSync(dir, 448);
1126
- const target = provisionalFilePath(rosterPath);
1127
- const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
943
+ async function interruptibleSleep(doSleep, intervalMs, interrupt) {
944
+ if (!interrupt) {
945
+ await doSleep(intervalMs);
946
+ return;
947
+ }
948
+ let timer;
949
+ const timed = new Promise((resolve) => {
950
+ timer = setTimeout(resolve, intervalMs);
951
+ });
1128
952
  try {
1129
- writeFileSync(fd, JSON.stringify(data));
953
+ await Promise.race([timed, interrupt]);
1130
954
  } finally {
1131
- closeQuietly(fd);
955
+ if (timer !== undefined)
956
+ clearTimeout(timer);
1132
957
  }
1133
- chmodSync(target, 384);
1134
958
  }
1135
- function readProvisional(rosterPath) {
1136
- const target = provisionalFilePath(rosterPath);
1137
- let raw;
1138
- try {
1139
- raw = readFileSync(target, "utf8");
1140
- } catch {
1141
- return null;
959
+ async function superviseServer(rosterPath, handle, opts = {}) {
960
+ const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
961
+ const tick = makeSuperviseTick(rosterPath, handle, opts);
962
+ const doSleep = opts.sleep ?? sleep;
963
+ const shouldStop = opts.shouldStop ?? (() => false);
964
+ let state = { failures: 0, lastReadyAt: tick.now() };
965
+ for (;; ) {
966
+ if (shouldStop())
967
+ return { reason: "signal" };
968
+ const result = await superviseTick(tick, state);
969
+ if (result.kind === "outcome")
970
+ return result.outcome;
971
+ state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
972
+ if (shouldStop())
973
+ return { reason: "signal" };
974
+ await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1142
975
  }
1143
- let json;
1144
- try {
1145
- json = JSON.parse(raw);
1146
- } catch {
1147
- return null;
976
+ }
977
+ async function waitForDeath(pid, budgetMs) {
978
+ const deadline = Date.now() + budgetMs;
979
+ while (Date.now() < deadline) {
980
+ if (!isAlive(pid))
981
+ return true;
982
+ await sleep(POLL_INTERVAL_MS);
1148
983
  }
1149
- const parsed = provisionalFileSchema.safeParse(json);
1150
- return parsed.success ? parsed.data : null;
984
+ return !isAlive(pid);
1151
985
  }
1152
- function removeProvisional(rosterPath) {
1153
- try {
1154
- unlinkSync(provisionalFilePath(rosterPath));
1155
- } catch {}
986
+ async function waitForGroupDeath(pid, budgetMs) {
987
+ const deadline = Date.now() + budgetMs;
988
+ const groupAlive = () => {
989
+ try {
990
+ process.kill(-pid, 0);
991
+ return true;
992
+ } catch {
993
+ return false;
994
+ }
995
+ };
996
+ while (Date.now() < deadline) {
997
+ if (!groupAlive())
998
+ return true;
999
+ await sleep(POLL_INTERVAL_MS);
1000
+ }
1001
+ return !groupAlive();
1156
1002
  }
1157
1003
 
1158
- // src/config.ts
1159
- var managedServerConfigSchema = z3.object({
1160
- command: z3.array(z3.string()).optional(),
1161
- cwd: z3.string().optional(),
1162
- port: z3.number().int().nonnegative().optional()
1163
- });
1164
- var serverConfigSchema = z3.object({
1165
- baseUrl: z3.url().optional(),
1166
- managed: managedServerConfigSchema.optional()
1167
- }).superRefine((val, ctx) => {
1168
- const hasBaseUrl = val.baseUrl !== undefined;
1169
- const hasManaged = val.managed !== undefined;
1170
- if (hasBaseUrl && hasManaged) {
1171
- ctx.addIssue({
1172
- code: "custom",
1173
- message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
1174
- });
1175
- } else if (!hasBaseUrl && !hasManaged) {
1176
- ctx.addIssue({
1177
- code: "custom",
1178
- message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
1179
- });
1180
- }
1181
- });
1182
- var manifestSchema = z3.object({
1183
- server: serverConfigSchema,
1184
- projects: z3.array(z3.object({
1185
- name: z3.string(),
1186
- path: z3.string(),
1187
- description: z3.string()
1188
- }))
1189
- });
1190
- function expandHome(path) {
1191
- return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
1192
- }
1193
- function resolveRosterPath(directory) {
1194
- const override = process.env["SPACE_BUS_CONFIG"];
1195
- if (override) {
1196
- if (override.includes("://")) {
1197
- throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
1198
- }
1199
- const expanded = expandHome(override);
1200
- if (!expanded.startsWith("/")) {
1201
- throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
1202
- }
1203
- return existsSync(expanded) ? realpathSync(expanded) : expanded;
1204
- }
1205
- if (directory) {
1206
- const candidate = join2(directory, "spacebus.json");
1207
- return existsSync(candidate) ? realpathSync(candidate) : candidate;
1208
- }
1209
- throw new Error("space-bus: cannot locate spacebus.json — pass a directory containing spacebus.json, or set SPACE_BUS_CONFIG to an absolute path (or ~-prefixed path) to the roster file");
1004
+ // src/mcp.ts
1005
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1006
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1007
+ import { z as z4 } from "zod";
1008
+
1009
+ // src/core.ts
1010
+ function findProject(projects, name) {
1011
+ return projects.find((p) => p.name === name);
1210
1012
  }
1211
- function getRoster(directory) {
1212
- const manifestPath = resolveRosterPath(directory);
1213
- let raw;
1214
- try {
1215
- raw = readFileSync2(manifestPath, "utf8");
1216
- } catch (err2) {
1217
- throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err2.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
1218
- }
1219
- let json;
1220
- try {
1221
- json = JSON.parse(raw);
1222
- } catch (err2) {
1223
- throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err2.message}`);
1224
- }
1225
- const parsed = manifestSchema.safeParse(json);
1226
- if (!parsed.success) {
1227
- throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
1228
- }
1229
- if (parsed.data.server.baseUrl !== undefined) {
1230
- const url = new URL(parsed.data.server.baseUrl);
1231
- const hostname = url.hostname;
1232
- if (!LOOPBACK_HOSTS.has(hostname)) {
1233
- throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
1234
- }
1235
- }
1236
- return parsed.data;
1013
+ function err(error) {
1014
+ return { ok: false, error };
1237
1015
  }
1238
- function getProjects(manifest) {
1239
- return manifest.projects.map((p) => {
1240
- const expandedPath = expandHome(p.path);
1241
- return { ...p, expandedPath, exists: existsSync(expandedPath) };
1242
- });
1016
+ function toBase64(s) {
1017
+ const bytes = new TextEncoder().encode(s);
1018
+ let bin = "";
1019
+ for (const b of bytes)
1020
+ bin += String.fromCharCode(b);
1021
+ return btoa(bin);
1243
1022
  }
1244
- function getCredentials() {
1245
- const password = process.env["OPENCODE_SERVER_PASSWORD"];
1246
- if (!password)
1023
+ function authHeader(credentials) {
1024
+ if (!credentials.password)
1247
1025
  return {};
1248
- const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
1249
- return { username, password };
1026
+ const username = credentials.username ?? "opencode";
1027
+ const token = toBase64(`${username}:${credentials.password}`);
1028
+ return { Authorization: `Basic ${token}` };
1250
1029
  }
1251
- function loadContext(directory) {
1252
- const rosterPath = resolveRosterPath(directory);
1253
- const manifest = getRoster(directory);
1254
- const projects = getProjects(manifest);
1255
- if (manifest.server.baseUrl === undefined) {
1256
- const live = attachLive(rosterPath);
1257
- if (!live) {
1258
- throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
1259
- }
1030
+ async function api(baseUrl, credentials, directory, path, init) {
1031
+ try {
1032
+ const res = await fetch(`${baseUrl}${path}`, {
1033
+ ...init,
1034
+ headers: {
1035
+ "content-type": "application/json",
1036
+ "x-opencode-directory": directory,
1037
+ ...authHeader(credentials),
1038
+ ...init?.headers
1039
+ },
1040
+ redirect: "error",
1041
+ signal: AbortSignal.timeout(30000)
1042
+ });
1043
+ const bodyText = await res.text().catch(() => "<unreadable body>");
1044
+ return { res, bodyText };
1045
+ } catch (e) {
1046
+ const message = e.message;
1260
1047
  return {
1261
- roster: { server: { baseUrl: live.baseUrl }, projects },
1262
- credentials: live.credentials
1048
+ res: new Response(null, {
1049
+ status: 599,
1050
+ statusText: "space-bus: request failed"
1051
+ }),
1052
+ bodyText: `space-bus: request failed: ${message}`
1263
1053
  };
1264
1054
  }
1265
- return {
1266
- roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
1267
- credentials: getCredentials()
1268
- };
1269
- }
1270
- function isManagedRoster(directory) {
1271
- const manifest = getRoster(directory);
1272
- return manifest.server.managed !== undefined;
1273
- }
1274
-
1275
- // src/server.ts
1276
- import { spawn } from "node:child_process";
1277
- import { randomBytes as randomBytes2 } from "node:crypto";
1278
- import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
1279
- import { dirname } from "node:path";
1280
- var DEFAULT_READINESS_BUDGET_MS = 15000;
1281
- var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
1282
- var POLL_INTERVAL_MS = 50;
1283
- var MIN_PROBE_PHASE_MS = 3000;
1284
- var PROBE_FETCH_TIMEOUT_MS = 2000;
1285
- var STOP_GRACE_MS = 2000;
1286
- var SUPERVISE_INTERVAL_MS = 5000;
1287
- var SUPERVISE_FAILURE_THRESHOLD = 3;
1288
- var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
1289
- function sleep2(ms) {
1290
- return new Promise((resolve) => setTimeout(resolve, ms));
1291
- }
1292
- function readManifest(rosterPath) {
1293
- const raw = readFileSync3(rosterPath, "utf8");
1294
- const json = JSON.parse(raw);
1295
- return manifestSchema.parse(json);
1296
1055
  }
1297
- function readLogTail(logPath, maxChars = 4000) {
1056
+ async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
1057
+ const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
1058
+ if (!res.ok)
1059
+ return [];
1060
+ let messages;
1298
1061
  try {
1299
- const content = readFileSync3(logPath, "utf8");
1300
- return content.length > maxChars ? content.slice(-maxChars) : content;
1062
+ messages = turnMessageListSchema.parse(JSON.parse(bodyText));
1301
1063
  } catch {
1302
- return "";
1303
- }
1304
- }
1305
- function basicAuthToken(password) {
1306
- return Buffer.from(`opencode:${password}`).toString("base64");
1307
- }
1308
- function redactSensitive(tail, password) {
1309
- return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
1310
- }
1311
- function redactedReadinessError(rosterPath, password, reason) {
1312
- const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
1313
- return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
1314
- ${tail}`);
1315
- }
1316
- function isEpermError(err2) {
1317
- return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === "EPERM";
1318
- }
1319
- function signalGroup(pid, sig) {
1320
- if (pid <= 1) {
1321
- try {
1322
- process.kill(pid, sig);
1323
- } catch {}
1324
- return false;
1064
+ return [];
1325
1065
  }
1326
- try {
1327
- process.kill(-pid, sig);
1328
- return true;
1329
- } catch (err2) {
1330
- if (err2.code === "EPERM") {
1331
- throw err2;
1066
+ const byFile = new Map;
1067
+ for (const m of messages) {
1068
+ if (m.info.role !== "user")
1069
+ continue;
1070
+ const diffs = m.info.summary?.diffs;
1071
+ if (!diffs || diffs.length === 0)
1072
+ continue;
1073
+ for (const d of diffs) {
1074
+ const key = d.file ?? `<unknown:${byFile.size}>`;
1075
+ byFile.set(key, d);
1332
1076
  }
1333
1077
  }
1334
- try {
1335
- process.kill(pid, sig);
1336
- } catch {}
1337
- return false;
1078
+ return Array.from(byFile.values());
1338
1079
  }
1339
- function signalGroupOnly(pid, sig) {
1340
- if (pid <= 1)
1341
- return false;
1080
+ async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
1081
+ const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
1082
+ let diff = [];
1342
1083
  try {
1343
- process.kill(-pid, sig);
1344
- return true;
1084
+ diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
1345
1085
  } catch {
1346
- return false;
1086
+ diff = [];
1087
+ }
1088
+ if (diff.length > 0) {
1089
+ return { diff, diffSource: "session" };
1347
1090
  }
1348
- }
1349
- function killIdentifiedProcess(pid, identity) {
1350
1091
  try {
1351
- if (identity !== null && identity !== undefined && identity !== "") {
1352
- if (verifyIdentity(pid, identity))
1353
- signalGroup(pid, "SIGTERM");
1354
- return;
1092
+ const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
1093
+ if (sessionRes.res.ok) {
1094
+ const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
1095
+ const summaryDiffs = parsed.summary?.diffs;
1096
+ if (summaryDiffs && summaryDiffs.length > 0) {
1097
+ return { diff: summaryDiffs, diffSource: "session" };
1098
+ }
1355
1099
  }
1356
- process.kill(pid, "SIGTERM");
1357
1100
  } catch {}
1358
- }
1359
- function attachServer(rosterPath) {
1360
- return attachLive(rosterPath);
1361
- }
1362
- async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1363
- const deadline = Date.now() + budgetMs;
1364
- const lockPath = lockFilePath(rosterPath);
1365
- while (Date.now() < deadline) {
1366
- const handle = attachServer(rosterPath);
1367
- if (handle)
1368
- return handle;
1369
- const lockInfo2 = readLockFile(lockPath);
1370
- const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
1371
- if (!winnerAlive) {
1372
- throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
1101
+ try {
1102
+ const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
1103
+ if (turnDiffs.length > 0) {
1104
+ return { diff: turnDiffs, diffSource: "turns" };
1373
1105
  }
1374
- await sleep2(POLL_INTERVAL_MS);
1375
- }
1376
- const lockInfo = readLockFile(lockPath);
1377
- const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
1378
- throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
1106
+ } catch {}
1107
+ try {
1108
+ const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
1109
+ if (vcsRes.res.ok) {
1110
+ const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
1111
+ if (vcsStatus.length > 0) {
1112
+ return {
1113
+ diff: vcsStatus.map((v) => ({
1114
+ file: v.file,
1115
+ additions: v.additions,
1116
+ deletions: v.deletions,
1117
+ status: v.status
1118
+ })),
1119
+ diffSource: "working-tree"
1120
+ };
1121
+ }
1122
+ }
1123
+ } catch {}
1124
+ return { diff, diffSource: "session" };
1379
1125
  }
1380
- async function probe(baseUrl, password) {
1126
+ function validateContext(context) {
1127
+ const parsed = busContextSchema.safeParse(context);
1128
+ if (!parsed.success) {
1129
+ return err(`space-bus: invalid context: ${parsed.error.message}`);
1130
+ }
1131
+ const { roster, credentials } = parsed.data;
1132
+ let hostname;
1381
1133
  try {
1382
- const res = await fetch(`${baseUrl}/session?limit=1`, {
1383
- headers: { authorization: `Basic ${basicAuthToken(password)}` },
1384
- signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
1385
- });
1386
- if (res.status === 200)
1387
- return "ready";
1388
- if (res.status === 401 || res.status === 403)
1389
- return "auth-failure";
1390
- return "retry";
1134
+ hostname = new URL(roster.server.baseUrl).hostname;
1391
1135
  } catch {
1392
- return "retry";
1136
+ return err("space-bus: context roster server.baseUrl is not a valid URL");
1137
+ }
1138
+ if (!LOOPBACK_HOSTS.has(hostname)) {
1139
+ return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
1393
1140
  }
1141
+ return {
1142
+ ok: true,
1143
+ baseUrl: roster.server.baseUrl,
1144
+ projects: roster.projects,
1145
+ credentials: credentials ?? {}
1146
+ };
1394
1147
  }
1395
- function childDied(child, pid) {
1396
- return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
1148
+ function isStatusBusy(entry) {
1149
+ return entry?.type === "busy" || entry?.type === "retry" || false;
1397
1150
  }
1398
- async function waitForReadinessLine(logPath, child, pid, deadline) {
1399
- const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
1400
- while (Date.now() < deadline) {
1401
- if (childDied(child, pid))
1402
- return null;
1403
- const tail = readLogTail(logPath);
1404
- const match = readinessLine.exec(tail);
1405
- if (match?.[1]) {
1406
- const port = Number.parseInt(match[1], 10);
1407
- if (Number.isInteger(port) && port > 0 && port <= 65535) {
1408
- return { port, baseUrl: `http://127.0.0.1:${port}` };
1409
- }
1410
- }
1411
- await sleep2(POLL_INTERVAL_MS);
1151
+ function resolveProjectOrErr(projects, name) {
1152
+ const project = findProject(projects, name);
1153
+ if (!project) {
1154
+ const valid = projects.map((p) => p.name).join(", ");
1155
+ return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
1412
1156
  }
1413
- return null;
1414
- }
1415
- async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1416
- while (Date.now() < deadline) {
1417
- if (childDied(child, pid))
1418
- return "died";
1419
- const outcome = await probe(baseUrl, password);
1420
- if (outcome === "ready")
1421
- return "ready";
1422
- if (outcome === "auth-failure")
1423
- return "auth-failure";
1424
- await sleep2(POLL_INTERVAL_MS);
1157
+ if (!project.exists) {
1158
+ return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
1425
1159
  }
1426
- return "timeout";
1160
+ return { ok: true, project };
1427
1161
  }
1428
- async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
1429
- const deadline = Date.now() + budgetMs;
1430
- const logPath = logFilePath(rosterPath);
1431
- const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
1432
- const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
1433
- const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
1434
- if (lineResult === null) {
1435
- const diedEarly = childDied(child, pid);
1436
- killIdentifiedProcess(pid, identity);
1437
- throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
1162
+ async function roster(opts) {
1163
+ const ctx = validateContext(opts.context);
1164
+ if (!ctx.ok)
1165
+ return ctx;
1166
+ const { baseUrl, projects, credentials } = ctx;
1167
+ const results = await Promise.all(projects.map(async (p) => {
1168
+ if (!p.exists) {
1169
+ return {
1170
+ name: p.name,
1171
+ path: p.expandedPath,
1172
+ description: p.description,
1173
+ pathExists: false
1174
+ };
1175
+ }
1176
+ try {
1177
+ const [statusRes, listRes] = await Promise.all([
1178
+ api(baseUrl, credentials, p.expandedPath, "/session/status"),
1179
+ api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
1180
+ ]);
1181
+ if (!statusRes.res.ok || !listRes.res.ok) {
1182
+ return {
1183
+ name: p.name,
1184
+ path: p.expandedPath,
1185
+ description: p.description,
1186
+ pathExists: true,
1187
+ statusError: `status=${statusRes.res.status}/${listRes.res.status}`
1188
+ };
1189
+ }
1190
+ const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
1191
+ const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
1192
+ const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
1193
+ const capped = sessions.length > 100;
1194
+ return {
1195
+ name: p.name,
1196
+ path: p.expandedPath,
1197
+ description: p.description,
1198
+ pathExists: true,
1199
+ busyCount,
1200
+ sessionCount: capped ? 100 : sessions.length,
1201
+ sessionCountCapped: capped
1202
+ };
1203
+ } catch (e) {
1204
+ return {
1205
+ name: p.name,
1206
+ path: p.expandedPath,
1207
+ description: p.description,
1208
+ pathExists: true,
1209
+ statusError: e.message
1210
+ };
1211
+ }
1212
+ }));
1213
+ return { ok: true, projects: results };
1214
+ }
1215
+ async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
1216
+ const resolved = resolveProjectOrErr(projects, project);
1217
+ if (!resolved.ok)
1218
+ return resolved;
1219
+ const directory = resolved.project.expandedPath;
1220
+ const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
1221
+ const createRes = await api(baseUrl, credentials, directory, "/session", {
1222
+ method: "POST",
1223
+ body: JSON.stringify({ title: sessionTitle })
1224
+ });
1225
+ if (!createRes.res.ok) {
1226
+ return err(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`);
1438
1227
  }
1439
- const { port, baseUrl } = lineResult;
1440
- const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
1441
- const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
1442
- if (outcome === "ready")
1443
- return { port, baseUrl };
1444
- killIdentifiedProcess(pid, identity);
1445
- if (outcome === "died") {
1446
- throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
1228
+ let session;
1229
+ try {
1230
+ session = sessionSchema.parse(JSON.parse(createRes.bodyText));
1231
+ } catch (e) {
1232
+ return err(`space-bus: unexpected /session response shape: ${e.message}`);
1447
1233
  }
1448
- if (outcome === "auth-failure") {
1449
- throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
1234
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
1235
+ method: "POST",
1236
+ body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
1237
+ });
1238
+ if (promptRes.res.status !== 204) {
1239
+ return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
1450
1240
  }
1451
- throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
1241
+ return { ok: true, sessionId: session.id, project, directory };
1452
1242
  }
1453
- var PROVISIONAL_FRESH_WINDOW_MS = 5000;
1454
- function reapOrphanedProvisional(rosterPath) {
1455
- const provisional = readProvisional(rosterPath);
1456
- if (!provisional)
1457
- return;
1458
- const discovery = readDiscovery(rosterPath);
1459
- if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
1460
- removeProvisional(rosterPath);
1461
- return;
1243
+ function toDispatchArgs(input) {
1244
+ if (input.sessionId !== undefined && input.sessionId === "") {
1245
+ return err("space-bus: sessionId must be a non-empty string");
1462
1246
  }
1463
- const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
1464
- const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
1465
- if (hasIdentity || isFresh) {
1466
- killIdentifiedProcess(provisional.pid, provisional.identity);
1247
+ if (!input.sessionId) {
1248
+ if (!input.project) {
1249
+ return err("space-bus: project is required when starting a new session");
1250
+ }
1251
+ return {
1252
+ ok: true,
1253
+ prompt: input.prompt,
1254
+ title: input.title,
1255
+ project: input.project
1256
+ };
1467
1257
  }
1468
- removeProvisional(rosterPath);
1258
+ return {
1259
+ ok: true,
1260
+ prompt: input.prompt,
1261
+ title: input.title,
1262
+ sessionId: input.sessionId,
1263
+ project: input.project
1264
+ };
1469
1265
  }
1470
- async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
1471
- reapOrphanedProvisional(rosterPath);
1472
- const password = randomBytes2(32).toString("base64url");
1473
- const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
1474
- const cwd = managedConfig.cwd ?? dirname(rosterPath);
1475
- const requestedPort = managedConfig.port ?? 0;
1476
- const logPath = logFilePath(rosterPath);
1477
- const logFd = openSync2(logPath, "w", 384);
1478
- let child;
1479
- let pid;
1480
- let spawnError;
1481
- try {
1482
- child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
1483
- cwd,
1484
- detached: true,
1485
- stdio: ["ignore", logFd, logFd],
1486
- env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
1487
- });
1488
- child.on("error", (err2) => {
1489
- spawnError = err2;
1490
- });
1491
- child.unref();
1492
- pid = child.pid;
1493
- } finally {
1494
- closeQuietly(logFd);
1495
- }
1496
- if (pid === undefined) {
1497
- throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
1266
+ async function dispatch(args, opts) {
1267
+ const ctx = validateContext(opts.context);
1268
+ if (!ctx.ok)
1269
+ return ctx;
1270
+ const { baseUrl, projects, credentials } = ctx;
1271
+ if (args.sessionId !== undefined && args.sessionId === "") {
1272
+ return err("space-bus: sessionId must be a non-empty string");
1498
1273
  }
1499
- const identity = captureIdentity(pid);
1500
- writeProvisional(rosterPath, {
1501
- pid,
1502
- identity: identity ?? "",
1503
- password,
1504
- since: Date.now()
1505
- });
1506
- let port;
1507
- let baseUrl;
1508
- try {
1509
- const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
1510
- const spawnErrorWatch = new Promise((_resolve, reject) => {
1511
- const check = setInterval(() => {
1512
- if (spawnError) {
1513
- clearInterval(check);
1514
- reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
1515
- }
1516
- }, POLL_INTERVAL_MS);
1517
- readiness.finally(() => clearInterval(check)).catch(() => {});
1518
- });
1519
- const result2 = await Promise.race([readiness, spawnErrorWatch]);
1520
- port = result2.port;
1521
- baseUrl = result2.baseUrl;
1522
- } finally {
1523
- removeProvisional(rosterPath);
1274
+ if (!args.sessionId) {
1275
+ if (!args.project) {
1276
+ return err("space-bus: project is required when starting a new session");
1277
+ }
1278
+ const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
1279
+ if (!r.ok)
1280
+ return r;
1281
+ return {
1282
+ ok: true,
1283
+ sessionId: r.sessionId,
1284
+ project: r.project,
1285
+ mode: "new",
1286
+ directory: r.directory
1287
+ };
1524
1288
  }
1525
- const finalIdentity = identity ?? captureIdentity(pid) ?? "";
1526
- writeDiscovery(rosterPath, {
1527
- port,
1528
- pid,
1529
- identity: finalIdentity,
1530
- password,
1531
- spawnConfig: { command, cwd, port: requestedPort },
1532
- baseUrl
1533
- });
1534
- return {
1535
- baseUrl,
1536
- credentials: { username: "opencode", password },
1537
- pid,
1538
- port
1539
- };
1540
- }
1541
- async function ensureServer(rosterPath, options = {}) {
1542
- const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
1543
- const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
1544
- const fastPath = attachServer(rosterPath);
1545
- if (fastPath)
1546
- return fastPath;
1547
- const manifest = readManifest(rosterPath);
1548
- if (manifest.server.managed === undefined) {
1549
- throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
1289
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
1290
+ if (!loc.ok)
1291
+ return loc;
1292
+ const { directory, project } = loc;
1293
+ if (args.project && args.project !== project) {
1294
+ return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
1550
1295
  }
1551
- const lock = acquireLock(rosterPath);
1552
- if (lock === null) {
1553
- return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
1296
+ return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project);
1297
+ }
1298
+ async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
1299
+ for (const p of projects) {
1300
+ if (!p.exists)
1301
+ continue;
1302
+ const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
1303
+ if (!res.ok)
1304
+ continue;
1305
+ let session;
1306
+ try {
1307
+ session = sessionSchema.parse(JSON.parse(bodyText));
1308
+ } catch {
1309
+ continue;
1310
+ }
1311
+ const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
1312
+ if (owner) {
1313
+ return { ok: true, directory: owner.expandedPath, project: owner.name };
1314
+ }
1315
+ return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
1554
1316
  }
1317
+ return err(`space-bus: no manifest project has a session with id ${sessionId}`);
1318
+ }
1319
+ function deriveSessionState(input) {
1320
+ if (!input.resolved)
1321
+ return "not_found";
1322
+ if (input.failed)
1323
+ return "failed";
1324
+ if (input.pendingQuestion)
1325
+ return "blocked";
1326
+ if (input.busy)
1327
+ return "running";
1328
+ return "complete";
1329
+ }
1330
+ function formatQuestionEntry(entry) {
1331
+ const firstQuestion = entry.questions?.[0];
1332
+ const text = firstQuestion?.question ?? "";
1333
+ const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
1334
+ const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
1335
+ return { sessionId: entry.sessionID, preview, options };
1336
+ }
1337
+ async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
1555
1338
  try {
1556
- const attached = attachServer(rosterPath);
1557
- if (attached)
1558
- return attached;
1559
- return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
1560
- } finally {
1561
- releaseLock(lock);
1339
+ const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
1340
+ if (!res.ok)
1341
+ return;
1342
+ const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
1343
+ const entry = entries.find((e) => e.sessionID === sessionId);
1344
+ if (!entry)
1345
+ return;
1346
+ const { preview, options } = formatQuestionEntry(entry);
1347
+ return { preview, options };
1348
+ } catch {
1349
+ return;
1562
1350
  }
1563
1351
  }
1564
- function serverStatus(rosterPath) {
1565
- const discovery = readDiscovery(rosterPath);
1566
- if (!discovery) {
1567
- return { running: false };
1568
- }
1569
- if (!verifyIdentity(discovery.pid, discovery.identity)) {
1570
- removeDiscoveryIfMatches(rosterPath, {
1571
- pid: discovery.pid,
1572
- identity: discovery.identity
1573
- });
1574
- return { running: false };
1352
+ async function status(sessionId, opts) {
1353
+ const ctx = validateContext(opts.context);
1354
+ if (!ctx.ok)
1355
+ return ctx;
1356
+ const { baseUrl, projects, credentials } = ctx;
1357
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
1358
+ if (!loc.ok)
1359
+ return loc;
1360
+ const { directory, project } = loc;
1361
+ const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
1362
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
1363
+ api(baseUrl, credentials, directory, "/session/status"),
1364
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
1365
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
1366
+ fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
1367
+ ]);
1368
+ if (!sessionRes.res.ok) {
1369
+ return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
1575
1370
  }
1576
- let configDrift;
1371
+ let session;
1372
+ let statusMap;
1373
+ let todos;
1577
1374
  try {
1578
- const manifest = readManifest(rosterPath);
1579
- if (manifest.server.managed) {
1580
- const current = manifest.server.managed;
1581
- const currentCommand = current.command ?? ["harness", "serve"];
1582
- const currentCwd = current.cwd ?? dirname(rosterPath);
1583
- const currentPort = current.port ?? 0;
1584
- const storedCommand = discovery.spawnConfig.command ?? [
1585
- "harness",
1586
- "serve"
1587
- ];
1588
- const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
1589
- const storedPort = discovery.spawnConfig.port ?? 0;
1590
- configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
1591
- }
1592
- } catch {}
1375
+ session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
1376
+ statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
1377
+ todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
1378
+ } catch (e) {
1379
+ return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
1380
+ }
1381
+ const entry = statusMap[sessionId];
1382
+ const busy = isStatusBusy(entry);
1383
+ const { diff, diffSource } = diffResult;
1384
+ const additions = diff.reduce((sum, d) => sum + d.additions, 0);
1385
+ const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
1386
+ const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
1593
1387
  return {
1594
- running: true,
1595
- port: discovery.port,
1596
- pid: discovery.pid,
1597
- configDrift
1388
+ ok: true,
1389
+ sessionId,
1390
+ project,
1391
+ busy,
1392
+ title: session.title,
1393
+ todos,
1394
+ diff: { files: diff.length, additions, deletions },
1395
+ diffSource,
1396
+ pendingQuestion,
1397
+ state,
1398
+ resultAvailable: state === "complete"
1598
1399
  };
1599
1400
  }
1600
- async function stopServer(rosterPath) {
1601
- const discovery = readDiscovery(rosterPath);
1602
- if (!discovery)
1603
- return { stopped: false };
1604
- if (!verifyIdentity(discovery.pid, discovery.identity)) {
1605
- await reapSurvivingGroup(discovery.pid);
1606
- removeDiscovery(rosterPath);
1607
- return { stopped: false };
1608
- }
1609
- const { pid } = discovery;
1610
- let groupSignaled;
1611
- const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
1612
- try {
1613
- groupSignaled = signalGroup(pid, "SIGTERM");
1614
- } catch (err2) {
1615
- if (isEpermError(err2)) {
1616
- return { stopped: false };
1401
+ async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
1402
+ const questionsRes = await api(baseUrl, credentials, directory, "/question");
1403
+ if (questionsRes.res.ok) {
1404
+ let questions;
1405
+ try {
1406
+ questions = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
1407
+ } catch {
1408
+ questions = [];
1409
+ }
1410
+ const pending = questions.find((q) => q.sessionID === sessionId);
1411
+ if (pending) {
1412
+ const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
1413
+ method: "POST",
1414
+ body: JSON.stringify({ answers: [[message]] })
1415
+ });
1416
+ if (!replyRes.res.ok) {
1417
+ return err(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`);
1418
+ }
1419
+ return { ok: true, sessionId, project, mode: "question-reply" };
1617
1420
  }
1618
- removeDiscovery(rosterPath);
1619
- return { stopped: true };
1620
1421
  }
1621
- if (await waitForCompletion(STOP_GRACE_MS)) {
1622
- removeDiscovery(rosterPath);
1623
- return { stopped: true };
1422
+ const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
1423
+ method: "POST",
1424
+ body: JSON.stringify({ parts: [{ type: "text", text: message }] })
1425
+ });
1426
+ if (promptRes.res.status !== 204) {
1427
+ return err(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`);
1428
+ }
1429
+ return { ok: true, sessionId, project, mode: "follow-up" };
1430
+ }
1431
+ async function result(sessionId, opts) {
1432
+ const ctx = validateContext(opts.context);
1433
+ if (!ctx.ok)
1434
+ return ctx;
1435
+ const { baseUrl, projects, credentials } = ctx;
1436
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
1437
+ if (!loc.ok)
1438
+ return loc;
1439
+ const { directory, project } = loc;
1440
+ const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
1441
+ if (statusMapRes.res.ok) {
1442
+ try {
1443
+ const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
1444
+ const entry = statusMap[sessionId];
1445
+ if (isStatusBusy(entry)) {
1446
+ return err(`space-bus: session ${sessionId} is still running, use bus_status`);
1447
+ }
1448
+ } catch {}
1449
+ }
1450
+ const [messageRes, diffResult] = await Promise.all([
1451
+ api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
1452
+ fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
1453
+ ]);
1454
+ if (!messageRes.res.ok) {
1455
+ return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
1624
1456
  }
1457
+ let messages;
1625
1458
  try {
1626
- groupSignaled = signalGroup(pid, "SIGKILL");
1627
- } catch (err2) {
1628
- if (isEpermError(err2)) {
1629
- return { stopped: false };
1459
+ messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
1460
+ } catch (e) {
1461
+ return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
1462
+ }
1463
+ const { diff, diffSource } = diffResult;
1464
+ const last = messages.filter((m) => m.info.role === "assistant").at(-1);
1465
+ const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
1466
+ `).trim() : "";
1467
+ return { ok: true, sessionId, project, text, diff, diffSource };
1468
+ }
1469
+ async function mapWithConcurrency(items, concurrency, fn) {
1470
+ const results = new Array(items.length);
1471
+ let next = 0;
1472
+ const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
1473
+ const workers = Array.from({ length: limit }, async () => {
1474
+ while (true) {
1475
+ const i = next++;
1476
+ if (i >= items.length)
1477
+ return;
1478
+ results[i] = await fn(items[i]);
1630
1479
  }
1631
- removeDiscovery(rosterPath);
1632
- return { stopped: true };
1480
+ });
1481
+ await Promise.all(workers);
1482
+ return results;
1483
+ }
1484
+ var DEFAULT_WAIT_TIMEOUT_MS = 60000;
1485
+ var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
1486
+ var DEFAULT_WAIT_CONCURRENCY = 4;
1487
+ var NEEDS_ATTENTION_STATES = [
1488
+ "complete",
1489
+ "blocked",
1490
+ "failed",
1491
+ "not_found"
1492
+ ];
1493
+ function sleep2(ms) {
1494
+ return new Promise((resolve) => setTimeout(resolve, ms));
1495
+ }
1496
+ async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
1497
+ const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
1498
+ const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
1499
+ return { id, loc };
1500
+ });
1501
+ const locationById = new Map;
1502
+ for (const { id, loc } of locations) {
1503
+ locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
1633
1504
  }
1634
- if (await waitForCompletion(STOP_GRACE_MS)) {
1635
- removeDiscovery(rosterPath);
1636
- return { stopped: true };
1505
+ const groups = new Map;
1506
+ for (const id of sessionIds) {
1507
+ const loc = locationById.get(id);
1508
+ if (!loc)
1509
+ continue;
1510
+ const group = groups.get(loc.directory) ?? {
1511
+ directory: loc.directory,
1512
+ sessionIds: []
1513
+ };
1514
+ group.sessionIds.push(id);
1515
+ groups.set(loc.directory, group);
1637
1516
  }
1638
- return { stopped: false };
1517
+ const lastKnown = new Map;
1518
+ for (const id of sessionIds) {
1519
+ const loc = locationById.get(id);
1520
+ lastKnown.set(id, {
1521
+ sessionId: id,
1522
+ project: loc?.project ?? "",
1523
+ state: loc ? "running" : "not_found",
1524
+ resultAvailable: false
1525
+ });
1526
+ }
1527
+ return { locationById, groupList: Array.from(groups.values()), lastKnown };
1639
1528
  }
1640
- async function reapSurvivingGroup(pid) {
1641
- try {
1642
- if (isAlive(pid))
1529
+ async function wait(sessionIds, opts) {
1530
+ const ctx = validateContext(opts.context);
1531
+ if (!ctx.ok)
1532
+ return ctx;
1533
+ const { baseUrl, projects, credentials } = ctx;
1534
+ const uniqueIds = Array.from(new Set(sessionIds));
1535
+ if (uniqueIds.length === 0) {
1536
+ return { ok: true, sessions: [], waker: [], timedOut: true };
1537
+ }
1538
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
1539
+ const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
1540
+ const deadline = Date.now() + timeoutMs;
1541
+ const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
1542
+ async function pollGroup(group) {
1543
+ const [statusRes, questionRes] = await Promise.all([
1544
+ api(baseUrl, credentials, group.directory, "/session/status"),
1545
+ api(baseUrl, credentials, group.directory, "/question")
1546
+ ]);
1547
+ if (!statusRes.res.ok)
1643
1548
  return;
1644
- let groupAlive;
1549
+ let statusMap;
1645
1550
  try {
1646
- process.kill(-pid, 0);
1647
- groupAlive = true;
1551
+ statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
1648
1552
  } catch {
1649
- groupAlive = false;
1650
- }
1651
- if (!groupAlive)
1652
- return;
1653
- if (!signalGroupOnly(pid, "SIGTERM"))
1654
- return;
1655
- if (await waitForGroupDeath(pid, STOP_GRACE_MS))
1656
1553
  return;
1657
- signalGroupOnly(pid, "SIGKILL");
1658
- await waitForGroupDeath(pid, STOP_GRACE_MS);
1659
- } catch {}
1660
- }
1661
- async function stopForHung(tick) {
1662
- try {
1663
- await tick.stop(tick.rosterPath);
1664
- } catch {}
1665
- return { kind: "outcome", outcome: { reason: "hung" } };
1666
- }
1667
- async function superviseTick(tick, state) {
1668
- const st = tick.status(tick.rosterPath);
1669
- if (!st.running) {
1670
- await reapSurvivingGroup(tick.handle.pid);
1671
- return { kind: "outcome", outcome: { reason: "died" } };
1672
- }
1673
- const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
1674
- const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
1675
- const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
1676
- if (failures >= tick.threshold) {
1677
- return stopForHung(tick);
1554
+ }
1555
+ const pendingBySession = parsePendingQuestions(questionRes);
1556
+ for (const id of group.sessionIds) {
1557
+ const entry = statusMap[id];
1558
+ const busy = isStatusBusy(entry);
1559
+ const pendingQuestion = pendingBySession.get(id);
1560
+ const state = deriveSessionState({
1561
+ busy,
1562
+ pendingQuestion,
1563
+ resolved: true
1564
+ });
1565
+ lastKnown.set(id, {
1566
+ sessionId: id,
1567
+ project: locationById.get(id)?.project ?? "",
1568
+ state,
1569
+ resultAvailable: state === "complete",
1570
+ pendingQuestion
1571
+ });
1572
+ }
1678
1573
  }
1679
- if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
1680
- return stopForHung(tick);
1574
+ while (true) {
1575
+ await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
1576
+ const sessions = uniqueIds.map((id) => lastKnown.get(id));
1577
+ const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
1578
+ if (waker.length > 0) {
1579
+ return { ok: true, sessions, waker, timedOut: false };
1580
+ }
1581
+ if (Date.now() >= deadline) {
1582
+ return { ok: true, sessions, waker: [], timedOut: true };
1583
+ }
1584
+ const remaining = deadline - Date.now();
1585
+ await sleep2(Math.min(pollIntervalMs, Math.max(0, remaining)));
1681
1586
  }
1682
- return { kind: "tick", failures, lastReadyAt };
1683
- }
1684
- function makeSuperviseTick(rosterPath, handle, opts) {
1685
- return {
1686
- rosterPath,
1687
- handle,
1688
- password: handle.credentials.password ?? "",
1689
- threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
1690
- unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
1691
- now: opts.now ?? Date.now,
1692
- status: opts.status ?? serverStatus,
1693
- probe: opts.probe ?? probe,
1694
- stop: opts.stop ?? stopServer
1695
- };
1696
1587
  }
1697
- async function interruptibleSleep(doSleep, intervalMs, interrupt) {
1698
- if (!interrupt) {
1699
- await doSleep(intervalMs);
1700
- return;
1701
- }
1702
- let timer;
1703
- const timed = new Promise((resolve) => {
1704
- timer = setTimeout(resolve, intervalMs);
1705
- });
1588
+ function parsePendingQuestions(questionRes) {
1589
+ if (!questionRes.res.ok)
1590
+ return new Map;
1706
1591
  try {
1707
- await Promise.race([timed, interrupt]);
1708
- } finally {
1709
- if (timer !== undefined)
1710
- clearTimeout(timer);
1592
+ const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
1593
+ return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
1594
+ } catch {
1595
+ return new Map;
1711
1596
  }
1712
1597
  }
1713
- async function superviseServer(rosterPath, handle, opts = {}) {
1714
- const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
1715
- const tick = makeSuperviseTick(rosterPath, handle, opts);
1716
- const doSleep = opts.sleep ?? sleep2;
1717
- const shouldStop = opts.shouldStop ?? (() => false);
1718
- let state = { failures: 0, lastReadyAt: tick.now() };
1719
- for (;; ) {
1720
- if (shouldStop())
1721
- return { reason: "signal" };
1722
- const result2 = await superviseTick(tick, state);
1723
- if (result2.kind === "outcome")
1724
- return result2.outcome;
1725
- state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
1726
- if (shouldStop())
1727
- return { reason: "signal" };
1728
- await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
1729
- }
1598
+
1599
+ // src/format.ts
1600
+ function formatRoster(projects) {
1601
+ return projects.map((p) => {
1602
+ if (!p.pathExists)
1603
+ return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
1604
+ if (p.statusError)
1605
+ return `${p.name}: status error (${p.statusError}) — ${p.description}`;
1606
+ const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
1607
+ return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
1608
+ }).join(`
1609
+ `);
1730
1610
  }
1731
- async function waitForDeath(pid, budgetMs) {
1732
- const deadline = Date.now() + budgetMs;
1733
- while (Date.now() < deadline) {
1734
- if (!isAlive(pid))
1735
- return true;
1736
- await sleep2(POLL_INTERVAL_MS);
1611
+ function formatDispatch(r) {
1612
+ switch (r.mode) {
1613
+ case "new":
1614
+ return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
1615
+ case "question-reply":
1616
+ return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
1617
+ case "follow-up":
1618
+ return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
1737
1619
  }
1738
- return !isAlive(pid);
1739
1620
  }
1740
- async function waitForGroupDeath(pid, budgetMs) {
1741
- const deadline = Date.now() + budgetMs;
1742
- const groupAlive = () => {
1743
- try {
1744
- process.kill(-pid, 0);
1745
- return true;
1746
- } catch {
1747
- return false;
1621
+ function dispatchMetadata(r) {
1622
+ return { sessionId: r.sessionId, project: r.project, mode: r.mode };
1623
+ }
1624
+ function formatStatus(r) {
1625
+ const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
1626
+ `) : " (none)";
1627
+ const lines = [
1628
+ `session: ${r.sessionId} (${r.project})`,
1629
+ `title: ${r.title ?? "(untitled)"}`,
1630
+ `busy: ${r.busy}`
1631
+ ];
1632
+ if (r.pendingQuestion) {
1633
+ lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
1634
+ if (r.pendingQuestion.options.length > 0) {
1635
+ lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
1748
1636
  }
1749
- };
1750
- while (Date.now() < deadline) {
1751
- if (!groupAlive())
1752
- return true;
1753
- await sleep2(POLL_INTERVAL_MS);
1637
+ lines.push(` (answer with bus_task using sessionId)`);
1754
1638
  }
1755
- return !groupAlive();
1639
+ 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);
1640
+ return lines.join(`
1641
+ `);
1642
+ }
1643
+ function formatWait(r) {
1644
+ const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
1645
+ const sessionLines = r.sessions.map((s) => {
1646
+ const parts = [
1647
+ ` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
1648
+ ];
1649
+ if (s.pendingQuestion) {
1650
+ parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
1651
+ if (s.pendingQuestion.options.length > 0) {
1652
+ parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
1653
+ }
1654
+ parts.push(` (answer with bus_task using sessionId)`);
1655
+ }
1656
+ return parts.join(`
1657
+ `);
1658
+ });
1659
+ return [header, ...sessionLines].join(`
1660
+ `);
1661
+ }
1662
+ function formatResult(r) {
1663
+ const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
1664
+ `) : " (no changes)";
1665
+ return [
1666
+ `session: ${r.sessionId} (${r.project})`,
1667
+ `--- reply ---`,
1668
+ r.text || "(empty)",
1669
+ r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
1670
+ diffLines
1671
+ ].join(`
1672
+ `);
1756
1673
  }
1757
-
1758
- // src/mcp.ts
1759
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1760
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1761
- import { z as z4 } from "zod";
1762
1674
 
1763
1675
  // src/tools/bus_result.ts
1764
1676
  import { tool } from "@opencode-ai/plugin";
@@ -1914,7 +1826,7 @@ async function mcpLoadContext() {
1914
1826
  }
1915
1827
  return loadContext();
1916
1828
  }
1917
- var version = "0.9.0";
1829
+ var version = "0.10.1";
1918
1830
  var server = new McpServer({
1919
1831
  name: "space-bus",
1920
1832
  version