@fro.bot/space-bus 0.15.0 → 0.15.2

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 CHANGED
@@ -69,7 +69,7 @@ Set `SPACE_BUS_CONFIG` to override roster discovery — it must be an absolute p
69
69
  - `bus_wait` — Block until any of the given sessions needs attention (completes, blocks on a question, fails, or is not found) or a bounded timeout elapses. Returns each watched session's normalized state and which session(s) woke the wait; on timeout returns the current snapshot, not an error.
70
70
  - `bus_registry` — Manage the roster registry: list registered rosters, create/register/unregister rosters, set the default, select an active roster for this connector session (`use`, MCP only), and add/remove/update projects on a registered roster. `set-default` also becomes the MCP ambient-resolution fallback (see below) once `SPACE_BUS_CONFIG` is unset.
71
71
 
72
- All five `bus_*` tools accept an optional `roster` param (a registry name — see `bus_registry`) to target a roster other than the ambient one, and every tool result opens with a `roster: <name-or-path>` line naming the roster it resolved against, on both surfaces. Resolution precedence:
72
+ All `bus_*` tools except `bus_registry` accept an optional `roster` param (a registry name — see `bus_registry`) to target a roster other than the ambient one, and every tool result opens with a `roster: <name-or-path>` line naming the roster it resolved against, on both surfaces. Resolution precedence:
73
73
 
74
74
  - **Plugin surface:** explicit `roster` param > workspace directory (`ctx.directory`).
75
75
  - **MCP surface:** explicit `roster` param > connector-session active roster (`bus_registry use`) > `SPACE_BUS_CONFIG` (ambient) > registry default (`bus_registry set-default`), consulted only when `SPACE_BUS_CONFIG` is unset > an actionable error listing the available rosters.
@@ -136,7 +136,7 @@ Semantics:
136
136
 
137
137
  ## Library surface
138
138
 
139
- 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.
139
+ Experimental subpath exports expose the bus's internals directly — the functions the `bus_*` 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.
140
140
 
141
141
  - `@fro.bot/space-bus/core` — browser-safe; no Node builtins, no ambient env reads. Every exported function takes a `context: BusContext` (`{ roster, credentials? }`) that you build yourself and pass in — core never resolves it for you. Includes `snapshot()`, a one-call composite of roster + per-project status + pending questions with bounded fan-out. Session-content primitives:
142
142
  - `messages(sessionId, { context, limit? })` — bounded full-message read. Resolves session ownership from the roster (never a caller-supplied directory), fetches `GET /session/:id/message?limit=N` (default 20, hard maximum 200 — `limit` must be a finite positive integer at or under the maximum; `0`, negative, fractional, `NaN`, `Infinity`, and over-maximum values are rejected before any fetch). Returns `{ sessionId, project, messages: [{ id?, role, createdAt?, parts: [{ type, text? }] }] }` in the order the server returns them — `id`/`createdAt` are the message's stable identity/ordering metadata (from the envelope's `info.id`/`info.time.created`), and only those explicit fields plus parsed `parts` cross the boundary; unknown envelope fields are dropped. No directory/credential fields in the result.
@@ -148,6 +148,9 @@ Experimental subpath exports expose the bus's internals directly — the functio
148
148
  - `@fro.bot/space-bus/format` — the pure formatters the tools use to render output, for tool-identical text.
