@fro.bot/space-bus 0.10.1 → 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.
package/dist/cli.js CHANGED
@@ -128,13 +128,44 @@ var managedSpawnConfigSchema = z.object({
128
128
  cwd: z.string().optional(),
129
129
  port: z.number().int().nonnegative().optional()
130
130
  });
131
+ var registryEntrySchema = z.object({
132
+ name: z.string().regex(/^[a-z0-9-]{1,64}$/, "roster name must be 1-64 lowercase letters, digits, or hyphens"),
133
+ path: z.string().min(1, "roster path must not be empty")
134
+ });
135
+ var registryFileSchema = z.object({
136
+ version: z.literal(1),
137
+ default: z.string().optional(),
138
+ rosters: z.array(registryEntrySchema)
139
+ }).superRefine((val, ctx) => {
140
+ const seen = new Set;
141
+ for (const entry of val.rosters) {
142
+ const key = entry.name.toLowerCase();
143
+ if (seen.has(key)) {
144
+ ctx.addIssue({
145
+ code: "custom",
146
+ message: `space-bus: duplicate roster name "${entry.name}" (case-insensitive) in registry`
147
+ });
148
+ }
149
+ seen.add(key);
150
+ }
151
+ if (val.default !== undefined) {
152
+ const matches = val.rosters.filter((entry) => entry.name === val.default);
153
+ if (matches.length !== 1) {
154
+ ctx.addIssue({
155
+ code: "custom",
156
+ message: `space-bus: registry's default "${val.default}" must match exactly one roster entry's name (matched ${matches.length})`
157
+ });
158
+ }
159
+ }
160
+ });
131
161
  var discoveryFileSchema = z.object({
132
162
  port: z.number().int().nonnegative(),
133
163
  pid: z.number().int().min(2),
134
164
  identity: z.string(),
135
165
  password: z.string(),
136
166
  spawnConfig: managedSpawnConfigSchema,
137
- baseUrl: z.url()
167
+ baseUrl: z.url(),
168
+ rosterPath: z.string().optional()
138
169
  });
139
170
 
140
171
  // src/discovery.ts
@@ -155,10 +186,12 @@ import {
155
186
  import { homedir } from "node:os";
156
187
  import { join } from "node:path";
157
188
  import { z as z2 } from "zod";
189
+ function rosterKey(rosterPath) {
190
+ return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
191
+ }
158
192
  function stateDirFor(rosterPath) {
159
193
  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);
194
+ return join(base, "space-bus", rosterKey(rosterPath));
162
195
  }
163
196
  function discoveryFilePath(rosterPath) {
164
197
  return join(stateDirFor(rosterPath), "discovery.json");
@@ -521,7 +554,7 @@ function isManagedRoster(directory) {
521
554
  // src/server.ts
522
555
  import { spawn } from "node:child_process";
523
556
  import { randomBytes as randomBytes2 } from "node:crypto";
524
- import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
557
+ import { existsSync as existsSync2, openSync as openSync2, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
525
558
  import { dirname } from "node:path";
526
559
  var DEFAULT_READINESS_BUDGET_MS = 15000;
527
560
  var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
@@ -775,7 +808,8 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
775
808
  identity: finalIdentity,
776
809
  password,
777
810
  spawnConfig: { command, cwd, port: requestedPort },
778
- baseUrl
811
+ baseUrl,
812
+ rosterPath
779
813
  });
780
814
  return {
781
815
  baseUrl,
@@ -785,6 +819,9 @@ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
785
819
  };
786
820
  }
