import { existsSync, unlinkSync } from "node:fs"; import { dirname } from "node:path"; import { assertNotRealLaunchAgentsUnderTest } from "../lib/test-home-guard"; import { sh } from "./guards"; import { plistPath } from "./state"; import { spawnSync } from "node:child_process"; import { chmodSync, mkdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { getConfigDir } from "../config"; import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime, type DurableBunRuntime } from "../lib/bun-runtime"; import { serviceApiTokenFilePath } from "../lib/service-secrets"; import { recordOwnedConfigPath } from "../lib/config-ownership"; import { writeServiceApiTokenFile, assertLiveServiceManagerAllowed } from "./guards"; import { resolveServiceListenPort, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv, pinnedServiceHomeShellAssignments, serviceApiTokenFileUnder } from "./definition"; import { SERVICE_MANAGED_ENV, LABEL, cliEntry, filterTransientServicePath, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, type ServiceInstallState, writeServiceInstallState, readServiceInstallState } from "./state"; import { writeServiceDefinitionFile } from "./windows-ops"; import { readTextOrNull } from "./windows-taskxml"; import { encodePlistString, plistKeyedString } from "./plist-xml"; /** Encode a plist value; `field` names it if it holds a character XML cannot carry. */ const plistString = encodePlistString; /** A concurrent cleanup may already have removed this install-owned file. */ function unlinkLaunchdOwnedFile(path: string): void { try { unlinkSync(path); } catch (error) { if ((error as { code?: string }).code !== "ENOENT") throw error; } } /** * Render the launchd plist from the package-local Bun + CLI pair. Unlike systemd, launchd * must not hand the service token and proxy environment to a PATH-discovered launcher: a * mutable version-manager shim could be replaced after installation and run with those * secrets. The legacy `launcher` dependency remains accepted for API compatibility but is * ignored. */ export function buildPlist( proxyEnv: { name: string; value: string }[] = resolvedProxyEnv(), deps: { runtime?: DurableBunRuntime; launcher?: string | null; homes?: LaunchdPinnedHomes } = {}, ): string { const runtime = deps.runtime ?? durableBunRuntime(); const { bun, bunRuntimeSource, cli } = cliEntry(runtime); const log = logPath(); const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "darwin"); const homes = deps.homes ?? currentLaunchdPinnedHomes(); const { codexHome, opencodexHome } = homes; const codexSqliteHome = currentCodexSqliteHomeAbsolute(); const envLines = [ ` OCX_SERVICE1`, // OCX_SERVICE alone cannot identify the managed job: `ocx claude` and `ocx opencode` // also set it on the proxies they spawn, to borrow its routing-preservation meaning // (src/cli/index.ts preserveRouting). Only the wrapper writes this second marker, so // the dashboard-stop refusal below can tell a real launchd job from an ordinary child. ` ${SERVICE_MANAGED_ENV}1`, ` ${BUN_RUNTIME_SOURCE_ENV}${bunRuntimeSource}`, ` ${BUN_RUNTIME_PATH_ENV}${plistString(bun, BUN_RUNTIME_PATH_ENV)}`, ` PATH${plistString(path, "PATH")}`, codexHome ? ` CODEX_HOME${plistString(codexHome, "CODEX_HOME")}` : null, codexSqliteHome ? ` CODEX_SQLITE_HOME${plistString(codexSqliteHome, "CODEX_SQLITE_HOME")}` : null, opencodexHome ? ` OPENCODEX_HOME${plistString(opencodexHome, "OPENCODEX_HOME")}` : null, ...proxyEnv.map(({ name, value }) => ` ${name}${plistString(value, name)}`), ].filter((line): line is string => Boolean(line)).join("\n"); const command = launchdServiceCommand(runtime, resolveServiceListenPort(), homes); // This agent serves interactive Codex/GUI requests. launchd's default class // throttles CPU and I/O under load; Adaptive requires XPC transactions we do not use. return ` Label${LABEL} ProgramArguments /bin/sh -lc ${plistString(command, "the service command")} RunAtLoad ProcessTypeInteractive KeepAliveSuccessfulExit EnvironmentVariables ${envLines} StandardOutPath${plistString(log, "the service log path")} StandardErrorPath${plistString(log, "the service log path")} `; } /** * The single `EnvironmentVariables` line {@link buildPlist} fills from the env of whatever * process happens to be repairing. */ const PLIST_PATH_ENTRY = /^(\s*PATH<\/key>)([^\n]*)(<\/string>)$/m; const PLIST_INTERACTIVE_POLICY = /^[ \t]*ProcessType<\/key>Interactive<\/string>\r?\n/m; function filterPlistPathVariable(plist: string): string { return plist.replace(PLIST_PATH_ENTRY, (_match, open: string, value: string, close: string) => `${open}${filterTransientServicePath(value, ":", "darwin")}${close}`); } /** * The rendered plist with the PREVIOUS definition's `PATH` put back — or null when `PATH` * and the addition of the Interactive policy are not the only differences. * * `buildPlist` bakes `process.env.PATH`, and `ocx service repair` is run by whatever has a * shell: a tray helper, `ocx update`'s child, an ssh session, a cron job. Each of those * carries a DIFFERENT PATH from the login shell that installed the service, so comparing * whole-file bytes made the "nothing to repair" pre-check miss almost every time it * mattered: a healthy hub was evicted, and its PATH rewritten to the narrower one, purely * because of who asked (#4236, review finding 2). * * Reuse rather than ignore. A plist that differs only in PATH is not "equal" — dropping the * difference silently would let a repair report a no-op while launchd keeps a PATH the * operator has changed on purpose. Putting the previous value back makes the two files * genuinely identical, so the caller's ordinary byte comparison decides, and the PATH the * service already runs with is the one that survives. * * The caller applies this only when the live job is loaded from exactly the exec line this * install baked. This preserves the operator's installed PATH, not evidence that a pending * definition was loaded; the caller still requires verified bootstrap. Whenever anything ELSE about * the definition changed the plist is rewritten in full, PATH included, so a real * re-install still updates it. Adding the Interactive policy also retains the previous * normalized PATH, but keeps the policy line so the caller still reloads the definition. */ export function reusePreviousPlistPathVariable(previous: string, rendered: string): string | null { if (previous === rendered) return null; const prev = PLIST_PATH_ENTRY.exec(previous); const next = PLIST_PATH_ENTRY.exec(rendered); if (!prev || !next) return null; const normalizedPrevious = filterPlistPathVariable(previous); const previousPath = filterTransientServicePath(prev[2] ?? "", ":", "darwin"); // A function replacer, not a `$1` template: a PATH entry containing `$&` or `$1` would // otherwise be re-expanded into the file. const adopted = rendered.replace(PLIST_PATH_ENTRY, (_match, open: string, _value: string, close: string) => `${open}${previousPath}${close}`); return adopted.replace(PLIST_INTERACTIVE_POLICY, "") === normalizedPrevious.replace(PLIST_INTERACTIVE_POLICY, "") ? adopted : null; } /** The homes a launchd plist pins, resolved once per definition. */ export type LaunchdPinnedHomes = { codexHome: string; opencodexHome: string }; function currentLaunchdPinnedHomes(): LaunchdPinnedHomes { return { codexHome: currentCodexHome(), opencodexHome: currentOpenCodexHome() }; } /** * The homes the installed plist pins, or null when it cannot be read or does not pin both. * The plist path does not follow either home, so this answers the same from any shell. */ function installedLaunchdPinnedHomes(readPlist: () => string): LaunchdPinnedHomes | null { let plist: string; try { plist = readPlist(); } catch { return null; } const codexHome = plistKeyedString(plist, "CODEX_HOME"); const opencodexHome = plistKeyedString(plist, "OPENCODEX_HOME"); return codexHome && opencodexHome ? { codexHome, opencodexHome } : null; } /** * The homes the installed job runs with: the plist on disk, then the recorded install state, * and the current shell only when neither records them. Every comparison against a job that * is already loaded starts here, so a shell exporting other homes cannot make it read stale. */ function installedLaunchdHomes(state: ServiceInstallState | null, readPlist: () => string): LaunchdPinnedHomes { return installedLaunchdPinnedHomes(readPlist) ?? (state?.codexHome && state.opencodexHome ? { codexHome: state.codexHome, opencodexHome: state.opencodexHome } : null) ?? currentLaunchdPinnedHomes(); } /** * The complete exec line {@link buildPlist} bakes, for the runtime a single install already * resolved. Shared so `installLaunchd` can verify the live job against the exact string it * just wrote instead of re-deriving it from install state that has not been written yet * (a fresh install has no state, so `expectedLaunchdCommand` falls back to the package * pair — identical here, but only by accident of the fresh state). * * The EnvironmentVariables dict is supplied first, but `/bin/sh -lc` runs a login shell * after launchd injects it. A profile export could otherwise overwrite the pinned homes, * so the command re-assigns both immediately before exec. The assignments are part of the * line every live-job comparison uses: a job loaded from an older plist without them, or * with other homes, must read as stale. */ function launchdServiceCommand( runtime: DurableBunRuntime = durableBunRuntime(), port: number = resolveServiceListenPort(), homes: LaunchdPinnedHomes = currentLaunchdPinnedHomes(), ): string { const { bun, cli } = cliEntry(runtime); // The token file lives under the pinned OpenCodex home, so it follows the homes too. const tokenFile = serviceApiTokenFileUnder(homes.opencodexHome); return `${pinnedServiceHomeShellAssignments(homes.codexHome, homes.opencodexHome)} ${buildServiceShellCommand(bun, cli, port, tokenFile)}`; } /** * The exec line the installed launchd plist is expected to carry, derived from the recorded * install state rather than rediscovered: a launcher install runs the launcher, a legacy or * stateless install runs the Bun + CLI pair. `start` and `status` compare the live job * against this, so both must follow the launcher or a healthy launcher-backed job reads as * "an OLDER plist" (#3464). PATH is deliberately NOT re-walked here. * * The pinned homes follow the same rule. A status run from a shell that exports another * CODEX_HOME must still recognise a job loaded from the plist on disk, so the homes come from * that plist, then from the recorded install state, and from the current environment only * when neither records them. A fresh install bakes its own line through * {@link launchdServiceCommand} and does not come through here. */ export function expectedLaunchdCommand( port: number, deps: { state?: ServiceInstallState | null; entry?: { bun: string; cli: string | null }; homes?: LaunchdPinnedHomes; readPlist?: () => string; } = {}, ): string { const state = deps.state === undefined ? readServiceInstallState() : deps.state; const homes = deps.homes ?? installedLaunchdHomes(state, deps.readPlist ?? (() => readFileSync(plistPath(), "utf8"))); const pinned = pinnedServiceHomeShellAssignments(homes.codexHome, homes.opencodexHome); const tokenFile = serviceApiTokenFileUnder(homes.opencodexHome); if (state?.launcherPath) return `${pinned} ${buildServiceLauncherShellCommand(state.launcherPath, port, tokenFile)}`; const entry = deps.entry ?? cliEntry(); return `${pinned} ${buildServiceShellCommand(entry.bun, entry.cli, port, tokenFile)}`; } /** * The `--port ` actually baked into the installed launchd plist, or null when it * cannot be read. macOS only — named for launchd rather than "service" so no caller * assumes it covers systemd or the Windows wrapper. * * `start` needs this because it does NOT rewrite the plist: an install made under * OCX_BAKE_PORT, or any later config.port edit, would otherwise leave launchd serving * one port while the confirmation probes another, failing a healthy service. * * Anchored on the closing tag and matched LAST: the command also carries the Bun and * CLI paths, and a path containing the literal `start --port 9999` must not shadow * the real argument. buildPlist emits the command as the final ProgramArguments * string, and buildServiceShellCommand puts the port at the very end of it. */ export function launchdListenPort(deps: { readPlist?: () => string } = {}): number | null { try { const text = (deps.readPlist ?? (() => readFileSync(plistPath(), "utf8")))(); const last = [...text.matchAll(/start --port (\d{1,5})\s*<\/string>/g)].at(-1); if (!last) return null; const n = Number(last[1]); return n > 0 && n <= 65535 ? n : null; } catch { return null; } } /** * Run `launchctl` and report BOTH streams regardless of exit status. * * `launchctl load` writes "Load failed: : " to stderr and exits 0 for * every already-bootstrapped job. `sh()` above is execSync, which throws only on a * non-zero exit, so install and start both reported success for a load that did * nothing — leaving launchd running the PREVIOUS plist while a freshly written one * sat unused on disk. That is the 2026-08-02 report: `ocx service` prints a * checkmark, `launchctl list` shows the job, and the port answers nothing. * * spawnSync, NOT execFileSync: execFileSync discards stderr when the child exits 0, * which is precisely this case — a runner built on it returns an empty stderr and * the guard below can never fire. Measured on macOS 27.0. */ export function runLaunchctl( args: string[], deps: { run?: typeof spawnSync } = {}, ): { ok: boolean; stdout: string; stderr: string; status: number | null } { const run = deps.run ?? spawnSync; // Only the real runner is guarded. Tests that inject a spawnSync stand-in are // exercising the parsing, not reaching launchd, and must keep working. if (run === spawnSync) assertLiveServiceManagerAllowed(`launchctl ${args.join(" ")}`); const result = run("/bin/launchctl", args, { encoding: "utf8", windowsHide: true }); // `error` is set when the spawn itself failed (ENOENT off macOS) and `status` is // null for a signalled child; neither may be reported as success. if (result.error) { return { ok: false, stdout: "", stderr: String(result.error.message ?? ""), status: null }; } return { ok: result.status === 0, stdout: String(result.stdout ?? "").trim(), stderr: String(result.stderr ?? "").trim(), /* * The NUMBER, not just its zero-ness. * * `launchctl print` distinguishes "that domain does not exist" (112) from * "the domain answered and has no such service" (113), and an ownership * probe needs that difference: the second proves absence, the first only * proves we could not look. Collapsing both into `ok: false` forced callers * to parse stderr, which Apple does not treat as a stable interface. */ status: result.status ?? null, }; } /** * Whether launchctl output indicates the operation did not take. Needed because * `ok` alone is insufficient for the legacy `load`/`unload` subcommands, which * report failure on stderr while exiting 0. `bootstrap` exits 5, so for that path * this is belt-and-braces rather than the only signal. */ export function launchctlLoadFailed(stderr: string): boolean { return /\b(?:Load|Bootstrap) failed\b/i.test(stderr); } /** launchd domain target for the current user's GUI session. */ export function launchdGuiDomain(): string { return `gui/${process.getuid?.() ?? 0}`; } /** * Whether launchd is running the job from the CURRENT plist. `launchctl list` only * proves domain membership — a job bootstrapped from an older plist stays listed * forever. `launchctl print` exposes the live `arguments`, which is the only way to * catch a load that silently no-op'd. */ export function launchdJobMatchesPlist( expectedCommand: string, deps: { run?: typeof runLaunchctl } = {}, ): { loaded: boolean; matchesPlist: boolean } { const run = deps.run ?? runLaunchctl; const printed = run(["print", `${launchdGuiDomain()}/${LABEL}`]); if (!printed.ok) return { loaded: false, matchesPlist: false }; // `print` writes the arguments block to stdout for a live job. Search both streams // anyway so a future launchctl that moves diagnostics between them cannot turn this // into a false negative — a false "stale" verdict would send users to `bootout` for // nothing. const printedText = `${printed.stdout}\n${printed.stderr}`; return { loaded: true, matchesPlist: printedText.includes(expectedCommand) }; } /** `launchctl print`: the domain answered and holds no such service. */ const LAUNCHCTL_NO_SUCH_SERVICE = 113; /** `launchctl print`: that domain does not exist at all (label-independent). */ const LAUNCHCTL_NO_SUCH_DOMAIN = 112; /** `launchctl bootstrap`: something is already bootstrapped under that label. */ const LAUNCHCTL_BOOTSTRAP_BUSY = 5; /** `launchctl bootstrap`: the domain is busy with another operation. */ const LAUNCHCTL_BOOTSTRAP_IN_PROGRESS = 37; /** `launchctl bootout`: nothing was loaded under that label, i.e. already stopped. */ const LAUNCHCTL_BOOTOUT_NO_SUCH_PROCESS = 3; /** * Whether a failed `bootstrap` is the still-tearing-down race rather than a definition that * launchd will never accept. * * Exit 5, and the transient 37 ("Operation already in progress"), are both measured answers * while a booted-out process is still exiting (#8362). A malformed plist (1) or EPERM is NOT * retried: waiting cannot fix it, and the operator needs the real stderr instead of a delayed * copy of it. */ function launchctlBootstrapRacedTeardown(result: { status: number | null; stderr: string; }): boolean { if (result.status === LAUNCHCTL_BOOTSTRAP_BUSY || result.status === LAUNCHCTL_BOOTSTRAP_IN_PROGRESS) { return true; } // The legacy "Load failed" shape keeps the retry it had. A `bootstrap`-prefixed message has // to name a transient NUMBER: "Bootstrap failed: 1: Operation not permitted" and a malformed // plist share the prefix but are not races, and retrying them only delays the real report. return /\b(?:Bootstrap failed: (?:5|37)|Load failed)\b/i.test(result.stderr); } /** * Up to 50 attempts with 49 waits of 500 ms between them (24.5 s), past launchd's 20 s * `ExitTimeOut`, so an unregistered-but-draining job gets the patience the eviction settle * loop gives a registered one. */ const LAUNCHD_BOOTSTRAP_TEARDOWN_ATTEMPTS = 50; const LAUNCHD_BOOTSTRAP_TEARDOWN_DELAY_MS = 500; /** * Bootstrap, waiting out a teardown `launchctl print` cannot see (#8362). * * `bootout` is asynchronous, and a job booted out BY HAND an instant before this command is * in the same window: the label is already UNREGISTERED, so `launchctl print` answers 113 * and the eviction settle loop returns at once — yet `bootstrap` keeps failing 5/EIO until * the previous process is gone. The old recovery retried ONCE, back-to-back, which landed * inside that very window: the first `ocx service restart`/`repair` printed * `installed, not loaded ... no proxy is answering`, and the second run found the domain * quiet and succeeded. * * This waits between attempts instead, and is BOUNDED so a genuinely wedged domain still * reaches the diagnosable throw instead of hanging. `sleepSync` is the same seam the * eviction settle loop uses. */ function bootstrapWaitingOutTeardown( run: typeof runLaunchctl, domain: string, plist: string, sleepSync: (ms: number) => void, ): ReturnType { let result = run(["bootstrap", domain, plist]); for (let attempt = 1; attempt < LAUNCHD_BOOTSTRAP_TEARDOWN_ATTEMPTS; attempt += 1) { if (!launchctlBootstrapRacedTeardown(result)) return result; sleepSync(LAUNCHD_BOOTSTRAP_TEARDOWN_DELAY_MS); result = run(["bootstrap", domain, plist]); } return result; } /** * Every domain target an eviction has to cover. * * {@link probeLaunchdLoadState} asks `gui/` AND `user/` because the two domains * are independent and hold separate service sets, while every MUTATING verb in this file * addressed `gui/` alone. So a `user/`-domain registration of our Label used to: * survive `ocx service stop` (`bootout gui//