149
149
  - `@fro.bot/space-bus/managed-server` — Node-only. The managed-server lifecycle (`ensureServer`/`serverStatus`/`stopServer`) for consumers driving spawn/attach/stop directly — see [Managed server](#managed-server).
150
150
  - `@fro.bot/space-bus/attach` — browser-safe. `resolveManagedServer(workspaceDir, seams)` resolves a managed roster's running endpoint by reading the discovery file through injected filesystem/env/crypto seams — re-checking the localhost guard and probing liveness — so an external attacher such as a Tauri webview can attach without any `node:*` imports or reimplementing the discovery contract. Returns `{ baseUrl, credentials, alive }` or an actionable error.
151
+ - `@fro.bot/space-bus/registry` — Node-only, experimental. The roster registry and roster-edit substrate behind `bus_registry` (`readRegistry`/`registerRoster`/`unregisterRoster`/`setDefaultRoster`/`resolveRosterByName`, plus roster creation and project add/remove/update), for consumers that want to manage rosters programmatically without the tool or MCP surfaces.
152
+
153
+ `@fro.bot/space-bus/server` is not a library entry: OpenCode's plugin loader reserves that subpath for the plugin itself, so it resolves to the plugin entry. Use `/managed-server` for the lifecycle API.
151
154
 
152
155
  Node example (`/config` + `/core`):
153
156
 
package/dist/attach.js CHANGED
@@ -288,6 +288,6 @@ async function probeLiveness(baseUrl, password) {
288
288
  return { ok: true };
289
289
  }
290
290
  export {
291
- resolveManagedServer,
292
- posixJoin
291
+ posixJoin,
292
+ resolveManagedServer
293
293
  };
package/dist/cli.js CHANGED
@@ -2,6 +2,9 @@
2
2
  import { createRequire } from "node:module";
3
3
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
4
 
5
+ // src/cli.ts
6
+ import { fileURLToPath } from "node:url";
7
+
5
8
  // src/config.ts
6
9
  import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
7
10
  import { homedir as homedir3 } from "node:os";
@@ -718,7 +721,7 @@ function registerRoster(name, rosterPath) {
718
721
  if (!readResult.ok)
719
722
  return readResult;
720
723
  const registry = readResult.registry;
721
- const collision = registry.rosters.find((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
724
+ const collision = registry.rosters.find((entry) => entry.name.toLowerCase() === name.toLowerCase());
722
725
  if (collision) {
723
726
  return {
724
727
  ok: false,
@@ -1059,8 +1062,8 @@ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1059
1062
  const handle = attachServer(rosterPath);
1060
1063
  if (handle)
1061
1064
  return handle;
1062
- const lockInfo2 = readLockFile(lockPath);
1063
- const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
1065
+ const lockInfo = readLockFile(lockPath);
1066
+ const winnerAlive = lockInfo !== null && verifyIdentity(lockInfo.pid, lockInfo.startTime);
1064
1067
  if (!winnerAlive) {
1065
1068
  throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
1066
1069
  }
@@ -1452,22 +1455,21 @@ async function waitForGroupDeath(pid, budgetMs) {
1452
1455
  return !groupAlive();
1453
1456
  }
1454
1457
 
1455
- // src/cli.ts
1456
- import { fileURLToPath } from "node:url";
1457
-
1458
1458
  // src/service.ts
1459
1459
  import {
1460
1460
  chmodSync as chmodSync3,
1461
- closeSync as closeSync4,
1461
+ closeSync as closeSync5,
1462
1462
  existsSync as existsSync3,
1463
1463
  fchmodSync,
1464
- constants as fsConstants4,
1464
+ constants as fsConstants5,
1465
+ lstatSync as lstatSync3,
1465
1466
  mkdirSync as mkdirSync3,
1466
- openSync as openSync5,
1467
- unlinkSync as unlinkSync3
1467
+ openSync as openSync6,
1468
+ readlinkSync,
1469
+ unlinkSync as unlinkSync4
1468
1470
  } from "node:fs";
1469
1471
  import { homedir as homedir5 } from "node:os";
1470
- import { isAbsolute as isAbsolute2, join as join5 } from "node:path";
1472
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, sep } from "node:path";
1471
1473
 
1472
1474
  // src/launchd.ts
1473
1475
  import { spawn as spawn2 } from "node:child_process";
@@ -1571,7 +1573,7 @@ function writePlistAtomic(path, content) {
1571
1573
  }
1572
1574
  return { ok: true };
1573
1575
  }
1574
- function verifyPlistSafe(path) {
1576
+ function verifyPlistSafe(path, expectedUid = typeof process.getuid === "function" ? process.getuid() : undefined) {
1575
1577
  let mode;
1576
1578
  let uid;
1577
1579
  try {
@@ -1589,7 +1591,7 @@ function verifyPlistSafe(path) {
1589
1591
  } catch (err) {
1590
1592
  return { safe: false, reason: `failed to stat plist: ${String(err)}` };
1591
1593
  }
1592
- if (typeof process.getuid === "function" && uid !== process.getuid()) {
1594
+ if (expectedUid !== undefined && uid !== expectedUid) {
1593
1595
  return {
1594
1596
  safe: false,
1595
1597
  reason: `plist is not owned by the current user (uid ${uid})`
@@ -1689,6 +1691,180 @@ ${result.stderr}`.toLowerCase();
1689
1691
  };
1690
1692
  }
1691
1693
 
1694
+ // src/service-lock.ts
1695
+ import { execFileSync as execFileSync2 } from "node:child_process";
1696
+ import { randomBytes as randomBytes5 } from "node:crypto";
1697
+ import {
1698
+ closeSync as closeSync4,
1699
+ constants as fsConstants4,
1700
+ openSync as openSync5,
1701
+ readFileSync as readFileSync5,
1702
+ unlinkSync as unlinkSync3,
1703
+ writeFileSync as writeFileSync3
1704
+ } from "node:fs";
1705
+ import { join as join5 } from "node:path";
1706
+ import { z as z4 } from "zod";
1707
+ var lockSchema = z4.object({
1708
+ pid: z4.number().int().min(2),
1709
+ startTime: z4.string(),
1710
+ since: z4.number(),
1711
+ token: z4.string().min(16)
1712
+ });
1713
+ function serviceLockPath(stateDir) {
1714
+ return join5(stateDir, "service.lock");
1715
+ }
1716
+ function isErrno(err, code) {
1717
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
1718
+ }
1719
+ function createExclusive(path, content) {
1720
+ let fd;
1721
+ try {
1722
+ fd = openSync5(path, fsConstants4.O_EXCL | fsConstants4.O_CREAT | fsConstants4.O_WRONLY, 384);
1723
+ } catch (err) {
1724
+ if (isErrno(err, "EEXIST"))
1725
+ return false;
1726
+ throw err;
1727
+ }
1728
+ try {
1729
+ writeFileSync3(fd, content);
1730
+ } finally {
1731
+ closeSync4(fd);
1732
+ }
1733
+ return true;
1734
+ }
1735
+ function readRaw(path) {
1736
+ try {
1737
+ return readFileSync5(path, "utf8");
1738
+ } catch (err) {
1739
+ if (isErrno(err, "ENOENT"))
1740
+ return;
1741
+ throw err;
1742
+ }
1743
+ }
1744
+ function parseLock(raw) {
1745
+ try {
1746
+ const parsed = lockSchema.safeParse(JSON.parse(raw));
1747
+ return parsed.success ? parsed.data : null;
1748
+ } catch {
1749
+ return null;
1750
+ }
1751
+ }
1752
+ function processStartTime(pid) {
1753
+ try {
1754
+ const out = execFileSync2("ps", ["-p", String(pid), "-o", "lstart="], {
1755
+ env: { ...process.env, LC_ALL: "C", TZ: "UTC0" },
1756
+ encoding: "utf8",
1757
+ stdio: ["ignore", "pipe", "ignore"]
1758
+ }).trim();
1759
+ return out.length > 0 ? out : null;
1760
+ } catch {
1761
+ return null;
1762
+ }
1763
+ }
1764
+ function pidMayExist(pid) {
1765
+ try {
1766
+ process.kill(pid, 0);
1767
+ return true;
1768
+ } catch (err) {
1769
+ return !isErrno(err, "ESRCH");
1770
+ }
1771
+ }
1772
+ function ownerMayBeLive(lock) {
1773
+ if (!pidMayExist(lock.pid))
1774
+ return false;
1775
+ if (lock.startTime === "")
1776
+ return true;
1777
+ const current = processStartTime(lock.pid);
1778
+ return current === null || current === lock.startTime;
1779
+ }
1780
+ function busy(lockPath, lock) {
1781
+ return {
1782
+ ok: false,
1783
+ error: `another space-bus service operation is in progress for this roster (held by pid ${lock.pid}; lock ${lockPath}) — retry when it finishes`
1784
+ };
1785
+ }
1786
+ function unattributable(lockPath) {
1787
+ return {
1788
+ ok: false,
1789
+ error: `the service lock ${lockPath} exists but is incomplete or unreadable, so its owner cannot be identified; it may belong to a command that is still starting. Do not remove it unless every space-bus service command for this roster has stopped, then delete the file and retry`
1790
+ };
1791
+ }
1792
+ function makeRelease(lockPath, token) {
1793
+ return () => {
1794
+ try {
1795
+ const raw = readRaw(lockPath);
1796
+ if (raw !== undefined && parseLock(raw)?.token === token) {
1797
+ unlinkSync3(lockPath);
1798
+ }
1799
+ } catch {}
1800
+ };
1801
+ }
1802
+ function reclaim(lockPath, seenRaw, mine, token) {
1803
+ const mutex = `${lockPath}.reclaim`;
1804
+ if (!createExclusive(mutex, String(process.pid))) {
1805
+ return {
1806
+ ok: false,
1807
+ error: `another process is reclaiming the service lock (${mutex}). Do not remove that file unless every space-bus service command for this roster has stopped, then delete it and retry`
1808
+ };
1809
+ }
1810
+ try {
1811
+ const nowRaw = readRaw(lockPath);
1812
+ if (nowRaw !== undefined && nowRaw !== seenRaw) {
1813
+ return contended(lockPath, nowRaw);
1814
+ }
1815
+ if (nowRaw !== undefined)
1816
+ unlinkSync3(lockPath);
1817
+ if (!createExclusive(lockPath, mine)) {
1818
+ return contended(lockPath, readRaw(lockPath));
1819
+ }
1820
+ return { ok: true, lock: { release: makeRelease(lockPath, token) } };
1821
+ } finally {
1822
+ try {
1823
+ unlinkSync3(mutex);
1824
+ } catch {}
1825
+ }
1826
+ }
1827
+ function contended(lockPath, raw) {
1828
+ const held = raw === undefined ? null : parseLock(raw);
1829
+ return held ? busy(lockPath, held) : unattributable(lockPath);
1830
+ }
1831
+ function tryAcquire(stateDir) {
1832
+ const lockPath = serviceLockPath(stateDir);
1833
+ const token = randomBytes5(16).toString("hex");
1834
+ const mine = JSON.stringify({
1835
+ pid: process.pid,
1836
+ startTime: processStartTime(process.pid) ?? "",
1837
+ since: Date.now(),
1838
+ token
1839
+ });
1840
+ const won = () => ({
1841
+ ok: true,
1842
+ lock: { release: makeRelease(lockPath, token) }
1843
+ });
1844
+ if (createExclusive(lockPath, mine))
1845
+ return won();
1846
+ const seenRaw = readRaw(lockPath);
1847
+ if (seenRaw === undefined) {
1848
+ return createExclusive(lockPath, mine) ? won() : contended(lockPath, readRaw(lockPath));
1849
+ }
1850
+ const held = parseLock(seenRaw);
1851
+ if (held === null)
1852
+ return unattributable(lockPath);
1853
+ if (ownerMayBeLive(held))
1854
+ return busy(lockPath, held);
1855
+ return reclaim(lockPath, seenRaw, mine, token);
1856
+ }
1857
+ function acquireServiceLock(stateDir) {
1858
+ try {
1859
+ return tryAcquire(stateDir);
1860
+ } catch (err) {
1861
+ return {
1862
+ ok: false,
1863
+ error: `failed to acquire the service lock ${serviceLockPath(stateDir)}: ${String(err)}`
1864
+ };
1865
+ }
1866
+ }
1867
+
1692
1868
  // src/service.ts
1693
1869
  var NOT_SUPPORTED_ERROR = "space-bus service is not supported on this platform (v1 supports macOS/launchd)";
1694
1870
  var EPHEMERAL_CACHE_SEGMENTS = [
@@ -1718,7 +1894,8 @@ function resolveDeps(deps) {
1718
1894
  now: deps.now ?? Date.now,
1719
1895
  verifyBudgetMs: deps.verifyBudgetMs ?? DEFAULT_VERIFY_BUDGET_MS,
1720
1896
  verifyPollMs: deps.verifyPollMs ?? DEFAULT_VERIFY_POLL_MS,
1721
- launchAgentsDir: deps.launchAgentsDir ?? join5(homedir5(), "Library", "LaunchAgents")
1897
+ launchAgentsDir: deps.launchAgentsDir ?? join6(homedir5(), "Library", "LaunchAgents"),
1898
+ plistOwnerUid: deps.plistOwnerUid
1722
1899
  };
1723
1900
  }
1724
1901
  function isEphemeralCachePath(path) {
@@ -1742,10 +1919,96 @@ function identityFor(rosterPath, launchAgentsDir) {
1742
1919
  stateDir: stateDirFor(rosterPath)
1743
1920
  };
1744
1921
  }
1922
+ var MAX_ROSTER_LINK_HOPS = 40;
1923
+ function statStep(path) {
1924
+ try {
1925
+ return lstatSync3(path).isSymbolicLink() ? { kind: "link", target: readlinkSync(path) } : { kind: "plain" };
1926
+ } catch (err) {
1927
+ return isEnoent3(err) ? { kind: "missing" } : { kind: "error", detail: `${path}: ${String(err)}` };
1928
+ }
1929
+ }
1930
+ function splitPath(path) {
1931
+ return path.split(sep).filter((s) => s !== "" && s !== ".");
1932
+ }
1933
+ function realpathLoose(input) {
1934
+ const fail = (detail) => ({
1935
+ ok: false,
1936
+ error: `cannot resolve roster path ${input}: ${detail}`
1937
+ });
1938
+ let pending = splitPath(input);
1939
+ let current = sep;
1940
+ let hops = 0;
1941
+ while (pending.length > 0) {
1942
+ const [segment = "", ...rest] = pending;
1943
+ pending = rest;
1944
+ if (segment === "..") {
1945
+ current = dirname2(current);
1946
+ continue;
1947
+ }
1948
+ const candidate = join6(current, segment);
1949
+ const step = statStep(candidate);
1950
+ if (step.kind === "missing") {
1951
+ return { ok: true, value: join6(candidate, ...rest) };
1952
+ }
1953
+ if (step.kind === "plain") {
1954
+ current = candidate;
1955
+ continue;
1956
+ }
1957
+ if (step.kind === "error")
1958
+ return fail(step.detail);
1959
+ hops += 1;
1960
+ if (hops > MAX_ROSTER_LINK_HOPS) {
1961
+ return fail("roster symlink chain loops or is too long");
1962
+ }
1963
+ if (isAbsolute2(step.target))
1964
+ current = sep;
1965
+ pending = [...splitPath(step.target), ...pending];
1966
+ }
1967
+ return { ok: true, value: current };
1968
+ }
1969
+ function isSymlink(path) {
1970
+ try {
1971
+ return lstatSync3(path).isSymbolicLink();
1972
+ } catch {
1973
+ return false;
1974
+ }
1975
+ }
1976
+ function resolveIdentity(rosterPath, launchAgentsDir) {
1977
+ const given = identityFor(rosterPath, launchAgentsDir);
1978
+ const walked = isAbsolute2(rosterPath) ? realpathLoose(rosterPath) : { ok: true, value: rosterPath };
1979
+ if (!walked.ok)
1980
+ return walked;
1981
+ if (walked.value === rosterPath)
1982
+ return { ok: true, value: { ...given, rosterPath } };
1983
+ const canonical = identityFor(walked.value, launchAgentsDir);
1984
+ const hasCanonical = existsSync3(canonical.plistFilePath);
1985
+ const hasGiven = existsSync3(given.plistFilePath);
1986
+ if (hasCanonical && hasGiven) {
1987
+ return {
1988
+ ok: false,
1989
+ error: `ambiguous service identity for roster ${rosterPath}: a plist exists for both ${walked.value} (${canonical.plistFilePath}) and the path as given (${given.plistFilePath}); boot out and remove the stale one by hand`
1990
+ };
1991
+ }
1992
+ const useCanonical = hasCanonical || !hasGiven && isSymlink(rosterPath);
1993
+ return useCanonical ? { ok: true, value: { ...canonical, rosterPath: walked.value } } : { ok: true, value: { ...given, rosterPath } };
1994
+ }
1995
+ async function withServiceLock(stateDir, run) {
1996
+ const dir = ensureStateDir(stateDir);
1997
+ if (!dir.ok)
1998
+ return dir;
1999
+ const acquired = acquireServiceLock(stateDir);
2000
+ if (!acquired.ok)
2001
+ return acquired;
2002
+ try {
2003
+ return await run();
2004
+ } finally {
2005
+ acquired.lock.release();
2006
+ }
2007
+ }
1745
2008
  function preCreateLog(path) {
1746
2009
  let fd;
1747
2010
  try {
1748
- fd = openSync5(path, fsConstants4.O_WRONLY | fsConstants4.O_APPEND | fsConstants4.O_CREAT | fsConstants4.O_NOFOLLOW, 384);
2011
+ fd = openSync6(path, fsConstants5.O_WRONLY | fsConstants5.O_APPEND | fsConstants5.O_CREAT | fsConstants5.O_NOFOLLOW, 384);
1749
2012
  } catch (err) {
1750
2013
  if (isSymlinkError(err)) {
1751
2014
  return { ok: false, error: `refusing symlinked log path: ${path}` };
@@ -1757,7 +2020,7 @@ function preCreateLog(path) {
1757
2020
  } catch (err) {
1758
2021
  return { ok: false, error: `failed to chmod log ${path}: ${String(err)}` };
1759
2022
  } finally {
1760
- closeSync4(fd);
2023
+ closeSync5(fd);
1761
2024
  }
1762
2025
  return { ok: true };
1763
2026
  }
@@ -1878,7 +2141,14 @@ async function installService(rosterPath, deps = {}) {
1878
2141
  const gate = platformGate(resolved.platform);
1879
2142
  if (!gate.ok)
1880
2143
  return { ok: false, error: gate.error };
1881
- const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
2144
+ const identity = resolveIdentity(rosterPath, resolved.launchAgentsDir);
2145
+ if (!identity.ok)
2146
+ return { ok: false, error: identity.error };
2147
+ return withServiceLock(identity.value.stateDir, () => installLocked(resolved, identity.value));
2148
+ }
2149
+ async function installLocked(resolved, identity) {
2150
+ const { label, plistFilePath, stateDir } = identity;
2151
+ const roster = identity.rosterPath;
1882
2152
  const warning = ephemeralCacheWarning(resolved);
1883
2153
  const fsResult = prepareInstallFilesystem(resolved, stateDir);
1884
2154
  if (!fsResult.ok)
@@ -1902,7 +2172,7 @@ async function installService(rosterPath, deps = {}) {
1902
2172
  const plistXml = renderPlist({
1903
2173
  runtime: resolved.execPath,
1904
2174
  cliEntry: resolved.cliEntryPath,
1905
- rosterPath,
2175
+ rosterPath: roster,
1906
2176
  stateDir,
1907
2177
  label,
1908
2178
  path: process.env["PATH"],
@@ -1912,7 +2182,7 @@ async function installService(rosterPath, deps = {}) {
1912
2182
  if (!writeResult.ok) {
1913
2183
  return { ok: false, error: writeResult.error };
1914
2184
  }
1915
- const safety = verifyPlistSafe(plistFilePath);
2185
+ const safety = verifyPlistSafe(plistFilePath, resolved.plistOwnerUid);
1916
2186
  if (!safety.safe) {
1917
2187
  return { ok: false, error: `refusing to install: ${safety.reason}` };
1918
2188
  }
@@ -1926,7 +2196,7 @@ async function installService(rosterPath, deps = {}) {
1926
2196
  error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
1927
2197
  };
1928
2198
  }
1929
- const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
2199
+ const verified = await verifyRunning(roster, label, resolved, plistFilePath);
1930
2200
  if (!verified.ok)
1931
2201
  return verified;
1932
2202
  return {
@@ -1962,7 +2232,7 @@ async function verifyRunning(rosterPath, label, resolved, plistFilePath) {
1962
2232
  await resolved.sleep(resolved.verifyPollMs);
1963
2233
  }
1964
2234
  const stateDir = stateDirFor(rosterPath);
1965
- const logPath = join5(stateDir, "service.log");
2235
+ const logPath = join6(stateDir, "service.log");
1966
2236
  return {
1967
2237
  ok: false,
1968
2238
  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}`
@@ -1973,7 +2243,13 @@ async function uninstallService(rosterPath, deps = {}) {
1973
2243
  const gate = platformGate(resolved.platform);
1974
2244
  if (!gate.ok)
1975
2245
  return { ok: false, error: gate.error };
1976
- const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
2246
+ const identity = resolveIdentity(rosterPath, resolved.launchAgentsDir);
2247
+ if (!identity.ok)
2248
+ return { ok: false, error: identity.error };
2249
+ return withServiceLock(identity.value.stateDir, () => uninstallLocked(resolved, identity.value));
2250
+ }
2251
+ async function uninstallLocked(resolved, identity) {
2252
+ const { label, plistFilePath } = identity;
1977
2253
  const job = await probeJob(resolved, label);
1978
2254
  if (!job.ok) {
1979
2255
  return { ok: false, error: `failed to probe job: ${job.error}` };
@@ -1987,7 +2263,7 @@ async function uninstallService(rosterPath, deps = {}) {
1987
2263
  }
1988
2264
  let plistRemoved = false;
1989
2265
  try {
1990
- unlinkSync3(plistFilePath);
2266
+ unlinkSync4(plistFilePath);
1991
2267
  plistRemoved = true;
1992
2268
  } catch (err) {
1993
2269
  if (!isEnoent3(err)) {
@@ -2011,13 +2287,16 @@ async function serviceStatus(rosterPath, deps = {}) {
2011
2287
  const gate = platformGate(resolved.platform);
2012
2288
  if (!gate.ok)
2013
2289
  return { ok: false, error: gate.error };
2014
- const { label, plistFilePath } = identityFor(rosterPath, resolved.launchAgentsDir);
2290
+ const identity = resolveIdentity(rosterPath, resolved.launchAgentsDir);
2291
+ if (!identity.ok)
2292
+ return { ok: false, error: identity.error };
2293
+ const { label, plistFilePath } = identity.value;
2015
2294
  const installed = existsSync3(plistFilePath);
2016
2295
  const job = await probeJob(resolved, label);
2017
2296
  if (!job.ok) {
2018
2297
  return { ok: false, error: `failed to probe job: ${job.error}` };
2019
2298
  }
2020
- const status = resolved.serverStatus(rosterPath);
2299
+ const status = resolved.serverStatus(identity.value.rosterPath);
2021
2300
  return {
2022
2301
  ok: true,
2023
2302
  installed,
@@ -2033,7 +2312,13 @@ async function stopService(rosterPath, deps = {}) {
2033
2312
  const gate = platformGate(resolved.platform);
2034
2313
  if (!gate.ok)
2035
2314
  return { ok: false, error: gate.error };
2036
- const { label } = identityFor(rosterPath, resolved.launchAgentsDir);
2315
+ const identity = resolveIdentity(rosterPath, resolved.launchAgentsDir);
2316
+ if (!identity.ok)
2317
+ return { ok: false, error: identity.error };
2318
+ return withServiceLock(identity.value.stateDir, () => stopLocked(resolved, identity.value));
2319
+ }
2320
+ async function stopLocked(resolved, identity) {
2321
+ const { label } = identity;
2037
2322
  const job = await probeJob(resolved, label);
2038
2323
  if (!job.ok) {
2039
2324
  return { ok: false, error: `failed to probe job: ${job.error}` };
@@ -2051,7 +2336,14 @@ async function startService(rosterPath, deps = {}) {
2051
2336
  const gate = platformGate(resolved.platform);
2052
2337
  if (!gate.ok)
2053
2338
  return { ok: false, error: gate.error };
2054
- const { label, plistFilePath, stateDir } = identityFor(rosterPath, resolved.launchAgentsDir);
2339
+ const identity = resolveIdentity(rosterPath, resolved.launchAgentsDir);
2340
+ if (!identity.ok)
2341
+ return { ok: false, error: identity.error };
2342
+ return withServiceLock(identity.value.stateDir, () => startLocked(resolved, identity.value));
2343
+ }
2344
+ async function startLocked(resolved, identity) {
2345
+ const { label, plistFilePath, stateDir } = identity;
2346
+ const roster = identity.rosterPath;
2055
2347
  if (!existsSync3(plistFilePath)) {
2056
2348
  return {
2057
2349
  ok: false,
@@ -2065,7 +2357,7 @@ async function startService(rosterPath, deps = {}) {
2065
2357
  const plistXml = renderPlist({
2066
2358
  runtime: resolved.execPath,
2067
2359
  cliEntry: resolved.cliEntryPath,
2068
- rosterPath,
2360
+ rosterPath: roster,
2069
2361
  stateDir,
2070
2362
  label,
2071
2363
  path: process.env["PATH"],
@@ -2075,7 +2367,7 @@ async function startService(rosterPath, deps = {}) {
2075
2367
  if (!writeResult.ok) {
2076
2368
  return { ok: false, error: writeResult.error };
2077
2369
  }
2078
- const safety = verifyPlistSafe(plistFilePath);
2370
+ const safety = verifyPlistSafe(plistFilePath, resolved.plistOwnerUid);
2079
2371
  if (!safety.safe) {
2080
2372
  return { ok: false, error: `refusing to start: ${safety.reason}` };
2081
2373
  }
@@ -2093,7 +2385,7 @@ async function startService(rosterPath, deps = {}) {
2093
2385
  error: `launchctl kickstart failed (exit ${kickstartResult.code})${stderrDetail(kickstartResult)}`
2094
2386
  };
2095
2387
  }
2096
- const verified = await verifyRunning(rosterPath, label, resolved, plistFilePath);
2388
+ const verified = await verifyRunning(roster, label, resolved, plistFilePath);
2097
2389
  if (!verified.ok)
2098
2390
  return verified;
2099
2391
  return { ok: true, label, pid: verified.pid };
@@ -2171,7 +2463,7 @@ function printJson(json, data, plain) {
2171
2463
  async function runServe(args, deps = {}) {
2172
2464
  const doEnsureServer = deps.ensureServer ?? ensureServer;
2173
2465
  const doStopServer = deps.stopServer ?? stopServer;
2174
- const doSuperviseServer = deps.superviseServer ?? ((rosterPath2, handle2, shouldStop, interrupt) => superviseServer(rosterPath2, handle2, { shouldStop, interrupt }));
2466
+ const doSuperviseServer = deps.superviseServer ?? ((rosterPath, handle, shouldStop, interrupt) => superviseServer(rosterPath, handle, { shouldStop, interrupt }));
2175
2467
  const rosterPath = resolveRoster(args.config);
2176
2468
  const handle = await doEnsureServer(rosterPath);
2177
2469
  const data = {
@@ -2387,6 +2679,6 @@ if (__require.main == __require.module) {
2387
2679
  });
2388
2680
  }
2389
2681
  export {
2390
- runService,
2391
- runServe
2682
+ runServe,
2683
+ runService
2392
2684
  };
package/dist/config.js CHANGED
@@ -1,6 +1,3 @@
1
- import { createRequire } from "node:module";
2
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
-
4
1
  // src/config.ts
5
2
  import { existsSync, readFileSync as readFileSync3, realpathSync as realpathSync2 } from "node:fs";
6
3
  import { homedir as homedir3 } from "node:os";
@@ -717,7 +714,7 @@ function registerRoster(name, rosterPath) {
717
714
  if (!readResult.ok)
718
715
  return readResult;
719
716
  const registry = readResult.registry;
720
- const collision = registry.rosters.find((entry2) => entry2.name.toLowerCase() === name.toLowerCase());
717
+ const collision = registry.rosters.find((entry) => entry.name.toLowerCase() === name.toLowerCase());
721
718
  if (collision) {
722
719
  return {
723
720
  ok: false,
@@ -964,18 +961,18 @@ function isManagedRoster(directory) {
964
961
  return manifest.server.managed !== undefined;
965
962
  }
966
963
  export {
967
- serverConfigSchema,
968
- resolveRosterPath,
969
- manifestSchema,
970
- managedServerConfigSchema,
971
- loadContextForRosterPath,
972
- loadContextForRoster,
973
- loadContext,
974
- isManagedRosterAtPath,
975
- isManagedRoster,
976
- getRosterAtPath,
977
- getRoster,
978
- getProjects,
964
+ expandHome,
979
965
  getCredentials,
980
- expandHome
966
+ getProjects,
967
+ getRoster,
968
+ getRosterAtPath,
969
+ isManagedRoster,
970
+ isManagedRosterAtPath,
971
+ loadContext,
972
+ loadContextForRoster,
973
+ loadContextForRosterPath,
974
+ managedServerConfigSchema,
975
+ manifestSchema,
976
+ resolveRosterPath,
977
+ serverConfigSchema
981
978
  };
package/dist/contract.js CHANGED
@@ -168,35 +168,35 @@ var discoveryFileSchema = z.object({
168
168
  rosterPath: z.string().optional()
169
169
  });
170
170
  export {
171
- vcsStatusSchema,
172
- vcsStatusEntrySchema,
173
- turnMessageSchema,
174
- turnMessageListSchema,
175
- turnDiffEntrySchema,
176
- todoSchema,
177
- sessionSummarySchema,
178
- sessionStatusMapSchema,
179
- sessionStateSchema,
180
- sessionStateInfoSchema,
181
- sessionSchema,
182
- sessionListSchema,
183
- rosterSchema,
184
- registryFileSchema,
185
- registryEntrySchema,
186
- questionListSchema,
187
- questionEntrySchema,
188
- projectSchema,
189
- pendingQuestionListSchema,
190
- pendingQuestionEntrySchema,
191
- messagePartSchema,
192
- messageListSchema,
193
- messageEnvelopeSchema,
194
- managedSpawnConfigSchema,
195
- loopbackOk,
196
- discoveryFileSchema,
197
- diffSchema,
198
- diffEntrySchema,
199
- credentialsSchema,
171
+ LOOPBACK_HOSTS,
200
172
  busContextSchema,
201
- LOOPBACK_HOSTS
173
+ credentialsSchema,
174
+ diffEntrySchema,
175
+ diffSchema,
176
+ discoveryFileSchema,
177
+ loopbackOk,
178
+ managedSpawnConfigSchema,
179
+ messageEnvelopeSchema,
180
+ messageListSchema,
181
+ messagePartSchema,
182
+ pendingQuestionEntrySchema,
183
+ pendingQuestionListSchema,
184
+ projectSchema,
185
+ questionEntrySchema,
186
+ questionListSchema,
187
+ registryEntrySchema,
188
+ registryFileSchema,
189
+ rosterSchema,
190
+ sessionListSchema,
191
+ sessionSchema,
192
+ sessionStateInfoSchema,
193
+ sessionStateSchema,
194
+ sessionStatusMapSchema,
195
+ sessionSummarySchema,
196
+ todoSchema,
197
+ turnDiffEntrySchema,
198
+ turnMessageListSchema,
199
+ turnMessageSchema,
200
+ vcsStatusEntrySchema,
201
+ vcsStatusSchema
202
202
  };