@fro.bot/space-bus 0.10.1 → 0.11.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/README.md +22 -0
- package/dist/cli.d.ts +14 -0
- package/dist/cli.js +759 -2
- package/dist/config.js +4 -2
- package/dist/discovery.d.ts +7 -0
- package/dist/index.js +4 -2
- package/dist/launchd.d.ts +108 -0
- package/dist/mcp.js +5 -3
- package/dist/server.js +4 -2
- package/dist/service.d.ts +105 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -106,6 +106,28 @@ Security posture: each spawn gets a freshly generated password (never reused, ne
|
|
|
106
106
|
|
|
107
107
|
Programmatic consumers (e.g. Mothership) that want to drive the lifecycle directly without the CLI can import `@fro.bot/space-bus/managed-server` (Node-only; `ensureServer`/`serverStatus`/`stopServer`).
|
|
108
108
|
|
|
109
|
+
## `space-bus service` (macOS, launchd v1)
|
|
110
|
+
|
|
111
|
+
Reboot-persistent daemon on top of the managed server: registers a per-user launchd agent that wraps `serve --foreground`, so the roster's server survives host reboots and crashes without a live operator noticing it died.
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
space-bus service install [--json] [--config <path>] install the launchd agent, start it now
|
|
115
|
+
space-bus service uninstall [--json] [--config <path>] bootout the job and remove the plist
|
|
116
|
+
space-bus service status [--json] [--config <path>] installed / loaded / running, with pid
|
|
117
|
+
space-bus service stop [--json] [--config <path>] bootout the loaded job (plist stays)
|
|
118
|
+
space-bus service start [--json] [--config <path>] bootstrap + kickstart the job
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Semantics:
|
|
122
|
+
|
|
123
|
+
- Starts at **login**, not boot — it's a `gui/$UID` launchd agent, not a system daemon.
|
|
124
|
+
- Restarts only on abnormal exit (`KeepAlive.SuccessfulExit=false`), consuming the existing `serve --foreground` exit-code contract (0 = deliberate stop, no restart; 1 = death, restart). Restarts are throttled to once per 10s to avoid a crash loop.
|
|
125
|
+
- `service stop` deregisters the job (`bootout`) but leaves the plist in place; `service start` re-registers it (`bootstrap` + `kickstart`). A stopped service comes back automatically at the next login (`RunAtLoad`) unless you `service start` it back sooner — there's no persistent "disabled" latch in v1.
|
|
126
|
+
- Logs land at the roster's state dir: `service.log` (stdout) / `service.err.log` (stderr), created 0600.
|
|
127
|
+
- Upgrades: the plist pins absolute paths to the runtime and CLI entry resolved at install time. After a version bump (or if you moved/reinstalled the runtime), re-run `space-bus service install` — it's idempotent and refreshes the pinned paths.
|
|
128
|
+
- macOS only in v1; every verb fails fast with an explicit error on other platforms.
|
|
129
|
+
- `install`/`uninstall` are explicit operator actions only — nothing auto-installs the service on your behalf.
|
|
130
|
+
|
|
109
131
|
## Library surface
|
|
110
132
|
|
|
111
133
|
Experimental subpath exports expose the bus's internals directly — the functions the four tools run on, plus the managed-server lifecycle and the attach resolver — for renderers and other consumers that want structured state instead of formatted strings. Subpaths are experimental: shapes may change in minor releases; pin the version if you adopt them.
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { ensureServer, type ServerHandle, type SuperviseOutcome, stopServer } from "./server";
|
|
2
|
+
import { installService, serviceStatus, startService, stopService, uninstallService } from "./service";
|
|
2
3
|
interface ParsedArgs {
|
|
3
4
|
command: string | undefined;
|
|
5
|
+
/** Second positional arg — only meaningful when command === "service". */
|
|
6
|
+
subcommand?: string | undefined;
|
|
4
7
|
json: boolean;
|
|
5
8
|
foreground: boolean;
|
|
6
9
|
config: string | undefined;
|
|
@@ -23,4 +26,15 @@ export interface RunServeDeps {
|
|
|
23
26
|
superviseServer?: (rosterPath: string, handle: ServerHandle, shouldStop: () => boolean, interrupt: Promise<void>) => Promise<SuperviseOutcome>;
|
|
24
27
|
}
|
|
25
28
|
export declare function runServe(args: ParsedArgs, deps?: RunServeDeps): Promise<number>;
|
|
29
|
+
/** Injectable dependencies for `runService` — lets tests swap in fake
|
|
30
|
+
* verb implementations so they never touch the real launchd / LaunchAgents
|
|
31
|
+
* directory. Defaults to the real implementations from service.ts. */
|
|
32
|
+
export interface RunServiceDeps {
|
|
33
|
+
installService?: typeof installService;
|
|
34
|
+
uninstallService?: typeof uninstallService;
|
|
35
|
+
serviceStatus?: typeof serviceStatus;
|
|
36
|
+
stopService?: typeof stopService;
|
|
37
|
+
startService?: typeof startService;
|
|
38
|
+
}
|
|
39
|
+
export declare function runService(args: ParsedArgs, deps?: RunServiceDeps): Promise<number>;
|
|
26
40
|
export {};
|
package/dist/cli.js
CHANGED
|
@@ -155,10 +155,12 @@ import {
|
|
|
155
155
|
import { homedir } from "node:os";
|
|
156
156
|
import { join } from "node:path";
|
|
157
157
|
import { z as z2 } from "zod";
|
|
158
|
+
function rosterKey(rosterPath) {
|
|
159
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
160
|
+
}
|
|
158
161
|
function stateDirFor(rosterPath) {
|
|
159
162
|
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
160
|
-
|
|
161
|
-
return join(base, "space-bus", hash);
|
|
163
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
162
164
|
}
|
|
163
165
|
function discoveryFilePath(rosterPath) {
|
|
164
166
|
return join(stateDirFor(rosterPath), "discovery.json");
|
|
@@ -1001,6 +1003,653 @@ async function waitForGroupDeath(pid, budgetMs) {
|
|
|
1001
1003
|
return !groupAlive();
|
|
1002
1004
|
}
|
|
1003
1005
|
|
|
1006
|
+
// src/cli.ts
|
|
1007
|
+
import { fileURLToPath } from "node:url";
|
|
1008
|
+
|
|
1009
|
+
// src/service.ts
|
|
1010
|
+
import {
|
|
1011
|
+
chmodSync as chmodSync3,
|
|
1012
|
+
closeSync as closeSync3,
|
|
1013
|
+
existsSync as existsSync2,
|
|
1014
|
+
fchmodSync,
|
|
1015
|
+
constants as fsConstants3,
|
|
1016
|
+
mkdirSync as mkdirSync2,
|
|
1017
|
+
openSync as openSync4,
|
|
1018
|
+
unlinkSync as unlinkSync2
|
|
1019
|
+
} from "node:fs";
|
|
1020
|
+
import { homedir as homedir4 } from "node:os";
|
|
1021
|
+
import { isAbsolute, join as join4 } from "node:path";
|
|
1022
|
+
|
|
1023
|
+
// src/launchd.ts
|
|
1024
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1025
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
1026
|
+
import {
|
|
1027
|
+
chmodSync as chmodSync2,
|
|
1028
|
+
closeSync as closeSync2,
|
|
1029
|
+
constants as fsConstants2,
|
|
1030
|
+
lstatSync,
|
|
1031
|
+
openSync as openSync3,
|
|
1032
|
+
renameSync as renameSync2,
|
|
1033
|
+
statSync as statSync2,
|
|
1034
|
+
writeFileSync as writeFileSync2
|
|
1035
|
+
} from "node:fs";
|
|
1036
|
+
import { homedir as homedir3 } from "node:os";
|
|
1037
|
+
import { join as join3 } from "node:path";
|
|
1038
|
+
function serviceLabel(rosterPath) {
|
|
1039
|
+
return `bot.fro.space-bus.${rosterKey(rosterPath)}`;
|
|
1040
|
+
}
|
|
1041
|
+
function plistPath(label, baseDir) {
|
|
1042
|
+
return join3(baseDir ?? join3(homedir3(), "Library", "LaunchAgents"), `${label}.plist`);
|
|
1043
|
+
}
|
|
1044
|
+
function xmlEscape(value) {
|
|
1045
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1046
|
+
}
|
|
1047
|
+
function renderPlist(opts) {
|
|
1048
|
+
const runtime = xmlEscape(opts.runtime);
|
|
1049
|
+
const cliEntry = xmlEscape(opts.cliEntry);
|
|
1050
|
+
const rosterPath = xmlEscape(opts.rosterPath);
|
|
1051
|
+
const label = xmlEscape(opts.label);
|
|
1052
|
+
const outLog = xmlEscape(join3(opts.stateDir, "service.log"));
|
|
1053
|
+
const errLog = xmlEscape(join3(opts.stateDir, "service.err.log"));
|
|
1054
|
+
const envEntries = [
|
|
1055
|
+
` <key>SPACE_BUS_CONFIG</key>
|
|
1056
|
+
<string>${rosterPath}</string>`
|
|
1057
|
+
];
|
|
1058
|
+
if (opts.path !== undefined) {
|
|
1059
|
+
envEntries.push(` <key>PATH</key>
|
|
1060
|
+
<string>${xmlEscape(opts.path)}</string>`);
|
|
1061
|
+
}
|
|
1062
|
+
if (opts.xdgStateHome !== undefined) {
|
|
1063
|
+
envEntries.push(` <key>XDG_STATE_HOME</key>
|
|
1064
|
+
<string>${xmlEscape(opts.xdgStateHome)}</string>`);
|
|
1065
|
+
}
|
|
1066
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1067
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1068
|
+
<plist version="1.0">
|
|
1069
|
+
<dict>
|
|
1070
|
+
<key>Label</key>
|
|
1071
|
+
<string>${label}</string>
|
|
1072
|
+
<key>ProgramArguments</key>
|
|
1073
|
+
<array>
|
|
1074
|
+
<string>${runtime}</string>
|
|
1075
|
+
<string>${cliEntry}</string>
|
|
1076
|
+
<string>serve</string>
|
|
1077
|
+
<string>--foreground</string>
|
|
1078
|
+
</array>
|
|
1079
|
+
<key>KeepAlive</key>
|
|
1080
|
+
<dict>
|
|
1081
|
+
<key>SuccessfulExit</key>
|
|
1082
|
+
<false/>
|
|
1083
|
+
</dict>
|
|
1084
|
+
<key>RunAtLoad</key>
|
|
1085
|
+
<true/>
|
|
1086
|
+
<key>ThrottleInterval</key>
|
|
1087
|
+
<integer>10</integer>
|
|
1088
|
+
<key>EnvironmentVariables</key>
|
|
1089
|
+
<dict>
|
|
1090
|
+
${envEntries.join(`
|
|
1091
|
+
`)}
|
|
1092
|
+
</dict>
|
|
1093
|
+
<key>StandardOutPath</key>
|
|
1094
|
+
<string>${outLog}</string>
|
|
1095
|
+
<key>StandardErrorPath</key>
|
|
1096
|
+
<string>${errLog}</string>
|
|
1097
|
+
</dict>
|
|
1098
|
+
</plist>
|
|
1099
|
+
`;
|
|
1100
|
+
}
|
|
1101
|
+
function writePlistAtomic(path, content) {
|
|
1102
|
+
const dir = join3(path, "..");
|
|
1103
|
+
const tempPath = join3(dir, `.${randomBytes3(8).toString("hex")}.tmp`);
|
|
1104
|
+
let fd;
|
|
1105
|
+
try {
|
|
1106
|
+
fd = openSync3(tempPath, fsConstants2.O_EXCL | fsConstants2.O_CREAT | fsConstants2.O_WRONLY, 420);
|
|
1107
|
+
} catch (err) {
|
|
1108
|
+
return { ok: false, error: `failed to create temp plist: ${String(err)}` };
|
|
1109
|
+
}
|
|
1110
|
+
try {
|
|
1111
|
+
writeFileSync2(fd, content);
|
|
1112
|
+
} catch (err) {
|
|
1113
|
+
closeQuietly2(fd);
|
|
1114
|
+
return { ok: false, error: `failed to write temp plist: ${String(err)}` };
|
|
1115
|
+
}
|
|
1116
|
+
closeQuietly2(fd);
|
|
1117
|
+
try {
|
|
1118
|
+
chmodSync2(tempPath, 420);
|
|
1119
|
+
renameSync2(tempPath, path);
|
|
1120
|
+
} catch (err) {
|
|
1121
|
+
return { ok: false, error: `failed to install plist: ${String(err)}` };
|
|
1122
|
+
}
|
|
1123
|
+
return { ok: true };
|
|
1124
|
+
}
|
|
1125
|
+
function verifyPlistSafe(path) {
|
|
1126
|
+
let mode;
|
|
1127
|
+
let uid;
|
|
1128
|
+
try {
|
|
1129
|
+
const linkStat = lstatSync(path);
|
|
1130
|
+
if (linkStat.isSymbolicLink()) {
|
|
1131
|
+
return { safe: false, reason: "plist path is a symlink" };
|
|
1132
|
+
}
|
|
1133
|
+
} catch (err) {
|
|
1134
|
+
return { safe: false, reason: `failed to stat plist: ${String(err)}` };
|
|
1135
|
+
}
|
|
1136
|
+
try {
|
|
1137
|
+
const stat = statSync2(path);
|
|
1138
|
+
mode = stat.mode & 511;
|
|
1139
|
+
uid = stat.uid;
|
|
1140
|
+
} catch (err) {
|
|
1141
|
+
return { safe: false, reason: `failed to stat plist: ${String(err)}` };
|
|
1142
|
+
}
|
|
1143
|
+
if (typeof process.getuid === "function" && uid !== process.getuid()) {
|
|
1144
|
+
return {
|
|
1145
|
+
safe: false,
|
|
1146
|
+
reason: `plist is not owned by the current user (uid ${uid})`
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
if ((mode & 18) !== 0) {
|
|
1150
|
+
return {
|
|
1151
|
+
safe: false,
|
|
1152
|
+
reason: `plist is group/world-writable (mode ${mode.toString(8)})`
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
return { safe: true };
|
|
1156
|
+
}
|
|
1157
|
+
function closeQuietly2(fd) {
|
|
1158
|
+
try {
|
|
1159
|
+
closeSync2(fd);
|
|
1160
|
+
} catch {}
|
|
1161
|
+
}
|
|
1162
|
+
var LAUNCHCTL_TIMEOUT_MS = 15000;
|
|
1163
|
+
var MAX_CAPTURED_OUTPUT_BYTES = 64 * 1024;
|
|
1164
|
+
function capOutput(value) {
|
|
1165
|
+
return value.length > MAX_CAPTURED_OUTPUT_BYTES ? `${value.slice(0, MAX_CAPTURED_OUTPUT_BYTES)}
|
|
1166
|
+
...[truncated]` : value;
|
|
1167
|
+
}
|
|
1168
|
+
var defaultLaunchctl = (args) => new Promise((resolve) => {
|
|
1169
|
+
let settled = false;
|
|
1170
|
+
const settle = (result) => {
|
|
1171
|
+
if (settled)
|
|
1172
|
+
return;
|
|
1173
|
+
settled = true;
|
|
1174
|
+
clearTimeout(timer);
|
|
1175
|
+
resolve(result);
|
|
1176
|
+
};
|
|
1177
|
+
const child = spawn2("launchctl", args, {
|
|
1178
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1179
|
+
});
|
|
1180
|
+
let stdout = "";
|
|
1181
|
+
let stderr = "";
|
|
1182
|
+
child.stdout.on("data", (chunk) => {
|
|
1183
|
+
stdout += chunk.toString();
|
|
1184
|
+
});
|
|
1185
|
+
child.stderr.on("data", (chunk) => {
|
|
1186
|
+
stderr += chunk.toString();
|
|
1187
|
+
});
|
|
1188
|
+
child.on("error", (err) => {
|
|
1189
|
+
settle({
|
|
1190
|
+
code: -1,
|
|
1191
|
+
stdout: capOutput(stdout),
|
|
1192
|
+
stderr: capOutput(`${stderr}
|
|
1193
|
+
launchctl spawn error: ${String(err)}`)
|
|
1194
|
+
});
|
|
1195
|
+
});
|
|
1196
|
+
child.on("close", (code) => {
|
|
1197
|
+
settle({
|
|
1198
|
+
code: code ?? -1,
|
|
1199
|
+
stdout: capOutput(stdout),
|
|
1200
|
+
stderr: capOutput(stderr)
|
|
1201
|
+
});
|
|
1202
|
+
});
|
|
1203
|
+
const timer = setTimeout(() => {
|
|
1204
|
+
try {
|
|
1205
|
+
child.kill("SIGKILL");
|
|
1206
|
+
} catch {}
|
|
1207
|
+
settle({
|
|
1208
|
+
code: -1,
|
|
1209
|
+
stdout: capOutput(stdout),
|
|
1210
|
+
stderr: capOutput(`${stderr}
|
|
1211
|
+
launchctl timed out after ${LAUNCHCTL_TIMEOUT_MS}ms (args: ${args.join(" ")})`)
|
|
1212
|
+
});
|
|
1213
|
+
}, LAUNCHCTL_TIMEOUT_MS);
|
|
1214
|
+
});
|
|
1215
|
+
async function bootstrap(uid, plist, exec) {
|
|
1216
|
+
return exec(["bootstrap", `gui/${uid}`, plist]);
|
|
1217
|
+
}
|
|
1218
|
+
async function bootout(uid, label, exec) {
|
|
1219
|
+
return exec(["bootout", `gui/${uid}/${label}`]);
|
|
1220
|
+
}
|
|
1221
|
+
async function kickstart(uid, label, exec) {
|
|
1222
|
+
return exec(["kickstart", "-k", `gui/${uid}/${label}`]);
|
|
1223
|
+
}
|
|
1224
|
+
var NOT_LOADED_MARKERS = ["could not find", "no such process"];
|
|
1225
|
+
async function printJob(uid, label, exec) {
|
|
1226
|
+
const result = await exec(["print", `gui/${uid}/${label}`]);
|
|
1227
|
+
if (result.code === 0) {
|
|
1228
|
+
const match = /pid\s*=\s*(\d+)/.exec(result.stdout);
|
|
1229
|
+
return match ? { ok: true, loaded: true, pid: Number(match[1]) } : { ok: true, loaded: true };
|
|
1230
|
+
}
|
|
1231
|
+
const combined = `${result.stdout}
|
|
1232
|
+
${result.stderr}`.toLowerCase();
|
|
1233
|
+
if (NOT_LOADED_MARKERS.some((marker) => combined.includes(marker))) {
|
|
1234
|
+
return { ok: true, loaded: false };
|
|
1235
|
+
}
|
|
1236
|
+
const detail = result.stderr.trim() || result.stdout.trim();
|
|
1237
|
+
return {
|
|
1238
|
+
ok: false,
|
|
1239
|
+
error: `launchctl print failed (exit ${result.code})${detail ? ` — ${detail}` : ""}`
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// src/service.ts
|
|
1244
|
+
var NOT_SUPPORTED_ERROR = "space-bus service is not supported on this platform (v1 supports macOS/launchd)";
|
|
1245
|
+
var EPHEMERAL_CACHE_SEGMENTS = [
|
|
1246
|
+
"/.bun/install/cache/",
|
|
1247
|
+
"/_npx/",
|
|
1248
|
+
"/.npm/_npx/"
|
|
1249
|
+
];
|
|
1250
|
+
var DEFAULT_VERIFY_BUDGET_MS = 20000;
|
|
1251
|
+
var DEFAULT_VERIFY_POLL_MS = 200;
|
|
1252
|
+
var EXIT5_RETRY_DELAY_MS = 500;
|
|
1253
|
+
function sleep2(ms) {
|
|
1254
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1255
|
+
}
|
|
1256
|
+
function defaultCliEntryPath() {
|
|
1257
|
+
const argv1 = process.argv[1];
|
|
1258
|
+
return argv1 ?? process.execPath;
|
|
1259
|
+
}
|
|
1260
|
+
function resolveDeps(deps) {
|
|
1261
|
+
return {
|
|
1262
|
+
exec: deps.exec ?? defaultLaunchctl,
|
|
1263
|
+
platform: deps.platform ?? process.platform,
|
|
1264
|
+
uid: deps.uid ?? (process.getuid ? process.getuid() : 0),
|
|
1265
|
+
execPath: deps.execPath ?? process.execPath,
|
|
1266
|
+
cliEntryPath: deps.cliEntryPath ?? defaultCliEntryPath(),
|
|
1267
|
+
serverStatus: deps.serverStatus ?? serverStatus,
|
|
1268
|
+
sleep: deps.sleep ?? sleep2,
|
|
1269
|
+
now: deps.now ?? Date.now,
|
|
1270
|
+
verifyBudgetMs: deps.verifyBudgetMs ?? DEFAULT_VERIFY_BUDGET_MS,
|
|
1271
|
+
verifyPollMs: deps.verifyPollMs ?? DEFAULT_VERIFY_POLL_MS,
|
|
1272
|
+
launchAgentsDir: deps.launchAgentsDir ?? join4(homedir4(), "Library", "LaunchAgents")
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
function isEphemeralCachePath(path) {
|
|
1276
|
+
return EPHEMERAL_CACHE_SEGMENTS.some((segment) => path.includes(segment));
|
|
1277
|
+
}
|
|
1278
|
+
function stderrDetail(result) {
|
|
1279
|
+
const stderr = result.stderr.trim();
|
|
1280
|
+
return stderr.length > 0 ? ` — ${stderr}` : result.stdout.trim().length > 0 ? ` — ${result.stdout.trim()}` : "";
|
|
1281
|
+
}
|
|
1282
|
+
function platformGate(platform) {
|
|
1283
|
+
if (platform !== "darwin") {
|
|
1284
|
+
return { ok: false, error: NOT_SUPPORTED_ERROR };
|
|
1285
|
+
}
|
|
1286
|
+
return { ok: true };
|
|
1287
|
+
}
|
|
1288
|
+
function identityFor(rosterPath, launchAgentsDir) {
|
|
1289
|
+
const label = serviceLabel(rosterPath);
|
|
1290
|
+
return {
|
|
1291
|
+
label,
|
|
1292
|
+
plistFilePath: plistPath(label, launchAgentsDir),
|
|
1293
|
+
stateDir: stateDirFor(rosterPath)
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
function preCreateLog(path) {
|
|
1297
|
+
let fd;
|
|
1298
|
+
try {
|
|
1299
|
+
fd = openSync4(path, fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW, 384);
|
|
1300
|
+
} catch (err) {
|
|
1301
|
+
if (isSymlinkError(err)) {
|
|
1302
|
+
return { ok: false, error: `refusing symlinked log path: ${path}` };
|
|
1303
|
+
}
|
|
1304
|
+
return { ok: false, error: `failed to create log ${path}: ${String(err)}` };
|
|
1305
|
+
}
|
|
1306
|
+
try {
|
|
1307
|
+
fchmodSync(fd, 384);
|
|
1308
|
+
} catch (err) {
|
|
1309
|
+
return { ok: false, error: `failed to chmod log ${path}: ${String(err)}` };
|
|
1310
|
+
} finally {
|
|
1311
|
+
closeSync3(fd);
|
|
1312
|
+
}
|
|
1313
|
+
return { ok: true };
|
|
1314
|
+
}
|
|
1315
|
+
function isSymlinkError(err) {
|
|
1316
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "ELOOP";
|
|
1317
|
+
}
|
|
1318
|
+
function ensureStateDir(stateDir) {
|
|
1319
|
+
try {
|
|
1320
|
+
mkdirSync2(stateDir, { recursive: true, mode: 448 });
|
|
1321
|
+
} catch (err) {
|
|
1322
|
+
return {
|
|
1323
|
+
ok: false,
|
|
1324
|
+
error: `failed to create state directory ${stateDir}: ${String(err)}`
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
try {
|
|
1328
|
+
chmodSync3(stateDir, 448);
|
|
1329
|
+
} catch (err) {
|
|
1330
|
+
return {
|
|
1331
|
+
ok: false,
|
|
1332
|
+
error: `failed to harden state directory ${stateDir}: ${String(err)}`
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
return { ok: true };
|
|
1336
|
+
}
|
|
1337
|
+
async function probeJob(resolved, label) {
|
|
1338
|
+
const result = await printJob(resolved.uid, label, resolved.exec);
|
|
1339
|
+
if (!result.ok) {
|
|
1340
|
+
return { ok: false, error: result.error };
|
|
1341
|
+
}
|
|
1342
|
+
return result.pid !== undefined ? { ok: true, loaded: result.loaded, pid: result.pid } : { ok: true, loaded: result.loaded };
|
|
1343
|
+
}
|
|
1344
|
+
function resolveXdgStateHome() {
|
|
1345
|
+
const xdgStateHomeEnv = process.env["XDG_STATE_HOME"];
|
|
1346
|
+
if (xdgStateHomeEnv === undefined)
|
|
1347
|
+
return { ok: true, value: undefined };
|
|
1348
|
+
if (!isAbsolute(xdgStateHomeEnv)) {
|
|
1349
|
+
return {
|
|
1350
|
+
ok: false,
|
|
1351
|
+
error: `XDG_STATE_HOME must be an absolute path to pin into the launchd environment, got: ${xdgStateHomeEnv}`
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
return { ok: true, value: xdgStateHomeEnv };
|
|
1355
|
+
}
|
|
1356
|
+
async function bootstrapWithExit5Retry(resolved, label, plistFilePath) {
|
|
1357
|
+
const bootstrapResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
|
|
1358
|
+
if (bootstrapResult.code === 0)
|
|
1359
|
+
return { ok: true };
|
|
1360
|
+
if (bootstrapResult.code !== 5) {
|
|
1361
|
+
return {
|
|
1362
|
+
ok: false,
|
|
1363
|
+
error: `launchctl bootstrap failed (exit ${bootstrapResult.code})${stderrDetail(bootstrapResult)}`
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
const reprobe = await probeJob(resolved, label);
|
|
1367
|
+
if (!reprobe.ok) {
|
|
1368
|
+
return {
|
|
1369
|
+
ok: false,
|
|
1370
|
+
error: `launchctl bootstrap failed (exit 5)${stderrDetail(bootstrapResult)}; re-probe also failed: ${reprobe.error}`
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
if (reprobe.loaded)
|
|
1374
|
+
return { ok: true };
|
|
1375
|
+
await resolved.sleep(EXIT5_RETRY_DELAY_MS);
|
|
1376
|
+
const retryResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
|
|
1377
|
+
if (retryResult.code !== 0) {
|
|
1378
|
+
return {
|
|
1379
|
+
ok: false,
|
|
1380
|
+
error: `launchctl bootstrap failed twice (exit 5, then exit ${retryResult.code})${stderrDetail(bootstrapResult)}; retry: ${stderrDetail(retryResult)}`
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
return { ok: true };
|
|
1384
|
+
}
|
|
1385
|
+
function prepareInstallFilesystem(resolved, stateDir) {
|
|
1386
|
+
try {
|
|
1387
|
+
mkdirSync2(resolved.launchAgentsDir, { recursive: true, mode: 493 });
|
|
1388
|
+
} catch (err) {
|
|
1389
|
+
return {
|
|
1390
|
+
ok: false,
|
|
1391
|
+
error: `failed to create LaunchAgents directory ${resolved.launchAgentsDir}: ${String(err)}`
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
const stateDirResult = ensureStateDir(stateDir);
|
|
1395
|
+
if (!stateDirResult.ok)
|
|
1396
|
+
return stateDirResult;
|
|
1397
|
+
const outLogResult = preCreateLog(`${stateDir}/service.log`);
|
|
1398
|
+
if (!outLogResult.ok)
|
|
1399
|
+
return outLogResult;
|
|
1400
|
+
return preCreateLog(`${stateDir}/service.err.log`);
|
|
1401
|
+
}
|
|
1402
|
+
function ephemeralCacheWarning(resolved) {
|
|
1403
|
+
if (isEphemeralCachePath(resolved.execPath) || isEphemeralCachePath(resolved.cliEntryPath)) {
|
|
1404
|
+
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`.";
|
|
1405
|
+
}
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
async function bootoutUntilAbsentOrFail(resolved, label) {
|
|
1409
|
+
const bootoutResult = await bootout(resolved.uid, label, resolved.exec);
|
|
1410
|
+
if (bootoutResult.code === 0)
|
|
1411
|
+
return { ok: true };
|
|
1412
|
+
const reprobe = await probeJob(resolved, label);
|
|
1413
|
+
if (!reprobe.ok) {
|
|
1414
|
+
return {
|
|
1415
|
+
ok: false,
|
|
1416
|
+
error: `launchctl bootout failed (exit ${bootoutResult.code})${stderrDetail(bootoutResult)}; re-probe to confirm absence also failed: ${reprobe.error}`
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
if (reprobe.loaded) {
|
|
1420
|
+
return {
|
|
1421
|
+
ok: false,
|
|
1422
|
+
error: `launchctl bootout failed (exit ${bootoutResult.code})${stderrDetail(bootoutResult)} and the job is still loaded`
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return { ok: true };
|
|
1426
|
+
}
|
|
1427
|
+
async function installService(rosterPath, deps = {}) {
|
|
1428
|
+
const resolved = resolveDeps(deps);
|
|
1429
|
+
const gate = platformGate(resolved.platform);
|
|
1430
|
+
if (!gate.ok)
|
|
1431
|
+
return { ok: false, error: gate.error };
|
|
1432
|
+
const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
|
|
1433
|
+
const warning = ephemeralCacheWarning(resolved);
|
|
1434
|
+
const fsResult = prepareInstallFilesystem(resolved, stateDir);
|
|
1435
|
+
if (!fsResult.ok)
|
|
1436
|
+
return fsResult;
|
|
1437
|
+
const xdgResolved = resolveXdgStateHome();
|
|
1438
|
+
if (!xdgResolved.ok)
|
|
1439
|
+
return { ok: false, error: xdgResolved.error };
|
|
1440
|
+
const xdgStateHome = xdgResolved.value;
|
|
1441
|
+
const existing = await probeJob(resolved, label);
|
|
1442
|
+
if (!existing.ok) {
|
|
1443
|
+
return {
|
|
1444
|
+
ok: false,
|
|
1445
|
+
error: `failed to probe existing job: ${existing.error}`
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
if (existing.loaded) {
|
|
1449
|
+
const bootoutOutcome = await bootoutUntilAbsentOrFail(resolved, label);
|
|
1450
|
+
if (!bootoutOutcome.ok)
|
|
1451
|
+
return bootoutOutcome;
|
|
1452
|
+
}
|
|
1453
|
+
const plistXml = renderPlist({
|
|
1454
|
+
runtime: resolved.execPath,
|
|
1455
|
+
cliEntry: resolved.cliEntryPath,
|
|
1456
|
+
rosterPath,
|
|
1457
|
+
stateDir,
|
|
1458
|
+
label,
|
|
1459
|
+
path: process.env["PATH"],
|
|
1460
|
+
xdgStateHome
|
|
1461
|
+
});
|
|
1462
|
+
const writeResult = writePlistAtomic(plistFilePath, plistXml);
|
|
1463
|
+
if (!writeResult.ok) {
|
|
1464
|
+
return { ok: false, error: writeResult.error };
|
|
1465
|
+
}
|
|
1466
|
+
const safety = verifyPlistSafe(plistFilePath);
|
|
1467
|
+
if (!safety.safe) {
|
|
1468
|
+
return { ok: false, error: `refusing to install: ${safety.reason}` };
|
|
1469
|
+
}
|
|
1470
|
+
const bootstrapOutcome = await bootstrapWithExit5Retry(resolved, label, plistFilePath);
|
|
1471
|
+
if (!bootstrapOutcome.ok)
|
|
1472
|
+
return bootstrapOutcome;
|
|
1473
|
+
const kickstartResult = await kickstart(resolved.uid, label, resolved.exec);
|
|
1474
|
+
if (kickstartResult.code !== 0) {
|
|
1475
|
+
return {
|
|
1476
|
+
ok: false,
|
|
1477
|
+
error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
|
|
1481
|
+
if (!verified.ok)
|
|
1482
|
+
return verified;
|
|
1483
|
+
return {
|
|
1484
|
+
ok: true,
|
|
1485
|
+
label,
|
|
1486
|
+
plistPath: plistFilePath,
|
|
1487
|
+
pid: verified.pid,
|
|
1488
|
+
warning
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
async function verifyRunning(rosterPath, label, resolved, plistFilePath) {
|
|
1492
|
+
const deadline = resolved.now() + resolved.verifyBudgetMs;
|
|
1493
|
+
let lastLoaded = false;
|
|
1494
|
+
let lastRunning = false;
|
|
1495
|
+
let lastPid;
|
|
1496
|
+
let lastProbeError;
|
|
1497
|
+
for (;; ) {
|
|
1498
|
+
const job = await probeJob(resolved, label);
|
|
1499
|
+
const status = resolved.serverStatus(rosterPath);
|
|
1500
|
+
lastRunning = status.running;
|
|
1501
|
+
if (job.ok) {
|
|
1502
|
+
lastLoaded = job.loaded;
|
|
1503
|
+
lastPid = job.pid ?? status.pid;
|
|
1504
|
+
lastProbeError = undefined;
|
|
1505
|
+
if (job.loaded && status.running) {
|
|
1506
|
+
return { ok: true, pid: lastPid };
|
|
1507
|
+
}
|
|
1508
|
+
} else {
|
|
1509
|
+
lastProbeError = job.error;
|
|
1510
|
+
}
|
|
1511
|
+
if (resolved.now() >= deadline)
|
|
1512
|
+
break;
|
|
1513
|
+
await resolved.sleep(resolved.verifyPollMs);
|
|
1514
|
+
}
|
|
1515
|
+
const stateDir = stateDirFor(rosterPath);
|
|
1516
|
+
const logPath = join4(stateDir, "service.log");
|
|
1517
|
+
return {
|
|
1518
|
+
ok: false,
|
|
1519
|
+
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}`
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
async function uninstallService(rosterPath, deps = {}) {
|
|
1523
|
+
const resolved = resolveDeps(deps);
|
|
1524
|
+
const gate = platformGate(resolved.platform);
|
|
1525
|
+
if (!gate.ok)
|
|
1526
|
+
return { ok: false, error: gate.error };
|
|
1527
|
+
const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
|
|
1528
|
+
const job = await probeJob(resolved, label);
|
|
1529
|
+
if (!job.ok) {
|
|
1530
|
+
return { ok: false, error: `failed to probe job: ${job.error}` };
|
|
1531
|
+
}
|
|
1532
|
+
let jobRemoved = false;
|
|
1533
|
+
if (job.loaded) {
|
|
1534
|
+
const outcome = await bootoutUntilAbsentOrFail(resolved, label);
|
|
1535
|
+
if (!outcome.ok)
|
|
1536
|
+
return outcome;
|
|
1537
|
+
jobRemoved = true;
|
|
1538
|
+
}
|
|
1539
|
+
let plistRemoved = false;
|
|
1540
|
+
try {
|
|
1541
|
+
unlinkSync2(plistFilePath);
|
|
1542
|
+
plistRemoved = true;
|
|
1543
|
+
} catch (err) {
|
|
1544
|
+
if (!isEnoent2(err)) {
|
|
1545
|
+
return {
|
|
1546
|
+
ok: false,
|
|
1547
|
+
error: `failed to remove plist ${plistFilePath}: ${String(err)}`
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
return {
|
|
1552
|
+
ok: true,
|
|
1553
|
+
removed: { job: jobRemoved, plist: plistRemoved },
|
|
1554
|
+
label
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
function isEnoent2(err) {
|
|
1558
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
|
|
1559
|
+
}
|
|
1560
|
+
async function serviceStatus(rosterPath, deps = {}) {
|
|
1561
|
+
const resolved = resolveDeps(deps);
|
|
1562
|
+
const gate = platformGate(resolved.platform);
|
|
1563
|
+
if (!gate.ok)
|
|
1564
|
+
return { ok: false, error: gate.error };
|
|
1565
|
+
const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
|
|
1566
|
+
const installed = existsSync2(plistFilePath);
|
|
1567
|
+
const job = await probeJob(resolved, label);
|
|
1568
|
+
if (!job.ok) {
|
|
1569
|
+
return { ok: false, error: `failed to probe job: ${job.error}` };
|
|
1570
|
+
}
|
|
1571
|
+
const status = resolved.serverStatus(rosterPath);
|
|
1572
|
+
return {
|
|
1573
|
+
ok: true,
|
|
1574
|
+
installed,
|
|
1575
|
+
loaded: job.loaded,
|
|
1576
|
+
running: status.running,
|
|
1577
|
+
pid: job.pid ?? status.pid,
|
|
1578
|
+
label,
|
|
1579
|
+
plistPath: plistFilePath
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
async function stopService(rosterPath, deps = {}) {
|
|
1583
|
+
const resolved = resolveDeps(deps);
|
|
1584
|
+
const gate = platformGate(resolved.platform);
|
|
1585
|
+
if (!gate.ok)
|
|
1586
|
+
return { ok: false, error: gate.error };
|
|
1587
|
+
const { label } = identityFor(rosterPath, resolved.launchAgentsDir);
|
|
1588
|
+
const job = await probeJob(resolved, label);
|
|
1589
|
+
if (!job.ok) {
|
|
1590
|
+
return { ok: false, error: `failed to probe job: ${job.error}` };
|
|
1591
|
+
}
|
|
1592
|
+
if (!job.loaded) {
|
|
1593
|
+
return { ok: true, label, wasLoaded: false };
|
|
1594
|
+
}
|
|
1595
|
+
const outcome = await bootoutUntilAbsentOrFail(resolved, label);
|
|
1596
|
+
if (!outcome.ok)
|
|
1597
|
+
return outcome;
|
|
1598
|
+
return { ok: true, label, wasLoaded: true };
|
|
1599
|
+
}
|
|
1600
|
+
async function startService(rosterPath, deps = {}) {
|
|
1601
|
+
const resolved = resolveDeps(deps);
|
|
1602
|
+
const gate = platformGate(resolved.platform);
|
|
1603
|
+
if (!gate.ok)
|
|
1604
|
+
return { ok: false, error: gate.error };
|
|
1605
|
+
const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
|
|
1606
|
+
if (!existsSync2(plistFilePath)) {
|
|
1607
|
+
return {
|
|
1608
|
+
ok: false,
|
|
1609
|
+
error: `space-bus service is not installed for this roster — run \`space-bus service install\``
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
const xdgResolved = resolveXdgStateHome();
|
|
1613
|
+
if (!xdgResolved.ok)
|
|
1614
|
+
return { ok: false, error: xdgResolved.error };
|
|
1615
|
+
const xdgStateHome = xdgResolved.value;
|
|
1616
|
+
const plistXml = renderPlist({
|
|
1617
|
+
runtime: resolved.execPath,
|
|
1618
|
+
cliEntry: resolved.cliEntryPath,
|
|
1619
|
+
rosterPath,
|
|
1620
|
+
stateDir,
|
|
1621
|
+
label,
|
|
1622
|
+
path: process.env["PATH"],
|
|
1623
|
+
xdgStateHome
|
|
1624
|
+
});
|
|
1625
|
+
const writeResult = writePlistAtomic(plistFilePath, plistXml);
|
|
1626
|
+
if (!writeResult.ok) {
|
|
1627
|
+
return { ok: false, error: writeResult.error };
|
|
1628
|
+
}
|
|
1629
|
+
const safety = verifyPlistSafe(plistFilePath);
|
|
1630
|
+
if (!safety.safe) {
|
|
1631
|
+
return { ok: false, error: `refusing to start: ${safety.reason}` };
|
|
1632
|
+
}
|
|
1633
|
+
const bootstrapResult = await bootstrap(resolved.uid, plistFilePath, resolved.exec);
|
|
1634
|
+
if (bootstrapResult.code !== 0) {
|
|
1635
|
+
return {
|
|
1636
|
+
ok: false,
|
|
1637
|
+
error: `launchctl bootstrap failed (exit ${bootstrapResult.code})${stderrDetail(bootstrapResult)}`
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
const kickstartResult = await kickstart(resolved.uid, label, resolved.exec);
|
|
1641
|
+
if (kickstartResult.code !== 0) {
|
|
1642
|
+
return {
|
|
1643
|
+
ok: false,
|
|
1644
|
+
error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
|
|
1648
|
+
if (!verified.ok)
|
|
1649
|
+
return verified;
|
|
1650
|
+
return { ok: true, label, pid: verified.pid };
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1004
1653
|
// src/cli.ts
|
|
1005
1654
|
var USAGE = `space-bus — thin CLI for the managed OpenCode bus server
|
|
1006
1655
|
|
|
@@ -1008,6 +1657,11 @@ Usage:
|
|
|
1008
1657
|
space-bus serve [--foreground] [--json] [--config <path>]
|
|
1009
1658
|
space-bus status [--json] [--config <path>]
|
|
1010
1659
|
space-bus stop [--json] [--config <path>]
|
|
1660
|
+
space-bus service install [--json] [--config <path>] install the launchd agent (macOS)
|
|
1661
|
+
space-bus service uninstall [--json] [--config <path>] remove the launchd agent
|
|
1662
|
+
space-bus service status [--json] [--config <path>] installed/loaded/running state
|
|
1663
|
+
space-bus service stop [--json] [--config <path>] bootout the loaded job (plist stays)
|
|
1664
|
+
space-bus service start [--json] [--config <path>] bootstrap + kickstart the job
|
|
1011
1665
|
space-bus --help
|
|
1012
1666
|
|
|
1013
1667
|
Roster resolution: SPACE_BUS_CONFIG env var, or --config <path>.
|
|
@@ -1015,6 +1669,7 @@ Roster resolution: SPACE_BUS_CONFIG env var, or --config <path>.
|
|
|
1015
1669
|
function parseArgs(argv) {
|
|
1016
1670
|
const result = {
|
|
1017
1671
|
command: undefined,
|
|
1672
|
+
subcommand: undefined,
|
|
1018
1673
|
json: false,
|
|
1019
1674
|
foreground: false,
|
|
1020
1675
|
config: undefined,
|
|
@@ -1047,6 +1702,8 @@ function consumeArg(argv, i, result) {
|
|
|
1047
1702
|
result.unknownFlags.push(arg);
|
|
1048
1703
|
} else if (result.command === undefined && arg !== undefined) {
|
|
1049
1704
|
result.command = arg;
|
|
1705
|
+
} else if (result.command === "service" && result.subcommand === undefined && arg !== undefined) {
|
|
1706
|
+
result.subcommand = arg;
|
|
1050
1707
|
}
|
|
1051
1708
|
return i;
|
|
1052
1709
|
}
|
|
@@ -1136,6 +1793,103 @@ async function runStop(args) {
|
|
|
1136
1793
|
printJson(args.json, result, plain);
|
|
1137
1794
|
return 0;
|
|
1138
1795
|
}
|
|
1796
|
+
var SERVICE_VERBS = [
|
|
1797
|
+
"install",
|
|
1798
|
+
"uninstall",
|
|
1799
|
+
"status",
|
|
1800
|
+
"stop",
|
|
1801
|
+
"start"
|
|
1802
|
+
];
|
|
1803
|
+
function isServiceVerb(value) {
|
|
1804
|
+
return SERVICE_VERBS.includes(value);
|
|
1805
|
+
}
|
|
1806
|
+
function installPlainMessage(result) {
|
|
1807
|
+
return `space-bus: service installed: ${result.label}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}${result.warning ? `
|
|
1808
|
+
warning: ${result.warning}` : ""}`;
|
|
1809
|
+
}
|
|
1810
|
+
function uninstallPlainMessage(result) {
|
|
1811
|
+
return `space-bus: service uninstalled: ${result.label} (job removed: ${result.removed.job}, plist removed: ${result.removed.plist})`;
|
|
1812
|
+
}
|
|
1813
|
+
function statusPlainMessage(result) {
|
|
1814
|
+
return `space-bus: service ${result.label} — installed: ${result.installed}, loaded: ${result.loaded}, running: ${result.running}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}`;
|
|
1815
|
+
}
|
|
1816
|
+
function stopPlainMessage(result) {
|
|
1817
|
+
return `space-bus: service stopped: ${result.label} (was loaded: ${result.wasLoaded}); will start again at next login`;
|
|
1818
|
+
}
|
|
1819
|
+
function startPlainMessage(result) {
|
|
1820
|
+
return `space-bus: service started: ${result.label}${result.pid !== undefined ? ` (pid ${result.pid})` : ""}`;
|
|
1821
|
+
}
|
|
1822
|
+
function servicePlainMessage(verb, result) {
|
|
1823
|
+
switch (verb) {
|
|
1824
|
+
case "install":
|
|
1825
|
+
return installPlainMessage(result);
|
|
1826
|
+
case "uninstall":
|
|
1827
|
+
return uninstallPlainMessage(result);
|
|
1828
|
+
case "status":
|
|
1829
|
+
return statusPlainMessage(result);
|
|
1830
|
+
case "stop":
|
|
1831
|
+
return stopPlainMessage(result);
|
|
1832
|
+
case "start":
|
|
1833
|
+
return startPlainMessage(result);
|
|
1834
|
+
default:
|
|
1835
|
+
return "space-bus: service ok";
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
async function runService(args, deps = {}) {
|
|
1839
|
+
if (!isServiceVerb(args.subcommand)) {
|
|
1840
|
+
process.stderr.write(`space-bus: unknown or missing service verb "${args.subcommand ?? ""}"
|
|
1841
|
+
|
|
1842
|
+
`);
|
|
1843
|
+
process.stderr.write(USAGE);
|
|
1844
|
+
return 1;
|
|
1845
|
+
}
|
|
1846
|
+
const doInstallService = deps.installService ?? installService;
|
|
1847
|
+
const doUninstallService = deps.uninstallService ?? uninstallService;
|
|
1848
|
+
const doServiceStatus = deps.serviceStatus ?? serviceStatus;
|
|
1849
|
+
const doStopService = deps.stopService ?? stopService;
|
|
1850
|
+
const doStartService = deps.startService ?? startService;
|
|
1851
|
+
const rosterPath = resolveRoster(args.config);
|
|
1852
|
+
const serviceDeps = { cliEntryPath: fileURLToPath(import.meta.url) };
|
|
1853
|
+
const result = await (() => {
|
|
1854
|
+
switch (args.subcommand) {
|
|
1855
|
+
case "install":
|
|
1856
|
+
return doInstallService(rosterPath, serviceDeps);
|
|
1857
|
+
case "uninstall":
|
|
1858
|
+
return doUninstallService(rosterPath, serviceDeps);
|
|
1859
|
+
case "status":
|
|
1860
|
+
return doServiceStatus(rosterPath, serviceDeps);
|
|
1861
|
+
case "stop":
|
|
1862
|
+
return doStopService(rosterPath, serviceDeps);
|
|
1863
|
+
case "start":
|
|
1864
|
+
return doStartService(rosterPath, serviceDeps);
|
|
1865
|
+
default:
|
|
1866
|
+
throw new Error("unreachable");
|
|
1867
|
+
}
|
|
1868
|
+
})();
|
|
1869
|
+
if (!result.ok) {
|
|
1870
|
+
process.stderr.write(`space-bus: ${result.error}
|
|
1871
|
+
`);
|
|
1872
|
+
return 1;
|
|
1873
|
+
}
|
|
1874
|
+
const plain = (() => {
|
|
1875
|
+
switch (args.subcommand) {
|
|
1876
|
+
case "install":
|
|
1877
|
+
return servicePlainMessage("install", result);
|
|
1878
|
+
case "uninstall":
|
|
1879
|
+
return servicePlainMessage("uninstall", result);
|
|
1880
|
+
case "status":
|
|
1881
|
+
return servicePlainMessage("status", result);
|
|
1882
|
+
case "stop":
|
|
1883
|
+
return servicePlainMessage("stop", result);
|
|
1884
|
+
case "start":
|
|
1885
|
+
return servicePlainMessage("start", result);
|
|
1886
|
+
default:
|
|
1887
|
+
return "space-bus: service ok";
|
|
1888
|
+
}
|
|
1889
|
+
})();
|
|
1890
|
+
printJson(args.json, result, plain);
|
|
1891
|
+
return 0;
|
|
1892
|
+
}
|
|
1139
1893
|
async function main() {
|
|
1140
1894
|
const args = parseArgs(process.argv.slice(2));
|
|
1141
1895
|
if (args.help) {
|
|
@@ -1167,6 +1921,8 @@ async function main() {
|
|
|
1167
1921
|
return runStatus(args);
|
|
1168
1922
|
case "stop":
|
|
1169
1923
|
return await runStop(args);
|
|
1924
|
+
case "service":
|
|
1925
|
+
return await runService(args);
|
|
1170
1926
|
default:
|
|
1171
1927
|
process.stderr.write(`space-bus: unknown command "${args.command}"
|
|
1172
1928
|
|
|
@@ -1185,5 +1941,6 @@ if (__require.main == __require.module) {
|
|
|
1185
1941
|
});
|
|
1186
1942
|
}
|
|
1187
1943
|
export {
|
|
1944
|
+
runService,
|
|
1188
1945
|
runServe
|
|
1189
1946
|
};
|
package/dist/config.js
CHANGED
|
@@ -154,10 +154,12 @@ import {
|
|
|
154
154
|
import { homedir } from "node:os";
|
|
155
155
|
import { join } from "node:path";
|
|
156
156
|
import { z as z2 } from "zod";
|
|
157
|
+
function rosterKey(rosterPath) {
|
|
158
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
159
|
+
}
|
|
157
160
|
function stateDirFor(rosterPath) {
|
|
158
161
|
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
159
|
-
|
|
160
|
-
return join(base, "space-bus", hash);
|
|
162
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
161
163
|
}
|
|
162
164
|
function discoveryFilePath(rosterPath) {
|
|
163
165
|
return join(stateDirFor(rosterPath), "discovery.json");
|
package/dist/discovery.d.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { discoveryFileSchema, loopbackOk, managedSpawnConfigSchema } from "./contract";
|
|
3
3
|
export { discoveryFileSchema, managedSpawnConfigSchema };
|
|
4
|
+
/**
|
|
5
|
+
* First 16 hex chars of sha256(roster path) — the shared per-roster
|
|
6
|
+
* identity key used by both `stateDirFor` (filesystem layout) and
|
|
7
|
+
* `launchd.ts`'s `serviceLabel` (launchd label/plist filename), so the two
|
|
8
|
+
* stay in lockstep without duplicating the hash derivation.
|
|
9
|
+
*/
|
|
10
|
+
export declare function rosterKey(rosterPath: string): string;
|
|
4
11
|
/**
|
|
5
12
|
* Per-roster state directory: `$XDG_STATE_HOME|~/.local/state`/
|
|
6
13
|
* `space-bus/<first 16 hex of sha256(absolute roster path)>/`. Keying by a
|
package/dist/index.js
CHANGED
|
@@ -154,10 +154,12 @@ import {
|
|
|
154
154
|
import { homedir } from "node:os";
|
|
155
155
|
import { join } from "node:path";
|
|
156
156
|
import { z as z2 } from "zod";
|
|
157
|
+
function rosterKey(rosterPath) {
|
|
158
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
159
|
+
}
|
|
157
160
|
function stateDirFor(rosterPath) {
|
|
158
161
|
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
159
|
-
|
|
160
|
-
return join(base, "space-bus", hash);
|
|
162
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
161
163
|
}
|
|
162
164
|
function discoveryFilePath(rosterPath) {
|
|
163
165
|
return join(stateDirFor(rosterPath), "discovery.json");
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** `bot.fro.space-bus.<rosterKey>` — one label per roster identity (R7). */
|
|
2
|
+
export declare function serviceLabel(rosterPath: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* `<baseDir>/<label>.plist`. Defaults to `~/Library/LaunchAgents` when
|
|
5
|
+
* `baseDir` is omitted — tests MUST pass an injected temp directory so
|
|
6
|
+
* writes never land in the operator's real LaunchAgents folder.
|
|
7
|
+
*/
|
|
8
|
+
export declare function plistPath(label: string, baseDir?: string): string;
|
|
9
|
+
export interface RenderPlistOpts {
|
|
10
|
+
runtime: string;
|
|
11
|
+
cliEntry: string;
|
|
12
|
+
rosterPath: string;
|
|
13
|
+
stateDir: string;
|
|
14
|
+
label: string;
|
|
15
|
+
/**
|
|
16
|
+
* Absolute `PATH` to pin into the launched process's sparse launchd
|
|
17
|
+
* environment. launchd agents don't inherit the login shell's PATH, so
|
|
18
|
+
* without this a mise/asdf-shim-resolved `runtime`/`cliEntry` absolute
|
|
19
|
+
* path is fine, but any subprocess *it* shells out to (or a future
|
|
20
|
+
* change resolving a bare command name) would silently resolve
|
|
21
|
+
* differently than at install time. Optional — omitted entirely from
|
|
22
|
+
* the plist when not supplied, since not every caller can safely derive
|
|
23
|
+
* a sane absolute PATH (tests, callers targeting an older contract).
|
|
24
|
+
*/
|
|
25
|
+
path?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Absolute `XDG_STATE_HOME` to pin into the launched environment when
|
|
28
|
+
* the installer resolved `stateDir` using an `XDG_STATE_HOME` override.
|
|
29
|
+
* Without this, `stateDirFor` inside the launchd-launched process (which
|
|
30
|
+
* runs under launchd's own sparse env, NOT the installer's shell env)
|
|
31
|
+
* falls back to `~/.local/state`, diverging from the installer's view of
|
|
32
|
+
* `stateDir` — the exact split this option exists to prevent. Caller
|
|
33
|
+
* (installService) is responsible for validating this is absolute
|
|
34
|
+
* before passing it in.
|
|
35
|
+
*/
|
|
36
|
+
xdgStateHome?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Renders the launchd agent plist XML for a roster. Pins absolute
|
|
40
|
+
* ProgramArguments (`[runtime, cliEntry, "serve", "--foreground"]`),
|
|
41
|
+
* restarts only on abnormal exit (`KeepAlive.SuccessfulExit=false`,
|
|
42
|
+
* consuming the existing 0/1 exit contract — R6), throttles restarts
|
|
43
|
+
* (R8), and routes stdout/stderr into the roster's state dir (R10). The
|
|
44
|
+
* environment carries `SPACE_BUS_CONFIG` plus, when supplied, `PATH` and
|
|
45
|
+
* `XDG_STATE_HOME` — never credentials (R12). All interpolated strings
|
|
46
|
+
* are XML-escaped.
|
|
47
|
+
*/
|
|
48
|
+
export declare function renderPlist(opts: RenderPlistOpts): string;
|
|
49
|
+
export type WriteResult = {
|
|
50
|
+
ok: true;
|
|
51
|
+
} | {
|
|
52
|
+
ok: false;
|
|
53
|
+
error: string;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Writes the plist atomically: a temp file (0644, since launchd — not just
|
|
57
|
+
* the owner — must be able to read it) in the same directory as the
|
|
58
|
+
* target, then rename over it. Mirrors `writeDiscovery`'s temp+rename
|
|
59
|
+
* pattern; final mode is 0644 (owner read/write, group/world read-only —
|
|
60
|
+
* never writable, per R15).
|
|
61
|
+
*/
|
|
62
|
+
export declare function writePlistAtomic(path: string, content: string): WriteResult;
|
|
63
|
+
export type PlistSafety = {
|
|
64
|
+
safe: true;
|
|
65
|
+
} | {
|
|
66
|
+
safe: false;
|
|
67
|
+
reason: string;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Refuses a plist that isn't owned by the current user or is
|
|
71
|
+
* group/world-writable — a tampered plist must never become login-time
|
|
72
|
+
* code execution (R15).
|
|
73
|
+
*/
|
|
74
|
+
export declare function verifyPlistSafe(path: string): PlistSafety;
|
|
75
|
+
export interface ExecResult {
|
|
76
|
+
code: number;
|
|
77
|
+
stdout: string;
|
|
78
|
+
stderr: string;
|
|
79
|
+
}
|
|
80
|
+
export type ExecSeam = (args: string[]) => Promise<ExecResult>;
|
|
81
|
+
/** Default `ExecSeam`: spawns the real `launchctl` binary. Never rejects —
|
|
82
|
+
* a spawn error or a timeout both resolve a `{code:-1,...}` ExecResult with
|
|
83
|
+
* an actionable stderr, so callers' no-throw-across-the-boundary contract
|
|
84
|
+
* holds even when the exec primitive itself misbehaves. */
|
|
85
|
+
export declare const defaultLaunchctl: ExecSeam;
|
|
86
|
+
export declare function bootstrap(uid: number, plist: string, exec: ExecSeam): Promise<ExecResult>;
|
|
87
|
+
export declare function bootout(uid: number, label: string, exec: ExecSeam): Promise<ExecResult>;
|
|
88
|
+
export declare function kickstart(uid: number, label: string, exec: ExecSeam): Promise<ExecResult>;
|
|
89
|
+
export type PrintJobResult = {
|
|
90
|
+
ok: true;
|
|
91
|
+
loaded: boolean;
|
|
92
|
+
pid?: number;
|
|
93
|
+
} | {
|
|
94
|
+
ok: false;
|
|
95
|
+
error: string;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Probes a launchd job by label. A zero exit is authoritative "loaded";
|
|
99
|
+
* a permissive `pid = (\d+)` match against stdout is best-effort only —
|
|
100
|
+
* an unparsable but zero-exit response is still `loaded: true` with
|
|
101
|
+
* `pid: undefined`, since `print`'s exact line format drifts across macOS
|
|
102
|
+
* versions. A non-zero exit is `loaded: false` ONLY when launchd's own
|
|
103
|
+
* "job not found" wording is present in the combined output; any other
|
|
104
|
+
* non-zero exit (permission denied, IO error, our own timeout/spawn-error
|
|
105
|
+
* synthetic result) is reported as `ok:false` so callers can fail honestly
|
|
106
|
+
* instead of silently treating a probe failure as "not loaded".
|
|
107
|
+
*/
|
|
108
|
+
export declare function printJob(uid: number, label: string, exec: ExecSeam): Promise<PrintJobResult>;
|
package/dist/mcp.js
CHANGED
|
@@ -155,10 +155,12 @@ import {
|
|
|
155
155
|
import { homedir } from "node:os";
|
|
156
156
|
import { join } from "node:path";
|
|
157
157
|
import { z as z2 } from "zod";
|
|
158
|
+
function rosterKey(rosterPath) {
|
|
159
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
160
|
+
}
|
|
158
161
|
function stateDirFor(rosterPath) {
|
|
159
162
|
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
160
|
-
|
|
161
|
-
return join(base, "space-bus", hash);
|
|
163
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
162
164
|
}
|
|
163
165
|
function discoveryFilePath(rosterPath) {
|
|
164
166
|
return join(stateDirFor(rosterPath), "discovery.json");
|
|
@@ -1826,7 +1828,7 @@ async function mcpLoadContext() {
|
|
|
1826
1828
|
}
|
|
1827
1829
|
return loadContext();
|
|
1828
1830
|
}
|
|
1829
|
-
var version = "0.
|
|
1831
|
+
var version = "0.11.0";
|
|
1830
1832
|
var server = new McpServer({
|
|
1831
1833
|
name: "space-bus",
|
|
1832
1834
|
version
|
package/dist/server.js
CHANGED
|
@@ -154,10 +154,12 @@ import {
|
|
|
154
154
|
import { homedir } from "node:os";
|
|
155
155
|
import { join } from "node:path";
|
|
156
156
|
import { z as z2 } from "zod";
|
|
157
|
+
function rosterKey(rosterPath) {
|
|
158
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
159
|
+
}
|
|
157
160
|
function stateDirFor(rosterPath) {
|
|
158
161
|
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
159
|
-
|
|
160
|
-
return join(base, "space-bus", hash);
|
|
162
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
161
163
|
}
|
|
162
164
|
function discoveryFilePath(rosterPath) {
|
|
163
165
|
return join(stateDirFor(rosterPath), "discovery.json");
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { type ExecSeam } from "./launchd";
|
|
2
|
+
import { serverStatus as defaultServerStatus } from "./server";
|
|
3
|
+
declare const NOT_SUPPORTED_ERROR = "space-bus service is not supported on this platform (v1 supports macOS/launchd)";
|
|
4
|
+
/** Injectable seams for the service verbs — mirrors `RunServeDeps`'s
|
|
5
|
+
* pattern in cli.ts. All fields are optional and default to the real
|
|
6
|
+
* implementations. */
|
|
7
|
+
export interface ServiceDeps {
|
|
8
|
+
exec?: ExecSeam;
|
|
9
|
+
platform?: NodeJS.Platform;
|
|
10
|
+
uid?: number;
|
|
11
|
+
execPath?: string;
|
|
12
|
+
/** Absolute path of the CLI entry module. Defaults to `process.argv[1]`
|
|
13
|
+
* resolved to absolute — Unit 3 is responsible for wiring a durable
|
|
14
|
+
* resolution (e.g. `fileURLToPath(import.meta.url)`) when invoking these
|
|
15
|
+
* verbs from the running CLI. */
|
|
16
|
+
cliEntryPath?: string;
|
|
17
|
+
serverStatus?: typeof defaultServerStatus;
|
|
18
|
+
/** Injectable sleep, for deterministic tests. */
|
|
19
|
+
sleep?: (ms: number) => Promise<void>;
|
|
20
|
+
/** Injectable clock, for deterministic tests. */
|
|
21
|
+
now?: () => number;
|
|
22
|
+
/** Bounds the install verification poll loop. Default 10s. */
|
|
23
|
+
verifyBudgetMs?: number;
|
|
24
|
+
/** Poll interval for the install verification loop. Default 200ms. */
|
|
25
|
+
verifyPollMs?: number;
|
|
26
|
+
/**
|
|
27
|
+
* Base directory for the launchd agent plist. Defaults to
|
|
28
|
+
* `~/Library/LaunchAgents`. Tests MUST inject a mkdtemp dir here — never
|
|
29
|
+
* exercise the default against the real filesystem.
|
|
30
|
+
*/
|
|
31
|
+
launchAgentsDir?: string;
|
|
32
|
+
}
|
|
33
|
+
export type PlatformGate = {
|
|
34
|
+
ok: true;
|
|
35
|
+
} | {
|
|
36
|
+
ok: false;
|
|
37
|
+
error: string;
|
|
38
|
+
};
|
|
39
|
+
interface ServiceIdentity {
|
|
40
|
+
label: string;
|
|
41
|
+
plistFilePath: string;
|
|
42
|
+
stateDir: string;
|
|
43
|
+
}
|
|
44
|
+
declare function identityFor(rosterPath: string, launchAgentsDir: string): ServiceIdentity;
|
|
45
|
+
export type PreCreateLogResult = {
|
|
46
|
+
ok: true;
|
|
47
|
+
} | {
|
|
48
|
+
ok: false;
|
|
49
|
+
error: string;
|
|
50
|
+
};
|
|
51
|
+
export type InstallResult = {
|
|
52
|
+
ok: true;
|
|
53
|
+
label: string;
|
|
54
|
+
plistPath: string;
|
|
55
|
+
pid?: number;
|
|
56
|
+
warning?: string;
|
|
57
|
+
} | {
|
|
58
|
+
ok: false;
|
|
59
|
+
error: string;
|
|
60
|
+
};
|
|
61
|
+
export declare function installService(rosterPath: string, deps?: ServiceDeps): Promise<InstallResult>;
|
|
62
|
+
export type UninstallResult = {
|
|
63
|
+
ok: true;
|
|
64
|
+
removed: {
|
|
65
|
+
job: boolean;
|
|
66
|
+
plist: boolean;
|
|
67
|
+
};
|
|
68
|
+
label: string;
|
|
69
|
+
} | {
|
|
70
|
+
ok: false;
|
|
71
|
+
error: string;
|
|
72
|
+
};
|
|
73
|
+
export declare function uninstallService(rosterPath: string, deps?: ServiceDeps): Promise<UninstallResult>;
|
|
74
|
+
export type StatusResult = {
|
|
75
|
+
ok: true;
|
|
76
|
+
installed: boolean;
|
|
77
|
+
loaded: boolean;
|
|
78
|
+
running: boolean;
|
|
79
|
+
pid?: number;
|
|
80
|
+
label: string;
|
|
81
|
+
plistPath: string;
|
|
82
|
+
} | {
|
|
83
|
+
ok: false;
|
|
84
|
+
error: string;
|
|
85
|
+
};
|
|
86
|
+
export declare function serviceStatus(rosterPath: string, deps?: ServiceDeps): Promise<StatusResult>;
|
|
87
|
+
export type StopResult = {
|
|
88
|
+
ok: true;
|
|
89
|
+
label: string;
|
|
90
|
+
wasLoaded: boolean;
|
|
91
|
+
} | {
|
|
92
|
+
ok: false;
|
|
93
|
+
error: string;
|
|
94
|
+
};
|
|
95
|
+
export declare function stopService(rosterPath: string, deps?: ServiceDeps): Promise<StopResult>;
|
|
96
|
+
export type StartResult = {
|
|
97
|
+
ok: true;
|
|
98
|
+
label: string;
|
|
99
|
+
pid?: number;
|
|
100
|
+
} | {
|
|
101
|
+
ok: false;
|
|
102
|
+
error: string;
|
|
103
|
+
};
|
|
104
|
+
export declare function startService(rosterPath: string, deps?: ServiceDeps): Promise<StartResult>;
|
|
105
|
+
export { identityFor as serviceIdentity, NOT_SUPPORTED_ERROR as SERVICE_NOT_SUPPORTED_ERROR, };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fro.bot/space-bus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Space Bus — workspace agent bus for OpenCode. One control agent tasking per-project agents over the OpenCode server API, with an MCP facade for Claude Desktop.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|