@fro.bot/space-bus 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1218 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
4
+ // src/config.ts
5
+ import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
6
+ import { homedir as homedir2 } from "node:os";
7
+ import { join as join2 } from "node:path";
8
+ import { z as z3 } from "zod";
9
+
10
+ // src/contract.ts
11
+ import { z } from "zod";
12
+ var sessionSchema = z.looseObject({
13
+ id: z.string(),
14
+ directory: z.string().optional(),
15
+ title: z.string().optional()
16
+ });
17
+ var sessionListSchema = z.array(sessionSchema);
18
+ var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
19
+ var sessionStateSchema = z.enum([
20
+ "running",
21
+ "blocked",
22
+ "complete",
23
+ "failed",
24
+ "not_found"
25
+ ]);
26
+ var sessionStateInfoSchema = z.object({
27
+ sessionId: z.string(),
28
+ project: z.string(),
29
+ state: sessionStateSchema,
30
+ resultAvailable: z.boolean(),
31
+ pendingQuestion: z.object({
32
+ preview: z.string(),
33
+ options: z.array(z.string())
34
+ }).optional()
35
+ });
36
+ var todoSchema = z.array(z.looseObject({
37
+ content: z.string(),
38
+ status: z.string(),
39
+ priority: z.string()
40
+ })).default([]);
41
+ var diffEntrySchema = z.looseObject({
42
+ file: z.string().optional(),
43
+ additions: z.number(),
44
+ deletions: z.number(),
45
+ status: z.string().optional()
46
+ });
47
+ var diffSchema = z.array(diffEntrySchema).default([]);
48
+ var vcsStatusEntrySchema = z.looseObject({
49
+ file: z.string(),
50
+ additions: z.number(),
51
+ deletions: z.number(),
52
+ status: z.string().optional()
53
+ });
54
+ var vcsStatusSchema = z.array(vcsStatusEntrySchema).default([]);
55
+ var turnDiffEntrySchema = diffEntrySchema;
56
+ var turnMessageSchema = z.looseObject({
57
+ info: z.looseObject({
58
+ role: z.string(),
59
+ summary: z.looseObject({
60
+ diffs: z.array(turnDiffEntrySchema).optional()
61
+ }).optional()
62
+ })
63
+ });
64
+ var turnMessageListSchema = z.array(turnMessageSchema);
65
+ var sessionSummarySchema = z.looseObject({
66
+ summary: z.looseObject({
67
+ diffs: z.array(turnDiffEntrySchema).optional()
68
+ }).optional()
69
+ });
70
+ var messagePartSchema = z.looseObject({
71
+ type: z.string(),
72
+ text: z.string().optional()
73
+ });
74
+ var messageEnvelopeSchema = z.looseObject({
75
+ info: z.looseObject({ role: z.string() }),
76
+ parts: z.array(messagePartSchema)
77
+ });
78
+ var messageListSchema = z.array(messageEnvelopeSchema);
79
+ var pendingQuestionEntrySchema = z.looseObject({
80
+ id: z.string(),
81
+ sessionID: z.string(),
82
+ questions: z.array(z.looseObject({
83
+ question: z.string().optional(),
84
+ options: z.array(z.looseObject({ label: z.string().optional() })).optional()
85
+ })).optional()
86
+ });
87
+ var pendingQuestionListSchema = z.array(pendingQuestionEntrySchema);
88
+ var questionEntrySchema = z.looseObject({
89
+ id: z.string(),
90
+ sessionID: z.string()
91
+ });
92
+ var questionListSchema = z.array(questionEntrySchema);
93
+ var LOOPBACK_HOSTS = new Set([
94
+ "127.0.0.1",
95
+ "::1",
96
+ "[::1]",
97
+ "localhost"
98
+ ]);
99
+ function loopbackOk(baseUrl) {
100
+ try {
101
+ return LOOPBACK_HOSTS.has(new URL(baseUrl).hostname);
102
+ } catch {
103
+ return false;
104
+ }
105
+ }
106
+ var projectSchema = z.looseObject({
107
+ name: z.string(),
108
+ path: z.string(),
109
+ description: z.string(),
110
+ expandedPath: z.string(),
111
+ exists: z.boolean()
112
+ });
113
+ var rosterSchema = z.object({
114
+ server: z.object({ baseUrl: z.url() }),
115
+ projects: z.array(projectSchema)
116
+ });
117
+ var credentialsSchema = z.object({
118
+ username: z.string().optional(),
119
+ password: z.string().optional()
120
+ });
121
+ var busContextSchema = z.object({
122
+ roster: rosterSchema,
123
+ credentials: credentialsSchema.optional()
124
+ });
125
+ var managedSpawnConfigSchema = z.object({
126
+ command: z.array(z.string()).optional(),
127
+ cwd: z.string().optional(),
128
+ port: z.number().int().nonnegative().optional()
129
+ });
130
+ var registryEntrySchema = z.object({
131
+ name: z.string().regex(/^[a-z0-9-]{1,64}$/, "roster name must be 1-64 lowercase letters, digits, or hyphens"),
132
+ path: z.string().min(1, "roster path must not be empty")
133
+ });
134
+ var registryFileSchema = z.object({
135
+ version: z.literal(1),
136
+ default: z.string().optional(),
137
+ rosters: z.array(registryEntrySchema)
138
+ }).superRefine((val, ctx) => {
139
+ const seen = new Set;
140
+ for (const entry of val.rosters) {
141
+ const key = entry.name.toLowerCase();
142
+ if (seen.has(key)) {
143
+ ctx.addIssue({
144
+ code: "custom",
145
+ message: `space-bus: duplicate roster name "${entry.name}" (case-insensitive) in registry`
146
+ });
147
+ }
148
+ seen.add(key);
149
+ }
150
+ if (val.default !== undefined) {
151
+ const matches = val.rosters.filter((entry) => entry.name === val.default);
152
+ if (matches.length !== 1) {
153
+ ctx.addIssue({
154
+ code: "custom",
155
+ message: `space-bus: registry's default "${val.default}" must match exactly one roster entry's name (matched ${matches.length})`
156
+ });
157
+ }
158
+ }
159
+ });
160
+ var discoveryFileSchema = z.object({
161
+ port: z.number().int().nonnegative(),
162
+ pid: z.number().int().min(2),
163
+ identity: z.string(),
164
+ password: z.string(),
165
+ spawnConfig: managedSpawnConfigSchema,
166
+ baseUrl: z.url(),
167
+ rosterPath: z.string().optional()
168
+ });
169
+
170
+ // src/discovery.ts
171
+ import { execFileSync } from "node:child_process";
172
+ import { createHash, randomBytes } from "node:crypto";
173
+ import {
174
+ chmodSync,
175
+ closeSync,
176
+ constants as fsConstants,
177
+ mkdirSync,
178
+ openSync,
179
+ readFileSync,
180
+ renameSync,
181
+ statSync,
182
+ unlinkSync,
183
+ writeFileSync
184
+ } from "node:fs";
185
+ import { homedir } from "node:os";
186
+ import { join } from "node:path";
187
+ import { z as z2 } from "zod";
188
+ function rosterKey(rosterPath) {
189
+ return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
190
+ }
191
+ function stateDirFor(rosterPath) {
192
+ const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
193
+ return join(base, "space-bus", rosterKey(rosterPath));
194
+ }
195
+ function discoveryFilePath(rosterPath) {
196
+ return join(stateDirFor(rosterPath), "discovery.json");
197
+ }
198
+ function lockFilePath(rosterPath) {
199
+ return join(stateDirFor(rosterPath), "spawn.lock");
200
+ }
201
+ function logFilePath(rosterPath) {
202
+ return join(stateDirFor(rosterPath), "server.log");
203
+ }
204
+ function writeDiscovery(rosterPath, data) {
205
+ const dir = stateDirFor(rosterPath);
206
+ mkdirSync(dir, { recursive: true, mode: 448 });
207
+ chmodSync(dir, 448);
208
+ const target = discoveryFilePath(rosterPath);
209
+ const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
210
+ const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
211
+ try {
212
+ writeFileSync(fd, JSON.stringify(data));
213
+ } finally {
214
+ closeQuietly(fd);
215
+ }
216
+ renameSync(tempPath, target);
217
+ chmodSync(target, 384);
218
+ }
219
+ function readDiscovery(rosterPath) {
220
+ const target = discoveryFilePath(rosterPath);
221
+ let raw;
222
+ try {
223
+ raw = readFileSync(target, "utf8");
224
+ } catch {
225
+ return null;
226
+ }
227
+ let json;
228
+ try {
229
+ json = JSON.parse(raw);
230
+ } catch {
231
+ return null;
232
+ }
233
+ const parsed = discoveryFileSchema.safeParse(json);
234
+ return parsed.success ? parsed.data : null;
235
+ }
236
+ function removeDiscovery(rosterPath) {
237
+ try {
238
+ unlinkSync(discoveryFilePath(rosterPath));
239
+ } catch (err) {
240
+ if (!isEnoent(err))
241
+ throw err;
242
+ }
243
+ }
244
+ function removeDiscoveryIfMatches(rosterPath, expected) {
245
+ try {
246
+ const current = readDiscovery(rosterPath);
247
+ if (current && current.pid === expected.pid && current.identity === expected.identity) {
248
+ removeDiscovery(rosterPath);
249
+ }
250
+ } catch {}
251
+ }
252
+ function attachLive(rosterPath) {
253
+ const discovery = readDiscovery(rosterPath);
254
+ if (!discovery)
255
+ return null;
256
+ if (!loopbackOk(discovery.baseUrl))
257
+ return null;
258
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
259
+ removeDiscoveryIfMatches(rosterPath, {
260
+ pid: discovery.pid,
261
+ identity: discovery.identity
262
+ });
263
+ return null;
264
+ }
265
+ return {
266
+ baseUrl: discovery.baseUrl,
267
+ credentials: { username: "opencode", password: discovery.password },
268
+ pid: discovery.pid,
269
+ port: discovery.port
270
+ };
271
+ }
272
+ function captureIdentity(pid) {
273
+ try {
274
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
275
+ env: { ...process.env, LC_ALL: "C" },
276
+ encoding: "utf8"
277
+ });
278
+ const trimmed = out.trim();
279
+ return trimmed.length > 0 ? trimmed : null;
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ function isAlive(pid) {
285
+ try {
286
+ process.kill(pid, 0);
287
+ return true;
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+ function verifyIdentity(pid, storedIdentity) {
293
+ if (!isAlive(pid))
294
+ return false;
295
+ const current = captureIdentity(pid);
296
+ return current !== null && current === storedIdentity;
297
+ }
298
+ var lockFileSchema = z2.object({
299
+ pid: z2.number().int().min(2),
300
+ startTime: z2.string(),
301
+ since: z2.number()
302
+ });
303
+ var CORRUPT_LOCK_GRACE_MS = 2000;
304
+ function acquireLock(rosterPath) {
305
+ const dir = stateDirFor(rosterPath);
306
+ mkdirSync(dir, { recursive: true, mode: 448 });
307
+ chmodSync(dir, 448);
308
+ const target = lockFilePath(rosterPath);
309
+ const identity = captureIdentity(process.pid) ?? "";
310
+ const lock = {
311
+ pid: process.pid,
312
+ startTime: identity,
313
+ since: Date.now()
314
+ };
315
+ if (tryCreateLockFile(target, lock)) {
316
+ return { rosterPath };
317
+ }
318
+ const existing = readLockFile(target);
319
+ if (existing) {
320
+ if (verifyIdentity(existing.pid, existing.startTime))
321
+ return null;
322
+ } else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
323
+ return null;
324
+ }
325
+ try {
326
+ unlinkSync(target);
327
+ } catch (err) {
328
+ if (!isEnoent(err))
329
+ throw err;
330
+ }
331
+ if (tryCreateLockFile(target, lock)) {
332
+ return { rosterPath };
333
+ }
334
+ return null;
335
+ }
336
+ function isOlderThan(path, ageMs) {
337
+ try {
338
+ return Date.now() - statSync(path).mtimeMs > ageMs;
339
+ } catch {
340
+ return false;
341
+ }
342
+ }
343
+ function releaseLock(handle) {
344
+ try {
345
+ unlinkSync(lockFilePath(handle.rosterPath));
346
+ } catch {}
347
+ }
348
+ function readLockFile(target) {
349
+ let raw;
350
+ try {
351
+ raw = readFileSync(target, "utf8");
352
+ } catch {
353
+ return null;
354
+ }
355
+ let json;
356
+ try {
357
+ json = JSON.parse(raw);
358
+ } catch {
359
+ return null;
360
+ }
361
+ const parsed = lockFileSchema.safeParse(json);
362
+ return parsed.success ? parsed.data : null;
363
+ }
364
+ function tryCreateLockFile(target, lock) {
365
+ let fd;
366
+ try {
367
+ fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
368
+ } catch (err) {
369
+ if (isErrnoCode(err, "EEXIST"))
370
+ return false;
371
+ throw err;
372
+ }
373
+ try {
374
+ writeFileSync(fd, JSON.stringify(lock));
375
+ } finally {
376
+ closeQuietly(fd);
377
+ }
378
+ return true;
379
+ }
380
+ function isEnoent(err) {
381
+ return isErrnoCode(err, "ENOENT");
382
+ }
383
+ function isErrnoCode(err, code) {
384
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
385
+ }
386
+ function closeQuietly(fd) {
387
+ try {
388
+ closeSync(fd);
389
+ } catch {}
390
+ }
391
+ function provisionalFilePath(rosterPath) {
392
+ return join(stateDirFor(rosterPath), "spawn.provisional.json");
393
+ }
394
+ var provisionalFileSchema = z2.object({
395
+ pid: z2.number().int().min(2),
396
+ identity: z2.string(),
397
+ password: z2.string(),
398
+ since: z2.number()
399
+ });
400
+ function writeProvisional(rosterPath, data) {
401
+ const dir = stateDirFor(rosterPath);
402
+ mkdirSync(dir, { recursive: true, mode: 448 });
403
+ chmodSync(dir, 448);
404
+ const target = provisionalFilePath(rosterPath);
405
+ const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
406
+ try {
407
+ writeFileSync(fd, JSON.stringify(data));
408
+ } finally {
409
+ closeQuietly(fd);
410
+ }
411
+ chmodSync(target, 384);
412
+ }
413
+ function readProvisional(rosterPath) {
414
+ const target = provisionalFilePath(rosterPath);
415
+ let raw;
416
+ try {
417
+ raw = readFileSync(target, "utf8");
418
+ } catch {
419
+ return null;
420
+ }
421
+ let json;
422
+ try {
423
+ json = JSON.parse(raw);
424
+ } catch {
425
+ return null;
426
+ }
427
+ const parsed = provisionalFileSchema.safeParse(json);
428
+ return parsed.success ? parsed.data : null;
429
+ }
430
+ function removeProvisional(rosterPath) {
431
+ try {
432
+ unlinkSync(provisionalFilePath(rosterPath));
433
+ } catch {}
434
+ }
435
+
436
+ // src/config.ts
437
+ var managedServerConfigSchema = z3.object({
438
+ command: z3.array(z3.string()).optional(),
439
+ cwd: z3.string().optional(),
440
+ port: z3.number().int().nonnegative().optional()
441
+ });
442
+ var serverConfigSchema = z3.object({
443
+ baseUrl: z3.url().optional(),
444
+ managed: managedServerConfigSchema.optional()
445
+ }).superRefine((val, ctx) => {
446
+ const hasBaseUrl = val.baseUrl !== undefined;
447
+ const hasManaged = val.managed !== undefined;
448
+ if (hasBaseUrl && hasManaged) {
449
+ ctx.addIssue({
450
+ code: "custom",
451
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
452
+ });
453
+ } else if (!hasBaseUrl && !hasManaged) {
454
+ ctx.addIssue({
455
+ code: "custom",
456
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
457
+ });
458
+ }
459
+ });
460
+ var manifestSchema = z3.object({
461
+ server: serverConfigSchema,
462
+ projects: z3.array(z3.object({
463
+ name: z3.string(),
464
+ path: z3.string(),
465
+ description: z3.string()
466
+ }))
467
+ });
468
+ function expandHome(path) {
469
+ return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
470
+ }
471
+ function resolveRosterPath(directory) {
472
+ const override = process.env["SPACE_BUS_CONFIG"];
473
+ if (override) {
474
+ if (override.includes("://")) {
475
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
476
+ }
477
+ const expanded = expandHome(override);
478
+ if (!expanded.startsWith("/")) {
479
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
480
+ }
481
+ return existsSync(expanded) ? realpathSync(expanded) : expanded;
482
+ }
483
+ if (directory) {
484
+ const candidate = join2(directory, "spacebus.json");
485
+ return existsSync(candidate) ? realpathSync(candidate) : candidate;
486
+ }
487
+ 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");
488
+ }
489
+ function getRoster(directory) {
490
+ const manifestPath = resolveRosterPath(directory);
491
+ let raw;
492
+ try {
493
+ raw = readFileSync2(manifestPath, "utf8");
494
+ } catch (err) {
495
+ 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)`);
496
+ }
497
+ let json;
498
+ try {
499
+ json = JSON.parse(raw);
500
+ } catch (err) {
501
+ throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
502
+ }
503
+ const parsed = manifestSchema.safeParse(json);
504
+ if (!parsed.success) {
505
+ throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
506
+ }
507
+ if (parsed.data.server.baseUrl !== undefined) {
508
+ const url = new URL(parsed.data.server.baseUrl);
509
+ const hostname = url.hostname;
510
+ if (!LOOPBACK_HOSTS.has(hostname)) {
511
+ throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
512
+ }
513
+ }
514
+ return parsed.data;
515
+ }
516
+ function getProjects(manifest) {
517
+ return manifest.projects.map((p) => {
518
+ const expandedPath = expandHome(p.path);
519
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
520
+ });
521
+ }
522
+ function getCredentials() {
523
+ const password = process.env["OPENCODE_SERVER_PASSWORD"];
524
+ if (!password)
525
+ return {};
526
+ const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
527
+ return { username, password };
528
+ }
529
+ function loadContext(directory) {
530
+ const rosterPath = resolveRosterPath(directory);
531
+ const manifest = getRoster(directory);
532
+ const projects = getProjects(manifest);
533
+ if (manifest.server.baseUrl === undefined) {
534
+ const live = attachLive(rosterPath);
535
+ if (!live) {
536
+ throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
537
+ }
538
+ return {
539
+ roster: { server: { baseUrl: live.baseUrl }, projects },
540
+ credentials: live.credentials
541
+ };
542
+ }
543
+ return {
544
+ roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
545
+ credentials: getCredentials()
546
+ };
547
+ }
548
+ function isManagedRoster(directory) {
549
+ const manifest = getRoster(directory);
550
+ return manifest.server.managed !== undefined;
551
+ }
552
+
553
+ // src/registry.ts
554
+ import { randomBytes as randomBytes2 } from "node:crypto";
555
+ import {
556
+ closeSync as closeSync2,
557
+ constants as fsConstants2,
558
+ fstatSync,
559
+ lstatSync,
560
+ mkdirSync as mkdirSync2,
561
+ openSync as openSync2,
562
+ readFileSync as readFileSync3,
563
+ realpathSync as realpathSync2,
564
+ renameSync as renameSync2,
565
+ statSync as statSync2,
566
+ unlinkSync as unlinkSync2,
567
+ writeSync
568
+ } from "node:fs";
569
+ import { homedir as homedir3 } from "node:os";
570
+ import { isAbsolute, join as join3 } from "node:path";
571
+ var EMPTY_REGISTRY = { version: 1, rosters: [] };
572
+ function registryPath() {
573
+ const base = process.env["XDG_CONFIG_HOME"] ?? join3(homedir3(), ".config");
574
+ return join3(base, "space-bus", "rosters.json");
575
+ }
576
+ function isEnoent2(err) {
577
+ return isErrnoCode2(err, "ENOENT");
578
+ }
579
+ function isErrnoCode2(err, code) {
580
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
581
+ }
582
+ function closeQuietly2(fd) {
583
+ try {
584
+ closeSync2(fd);
585
+ } catch {}
586
+ }
587
+ function readRegistry() {
588
+ const target = registryPath();
589
+ let raw;
590
+ try {
591
+ raw = readFileSync3(target, "utf8");
592
+ } catch (err) {
593
+ if (isEnoent2(err)) {
594
+ return { ok: true, registry: EMPTY_REGISTRY };
595
+ }
596
+ return {
597
+ ok: false,
598
+ error: `space-bus: cannot read registry at ${target}: ${String(err)}`
599
+ };
600
+ }
601
+ let json;
602
+ try {
603
+ json = JSON.parse(raw);
604
+ } catch (err) {
605
+ return {
606
+ ok: false,
607
+ error: `space-bus: registry at ${target} is not valid JSON: ${String(err)}`
608
+ };
609
+ }
610
+ const parsed = registryFileSchema.safeParse(json);
611
+ if (!parsed.success) {
612
+ return {
613
+ ok: false,
614
+ error: `space-bus: registry at ${target} failed schema validation: ${parsed.error.message}`
615
+ };
616
+ }
617
+ const nonAbsolute = parsed.data.rosters.find((entry) => !isAbsolute(entry.path));
618
+ if (nonAbsolute) {
619
+ return {
620
+ ok: false,
621
+ error: `space-bus: registry at ${target} contains a non-absolute path for roster "${nonAbsolute.name}": ${nonAbsolute.path}`
622
+ };
623
+ }
624
+ return { ok: true, registry: parsed.data };
625
+ }
626
+ function writeRegistryAtomic(data) {
627
+ const target = registryPath();
628
+ const dir = join3(target, "..");
629
+ try {
630
+ mkdirSync2(dir, { recursive: true, mode: 448 });
631
+ } catch (err) {
632
+ return {
633
+ ok: false,
634
+ error: `space-bus: failed to create registry dir ${dir}: ${String(err)}`
635
+ };
636
+ }
637
+ const tempPath = join3(dir, `.rosters.${randomBytes2(8).toString("hex")}.tmp`);
638
+ let fd;
639
+ try {
640
+ fd = openSync2(tempPath, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
641
+ writeSync(fd, JSON.stringify(data, null, 2));
642
+ closeSync2(fd);
643
+ fd = undefined;
644
+ renameSync2(tempPath, target);
645
+ } catch (err) {
646
+ if (fd !== undefined)
647
+ closeQuietly2(fd);
648
+ try {
649
+ unlinkSync2(tempPath);
650
+ } catch {}
651
+ return {
652
+ ok: false,
653
+ error: `space-bus: failed to write registry at ${target}: ${String(err)}`
654
+ };
655
+ }
656
+ return { ok: true };
657
+ }
658
+ function registryLockPath() {
659
+ return join3(registryPath(), "..", "rosters.lock");
660
+ }
661
+ var LOCK_RETRY_COUNT = 10;
662
+ var LOCK_RETRY_DELAY_MS = 50;
663
+ var LOCK_STALE_MS = 1e4;
664
+ function sleepSync(ms) {
665
+ const buf = new Int32Array(new SharedArrayBuffer(4));
666
+ Atomics.wait(buf, 0, 0, ms);
667
+ }
668
+ function tryCreateRegistryLock(target) {
669
+ let fd;
670
+ try {
671
+ fd = openSync2(target, fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY, 384);
672
+ } catch (err) {
673
+ if (isErrnoCode2(err, "EEXIST"))
674
+ return false;
675
+ throw err;
676
+ }
677
+ try {
678
+ writeSync(fd, String(process.pid));
679
+ } finally {
680
+ closeQuietly2(fd);
681
+ }
682
+ return true;
683
+ }
684
+ function isRegistryLockStale(target) {
685
+ try {
686
+ return Date.now() - statSync2(target).mtimeMs > LOCK_STALE_MS;
687
+ } catch {
688
+ return false;
689
+ }
690
+ }
691
+ function breakStaleAndRetry(target) {
692
+ if (!isRegistryLockStale(target))
693
+ return false;
694
+ try {
695
+ unlinkSync2(target);
696
+ } catch (err) {
697
+ if (!isEnoent2(err))
698
+ throw err;
699
+ }
700
+ return tryCreateRegistryLock(target);
701
+ }
702
+ function acquireRegistryLock() {
703
+ const dir = join3(registryPath(), "..");
704
+ mkdirSync2(dir, { recursive: true, mode: 448 });
705
+ const target = registryLockPath();
706
+ for (let attempt = 0;attempt <= LOCK_RETRY_COUNT; attempt++) {
707
+ if (tryCreateRegistryLock(target))
708
+ return true;
709
+ if (breakStaleAndRetry(target))
710
+ return true;
711
+ if (attempt < LOCK_RETRY_COUNT)
712
+ sleepSync(LOCK_RETRY_DELAY_MS);
713
+ }
714
+ return false;
715
+ }
716
+ function releaseRegistryLock() {
717
+ try {
718
+ unlinkSync2(registryLockPath());
719
+ } catch {}
720
+ }
721
+ function withRegistryLock(mutate) {
722
+ if (!acquireRegistryLock()) {
723
+ return {
724
+ ok: false,
725
+ error: "space-bus: timed out waiting for the registry lock (another process is mutating rosters.json) — try again"
726
+ };
727
+ }
728
+ try {
729
+ return mutate();
730
+ } finally {
731
+ releaseRegistryLock();
732
+ }
733
+ }
734
+ function openAndValidateRosterFile(rosterPath) {
735
+ let fd;
736
+ try {
737
+ fd = openSync2(rosterPath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
738
+ } catch (err) {
739
+ if (isErrnoCode2(err, "ELOOP")) {
740
+ return {
741
+ ok: false,
742
+ error: `space-bus: roster path ${rosterPath} is a symlink — refusing to register a symlinked roster file`
743
+ };
744
+ }
745
+ if (isEnoent2(err)) {
746
+ return {
747
+ ok: false,
748
+ error: `space-bus: roster path ${rosterPath} does not exist: ${String(err)}`
749
+ };
750
+ }
751
+ return {
752
+ ok: false,
753
+ error: `space-bus: failed to open roster path ${rosterPath}: ${String(err)}`
754
+ };
755
+ }
756
+ try {
757
+ let stat;
758
+ try {
759
+ stat = fstatSync(fd);
760
+ } catch (err) {
761
+ return {
762
+ ok: false,
763
+ error: `space-bus: failed to stat roster path ${rosterPath}: ${String(err)}`
764
+ };
765
+ }
766
+ if (!stat.isFile()) {
767
+ return {
768
+ ok: false,
769
+ error: `space-bus: roster path ${rosterPath} is not a regular file — refusing to register`
770
+ };
771
+ }
772
+ let raw;
773
+ try {
774
+ raw = readFileSync3(fd, "utf8");
775
+ } catch (err) {
776
+ return {
777
+ ok: false,
778
+ error: `space-bus: failed to read roster path ${rosterPath}: ${String(err)}`
779
+ };
780
+ }
781
+ let json;
782
+ try {
783
+ json = JSON.parse(raw);
784
+ } catch (err) {
785
+ return {
786
+ ok: false,
787
+ error: `space-bus: roster path ${rosterPath} is not valid JSON: ${String(err)}`
788
+ };
789
+ }
790
+ const parsed = manifestSchema.safeParse(json);
791
+ if (!parsed.success) {
792
+ return {
793
+ ok: false,
794
+ error: `space-bus: roster path ${rosterPath} is not a valid spacebus.json — refusing to register: ${parsed.error.message}`
795
+ };
796
+ }
797
+ } finally {
798
+ closeQuietly2(fd);
799
+ }
800
+ return { ok: true };
801
+ }
802
+ function registerRoster(name, rosterPath) {
803
+ const nameCheck = registryEntrySchema.shape.name.safeParse(name);
804
+ if (!nameCheck.success) {
805
+ return {
806
+ ok: false,
807
+ error: `space-bus: invalid roster name "${name}": ${nameCheck.error.issues[0]?.message ?? "must be 1-64 lowercase letters, digits, or hyphens"}`
808
+ };
809
+ }
810
+ const validated = openAndValidateRosterFile(rosterPath);
811
+ if (!validated.ok)
812
+ return validated;
813
+ let canonicalPath;
814
+ try {
815
+ canonicalPath = realpathSync2(rosterPath);
816
+ } catch (err) {
817
+ return {
818
+ ok: false,
819
+ error: `space-bus: failed to canonicalize roster path ${rosterPath}: ${String(err)}`
820
+ };
821
+ }
822
+ return withRegistryLock(() => {
823
+ const readResult = readRegistry();
824
+ if (!readResult.ok)
825
+ return readResult;
826
+ const registry = readResult.registry;
827
+ const collision = registry.rosters.find((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
828
+ if (collision) {
829
+ return {
830
+ ok: false,
831
+ error: `space-bus: a roster named "${collision.name}" is already registered`
832
+ };
833
+ }
834
+ const entry = { name, path: canonicalPath };
835
+ const next = {
836
+ ...registry,
837
+ rosters: [...registry.rosters, entry]
838
+ };
839
+ return writeRegistryAtomic(next);
840
+ });
841
+ }
842
+ function unregisterRoster(name) {
843
+ return withRegistryLock(() => {
844
+ const readResult = readRegistry();
845
+ if (!readResult.ok)
846
+ return readResult;
847
+ const registry = readResult.registry;
848
+ const exists = registry.rosters.some((entry) => entry.name.toLowerCase() === name.toLowerCase());
849
+ if (!exists) {
850
+ return {
851
+ ok: false,
852
+ error: `space-bus: no roster named "${name}" is registered`
853
+ };
854
+ }
855
+ const rosters = registry.rosters.filter((entry) => entry.name.toLowerCase() !== name.toLowerCase());
856
+ const next = {
857
+ ...registry,
858
+ rosters,
859
+ default: registry.default !== undefined && registry.default.toLowerCase() === name.toLowerCase() ? undefined : registry.default
860
+ };
861
+ return writeRegistryAtomic(next);
862
+ });
863
+ }
864
+ function setDefaultRoster(name) {
865
+ return withRegistryLock(() => {
866
+ const readResult = readRegistry();
867
+ if (!readResult.ok)
868
+ return readResult;
869
+ const registry = readResult.registry;
870
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
871
+ if (!entry) {
872
+ return {
873
+ ok: false,
874
+ error: `space-bus: no roster named "${name}" is registered`
875
+ };
876
+ }
877
+ const next = { ...registry, default: entry.name };
878
+ return writeRegistryAtomic(next);
879
+ });
880
+ }
881
+ function resolveRosterByName(name) {
882
+ const readResult = readRegistry();
883
+ if (!readResult.ok)
884
+ return readResult;
885
+ const registry = readResult.registry;
886
+ const entry = registry.rosters.find((r) => r.name.toLowerCase() === name.toLowerCase());
887
+ if (!entry) {
888
+ const known = registry.rosters.map((r) => r.name);
889
+ return {
890
+ ok: false,
891
+ error: known.length > 0 ? `space-bus: no roster named "${name}" is registered (known: ${known.join(", ")})` : `space-bus: no roster named "${name}" is registered (no rosters are registered)`
892
+ };
893
+ }
894
+ let stat;
895
+ try {
896
+ stat = lstatSync(entry.path);
897
+ } catch {
898
+ return {
899
+ ok: false,
900
+ error: `space-bus: registered roster file no longer exists at ${entry.path} (name "${entry.name}") — was it moved or deleted?`
901
+ };
902
+ }
903
+ if (stat.isSymbolicLink()) {
904
+ return {
905
+ ok: false,
906
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is now a symlink — refusing to resolve a symlinked roster file`
907
+ };
908
+ }
909
+ if (!stat.isFile()) {
910
+ return {
911
+ ok: false,
912
+ error: `space-bus: registered roster path ${entry.path} (name "${entry.name}") is no longer a regular file`
913
+ };
914
+ }
915
+ let canonicalPath;
916
+ try {
917
+ canonicalPath = realpathSync2(entry.path);
918
+ } catch (err) {
919
+ return {
920
+ ok: false,
921
+ error: `space-bus: failed to canonicalize registered roster path ${entry.path} (name "${entry.name}"): ${String(err)}`
922
+ };
923
+ }
924
+ return { ok: true, path: canonicalPath };
925
+ }
926
+ // src/roster-edit.ts
927
+ import { randomBytes as randomBytes3 } from "node:crypto";
928
+ import {
929
+ chmodSync as chmodSync2,
930
+ closeSync as closeSync3,
931
+ constants as fsConstants3,
932
+ lstatSync as lstatSync2,
933
+ mkdirSync as mkdirSync3,
934
+ openSync as openSync3,
935
+ readFileSync as readFileSync4,
936
+ renameSync as renameSync3,
937
+ statSync as statSync3,
938
+ unlinkSync as unlinkSync3,
939
+ writeSync as writeSync2
940
+ } from "node:fs";
941
+ import { join as join4 } from "node:path";
942
+ function closeQuietly3(fd) {
943
+ try {
944
+ closeSync3(fd);
945
+ } catch {}
946
+ }
947
+ function isErrnoCode3(err, code) {
948
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
949
+ }
950
+ function duplicateProjectName(projects) {
951
+ const seen = new Set;
952
+ for (const p of projects) {
953
+ if (seen.has(p.name))
954
+ return p.name;
955
+ seen.add(p.name);
956
+ }
957
+ return null;
958
+ }
959
+ function validateManifest(data) {
960
+ const parsed = manifestSchema.safeParse(data);
961
+ if (!parsed.success) {
962
+ return {
963
+ ok: false,
964
+ error: `space-bus: roster document failed schema validation: ${parsed.error.message}`
965
+ };
966
+ }
967
+ const baseUrl = parsed.data.server.baseUrl;
968
+ if (baseUrl !== undefined && !loopbackOk(baseUrl)) {
969
+ return {
970
+ ok: false,
971
+ error: `space-bus: roster's server.baseUrl must point to localhost (got ${baseUrl}) — refusing to send credentials off-machine`
972
+ };
973
+ }
974
+ const dup = duplicateProjectName(parsed.data.projects);
975
+ if (dup !== null) {
976
+ return {
977
+ ok: false,
978
+ error: `space-bus: roster document has duplicate project name "${dup}"`
979
+ };
980
+ }
981
+ return { ok: true, manifest: parsed.data };
982
+ }
983
+ function readManifest(rosterPath) {
984
+ let raw;
985
+ try {
986
+ raw = readFileSync4(rosterPath, "utf8");
987
+ } catch (err) {
988
+ return {
989
+ ok: false,
990
+ error: `space-bus: cannot read roster at ${rosterPath}: ${String(err)}`
991
+ };
992
+ }
993
+ let json;
994
+ try {
995
+ json = JSON.parse(raw);
996
+ } catch (err) {
997
+ return {
998
+ ok: false,
999
+ error: `space-bus: roster at ${rosterPath} is not valid JSON: ${String(err)}`
1000
+ };
1001
+ }
1002
+ return validateManifest(json);
1003
+ }
1004
+ function writeManifestAtomic(rosterPath, data) {
1005
+ const dir = join4(rosterPath, "..");
1006
+ try {
1007
+ mkdirSync3(dir, { recursive: true });
1008
+ } catch (err) {
1009
+ return {
1010
+ ok: false,
1011
+ error: `space-bus: failed to create directory ${dir}: ${String(err)}`
1012
+ };
1013
+ }
1014
+ let existingMode;
1015
+ try {
1016
+ existingMode = statSync3(rosterPath).mode & 511;
1017
+ } catch {
1018
+ existingMode = undefined;
1019
+ }
1020
+ const tempPath = join4(dir, `.spacebus.${randomBytes3(8).toString("hex")}.tmp`);
1021
+ let fd;
1022
+ try {
1023
+ fd = openSync3(tempPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY, 420);
1024
+ writeSync2(fd, JSON.stringify(data, null, 2));
1025
+ if (existingMode !== undefined) {
1026
+ chmodSync2(tempPath, existingMode);
1027
+ }
1028
+ closeSync3(fd);
1029
+ fd = undefined;
1030
+ renameSync3(tempPath, rosterPath);
1031
+ } catch (err) {
1032
+ if (fd !== undefined)
1033
+ closeQuietly3(fd);
1034
+ try {
1035
+ unlinkSync3(tempPath);
1036
+ } catch {}
1037
+ return {
1038
+ ok: false,
1039
+ error: `space-bus: failed to write roster at ${rosterPath}: ${String(err)}`
1040
+ };
1041
+ }
1042
+ return { ok: true };
1043
+ }
1044
+ function writeRosterExclusive(rosterPath, data) {
1045
+ const dir = join4(rosterPath, "..");
1046
+ try {
1047
+ mkdirSync3(dir, { recursive: true });
1048
+ } catch (err) {
1049
+ return {
1050
+ ok: false,
1051
+ error: `space-bus: failed to create directory ${dir}: ${String(err)}`
1052
+ };
1053
+ }
1054
+ let fd;
1055
+ try {
1056
+ fd = openSync3(rosterPath, fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | fsConstants3.O_NOFOLLOW, 420);
1057
+ } catch (err) {
1058
+ if (isErrnoCode3(err, "EEXIST")) {
1059
+ return {
1060
+ ok: false,
1061
+ error: `space-bus: refusing to overwrite existing roster file at ${rosterPath}`
1062
+ };
1063
+ }
1064
+ return {
1065
+ ok: false,
1066
+ error: `space-bus: failed to create roster file at ${rosterPath}: ${String(err)}`
1067
+ };
1068
+ }
1069
+ try {
1070
+ writeSync2(fd, JSON.stringify(data, null, 2));
1071
+ } catch (err) {
1072
+ closeQuietly3(fd);
1073
+ try {
1074
+ unlinkSync3(rosterPath);
1075
+ } catch {}
1076
+ return {
1077
+ ok: false,
1078
+ error: `space-bus: failed to write roster file at ${rosterPath}: ${String(err)}`
1079
+ };
1080
+ }
1081
+ closeQuietly3(fd);
1082
+ return { ok: true };
1083
+ }
1084
+ function editManifest(rosterPath, mutate) {
1085
+ try {
1086
+ if (lstatSync2(rosterPath).isSymbolicLink()) {
1087
+ return {
1088
+ ok: false,
1089
+ error: `space-bus: refusing to edit a symlinked roster file at ${rosterPath}`
1090
+ };
1091
+ }
1092
+ } catch {}
1093
+ const current = readManifest(rosterPath);
1094
+ if (!current.ok)
1095
+ return current;
1096
+ const mutated = mutate(current.manifest);
1097
+ if ("ok" in mutated)
1098
+ return mutated;
1099
+ const revalidated = validateManifest(mutated);
1100
+ if (!revalidated.ok)
1101
+ return revalidated;
1102
+ return writeManifestAtomic(rosterPath, revalidated.manifest);
1103
+ }
1104
+ function createRoster(opts) {
1105
+ const nameCheck = /^[a-z0-9-]{1,64}$/.test(opts.name);
1106
+ if (!nameCheck) {
1107
+ return {
1108
+ ok: false,
1109
+ error: `space-bus: invalid roster name "${opts.name}": must be 1-64 lowercase letters, digits, or hyphens`
1110
+ };
1111
+ }
1112
+ const readResult = readRegistry();
1113
+ if (!readResult.ok)
1114
+ return readResult;
1115
+ const collision = readResult.registry.rosters.find((entry) => entry.name.toLowerCase() === opts.name.toLowerCase());
1116
+ if (collision) {
1117
+ return {
1118
+ ok: false,
1119
+ error: `space-bus: a roster named "${collision.name}" is already registered — refusing to create "${opts.name}"`
1120
+ };
1121
+ }
1122
+ const candidate = {
1123
+ server: opts.server ?? { managed: {} },
1124
+ projects: []
1125
+ };
1126
+ const validated = validateManifest(candidate);
1127
+ if (!validated.ok)
1128
+ return validated;
1129
+ const written = writeRosterExclusive(opts.rosterPath, validated.manifest);
1130
+ if (!written.ok)
1131
+ return written;
1132
+ const registered = registerRoster(opts.name, opts.rosterPath);
1133
+ if (!registered.ok) {
1134
+ return {
1135
+ ok: false,
1136
+ fileCreated: true,
1137
+ error: `space-bus: roster file was created at ${opts.rosterPath}, but registering it as "${opts.name}" failed: ${registered.error} — retry registerRoster("${opts.name}", "${opts.rosterPath}") to recover`
1138
+ };
1139
+ }
1140
+ return { ok: true };
1141
+ }
1142
+ function addProject(rosterPath, project) {
1143
+ return editManifest(rosterPath, (current) => {
1144
+ if (current.projects.some((p) => p.name === project.name)) {
1145
+ return {
1146
+ ok: false,
1147
+ error: `space-bus: a project named "${project.name}" already exists in ${rosterPath}`
1148
+ };
1149
+ }
1150
+ return { ...current, projects: [...current.projects, project] };
1151
+ });
1152
+ }
1153
+ function removeProject(rosterPath, projectName) {
1154
+ return editManifest(rosterPath, (current) => {
1155
+ const exists = current.projects.some((p) => p.name === projectName);
1156
+ if (!exists) {
1157
+ const known = current.projects.map((p) => p.name);
1158
+ return {
1159
+ ok: false,
1160
+ error: known.length > 0 ? `space-bus: no project named "${projectName}" in ${rosterPath} (known: ${known.join(", ")})` : `space-bus: no project named "${projectName}" in ${rosterPath} (no projects defined)`
1161
+ };
1162
+ }
1163
+ return {
1164
+ ...current,
1165
+ projects: current.projects.filter((p) => p.name !== projectName)
1166
+ };
1167
+ });
1168
+ }
1169
+ function updateProject(rosterPath, projectName, patch) {
1170
+ return editManifest(rosterPath, (current) => {
1171
+ const index = current.projects.findIndex((p) => p.name === projectName);
1172
+ if (index === -1) {
1173
+ const known = current.projects.map((p) => p.name);
1174
+ return {
1175
+ ok: false,
1176
+ error: known.length > 0 ? `space-bus: no project named "${projectName}" in ${rosterPath} (known: ${known.join(", ")})` : `space-bus: no project named "${projectName}" in ${rosterPath} (no projects defined)`
1177
+ };
1178
+ }
1179
+ if (patch.name !== undefined && patch.name !== projectName && current.projects.some((p) => p.name === patch.name)) {
1180
+ return {
1181
+ ok: false,
1182
+ error: `space-bus: cannot rename project "${projectName}" to "${patch.name}" in ${rosterPath} — a project with that name already exists`
1183
+ };
1184
+ }
1185
+ const projects = [...current.projects];
1186
+ const existing = projects[index];
1187
+ if (!existing) {
1188
+ return {
1189
+ ok: false,
1190
+ error: `space-bus: internal error locating project "${projectName}"`
1191
+ };
1192
+ }
1193
+ projects[index] = { ...existing, ...patch };
1194
+ return { ...current, projects };
1195
+ });
1196
+ }
1197
+ function editServer(rosterPath, server) {
1198
+ if (attachLive(rosterPath) !== null) {
1199
+ return {
1200
+ ok: false,
1201
+ error: `space-bus: a managed daemon is running for roster ${rosterPath} — run \`space-bus stop\` first before editing its server block`
1202
+ };
1203
+ }
1204
+ return editManifest(rosterPath, (current) => ({ ...current, server }));
1205
+ }
1206
+ export {
1207
+ updateProject,
1208
+ unregisterRoster,
1209
+ setDefaultRoster,
1210
+ resolveRosterByName,
1211
+ removeProject,
1212
+ registryPath,
1213
+ registerRoster,
1214
+ readRegistry,
1215
+ editServer,
1216
+ createRoster,
1217
+ addProject
1218
+ };