787
821
  async function ensureServer(rosterPath, options = {}) {
822
+ if (existsSync2(rosterPath)) {
823
+ rosterPath = realpathSync2(rosterPath);
824
+ }
788
825
  const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
789
826
  const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
790
827
  const fastPath = attachServer(rosterPath);
@@ -1001,6 +1038,653 @@ async function waitForGroupDeath(pid, budgetMs) {
1001
1038
  return !groupAlive();
1002
1039
  }
1003
1040
 
1041
+ // src/cli.ts
1042
+ import { fileURLToPath } from "node:url";
1043
+
1044
+ // src/service.ts
1045
+ import {
1046
+ chmodSync as chmodSync3,
1047
+ closeSync as closeSync3,
1048
+ existsSync as existsSync3,
1049
+ fchmodSync,
1050
+ constants as fsConstants3,
1051
+ mkdirSync as mkdirSync2,
1052
+ openSync as openSync4,
1053
+ unlinkSync as unlinkSync2
1054
+ } from "node:fs";
1055
+ import { homedir as homedir4 } from "node:os";
1056
+ import { isAbsolute, join as join4 } from "node:path";
1057
+
1058
+ // src/launchd.ts
1059
+ import { spawn as spawn2 } from "node:child_process";
1060
+ import { randomBytes as randomBytes3 } from "node:crypto";
1061
+ import {
1062
+ chmodSync as chmodSync2,
1063
+ closeSync as closeSync2,
1064
+ constants as fsConstants2,
1065
+ lstatSync,
1066
+ openSync as openSync3,
1067
+ renameSync as renameSync2,
1068
+ statSync as statSync2,
1069
+ writeFileSync as writeFileSync2
1070
+ } from "node:fs";
1071
+ import { homedir as homedir3 } from "node:os";
1072
+ import { join as join3 } from "node:path";
1073
+ function serviceLabel(rosterPath) {
1074
+ return `bot.fro.space-bus.${rosterKey(rosterPath)}`;
1075
+ }
1076
+ function plistPath(label, baseDir) {
1077
+ return join3(baseDir ?? join3(homedir3(), "Library", "LaunchAgents"), `${label}.plist`);
1078
+ }
1079
+ function xmlEscape(value) {
1080
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1081
+ }
1082
+ function renderPlist(opts) {
1083
+ const runtime = xmlEscape(opts.runtime);
1084
+ const cliEntry = xmlEscape(opts.cliEntry);
1085
+ const rosterPath = xmlEscape(opts.rosterPath);
1086
+ const label = xmlEscape(opts.label);
1087
+ const outLog = xmlEscape(join3(opts.stateDir, "service.log"));
1088
+ const errLog = xmlEscape(join3(opts.stateDir, "service.err.log"));
1089
+ const envEntries = [
1090
+ ` <key>SPACE_BUS_CONFIG</key>
1091
+ <string>${rosterPath}</string>`
1092
+ ];
1093
+ if (opts.path !== undefined) {
1094
+ envEntries.push(` <key>PATH</key>
1095
+ <string>${xmlEscape(opts.path)}</string>`);
1096
+ }
1097
+ if (opts.xdgStateHome !== undefined) {
1098
+ envEntries.push(` <key>XDG_STATE_HOME</key>
1099
+ <string>${xmlEscape(opts.xdgStateHome)}</string>`);
1100
+ }
1101
+ return `<?xml version="1.0" encoding="UTF-8"?>
1102
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1103
+ <plist version="1.0">
1104
+ <dict>
1105
+ <key>Label</key>
1106
+ <string>${label}</string>
1107
+ <key>ProgramArguments</key>
1108
+ <array>
1109
+ <string>${runtime}</string>
1110
+ <string>${cliEntry}</string>
1111
+ <string>serve</string>
1112
+ <string>--foreground</string>
1113
+ </array>
1114
+ <key>KeepAlive</key>
1115
+ <dict>
1116
+ <key>SuccessfulExit</key>
1117
+ <false/>
1118
+ </dict>
1119
+ <key>RunAtLoad</key>
1120
+ <true/>
1121
+ <key>ThrottleInterval</key>
1122
+ <integer>10</integer>
1123
+ <key>EnvironmentVariables</key>
1124
+ <dict>
1125
+ ${envEntries.join(`
1126
+ `)}
1127
+ </dict>
1128
+ <key>StandardOutPath</key>
1129
+ <string>${outLog}</string>
1130
+ <key>StandardErrorPath</key>
1131
+ <string>${errLog}</string>
1132
+ </dict>
1133
+ </plist>
1134
+ `;
1135
+ }
1136
+ function writePlistAtomic(path, content) {
1137
+ const dir = join3(path, "..");
1138
+ const tempPath = join3(dir, `.${randomBytes3(8).toString("hex")}.tmp`);
1139
+ let fd;
1140
+ try {
1141
+ fd = openSync3(tempPath, fsConstants2.O_EXCL | fsConstants2.O_CREAT | fsConstants2.O_WRONLY, 420);
1142
+ } catch (err) {
1143
+ return { ok: false, error: `failed to create temp plist: ${String(err)}` };
1144
+ }
1145
+ try {
1146
+ writeFileSync2(fd, content);
1147
+ } catch (err) {
1148
+ closeQuietly2(fd);
1149
+ return { ok: false, error: `failed to write temp plist: ${String(err)}` };
1150
+ }
1151
+ closeQuietly2(fd);
1152
+ try {
1153
+ chmodSync2(tempPath, 420);
1154
+ renameSync2(tempPath, path);
1155
+ } catch (err) {
1156
+ return { ok: false, error: `failed to install plist: ${String(err)}` };
1157
+ }
1158
+ return { ok: true };
1159
+ }
1160
+ function verifyPlistSafe(path) {
1161
+ let mode;
1162
+ let uid;
1163
+ try {
1164
+ const linkStat = lstatSync(path);
1165
+ if (linkStat.isSymbolicLink()) {
1166
+ return { safe: false, reason: "plist path is a symlink" };
1167
+ }
1168
+ } catch (err) {
1169
+ return { safe: false, reason: `failed to stat plist: ${String(err)}` };
1170
+ }
1171
+ try {
1172
+ const stat = statSync2(path);
1173
+ mode = stat.mode & 511;
1174
+ uid = stat.uid;
1175
+ } catch (err) {
1176
+ return { safe: false, reason: `failed to stat plist: ${String(err)}` };
1177
+ }
1178
+ if (typeof process.getuid === "function" && uid !== process.getuid()) {
1179
+ return {
1180
+ safe: false,
1181
+ reason: `plist is not owned by the current user (uid ${uid})`
1182
+ };
1183
+ }
1184
+ if ((mode & 18) !== 0) {
1185
+ return {
1186
+ safe: false,
1187
+ reason: `plist is group/world-writable (mode ${mode.toString(8)})`
1188
+ };
1189
+ }
1190
+ return { safe: true };
1191
+ }
1192
+ function closeQuietly2(fd) {
1193
+ try {
1194
+ closeSync2(fd);
1195
+ } catch {}
1196
+ }
1197
+ var LAUNCHCTL_TIMEOUT_MS = 15000;
1198
+ var MAX_CAPTURED_OUTPUT_BYTES = 64 * 1024;
1199
+ function capOutput(value) {
1200
+ return value.length > MAX_CAPTURED_OUTPUT_BYTES ? `${value.slice(0, MAX_CAPTURED_OUTPUT_BYTES)}
1201
+ ...[truncated]` : value;
1202
+ }
1203
+ var defaultLaunchctl = (args) => new Promise((resolve) => {
1204
+ let settled = false;
1205
+ const settle = (result) => {
1206
+ if (settled)
1207
+ return;
1208
+ settled = true;
1209
+ clearTimeout(timer);
1210
+ resolve(result);
1211
+ };
1212
+ const child = spawn2("launchctl", args, {
1213
+ stdio: ["ignore", "pipe", "pipe"]
1214
+ });
1215
+ let stdout = "";
1216
+ let stderr = "";
1217
+ child.stdout.on("data", (chunk) => {
1218
+ stdout += chunk.toString();
1219
+ });
1220
+ child.stderr.on("data", (chunk) => {
1221
+ stderr += chunk.toString();
1222
+ });
1223
+ child.on("error", (err) => {
1224
+ settle({
1225
+ code: -1,
1226
+ stdout: capOutput(stdout),
1227
+ stderr: capOutput(`${stderr}
1228
+ launchctl spawn error: ${String(err)}`)
1229
+ });
1230
+ });
1231
+ child.on("close", (code) => {
1232
+ settle({
1233
+ code: code ?? -1,
1234
+ stdout: capOutput(stdout),
1235
+ stderr: capOutput(stderr)
1236
+ });
1237
+ });
1238
+ const timer = setTimeout(() => {
1239
+ try {
1240
+ child.kill("SIGKILL");
1241
+ } catch {}
1242
+ settle({
1243
+ code: -1,
1244
+ stdout: capOutput(stdout),
1245
+ stderr: capOutput(`${stderr}
1246
+ launchctl timed out after ${LAUNCHCTL_TIMEOUT_MS}ms (args: ${args.join(" ")})`)
1247
+ });
1248
+ }, LAUNCHCTL_TIMEOUT_MS);
1249
+ });
1250
+ async function bootstrap(uid, plist, exec) {
1251
+ return exec(["bootstrap", `gui/${uid}`, plist]);
1252
+ }
1253
+ async function bootout(uid, label, exec) {
1254
+ return exec(["bootout", `gui/${uid}/${label}`]);
1255
+ }
1256
+ async function kickstart(uid, label, exec) {
1257
+ return exec(["kickstart", "-k", `gui/${uid}/${label}`]);
1258
+ }
1259
+ var NOT_LOADED_MARKERS = ["could not find", "no such process"];
1260
+ async function printJob(uid, label, exec) {
1261
+ const result = await exec(["print", `gui/${uid}/${label}`]);
1262
+ if (result.code === 0) {
1263
+ const match = /pid\s*=\s*(\d+)/.exec(result.stdout);
1264
+ return match ? { ok: true, loaded: true, pid: Number(match[1]) } : { ok: true, loaded: true };
1265
+ }
1266
+ const combined = `${result.stdout}
1267
+ ${result.stderr}`.toLowerCase();
1268
+ if (NOT_LOADED_MARKERS.some((marker) => combined.includes(marker))) {
1269
+ return { ok: true, loaded: false };
1270
+ }
1271
+ const detail = result.stderr.trim() || result.stdout.trim();
1272
+ return {
1273
+ ok: false,
1274
+ error: `launchctl print failed (exit ${result.code})${detail ? ` — ${detail}` : ""}`
1275
+ };
1276
+ }
1277
+
1278
+ // src/service.ts
1279
+ var NOT_SUPPORTED_ERROR = "space-bus service is not supported on this platform (v1 supports macOS/launchd)";
1280
+ var EPHEMERAL_CACHE_SEGMENTS = [
1281
+ "/.bun/install/cache/",
1282
+ "/_npx/",
1283
+ "/.npm/_npx/"
1284
+ ];
1285
+ var DEFAULT_VERIFY_BUDGET_MS = 20000;
1286
+ var DEFAULT_VERIFY_POLL_MS = 200;
1287
+ var EXIT5_RETRY_DELAY_MS = 500;
1288
+ function sleep2(ms) {
1289
+ return new Promise((resolve) => setTimeout(resolve, ms));
1290
+ }
1291
+ function defaultCliEntryPath() {
1292
+ const argv1 = process.argv[1];
1293
+ return argv1 ?? process.execPath;
1294
+ }
1295
+ function resolveDeps(deps) {
1296
+ return {
1297
+ exec: deps.exec ?? defaultLaunchctl,
1298
+ platform: deps.platform ?? process.platform,
1299
+ uid: deps.uid ?? (process.getuid ? process.getuid() : 0),
1300
+ execPath: deps.execPath ?? process.execPath,
1301
+ cliEntryPath: deps.cliEntryPath ?? defaultCliEntryPath(),
1302
+ serverStatus: deps.serverStatus ?? serverStatus,
1303
+ sleep: deps.sleep ?? sleep2,
1304
+ now: deps.now ?? Date.now,
1305
+ verifyBudgetMs: deps.verifyBudgetMs ?? DEFAULT_VERIFY_BUDGET_MS,
1306
+ verifyPollMs: deps.verifyPollMs ?? DEFAULT_VERIFY_POLL_MS,
1307
+ launchAgentsDir: deps.launchAgentsDir ?? join4(homedir4(), "Library", "LaunchAgents")
1308
+ };
1309
+ }
1310
+ function isEphemeralCachePath(path) {
1311
+ return EPHEMERAL_CACHE_SEGMENTS.some((segment) => path.includes(segment));
1312
+ }
1313
+ function stderrDetail(result) {
1314
+ const stderr = result.stderr.trim();
1315
+ return stderr.length > 0 ? ` — ${stderr}` : result.stdout.trim().length > 0 ? ` — ${result.stdout.trim()}` : "";
1316
+ }
1317
+ function platformGate(platform) {
1318
+ if (platform !== "darwin") {
1319
+ return { ok: false, error: NOT_SUPPORTED_ERROR };
1320
+ }
1321
+ return { ok: true };
1322
+ }
1323
+ function identityFor(rosterPath, launchAgentsDir) {
1324
+ const label = serviceLabel(rosterPath);
1325
+ return {
1326
+ label,
1327
+ plistFilePath: plistPath(label, launchAgentsDir),
1328
+ stateDir: stateDirFor(rosterPath)
1329
+ };
1330
+ }
1331
+ function preCreateLog(path) {
1332
+ let fd;
1333
+ try {
1334
+ fd = openSync4(path, fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW, 384);
1335
+ } catch (err) {
1336
+ if (isSymlinkError(err)) {
1337
+ return { ok: false, error: `refusing symlinked log path: ${path}` };
1338
+ }
1339
+ return { ok: false, error: `failed to create log ${path}: ${String(err)}` };
1340
+ }
1341
+ try {
1342
+ fchmodSync(fd, 384);
1343
+ } catch (err) {
1344
+ return { ok: false, error: `failed to chmod log ${path}: ${String(err)}` };
1345
+ } finally {
1346
+ closeSync3(fd);
1347
+ }
1348
+ return { ok: true };
1349
+ }
1350
+ function isSymlinkError(err) {
1351
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ELOOP";
1352
+ }
1353
+ function ensureStateDir(stateDir) {
1354
+ try {
1355
+ mkdirSync2(stateDir, { recursive: true, mode: 448 });
1356
+ } catch (err) {
1357
+ return {
1358
+ ok: false,
1359
+ error: `failed to create state directory ${stateDir}: ${String(err)}`
1360
+ };
1361
+ }
1362
+ try {
1363
+ chmodSync3(stateDir, 448);
1364
+ } catch (err) {
1365
+ return {
1366
+ ok: false,
1367
+ error: `failed to harden state directory ${stateDir}: ${String(err)}`
1368
+ };
1369
+ }
1370
+ return { ok: true };
1371
+ }
1372
+ async function probeJob(resolved, label) {
1373
+ const result = await printJob(resolved.uid, label, resolved.exec);
1374
+ if (!result.ok) {
1375
+ return { ok: false, error: result.error };
1376
+ }
1377
+ return result.pid !== undefined ? { ok: true, loaded: result.loaded, pid: result.pid } : { ok: true, loaded: result.loaded };
1378
+ }
1379
+ function resolveXdgStateHome() {
1380
+ const xdgStateHomeEnv = process.env["XDG_STATE_HOME"];
1381
+ if (xdgStateHomeEnv === undefined)
1382
+ return { ok: true, value: undefined };
1383
+ if (!isAbsolute(xdgStateHomeEnv)) {
1384
+ return {
1385
+ ok: false,
1386
+ error: `XDG_STATE_HOME must be an absolute path to pin into the launchd environment, got: ${xdgStateHomeEnv}`
1387
+ };
1388
+ }
1389
+ return { ok: true, value: xdgStateHomeEnv };
1390
+ }
1391
+ async function bootstrapWithExit5Retry(resolved, label, plistFilePath) {
1392
+ const bootstrapResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
1393
+ if (bootstrapResult.code === 0)
1394
+ return { ok: true };
1395
+ if (bootstrapResult.code !== 5) {
1396
+ return {
1397
+ ok: false,
1398
+ error: `launchctl bootstrap failed (exit ${bootstrapResult.code})${stderrDetail(bootstrapResult)}`
1399
+ };
1400
+ }
1401
+ const reprobe = await probeJob(resolved, label);
1402
+ if (!reprobe.ok) {
1403
+ return {
1404
+ ok: false,
1405
+ error: `launchctl bootstrap failed (exit 5)${stderrDetail(bootstrapResult)}; re-probe also failed: ${reprobe.error}`
1406
+ };
1407
+ }
1408
+ if (reprobe.loaded)
1409
+ return { ok: true };
1410
+ await resolved.sleep(EXIT5_RETRY_DELAY_MS);
1411
+ const retryResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
1412
+ if (retryResult.code !== 0) {
1413
+ return {
1414
+ ok: false,
1415
+ error: `launchctl bootstrap failed twice (exit 5, then exit ${retryResult.code})${stderrDetail(bootstrapResult)}; retry: ${stderrDetail(retryResult)}`
1416
+ };
1417
+ }
1418
+ return { ok: true };
1419
+ }
1420
+ function prepareInstallFilesystem(resolved, stateDir) {
1421
+ try {
1422
+ mkdirSync2(resolved.launchAgentsDir, { recursive: true, mode: 493 });
1423
+ } catch (err) {
1424
+ return {
1425
+ ok: false,
1426
+ error: `failed to create LaunchAgents directory ${resolved.launchAgentsDir}: ${String(err)}`
1427
+ };
1428
+ }
1429
+ const stateDirResult = ensureStateDir(stateDir);
1430
+ if (!stateDirResult.ok)
1431
+ return stateDirResult;
1432
+ const outLogResult = preCreateLog(`${stateDir}/service.log`);
1433
+ if (!outLogResult.ok)
1434
+ return outLogResult;
1435
+ return preCreateLog(`${stateDir}/service.err.log`);
1436
+ }
1437
+ function ephemeralCacheWarning(resolved) {
1438
+ if (isEphemeralCachePath(resolved.execPath) || isEphemeralCachePath(resolved.cliEntryPath)) {
1439
+ return "space-bus service was installed pointing at an ephemeral package-manager cache path; this may break after the cache is cleared — install space-bus durably and re-run `service install`.";
1440
+ }
1441
+ return;
1442
+ }
1443
+ async function bootoutUntilAbsentOrFail(resolved, label) {
1444
+ const bootoutResult = await bootout(resolved.uid, label, resolved.exec);
1445
+ if (bootoutResult.code === 0)
1446
+ return { ok: true };
1447
+ const reprobe = await probeJob(resolved, label);
1448
+ if (!reprobe.ok) {
1449
+ return {
1450
+ ok: false,
1451
+ error: `launchctl bootout failed (exit ${bootoutResult.code})${stderrDetail(bootoutResult)}; re-probe to confirm absence also failed: ${reprobe.error}`
1452
+ };
1453
+ }
1454
+ if (reprobe.loaded) {
1455
+ return {
1456
+ ok: false,
1457
+ error: `launchctl bootout failed (exit ${bootoutResult.code})${stderrDetail(bootoutResult)} and the job is still loaded`
1458
+ };
1459
+ }
1460
+ return { ok: true };
1461
+ }
1462
+ async function installService(rosterPath, deps = {}) {
1463
+ const resolved = resolveDeps(deps);
1464
+ const gate = platformGate(resolved.platform);
1465
+ if (!gate.ok)
1466
+ return { ok: false, error: gate.error };
1467
+ const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
1468
+ const warning = ephemeralCacheWarning(resolved);
1469
+ const fsResult = prepareInstallFilesystem(resolved, stateDir);
1470
+ if (!fsResult.ok)
1471
+ return fsResult;
1472
+ const xdgResolved = resolveXdgStateHome();
1473
+ if (!xdgResolved.ok)
1474
+ return { ok: false, error: xdgResolved.error };
1475
+ const xdgStateHome = xdgResolved.value;
1476
+ const existing = await probeJob(resolved, label);
1477
+ if (!existing.ok) {
1478
+ return {
1479
+ ok: false,
1480
+ error: `failed to probe existing job: ${existing.error}`
1481
+ };
1482
+ }
1483
+ if (existing.loaded) {
1484
+ const bootoutOutcome = await bootoutUntilAbsentOrFail(resolved, label);
1485
+ if (!bootoutOutcome.ok)
1486
+ return bootoutOutcome;
1487
+ }
1488
+ const plistXml = renderPlist({
1489
+ runtime: resolved.execPath,
1490
+ cliEntry: resolved.cliEntryPath,
1491
+ rosterPath,
1492
+ stateDir,
1493
+ label,
1494
+ path: process.env["PATH"],
1495
+ xdgStateHome
1496
+ });
1497
+ const writeResult = writePlistAtomic(plistFilePath, plistXml);
1498
+ if (!writeResult.ok) {
1499
+ return { ok: false, error: writeResult.error };
1500
+ }
1501
+ const safety = verifyPlistSafe(plistFilePath);
1502
+ if (!safety.safe) {
1503
+ return { ok: false, error: `refusing to install: ${safety.reason}` };
1504
+ }
1505
+ const bootstrapOutcome = await bootstrapWithExit5Retry(resolved, label, plistFilePath);
1506
+ if (!bootstrapOutcome.ok)
1507
+ return bootstrapOutcome;
1508
+ const kickstartResult = await kickstart(resolved.uid, label, resolved.exec);
1509
+ if (kickstartResult.code !== 0) {
1510
+ return {
1511
+ ok: false,
1512
+ error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
1513
+ };
1514
+ }
1515
+ const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
1516
+ if (!verified.ok)
1517
+ return verified;
1518
+ return {
1519
+ ok: true,
1520
+ label,
1521
+ plistPath: plistFilePath,
1522
+ pid: verified.pid,
1523
+ warning
1524
+ };
1525
+ }
1526
+ async function verifyRunning(rosterPath, label, resolved, plistFilePath) {
1527
+ const deadline = resolved.now() + resolved.verifyBudgetMs;
1528
+ let lastLoaded = false;
1529
+ let lastRunning = false;
1530
+ let lastPid;
1531
+ let lastProbeError;
1532
+ for (;; ) {
1533
+ const job = await probeJob(resolved, label);
1534
+ const status = resolved.serverStatus(rosterPath);
1535
+ lastRunning = status.running;
1536
+ if (job.ok) {
1537
+ lastLoaded = job.loaded;
1538
+ lastPid = job.pid ?? status.pid;
1539
+ lastProbeError = undefined;
1540
+ if (job.loaded && status.running) {
1541
+ return { ok: true, pid: lastPid };
1542
+ }
1543
+ } else {
1544
+ lastProbeError = job.error;
1545
+ }
1546
+ if (resolved.now() >= deadline)
1547
+ break;
1548
+ await resolved.sleep(resolved.verifyPollMs);
1549
+ }
1550
+ const stateDir = stateDirFor(rosterPath);
1551
+ const logPath = join4(stateDir, "service.log");
1552
+ return {
1553
+ ok: false,
1554
+ error: `install did not verify as running within ${resolved.verifyBudgetMs}ms ` + `(loaded=${lastLoaded}, running=${lastRunning}` + `${lastProbeError ? `, last probe error: ${lastProbeError}` : ""})` + ` — label=${label}, plist=${plistFilePath ?? plistPath(label, resolved.launchAgentsDir)}, log=${logPath}`
1555
+ };
1556
+ }
1557
+ async function uninstallService(rosterPath, deps = {}) {
1558
+ const resolved = resolveDeps(deps);
1559
+ const gate = platformGate(resolved.platform);
1560
+ if (!gate.ok)
1561
+ return { ok: false, error: gate.error };
1562
+ const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
1563
+ const job = await probeJob(resolved, label);
1564
+ if (!job.ok) {
1565
+ return { ok: false, error: `failed to probe job: ${job.error}` };
1566
+ }
1567
+ let jobRemoved = false;
1568
+ if (job.loaded) {
1569
+ const outcome = await bootoutUntilAbsentOrFail(resolved, label);
1570
+ if (!outcome.ok)
1571
+ return outcome;
1572
+ jobRemoved = true;
1573
+ }
1574
+ let plistRemoved = false;
1575
+ try {
1576
+ unlinkSync2(plistFilePath);
1577
+ plistRemoved = true;
1578
+ } catch (err) {
1579
+ if (!isEnoent2(err)) {
1580
+ return {
1581
+ ok: false,
1582
+ error: `failed to remove plist ${plistFilePath}: ${String(err)}`
1583
+ };
1584
+ }
1585
+ }
1586
+ return {
1587
+ ok: true,
1588
+ removed: { job: jobRemoved, plist: plistRemoved },
1589
+ label
1590
+ };
1591
+ }
1592
+ function isEnoent2(err) {
1593
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
1594
+ }
1595
+ async function serviceStatus(rosterPath, deps = {}) {
1596
+ const resolved = resolveDeps(deps);
1597
+ const gate = platformGate(resolved.platform);
1598
+ if (!gate.ok)
1599
+ return { ok: false, error: gate.error };
1600
+ const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
1601
+ const installed = existsSync3(plistFilePath);
1602
+ const job = await probeJob(resolved, label);
1603
+ if (!job.ok) {
1604
+ return { ok: false, error: `failed to probe job: ${job.error}` };
1605
+ }
1606
+ const status = resolved.serverStatus(rosterPath);
1607
+ return {
1608
+ ok: true,
1609
+ installed,
1610
+ loaded: job.loaded,
1611
+ running: status.running,
1612
+ pid: job.pid ?? status.pid,
1613
+ label,
1614
+ plistPath: plistFilePath
1615
+ };
1616
+ }
1617
+ async function stopService(rosterPath, deps = {}) {
1618
+ const resolved = resolveDeps(deps);
1619
+ const gate = platformGate(resolved.platform);
1620
+ if (!gate.ok)
1621
+ return { ok: false, error: gate.error };
1622
+ const { label } = identityFor(rosterPath, resolved.launchAgentsDir);
1623
+ const job = await probeJob(resolved, label);
1624
+ if (!job.ok) {
1625
+ return { ok: false, error: `failed to probe job: ${job.error}` };
1626
+ }
1627
+ if (!job.loaded) {
1628
+ return { ok: true, label, wasLoaded: false };
1629
+ }
1630
+ const outcome = await bootoutUntilAbsentOrFail(resolved, label);
1631
+ if (!outcome.ok)
1632
+ return outcome;
1633
+ return { ok: true, label, wasLoaded: true };
1634
+ }
1635
+ async function startService(rosterPath, deps = {}) {
1636
+ const resolved = resolveDeps(deps);
1637
+ const gate = platformGate(resolved.platform);
1638
+ if (!gate.ok)
1639
+ return { ok: false, error: gate.error };
1640
+ const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
1641
+ if (!existsSync3(plistFilePath)) {
1642
+ return {
1643
+ ok: false,
1644
+ error: `space-bus service is not installed for this roster — run \`space-bus service install\``
1645
+ };
1646
+ }
1647
+ const xdgResolved = resolveXdgStateHome();
1648
+ if (!xdgResolved.ok)
1649
+ return { ok: false, error: xdgResolved.error };
1650
+ const xdgStateHome = xdgResolved.value;
1651
+ const plistXml = renderPlist({
1652
+ runtime: resolved.execPath,
1653
+ cliEntry: resolved.cliEntryPath,
1654
+ rosterPath,
1655
+ stateDir,
1656
+ label,
1657
+ path: process.env["PATH"],
1658
+ xdgStateHome
1659
+ });
1660
+ const writeResult = writePlistAtomic(plistFilePath, plistXml);
1661
+ if (!writeResult.ok) {
1662
+ return { ok: false, error: writeResult.error };
1663
+ }
1664
+ const safety = verifyPlistSafe(plistFilePath);
1665
+ if (!safety.safe) {
1666
+ return { ok: false, error: `refusing to start: ${safety.reason}` };
1667
+ }
1668
+ const bootstrapResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
1669
+ if (bootstrapResult.code !== 0) {
1670
+ return {
1671
+ ok: false,
1672
+ error: `launchctl bootstrap failed (exit ${bootstrapResult.code})${stderrDetail(bootstrapResult)}`
1673
+ };
1674
+ }
1675
+ const kickstartResult = await kickstart(resolved.uid, label, resolved.exec);
1676
+ if (kickstartResult.code !== 0) {
1677
+ return {
1678
+ ok: false,
1679
+ error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
1680
+ };
1681
+ }
1682
+ const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
1683
+ if (!verified.ok)
1684
+ return verified;
1685
+ return { ok: true, label, pid: verified.pid };
1686
+ }
1687
+
1004
1688
  // src/cli.ts
1005
1689
  var USAGE = `space-bus — thin CLI for the managed OpenCode bus server
1006
1690
 
@@ -1008,6 +1692,11 @@ Usage:
1008
1692
  space-bus serve [--foreground] [--json] [--config <path>]
1009
1693
  space-bus status [--json] [--config <path>]
1010
1694
  space-bus stop [--json] [--config <path>]
1695
+ space-bus service install [--json] [--config <path>] install the launchd agent (macOS)
1696
+ space-bus service uninstall [--json] [--config <path>] remove the launchd agent
1697
+ space-bus service status [--json] [--config <path>] installed/loaded/running state
1698
+ space-bus service stop [--json] [--config <path>] bootout the loaded job (plist stays)
1699
+ space-bus service start [--json] [--config <path>] bootstrap + kickstart the job
1011
1700
  space-bus --help
1012
1701
 
1013
1702
  Roster resolution: SPACE_BUS_CONFIG env var, or --config <path>.
@@ -1015,6 +1704,7 @@ Roster resolution: SPACE_BUS_CONFIG env var, or --config <path>.
1015
1704
  function parseArgs(argv) {
1016
1705
  const result = {
1017
1706
  command: undefined,
1707
+ subcommand: undefined,
1018
1708
  json: false,
1019
1709
  foreground: false,
1020
1710
  config: undefined,
@@ -1047,6 +1737,8 @@ function consumeArg(argv, i, result) {
1047
1737
  result.unknownFlags.push(arg);
1048
1738
  } else if (result.command === undefined && arg !== undefined) {
1049
1739
  result.command = arg;
1740
+ } else if (result.command === "service" && result.subcommand === undefined && arg !== undefined) {
1741
+ result.subcommand = arg;
1050
1742
  }
1051
1743
  return i;
1052
1744
  }
@@ -1136,6 +1828,103 @@ async function runStop(args) {
1136
1828
  printJson(args.json, result, plain);
1137
1829
  return 0;
1138
1830
  }
1831
+ var SERVICE_VERBS = [
1832
+ "install",
1833
+ "uninstall",
1834
+ "status",
1835
+ "stop",
1836
+ "start"
1837
+ ];
1838
+ function isServiceVerb(value) {
1839
+ return SERVICE_VERBS.includes(value);
1840
+ }
1841
+ function installPlainMessage(result) {
1842
+ return `space-bus: service installed: ${result.label}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}${result.warning ? `
1843
+ warning: ${result.warning}` : ""}`;
1844
+ }
1845
+ function uninstallPlainMessage(result) {
1846
+ return `space-bus: service uninstalled: ${result.label} (job removed: ${result.removed.job}, plist removed: ${result.removed.plist})`;
1847
+ }
1848
+ function statusPlainMessage(result) {
1849
+ return `space-bus: service ${result.label} — installed: ${result.installed}, loaded: ${result.loaded}, running: ${result.running}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}`;
1850
+ }
1851
+ function stopPlainMessage(result) {
1852
+ return `space-bus: service stopped: ${result.label} (was loaded: ${result.wasLoaded}); will start again at next login`;
1853
+ }
1854
+ function startPlainMessage(result) {
1855
+ return `space-bus: service started: ${result.label}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}`;
1856
+ }
1857
+ function servicePlainMessage(verb, result) {
1858
+ switch (verb) {
1859
+ case "install":
1860
+ return installPlainMessage(result);
1861
+ case "uninstall":
1862
+ return uninstallPlainMessage(result);
1863
+ case "status":
1864
+ return statusPlainMessage(result);
1865
+ case "stop":
1866
+ return stopPlainMessage(result);
1867
+ case "start":
1868
+ return startPlainMessage(result);
1869
+ default:
1870
+ return "space-bus: service ok";
1871
+ }
1872
+ }
1873
+ async function runService(args, deps = {}) {
1874
+ if (!isServiceVerb(args.subcommand)) {
1875
+ process.stderr.write(`space-bus: unknown or missing service verb "${args.subcommand ?? ""}"
1876
+
1877
+ `);
1878
+ process.stderr.write(USAGE);
1879
+ return 1;
1880
+ }
1881
+ const doInstallService = deps.installService ?? installService;
1882
+ const doUninstallService = deps.uninstallService ?? uninstallService;
1883
+ const doServiceStatus = deps.serviceStatus ?? serviceStatus;
1884
+ const doStopService = deps.stopService ?? stopService;
1885
+ const doStartService = deps.startService ?? startService;
1886
+ const rosterPath = resolveRoster(args.config);
1887
+ const serviceDeps = { cliEntryPath: fileURLToPath(import.meta.url) };
1888
+ const result = await (() => {
1889
+ switch (args.subcommand) {
1890
+ case "install":
1891
+ return doInstallService(rosterPath, serviceDeps);
1892
+ case "uninstall":
1893
+ return doUninstallService(rosterPath, serviceDeps);
1894
+ case "status":
1895
+ return doServiceStatus(rosterPath, serviceDeps);
1896
+ case "stop":
1897
+ return doStopService(rosterPath, serviceDeps);
1898
+ case "start":
1899
+ return doStartService(rosterPath, serviceDeps);
1900
+ default:
1901
+ throw new Error("unreachable");
1902
+ }
1903
+ })();
1904
+ if (!result.ok) {
1905
+ process.stderr.write(`space-bus: ${result.error}
1906
+ `);
1907
+ return 1;
1908
+ }
1909
+ const plain = (() => {
1910
+ switch (args.subcommand) {
1911
+ case "install":
1912
+ return servicePlainMessage("install", result);
1913
+ case "uninstall":
1914
+ return servicePlainMessage("uninstall", result);
1915
+ case "status":
1916
+ return servicePlainMessage("status", result);
1917
+ case "stop":
1918
+ return servicePlainMessage("stop", result);
1919
+ case "start":
1920
+ return servicePlainMessage("start", result);
1921
+ default:
1922
+ return "space-bus: service ok";
1923
+ }
1924
+ })();
1925
+ printJson(args.json, result, plain);
1926
+ return 0;
1927
+ }
1139
1928
  async function main() {
1140
1929
  const args = parseArgs(process.argv.slice(2));
1141
1930
  if (args.help) {
@@ -1167,6 +1956,8 @@ async function main() {
1167
1956
  return runStatus(args);
1168
1957
  case "stop":
1169
1958
  return await runStop(args);
1959
+ case "service":
1960
+ return await runService(args);
1170
1961
  default:
1171
1962
  process.stderr.write(`space-bus: unknown command "${args.command}"
1172
1963
 
@@ -1185,5 +1976,6 @@ if (__require.main == __require.module) {
1185
1976
  });
1186
1977
  }
1187
1978
  export {
1979
+ runService,
1188
1980
  runServe
1189
1981
  };