@fro.bot/space-bus 0.5.0 → 0.6.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/cli.js ADDED
@@ -0,0 +1,961 @@
1
+ #!/usr/bin/env node
2
+ // src/contract.ts
3
+ import { z } from "zod";
4
+ var sessionSchema = z.looseObject({
5
+ id: z.string(),
6
+ directory: z.string().optional(),
7
+ title: z.string().optional()
8
+ });
9
+ var sessionListSchema = z.array(sessionSchema);
10
+ var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
11
+ var todoSchema = z.array(z.looseObject({
12
+ content: z.string(),
13
+ status: z.string(),
14
+ priority: z.string()
15
+ })).default([]);
16
+ var diffEntrySchema = z.looseObject({
17
+ file: z.string().optional(),
18
+ additions: z.number(),
19
+ deletions: z.number(),
20
+ status: z.string().optional()
21
+ });
22
+ var diffSchema = z.array(diffEntrySchema).default([]);
23
+ var vcsStatusEntrySchema = z.looseObject({
24
+ file: z.string(),
25
+ additions: z.number(),
26
+ deletions: z.number(),
27
+ status: z.string().optional()
28
+ });
29
+ var vcsStatusSchema = z.array(vcsStatusEntrySchema).default([]);
30
+ var turnDiffEntrySchema = diffEntrySchema;
31
+ var turnMessageSchema = z.looseObject({
32
+ info: z.looseObject({
33
+ role: z.string(),
34
+ summary: z.looseObject({
35
+ diffs: z.array(turnDiffEntrySchema).optional()
36
+ }).optional()
37
+ })
38
+ });
39
+ var turnMessageListSchema = z.array(turnMessageSchema);
40
+ var sessionSummarySchema = z.looseObject({
41
+ summary: z.looseObject({
42
+ diffs: z.array(turnDiffEntrySchema).optional()
43
+ }).optional()
44
+ });
45
+ var messagePartSchema = z.looseObject({
46
+ type: z.string(),
47
+ text: z.string().optional()
48
+ });
49
+ var messageEnvelopeSchema = z.looseObject({
50
+ info: z.looseObject({ role: z.string() }),
51
+ parts: z.array(messagePartSchema)
52
+ });
53
+ var messageListSchema = z.array(messageEnvelopeSchema);
54
+ var pendingQuestionEntrySchema = z.looseObject({
55
+ id: z.string(),
56
+ sessionID: z.string(),
57
+ questions: z.array(z.looseObject({
58
+ question: z.string().optional(),
59
+ options: z.array(z.looseObject({ label: z.string().optional() })).optional()
60
+ })).optional()
61
+ });
62
+ var pendingQuestionListSchema = z.array(pendingQuestionEntrySchema);
63
+ var questionEntrySchema = z.looseObject({
64
+ id: z.string(),
65
+ sessionID: z.string()
66
+ });
67
+ var questionListSchema = z.array(questionEntrySchema);
68
+ var LOOPBACK_HOSTS = new Set([
69
+ "127.0.0.1",
70
+ "::1",
71
+ "[::1]",
72
+ "localhost"
73
+ ]);
74
+ var projectSchema = z.looseObject({
75
+ name: z.string(),
76
+ path: z.string(),
77
+ description: z.string(),
78
+ expandedPath: z.string(),
79
+ exists: z.boolean()
80
+ });
81
+ var rosterSchema = z.object({
82
+ server: z.object({ baseUrl: z.url() }),
83
+ projects: z.array(projectSchema)
84
+ });
85
+ var credentialsSchema = z.object({
86
+ username: z.string().optional(),
87
+ password: z.string().optional()
88
+ });
89
+ var busContextSchema = z.object({
90
+ roster: rosterSchema,
91
+ credentials: credentialsSchema.optional()
92
+ });
93
+
94
+ // src/config.ts
95
+ import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
96
+ import { homedir as homedir2 } from "node:os";
97
+ import { join as join2 } from "node:path";
98
+ import { z as z3 } from "zod";
99
+
100
+ // src/discovery.ts
101
+ import { execFileSync } from "node:child_process";
102
+ import { createHash, randomBytes } from "node:crypto";
103
+ import {
104
+ chmodSync,
105
+ closeSync,
106
+ constants as fsConstants,
107
+ mkdirSync,
108
+ openSync,
109
+ readFileSync,
110
+ renameSync,
111
+ statSync,
112
+ unlinkSync,
113
+ writeFileSync
114
+ } from "node:fs";
115
+ import { homedir } from "node:os";
116
+ import { join } from "node:path";
117
+ import { z as z2 } from "zod";
118
+ function stateDirFor(rosterPath) {
119
+ const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
120
+ const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
121
+ return join(base, "space-bus", hash);
122
+ }
123
+ function discoveryFilePath(rosterPath) {
124
+ return join(stateDirFor(rosterPath), "discovery.json");
125
+ }
126
+ function lockFilePath(rosterPath) {
127
+ return join(stateDirFor(rosterPath), "spawn.lock");
128
+ }
129
+ function logFilePath(rosterPath) {
130
+ return join(stateDirFor(rosterPath), "server.log");
131
+ }
132
+ var managedSpawnConfigSchema = z2.object({
133
+ command: z2.array(z2.string()).optional(),
134
+ cwd: z2.string().optional(),
135
+ port: z2.number().int().nonnegative().optional()
136
+ });
137
+ var discoveryFileSchema = z2.object({
138
+ port: z2.number().int().nonnegative(),
139
+ pid: z2.number().int().positive(),
140
+ identity: z2.string(),
141
+ password: z2.string(),
142
+ spawnConfig: managedSpawnConfigSchema,
143
+ baseUrl: z2.url()
144
+ });
145
+ function writeDiscovery(rosterPath, data) {
146
+ const dir = stateDirFor(rosterPath);
147
+ mkdirSync(dir, { recursive: true, mode: 448 });
148
+ chmodSync(dir, 448);
149
+ const target = discoveryFilePath(rosterPath);
150
+ const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
151
+ const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
152
+ try {
153
+ writeFileSync(fd, JSON.stringify(data));
154
+ } finally {
155
+ closeQuietly(fd);
156
+ }
157
+ renameSync(tempPath, target);
158
+ chmodSync(target, 384);
159
+ }
160
+ function readDiscovery(rosterPath) {
161
+ const target = discoveryFilePath(rosterPath);
162
+ let raw;
163
+ try {
164
+ raw = readFileSync(target, "utf8");
165
+ } catch {
166
+ return null;
167
+ }
168
+ let json;
169
+ try {
170
+ json = JSON.parse(raw);
171
+ } catch {
172
+ return null;
173
+ }
174
+ const parsed = discoveryFileSchema.safeParse(json);
175
+ return parsed.success ? parsed.data : null;
176
+ }
177
+ function removeDiscovery(rosterPath) {
178
+ try {
179
+ unlinkSync(discoveryFilePath(rosterPath));
180
+ } catch (err) {
181
+ if (!isEnoent(err))
182
+ throw err;
183
+ }
184
+ }
185
+ function loopbackOk(baseUrl) {
186
+ try {
187
+ const url = new URL(baseUrl);
188
+ return LOOPBACK_HOSTS.has(url.hostname);
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+ function attachLive(rosterPath) {
194
+ const discovery = readDiscovery(rosterPath);
195
+ if (!discovery)
196
+ return null;
197
+ if (!loopbackOk(discovery.baseUrl))
198
+ return null;
199
+ if (!verifyIdentity(discovery.pid, discovery.identity))
200
+ return null;
201
+ return {
202
+ baseUrl: discovery.baseUrl,
203
+ credentials: { username: "opencode", password: discovery.password },
204
+ pid: discovery.pid,
205
+ port: discovery.port
206
+ };
207
+ }
208
+ function captureIdentity(pid) {
209
+ try {
210
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
211
+ env: { ...process.env, LC_ALL: "C" },
212
+ encoding: "utf8"
213
+ });
214
+ const trimmed = out.trim();
215
+ return trimmed.length > 0 ? trimmed : null;
216
+ } catch {
217
+ return null;
218
+ }
219
+ }
220
+ function isAlive(pid) {
221
+ try {
222
+ process.kill(pid, 0);
223
+ return true;
224
+ } catch {
225
+ return false;
226
+ }
227
+ }
228
+ function verifyIdentity(pid, storedIdentity) {
229
+ if (!isAlive(pid))
230
+ return false;
231
+ const current = captureIdentity(pid);
232
+ return current !== null && current === storedIdentity;
233
+ }
234
+ var lockFileSchema = z2.object({
235
+ pid: z2.number().int().positive(),
236
+ startTime: z2.string(),
237
+ since: z2.number()
238
+ });
239
+ var CORRUPT_LOCK_GRACE_MS = 2000;
240
+ function acquireLock(rosterPath) {
241
+ const dir = stateDirFor(rosterPath);
242
+ mkdirSync(dir, { recursive: true, mode: 448 });
243
+ chmodSync(dir, 448);
244
+ const target = lockFilePath(rosterPath);
245
+ const identity = captureIdentity(process.pid) ?? "";
246
+ const lock = {
247
+ pid: process.pid,
248
+ startTime: identity,
249
+ since: Date.now()
250
+ };
251
+ if (tryCreateLockFile(target, lock)) {
252
+ return { rosterPath };
253
+ }
254
+ const existing = readLockFile(target);
255
+ if (existing) {
256
+ if (verifyIdentity(existing.pid, existing.startTime))
257
+ return null;
258
+ } else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
259
+ return null;
260
+ }
261
+ try {
262
+ unlinkSync(target);
263
+ } catch (err) {
264
+ if (!isEnoent(err))
265
+ throw err;
266
+ }
267
+ if (tryCreateLockFile(target, lock)) {
268
+ return { rosterPath };
269
+ }
270
+ return null;
271
+ }
272
+ function isOlderThan(path, ageMs) {
273
+ try {
274
+ return Date.now() - statSync(path).mtimeMs > ageMs;
275
+ } catch {
276
+ return false;
277
+ }
278
+ }
279
+ function releaseLock(handle) {
280
+ try {
281
+ unlinkSync(lockFilePath(handle.rosterPath));
282
+ } catch {}
283
+ }
284
+ function readLockFile(target) {
285
+ let raw;
286
+ try {
287
+ raw = readFileSync(target, "utf8");
288
+ } catch {
289
+ return null;
290
+ }
291
+ let json;
292
+ try {
293
+ json = JSON.parse(raw);
294
+ } catch {
295
+ return null;
296
+ }
297
+ const parsed = lockFileSchema.safeParse(json);
298
+ return parsed.success ? parsed.data : null;
299
+ }
300
+ function tryCreateLockFile(target, lock) {
301
+ let fd;
302
+ try {
303
+ fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
304
+ } catch (err) {
305
+ if (isErrnoCode(err, "EEXIST"))
306
+ return false;
307
+ throw err;
308
+ }
309
+ try {
310
+ writeFileSync(fd, JSON.stringify(lock));
311
+ } finally {
312
+ closeQuietly(fd);
313
+ }
314
+ return true;
315
+ }
316
+ function isEnoent(err) {
317
+ return isErrnoCode(err, "ENOENT");
318
+ }
319
+ function isErrnoCode(err, code) {
320
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
321
+ }
322
+ function closeQuietly(fd) {
323
+ try {
324
+ closeSync(fd);
325
+ } catch {}
326
+ }
327
+ function provisionalFilePath(rosterPath) {
328
+ return join(stateDirFor(rosterPath), "spawn.provisional.json");
329
+ }
330
+ var provisionalFileSchema = z2.object({
331
+ pid: z2.number().int().positive(),
332
+ identity: z2.string(),
333
+ password: z2.string(),
334
+ since: z2.number()
335
+ });
336
+ function writeProvisional(rosterPath, data) {
337
+ const dir = stateDirFor(rosterPath);
338
+ mkdirSync(dir, { recursive: true, mode: 448 });
339
+ chmodSync(dir, 448);
340
+ const target = provisionalFilePath(rosterPath);
341
+ const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
342
+ try {
343
+ writeFileSync(fd, JSON.stringify(data));
344
+ } finally {
345
+ closeQuietly(fd);
346
+ }
347
+ chmodSync(target, 384);
348
+ }
349
+ function readProvisional(rosterPath) {
350
+ const target = provisionalFilePath(rosterPath);
351
+ let raw;
352
+ try {
353
+ raw = readFileSync(target, "utf8");
354
+ } catch {
355
+ return null;
356
+ }
357
+ let json;
358
+ try {
359
+ json = JSON.parse(raw);
360
+ } catch {
361
+ return null;
362
+ }
363
+ const parsed = provisionalFileSchema.safeParse(json);
364
+ return parsed.success ? parsed.data : null;
365
+ }
366
+ function removeProvisional(rosterPath) {
367
+ try {
368
+ unlinkSync(provisionalFilePath(rosterPath));
369
+ } catch {}
370
+ }
371
+
372
+ // src/config.ts
373
+ var managedServerConfigSchema = z3.object({
374
+ command: z3.array(z3.string()).optional(),
375
+ cwd: z3.string().optional(),
376
+ port: z3.number().int().nonnegative().optional()
377
+ });
378
+ var serverConfigSchema = z3.object({
379
+ baseUrl: z3.url().optional(),
380
+ managed: managedServerConfigSchema.optional()
381
+ }).superRefine((val, ctx) => {
382
+ const hasBaseUrl = val.baseUrl !== undefined;
383
+ const hasManaged = val.managed !== undefined;
384
+ if (hasBaseUrl && hasManaged) {
385
+ ctx.addIssue({
386
+ code: "custom",
387
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
388
+ });
389
+ } else if (!hasBaseUrl && !hasManaged) {
390
+ ctx.addIssue({
391
+ code: "custom",
392
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
393
+ });
394
+ }
395
+ });
396
+ var manifestSchema = z3.object({
397
+ server: serverConfigSchema,
398
+ projects: z3.array(z3.object({
399
+ name: z3.string(),
400
+ path: z3.string(),
401
+ description: z3.string()
402
+ }))
403
+ });
404
+ function expandHome(path) {
405
+ return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
406
+ }
407
+ function resolveRosterPath(directory) {
408
+ const override = process.env["SPACE_BUS_CONFIG"];
409
+ if (override) {
410
+ if (override.includes("://")) {
411
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
412
+ }
413
+ const expanded = expandHome(override);
414
+ if (!expanded.startsWith("/")) {
415
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
416
+ }
417
+ return existsSync(expanded) ? realpathSync(expanded) : expanded;
418
+ }
419
+ if (directory) {
420
+ const candidate = join2(directory, "spacebus.json");
421
+ return existsSync(candidate) ? realpathSync(candidate) : candidate;
422
+ }
423
+ 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");
424
+ }
425
+ function getRoster(directory) {
426
+ const manifestPath = resolveRosterPath(directory);
427
+ let raw;
428
+ try {
429
+ raw = readFileSync2(manifestPath, "utf8");
430
+ } catch (err) {
431
+ 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)`);
432
+ }
433
+ let json;
434
+ try {
435
+ json = JSON.parse(raw);
436
+ } catch (err) {
437
+ throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
438
+ }
439
+ const parsed = manifestSchema.safeParse(json);
440
+ if (!parsed.success) {
441
+ throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
442
+ }
443
+ if (parsed.data.server.baseUrl !== undefined) {
444
+ const url = new URL(parsed.data.server.baseUrl);
445
+ const hostname = url.hostname;
446
+ if (!LOOPBACK_HOSTS.has(hostname)) {
447
+ throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
448
+ }
449
+ }
450
+ return parsed.data;
451
+ }
452
+ function getProjects(manifest) {
453
+ return manifest.projects.map((p) => {
454
+ const expandedPath = expandHome(p.path);
455
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
456
+ });
457
+ }
458
+ function getCredentials() {
459
+ const password = process.env["OPENCODE_SERVER_PASSWORD"];
460
+ if (!password)
461
+ return {};
462
+ const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
463
+ return { username, password };
464
+ }
465
+ function loadContext(directory) {
466
+ const rosterPath = resolveRosterPath(directory);
467
+ const manifest = getRoster(directory);
468
+ const projects = getProjects(manifest);
469
+ if (manifest.server.baseUrl === undefined) {
470
+ const live = attachLive(rosterPath);
471
+ if (!live) {
472
+ throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
473
+ }
474
+ return {
475
+ roster: { server: { baseUrl: live.baseUrl }, projects },
476
+ credentials: live.credentials
477
+ };
478
+ }
479
+ return {
480
+ roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
481
+ credentials: getCredentials()
482
+ };
483
+ }
484
+ function isManagedRoster(directory) {
485
+ const manifest = getRoster(directory);
486
+ return manifest.server.managed !== undefined;
487
+ }
488
+
489
+ // src/server.ts
490
+ import { spawn } from "node:child_process";
491
+ import { randomBytes as randomBytes2 } from "node:crypto";
492
+ import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
493
+ import { dirname } from "node:path";
494
+ var DEFAULT_READINESS_BUDGET_MS = 15000;
495
+ var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
496
+ var POLL_INTERVAL_MS = 50;
497
+ var MIN_PROBE_PHASE_MS = 3000;
498
+ var PROBE_FETCH_TIMEOUT_MS = 2000;
499
+ var STOP_GRACE_MS = 2000;
500
+ function sleep(ms) {
501
+ return new Promise((resolve) => setTimeout(resolve, ms));
502
+ }
503
+ function readManifest(rosterPath) {
504
+ const raw = readFileSync3(rosterPath, "utf8");
505
+ const json = JSON.parse(raw);
506
+ return manifestSchema.parse(json);
507
+ }
508
+ function readLogTail(logPath, maxChars = 4000) {
509
+ try {
510
+ const content = readFileSync3(logPath, "utf8");
511
+ return content.length > maxChars ? content.slice(-maxChars) : content;
512
+ } catch {
513
+ return "";
514
+ }
515
+ }
516
+ function basicAuthToken(password) {
517
+ return Buffer.from(`opencode:${password}`).toString("base64");
518
+ }
519
+ function redactSensitive(tail, password) {
520
+ return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
521
+ }
522
+ function redactedReadinessError(rosterPath, password, reason) {
523
+ const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
524
+ return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
525
+ ${tail}`);
526
+ }
527
+ function killIdentifiedProcess(pid, identity) {
528
+ try {
529
+ if (identity !== null && identity !== undefined && identity !== "") {
530
+ if (verifyIdentity(pid, identity))
531
+ process.kill(pid, "SIGTERM");
532
+ return;
533
+ }
534
+ process.kill(pid, "SIGTERM");
535
+ } catch {}
536
+ }
537
+ function attachServer(rosterPath) {
538
+ return attachLive(rosterPath);
539
+ }
540
+ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
541
+ const deadline = Date.now() + budgetMs;
542
+ const lockPath = lockFilePath(rosterPath);
543
+ while (Date.now() < deadline) {
544
+ const handle = attachServer(rosterPath);
545
+ if (handle)
546
+ return handle;
547
+ const lockInfo2 = readLockFile(lockPath);
548
+ const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
549
+ if (!winnerAlive) {
550
+ 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`);
551
+ }
552
+ await sleep(POLL_INTERVAL_MS);
553
+ }
554
+ const lockInfo = readLockFile(lockPath);
555
+ const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
556
+ throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
557
+ }
558
+ async function probe(baseUrl, password) {
559
+ try {
560
+ const res = await fetch(`${baseUrl}/session?limit=1`, {
561
+ headers: { authorization: `Basic ${basicAuthToken(password)}` },
562
+ signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
563
+ });
564
+ if (res.status === 200)
565
+ return "ready";
566
+ if (res.status === 401 || res.status === 403)
567
+ return "auth-failure";
568
+ return "retry";
569
+ } catch {
570
+ return "retry";
571
+ }
572
+ }
573
+ function childDied(child, pid) {
574
+ return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
575
+ }
576
+ async function waitForReadinessLine(logPath, child, pid, deadline) {
577
+ const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
578
+ while (Date.now() < deadline) {
579
+ if (childDied(child, pid))
580
+ return null;
581
+ const tail = readLogTail(logPath);
582
+ const match = readinessLine.exec(tail);
583
+ if (match?.[1]) {
584
+ const port = Number.parseInt(match[1], 10);
585
+ if (Number.isInteger(port) && port > 0 && port <= 65535) {
586
+ return { port, baseUrl: `http://127.0.0.1:${port}` };
587
+ }
588
+ }
589
+ await sleep(POLL_INTERVAL_MS);
590
+ }
591
+ return null;
592
+ }
593
+ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
594
+ while (Date.now() < deadline) {
595
+ if (childDied(child, pid))
596
+ return "died";
597
+ const outcome = await probe(baseUrl, password);
598
+ if (outcome === "ready")
599
+ return "ready";
600
+ if (outcome === "auth-failure")
601
+ return "auth-failure";
602
+ await sleep(POLL_INTERVAL_MS);
603
+ }
604
+ return "timeout";
605
+ }
606
+ async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
607
+ const deadline = Date.now() + budgetMs;
608
+ const logPath = logFilePath(rosterPath);
609
+ const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
610
+ const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
611
+ const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
612
+ if (lineResult === null) {
613
+ const diedEarly = childDied(child, pid);
614
+ killIdentifiedProcess(pid, identity);
615
+ throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
616
+ }
617
+ const { port, baseUrl } = lineResult;
618
+ const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
619
+ const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
620
+ if (outcome === "ready")
621
+ return { port, baseUrl };
622
+ killIdentifiedProcess(pid, identity);
623
+ if (outcome === "died") {
624
+ throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
625
+ }
626
+ if (outcome === "auth-failure") {
627
+ throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
628
+ }
629
+ throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
630
+ }
631
+ var PROVISIONAL_FRESH_WINDOW_MS = 5000;
632
+ function reapOrphanedProvisional(rosterPath) {
633
+ const provisional = readProvisional(rosterPath);
634
+ if (!provisional)
635
+ return;
636
+ const discovery = readDiscovery(rosterPath);
637
+ if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
638
+ removeProvisional(rosterPath);
639
+ return;
640
+ }
641
+ const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
642
+ const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
643
+ if (hasIdentity || isFresh) {
644
+ killIdentifiedProcess(provisional.pid, provisional.identity);
645
+ }
646
+ removeProvisional(rosterPath);
647
+ }
648
+ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
649
+ reapOrphanedProvisional(rosterPath);
650
+ const password = randomBytes2(32).toString("base64url");
651
+ const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
652
+ const cwd = managedConfig.cwd ?? dirname(rosterPath);
653
+ const requestedPort = managedConfig.port ?? 0;
654
+ const logPath = logFilePath(rosterPath);
655
+ const logFd = openSync2(logPath, "w", 384);
656
+ let child;
657
+ let pid;
658
+ let spawnError;
659
+ try {
660
+ child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
661
+ cwd,
662
+ detached: true,
663
+ stdio: ["ignore", logFd, logFd],
664
+ env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
665
+ });
666
+ child.on("error", (err) => {
667
+ spawnError = err;
668
+ });
669
+ child.unref();
670
+ pid = child.pid;
671
+ } finally {
672
+ closeQuietly(logFd);
673
+ }
674
+ if (pid === undefined) {
675
+ throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
676
+ }
677
+ const identity = captureIdentity(pid);
678
+ writeProvisional(rosterPath, {
679
+ pid,
680
+ identity: identity ?? "",
681
+ password,
682
+ since: Date.now()
683
+ });
684
+ let port;
685
+ let baseUrl;
686
+ try {
687
+ const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
688
+ const spawnErrorWatch = new Promise((_resolve, reject) => {
689
+ const check = setInterval(() => {
690
+ if (spawnError) {
691
+ clearInterval(check);
692
+ reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
693
+ }
694
+ }, POLL_INTERVAL_MS);
695
+ readiness.finally(() => clearInterval(check)).catch(() => {});
696
+ });
697
+ const result = await Promise.race([readiness, spawnErrorWatch]);
698
+ port = result.port;
699
+ baseUrl = result.baseUrl;
700
+ } finally {
701
+ removeProvisional(rosterPath);
702
+ }
703
+ const finalIdentity = identity ?? captureIdentity(pid) ?? "";
704
+ writeDiscovery(rosterPath, {
705
+ port,
706
+ pid,
707
+ identity: finalIdentity,
708
+ password,
709
+ spawnConfig: { command, cwd, port: requestedPort },
710
+ baseUrl
711
+ });
712
+ return {
713
+ baseUrl,
714
+ credentials: { username: "opencode", password },
715
+ pid,
716
+ port
717
+ };
718
+ }
719
+ async function ensureServer(rosterPath, options = {}) {
720
+ const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
721
+ const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
722
+ const fastPath = attachServer(rosterPath);
723
+ if (fastPath)
724
+ return fastPath;
725
+ const manifest = readManifest(rosterPath);
726
+ if (manifest.server.managed === undefined) {
727
+ throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
728
+ }
729
+ const lock = acquireLock(rosterPath);
730
+ if (lock === null) {
731
+ return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
732
+ }
733
+ try {
734
+ const attached = attachServer(rosterPath);
735
+ if (attached)
736
+ return attached;
737
+ return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
738
+ } finally {
739
+ releaseLock(lock);
740
+ }
741
+ }
742
+ function serverStatus(rosterPath) {
743
+ const discovery = readDiscovery(rosterPath);
744
+ if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
745
+ return { running: false };
746
+ }
747
+ let configDrift;
748
+ try {
749
+ const manifest = readManifest(rosterPath);
750
+ if (manifest.server.managed) {
751
+ const current = manifest.server.managed;
752
+ const currentCommand = current.command ?? ["harness", "serve"];
753
+ const currentCwd = current.cwd ?? dirname(rosterPath);
754
+ const currentPort = current.port ?? 0;
755
+ const storedCommand = discovery.spawnConfig.command ?? [
756
+ "harness",
757
+ "serve"
758
+ ];
759
+ const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
760
+ const storedPort = discovery.spawnConfig.port ?? 0;
761
+ configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
762
+ }
763
+ } catch {}
764
+ return {
765
+ running: true,
766
+ port: discovery.port,
767
+ pid: discovery.pid,
768
+ configDrift
769
+ };
770
+ }
771
+ async function stopServer(rosterPath) {
772
+ const discovery = readDiscovery(rosterPath);
773
+ if (!discovery)
774
+ return { stopped: false };
775
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
776
+ removeDiscovery(rosterPath);
777
+ return { stopped: false };
778
+ }
779
+ const { pid } = discovery;
780
+ try {
781
+ process.kill(pid, "SIGTERM");
782
+ } catch {
783
+ removeDiscovery(rosterPath);
784
+ return { stopped: true };
785
+ }
786
+ if (await waitForDeath(pid, STOP_GRACE_MS)) {
787
+ removeDiscovery(rosterPath);
788
+ return { stopped: true };
789
+ }
790
+ try {
791
+ process.kill(pid, "SIGKILL");
792
+ } catch {
793
+ removeDiscovery(rosterPath);
794
+ return { stopped: true };
795
+ }
796
+ if (await waitForDeath(pid, STOP_GRACE_MS)) {
797
+ removeDiscovery(rosterPath);
798
+ return { stopped: true };
799
+ }
800
+ return { stopped: false };
801
+ }
802
+ async function waitForDeath(pid, budgetMs) {
803
+ const deadline = Date.now() + budgetMs;
804
+ while (Date.now() < deadline) {
805
+ if (!isAlive(pid))
806
+ return true;
807
+ await sleep(POLL_INTERVAL_MS);
808
+ }
809
+ return !isAlive(pid);
810
+ }
811
+
812
+ // src/cli.ts
813
+ var USAGE = `space-bus — thin CLI for the managed OpenCode bus server
814
+
815
+ Usage:
816
+ space-bus serve [--foreground] [--json] [--config <path>]
817
+ space-bus status [--json] [--config <path>]
818
+ space-bus stop [--json] [--config <path>]
819
+ space-bus --help
820
+
821
+ Roster resolution: SPACE_BUS_CONFIG env var, or --config <path>.
822
+ `;
823
+ function parseArgs(argv) {
824
+ const result = {
825
+ command: undefined,
826
+ json: false,
827
+ foreground: false,
828
+ config: undefined,
829
+ help: false,
830
+ unknownFlags: [],
831
+ configMissingValue: false
832
+ };
833
+ for (let i = 0;i < argv.length; i++) {
834
+ i = consumeArg(argv, i, result);
835
+ }
836
+ return result;
837
+ }
838
+ function consumeArg(argv, i, result) {
839
+ const arg = argv[i];
840
+ if (arg === "--help" || arg === "-h") {
841
+ result.help = true;
842
+ } else if (arg === "--json") {
843
+ result.json = true;
844
+ } else if (arg === "--foreground") {
845
+ result.foreground = true;
846
+ } else if (arg === "--config") {
847
+ const value = argv[i + 1];
848
+ if (value === undefined) {
849
+ result.configMissingValue = true;
850
+ } else {
851
+ result.config = value;
852
+ }
853
+ return i + 1;
854
+ } else if (arg?.startsWith("--")) {
855
+ result.unknownFlags.push(arg);
856
+ } else if (result.command === undefined && arg !== undefined) {
857
+ result.command = arg;
858
+ }
859
+ return i;
860
+ }
861
+ function resolveRoster(config) {
862
+ if (config) {
863
+ process.env["SPACE_BUS_CONFIG"] = config;
864
+ }
865
+ return resolveRosterPath();
866
+ }
867
+ function printJson(json, data, plain) {
868
+ if (json) {
869
+ process.stdout.write(`${JSON.stringify(data)}
870
+ `);
871
+ } else {
872
+ process.stdout.write(`${plain}
873
+ `);
874
+ }
875
+ }
876
+ async function runServe(args) {
877
+ const rosterPath = resolveRoster(args.config);
878
+ const handle = await ensureServer(rosterPath);
879
+ const data = {
880
+ running: true,
881
+ port: handle.port,
882
+ pid: handle.pid,
883
+ baseUrl: handle.baseUrl
884
+ };
885
+ printJson(args.json, data, `space-bus: server running at ${handle.baseUrl} (pid ${handle.pid})`);
886
+ if (!args.foreground)
887
+ return 0;
888
+ return await new Promise((resolve) => {
889
+ let stopping = false;
890
+ const shutdown = (signal) => {
891
+ if (stopping)
892
+ return;
893
+ stopping = true;
894
+ process.stderr.write(`space-bus: received ${signal}, stopping...
895
+ `);
896
+ stopServer(rosterPath).finally(() => resolve(0));
897
+ };
898
+ process.on("SIGINT", () => shutdown("SIGINT"));
899
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
900
+ });
901
+ }
902
+ function runStatus(args) {
903
+ const rosterPath = resolveRoster(args.config);
904
+ const status = serverStatus(rosterPath);
905
+ const plain = status.running ? `space-bus: running (pid ${status.pid}, port ${status.port})${status.configDrift ? " [config drift detected]" : ""}` : "space-bus: not running";
906
+ printJson(args.json, status, plain);
907
+ return 0;
908
+ }
909
+ async function runStop(args) {
910
+ const rosterPath = resolveRoster(args.config);
911
+ const result = await stopServer(rosterPath);
912
+ const plain = result.stopped ? "space-bus: stopped" : "space-bus: nothing to stop";
913
+ printJson(args.json, result, plain);
914
+ return 0;
915
+ }
916
+ async function main() {
917
+ const args = parseArgs(process.argv.slice(2));
918
+ if (args.help) {
919
+ process.stdout.write(USAGE);
920
+ return 0;
921
+ }
922
+ if (args.configMissingValue) {
923
+ process.stderr.write(`space-bus: --config requires a path argument
924
+
925
+ `);
926
+ process.stderr.write(USAGE);
927
+ return 1;
928
+ }
929
+ if (args.unknownFlags.length > 0) {
930
+ process.stderr.write(`space-bus: unknown flag${args.unknownFlags.length > 1 ? "s" : ""}: ${args.unknownFlags.join(", ")}
931
+
932
+ `);
933
+ process.stderr.write(USAGE);
934
+ return 1;
935
+ }
936
+ if (args.command === undefined) {
937
+ process.stderr.write(USAGE);
938
+ return 1;
939
+ }
940
+ switch (args.command) {
941
+ case "serve":
942
+ return await runServe(args);
943
+ case "status":
944
+ return runStatus(args);
945
+ case "stop":
946
+ return await runStop(args);
947
+ default:
948
+ process.stderr.write(`space-bus: unknown command "${args.command}"
949
+
950
+ `);
951
+ process.stderr.write(USAGE);
952
+ return 1;
953
+ }
954
+ }
955
+ main().then((code) => {
956
+ process.exitCode = code;
957
+ }).catch((err) => {
958
+ process.stderr.write(`space-bus: ${err.message}
959
+ `);
960
+ process.exitCode = 1;
961
+ });