@bitkyc08/opencodex
Version:
Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code
1,167 lines • 59.9 kB
text/typescript
import type { ProxyRestartIo, ProxyRestartStartOutcome } from "./tray-proxy";
import type { RestartSupervisor } from "./restart-failure";
/**
* Registry-driven command dispatch (Phase 3 of the CLI deepening).
*
* The command switch moved out of src/cli/index.ts into a runner table keyed
* by command name. Aliases resolve through the registry's alias pairs
* (init/setup, restore/eject, uninstall/remove, models/model); the registry
* remains the single source of command metadata. index.ts passes its local
* helpers (start/stop/ensure/status/...) through CliDispatchDeps so dispatch
* never needs to import the entry module back (no cycle).
*/
import { CLI_COMMANDS } from "./registry";
import { runCliAction } from "./runtime-api";
import { uninstallArgsError, type CliHead } from "./root";
import type { ReadyArgs } from "./ready";
import type { LivenessIo, LiveProxy } from "../server/proxy-liveness";
import type { OcxConfig } from "../types";
import { hasHelpFlag, printSubcommandUsage, printUsage } from "./help";
import { printUnknownCommand } from "./help-recovery";
import {
HUB_GATED_SKIP_MESSAGE,
localClientSkipMessage,
shouldSyncCodexOnStart,
type LocalClientSkipReason,
} from "../codex/desired-state";
import { siblingSkipMessage } from "../codex/sibling-start";
import { setHomeIntegrationEnabled, type HomeIntegrationResult } from "../routing/home-route-capture";
import { syncModelsToCodex } from "../codex/sync";
import { collectOrcaCodexHomeDiagnostic } from "../codex/home";
import { restoreNativeCodexAsync, type CodexNativeRestoreResult } from "../codex/inject";
import { stripGrokConfig } from "../grok/inject";
import { handleRestartScopeAfterWrite, readRestartScope } from "./restart-scope";
import { normalizeUpdateChannel, runGuiUpdateWorker } from "../update/job";
import { isJsonOption, takeFlag } from "./runtime-api";
import { printStopSummary, type StopOutcome } from "./stop-report";
import { parseStopApproval, type StopApproval } from "./stop-approval";
import { resolveStopDeadlineMs, setStopDeadlineMs } from "../service/windows-stop-deadline";
import type { ResolveArgs } from "./resolve";
import type { ClientConnectionState } from "../client/state";
import { OCX_NATIVE_REPLAY_RECOVERY_NOTE } from "../responses/compaction";
import { inspectDesktopSupervision } from "../service/desktop-supervision.mjs";
import { desktopStopNotice } from "./desktop-runtime-guidance";
export interface CliDispatchDeps {
args: string[];
command: string | undefined;
head: CliHead;
loadConfig: () => OcxConfig;
findLiveProxy: (io?: LivenessIo) => Promise<LiveProxy | null>;
probeHostname: (hostname: string | undefined) => string;
waitForProxy: (timeoutMs?: number) => Promise<LiveProxy | null>;
startArgv: (port?: number) => string[];
/** Spawn a detached proxy child (stdio ignore, unref'd, provenance env). */
spawnDetached: (argv: readonly string[]) => void;
handleStart: () => Promise<void>;
handleStop: (approval?: StopApproval) => Promise<StopOutcome>;
inspectDesktopSupervision?: typeof inspectDesktopSupervision;
handleEnsure: (options?: { existingIsSuccess?: boolean }) => Promise<boolean>;
handleResolve: (args: ResolveArgs) => Promise<number>;
handleTrayProxyStart: (existingIsSuccess?: boolean) => Promise<boolean>;
handleTrayProxyRestart: () => Promise<void>;
handleRestartStartWhenStopped: (recoveringLiveRestart?: boolean) => Promise<ProxyRestartStartOutcome>;
/** `bindIo` lets a caller bind the restart to one target (ocx disconnect: src/cli/disconnect-runtime.ts). */
handleProxyRestart: (startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>, onSupervised?: (supervisor: RestartSupervisor) => void, bindIo?: (io: ProxyRestartIo, deadlineAt: number) => ProxyRestartIo) => Promise<boolean>;
handleUninstall: () => Promise<void>;
handleStatus: () => Promise<void>;
handleRecoverHistory: () => Promise<void>;
handleReady: (args: ReadyArgs) => Promise<number>;
serviceCommand: (...args: string[]) => Promise<void>;
}
type CommandRunner = (deps: CliDispatchDeps) => Promise<number>;
/**
* The hub's management ingress is deliberately loopback-only. Prefer it for
* a browser opened on the hub itself: the proxy listener may be restricted to
* a Tailscale address, while the ingress is the local authenticated dashboard.
*/
export function selectDefaultGuiUrl(
config: Pick<OcxConfig, "port" | "hostname" | "runtimeRole" | "hub">,
live: Pick<LiveProxy, "port" | "hostname"> | null,
probeHostname: (hostname: string | undefined) => string,
): string {
const ingress = config.runtimeRole === "hub" ? config.hub?.managementIngress : undefined;
if (ingress?.enabled) return `http://127.0.0.1:${ingress.port}`;
// Keep literal loopback addresses: standalone pairing admits the configured
// origin, so replacing 127.0.0.1 with localhost strands its browser flow.
const guiHost = probeHostname(live?.hostname ?? config.hostname);
return `http://${guiHost}:${live?.port ?? config.port ?? 10100}`;
}
/** An unavailable route-intent file names the file to repair; the other refusals keep their reason. */
function desiredStateRefusal(desired: Extract<HomeIntegrationResult, { ok: false }>): string {
return desired.reason === "unavailable" ? `Codex desired state was not saved (unavailable): ${desired.message}`
: `Codex desired state was not saved (${desired.reason}).`;
}
const commandRunners: Record<string, CommandRunner> = {
init: async () => {
const { runInit } = await import("./init");
await runInit();
// runInit sets process.exitCode = 1 on stdin EOF/closed; preserve it.
return Number(process.exitCode ?? 0);
},
start: async deps => {
const { readClientConnectionState } = await import("../client/state");
const clientState = readClientConnectionState();
await reconcileClientJournalBeforeLifecycle(clientState);
if (clientState.kind === "invalid" || clientState.kind === "mismatched") {
console.error(`Client state is ${clientState.kind}: ${clientState.reason}`);
return 1;
}
await deps.handleStart();
return Number(process.exitCode ?? 0);
},
stop: async deps => {
const parsed = parseStopApproval(deps.args.slice(1));
if (!parsed.ok) {
console.error("Usage: ocx stop [--deadline-ms <ms>] [--json [--expect-pid <pid> --expect-port <port> --expect-hostname <host> --expect-config-home <home> --expect-cli-version <version> --expect-compatibility-token <hex>]]");
return 64;
}
// #7771: the Windows checked stop's deadline, from this process's start (flag, then env, then 60 s).
setStopDeadlineMs(resolveStopDeadlineMs(parsed.deadlineMs));
// Downtime warning lives HERE, not in handleStop: `restart`/tray-restart callers
// re-start the proxy immediately, so warning there would contradict the next line.
const warning = "⚠️ Codex/Claude requests through the proxy will fail until it is restarted ('ocx start' or 'ocx service start').";
if (!parsed.json) {
const notice = desktopStopNotice((deps.inspectDesktopSupervision ?? inspectDesktopSupervision)());
if (notice) console.error(notice);
// handleStop returns the structured outcome now; an object is always truthy, so
// the warning must key on .ok — otherwise a failed stop would still claim downtime.
if ((await deps.handleStop()).ok) console.log(warning);
return Number(process.exitCode ?? 0);
}
// --json is a reporting layer over the SAME stop path: the receipt, the drain, the
// respawn verification and the client-config restore run unchanged. Human output
// still prints, but on stderr, so stdout carries exactly one JSON summary document.
// The exit code (0/1/79/80) crosses the process boundary untouched — the shell reads
// it from the child, and the stop-contract codes must survive the JSON mode.
const humanLog = console.log;
console.log = console.error;
let outcome: StopOutcome | undefined;
try {
outcome = await deps.handleStop(parsed.approval ?? undefined);
if (outcome.ok) console.log(warning);
} finally {
console.log = humanLog;
}
// A throw above propagates after the finally restores the console, so reaching here
// with an undefined outcome cannot happen; the guard keeps the assignment provable.
if (outcome) printStopSummary(outcome.summary);
// A guarded refusal never reaches the code that records process.exitCode, so the
// approval-bound form answers with its summary's code; plain stop keeps its contract.
return parsed.approval ? (outcome?.summary.exitCode ?? 1) : Number(process.exitCode ?? 0);
},
resolve: async deps => {
// Same fail-closed shape as `ready`: parseCliHead pre-parsed the verb before any
// preflight side effect, so a missing resolveArgs means dispatch diverged. Refuse
// with code 64 and perform NO I/O.
if (!deps.head.resolveArgs) return 64;
return await deps.handleResolve(deps.head.resolveArgs);
},
message: async deps => (await import("./message-command")).runMessageCommand(deps.args.slice(1)),
restore: async deps => {
const restoreArgs = deps.args.slice(1);
const restoreJson = takeFlag(restoreArgs, "--json");
const removeProviderTable = takeFlag(restoreArgs, "--remove-codex-provider-table");
if (restoreArgs[0] === "back") {
// Reverse switch: re-point plain `codex` at the RUNNING proxy without touching its
// lifecycle — the counterpart of `ocx restore`. Start/stop triggers are unchanged;
// this only re-runs the same inject (config + catalog + history) `ocx start` does.
// takeFlag above makes `ocx restore --json back` restore-back, not eject.
const { skippedRestoreEnvelope } = await import("../codex/inject");
const emitBack = (success: boolean, message: string, code: number): number => {
if (restoreJson) console.log(JSON.stringify(skippedRestoreEnvelope(success, message)));
else if (code === 0) console.log(message);
else console.error(message);
return code;
};
const live = await deps.findLiveProxy();
if (!live) {
return emitBack(false, "No running proxy found. Run 'ocx start' — it injects opencodex automatically.", 1);
}
const desired = setHomeIntegrationEnabled("codex", true);
if (!desired.ok) {
return emitBack(false, desiredStateRefusal(desired), desired.reason === "conflict" ? 2 : 1);
}
const synced = await syncModelsToCodex(live.port);
if (synced.status === "skipped") {
// `setHomeIntegrationEnabled` above just committed ON, so a skip here is NOT the toggle and
// is not a competing writer either — on a hub it is the role gate. Telling the operator
// to "retry after the competing integration change finishes" sent them waiting for a
// writer that does not exist (#4236).
return emitBack(
false,
synced.skippedReason === "hub-gated"
? `${HUB_GATED_SKIP_MESSAGE} restore back did not change Codex.`
: "Codex integration is OFF; restore back did not change Codex. Retry after the competing integration change finishes.",
2,
);
}
if (!synced.ok) {
return emitBack(false, "Plain `codex` was not switched back to opencodex. Fix the reported Codex config issue and retry.", 1);
}
const target = collectOrcaCodexHomeDiagnostic();
return emitBack(true, `Plain \`codex\` now routes through opencodex in ${target.effectiveCodexHome} (undo with: ocx restore).`, 0);
}
if (removeProviderTable && !restoreJson) {
console.log("⚠️ Removing [model_providers.opencodex] means conversations already tagged opencodex will stop opening.");
}
const desired = setHomeIntegrationEnabled("codex", false);
if (!desired.ok) {
if (restoreJson) {
// Machine-readable contract: every restore --json outcome emits one
// schema-complete envelope on stdout, including pre-machinery failures.
const { skippedRestoreEnvelope } = await import("../codex/inject");
console.log(JSON.stringify(skippedRestoreEnvelope(false, desiredStateRefusal(desired))));
} else {
console.error(desiredStateRefusal(desired));
}
return desired.reason === "conflict" ? 2 : 1;
}
// A repeated OFF on an already-clean home is a policy no-op. Do not enter
// restore's native-profile machinery merely to prove there is nothing to
// restore: those locks live in CODEX_HOME and a skip must create nothing.
if (desired.status === "unchanged") {
const { classifyNativeRoutedResidue } = await import("../codex/native-residue");
if (classifyNativeRoutedResidue().kind === "clean") {
// The Codex half being a no-op says nothing about the Grok half. Returning here
// without stripping the fence meant `ocx restore` could report success while Grok
// still pointed at a stopped proxy — and the deferred-teardown recovery path
// (#3008) tells operators to run exactly this command before deleting a receipt,
// so the incomplete teardown would be signed off and the obligation erased.
let grokNote = "";
let grokCode = 0;
try {
const g = stripGrokConfig();
if (g.changed) grokNote = ` ${g.message}`;
else if (!g.ok) { grokNote = ` Grok config cleanup failed: ${g.message}`; grokCode = 1; }
} catch (err) {
grokNote = ` Grok config cleanup failed: ${err instanceof Error ? err.message : String(err)}`;
grokCode = 1;
}
const alreadyOff = `Codex integration is already OFF and native; no Codex files changed.${grokNote}`;
if (restoreJson) {
const { skippedRestoreEnvelope } = await import("../codex/inject");
console.log(JSON.stringify(skippedRestoreEnvelope(grokCode === 0, alreadyOff)));
} else if (grokCode === 0) {
console.log(alreadyOff);
} else {
console.error(alreadyOff);
}
return grokCode;
}
}
let r: CodexNativeRestoreResult | Pick<CodexNativeRestoreResult, "success" | "message">;
try {
r = await restoreNativeCodexAsync({ revalidateDesiredState: true, removeProviderTable });
} catch (err) {
r = { success: false, message: err instanceof Error ? err.message : String(err) };
}
// Grok BEFORE either output. The JSON path used to return here, so `ocx restore --json`
// (and `ocx eject --json`, the same runner) could report success while the fence still
// pointed at the stopped proxy — and the deferred-teardown recovery on this branch
// tells operators to run exactly this before deleting a receipt (#3008).
let grokFailure: string | null = null;
let grokChangedMessage: string | null = null;
try {
const g = stripGrokConfig();
if (g.changed) grokChangedMessage = g.message;
else if (!g.ok) grokFailure = g.message;
} catch (err) {
grokFailure = err instanceof Error ? err.message : String(err);
}
if (restoreJson) {
// Spawned callers need the artifact-level result to distinguish a busy
// history worker from a successful native restore. Keep stdout machine
// readable — the Codex artifact schema is unchanged; the Grok outcome is
// folded into success/message so a caller cannot read a half teardown as done.
const message = grokFailure
? `${r.message} Grok config cleanup failed: ${grokFailure}`
: grokChangedMessage ? `${r.message} ${grokChangedMessage}` : r.message;
console.log(JSON.stringify({ ...r, success: r.success && !grokFailure, message }));
return r.success && !grokFailure ? 0 : 1;
}
if (r.success) console.log(`✅ ${r.message}`);
else {
console.error(`⚠️ ${r.message}`);
}
let code = r.success ? 0 : 1;
if (grokChangedMessage) console.log(`✅ ${grokChangedMessage}`);
if (grokFailure) {
console.error(`⚠️ ${grokFailure}`);
code = 1;
}
if (r.success) {
const retained = "retainedCodexProviderTable" in r ? r.retainedCodexProviderTable : undefined;
if (retained) {
console.log("Codex integration is OFF and plain `codex` now runs natively.");
console.log("The following lines remain in $CODEX_HOME/config.toml because conversations already tagged opencodex resolve their provider only through this table:");
console.log(retained.lines.join("\n"));
console.log(`Follow-up: ${retained.followUp}`);
console.log("Switch back with: ocx restore back");
} else {
console.log("Codex integration is OFF and plain `codex` now runs natively. Switch back with: ocx restore back");
}
console.log(`Note: ${OCX_NATIVE_REPLAY_RECOVERY_NOTE}`);
} else {
console.error("Plain `codex` was not fully restored. Inspect $CODEX_HOME/config.toml before using native Codex.");
}
return code;
},
"recover-history": async deps => {
await deps.handleRecoverHistory();
return Number(process.exitCode ?? 0);
},
uninstall: async deps => {
const error = uninstallArgsError("uninstall", deps.args);
if (error) {
console.error(error);
return 2;
}
await deps.handleUninstall();
return Number(process.exitCode ?? 0);
},
status: async deps => {
await deps.handleStatus();
return Number(process.exitCode ?? 0);
},
doctor: async deps => {
const doctorArgs = deps.args.slice(1);
// `--json` was silently ignored here: runDoctor scans for its own flags and prints human
// output regardless, so a caller that asked for JSON got prose and exit 0 -- and the skill
// recipes recommended exactly that invocation. Refusing it is worse than supporting it and
// better than lying about it.
//
// Not implemented rather than deferred silently: runDoctor has no report collection at all
// (a module-level failure bit plus ~90 direct console emissions), and this runner appends
// the Codex Log Guard's human output after it returns, so emitting a JSON document here
// would interleave prose with JSON on one stdout -- unparseable, which is worse than the
// ignored flag. The structured-report refactor is tracked as its own work-phase.
if (doctorArgs.some(isJsonOption)) {
console.error("ocx doctor does not support --json yet. Run `ocx doctor` for the human report, or use `ocx status --json` and `ocx ready --json` for machine-readable health.");
return 2;
}
const { RECOVER_ZERO_BYTE_COORDINATOR_FLAG, runDoctor, doctorFailed } = await import("./doctor");
await runDoctor(doctorArgs);
if (!doctorArgs.includes("--fix-codex-runtime") && !doctorArgs.includes(RECOVER_ZERO_BYTE_COORDINATOR_FLAG)) {
console.log("");
const { printCodexLogGuardDoctor } = await import("./codex-log-guard-doctor");
printCodexLogGuardDoctor();
}
// A diagnostic that always exits 0 cannot gate a script. `runDoctor` reports by direct
// console.log with no checks collection, and signals its own special-flag failures
// through process.exitCode, so honour both: an explicit exitCode wins, otherwise a
// FAIL-level check fails the command. This is a BREAKING change for pipelines that ran
// `ocx doctor` and ignored the result; a diagnostic that cannot fail is worse.
const explicit = Number(process.exitCode ?? 0);
if (explicit !== 0) return explicit;
return doctorFailed() ? 1 : 0;
},
debug: async deps => {
const { handleDebugCommand } = await import("./debug");
await handleDebugCommand(deps.args.slice(1));
return 0;
},
ensure: async deps => {
const { readClientConnectionState } = await import("../client/state");
const clientState = readClientConnectionState();
await reconcileClientJournalBeforeLifecycle(clientState);
if (clientState.kind !== "disconnected") {
console.error(clientState.kind === "connected"
? "Client mode does not start a local provider proxy; use 'ocx sync'."
: `Client state is ${clientState.kind}: ${clientState.reason}`);
// A validated client delegates inference to its hub; no local startup is needed.
return clientState.kind === "connected" ? 0 : 1;
}
await deps.handleEnsure();
return Number(process.exitCode ?? 0);
},
login: async deps => {
const loginArgs = deps.args.slice(1);
// `--headless` is the only flag this command takes; the provider is the first bare word, so
// `ocx login --headless anthropic` and `ocx login anthropic --headless` mean the same thing.
// It is deliberately not `--code`: that name carries a secret value everywhere else in the
// CLI (`ocx account login <provider> --code <value>`) and its operand is scrubbed from stderr.
const codeMode = loginArgs.includes("--headless");
const acceptAntigravityRisk = loginArgs.includes("--accept-antigravity-risk");
const positional = loginArgs.filter(arg => !arg.startsWith("--"));
// 'ocx login codex' is the command people type first, and until now it answered with
// the full provider wall because the Codex pool lives behind 'ocx account login'.
// Route the three Codex spellings to that flow instead of making the user discover
// a second noun. Everything else stays on the local OAuth/API-key path.
const { isCodexAccountLoginName, handleAccountAuthCommand } = await import("./account-auth");
if (isCodexAccountLoginName(positional[0] ?? "")) {
// `--headless` is the OAuth code-display mode, which Codex does not have; account-auth
// would reject the flag as an unexpected argument. Codex's headless path is the device-code
// login, so point there instead.
if (codeMode) {
console.error("Codex has no code-display login. For a headless host use: ocx account login codex --device");
return 1;
}
// null means "unknown subcommand", which "login" never is; the coalesce exists because
// the shared signature serves callers that do pass an unknown one.
const code = await handleAccountAuthCommand("login", loginArgs, { findLiveProxy: deps.findLiveProxy });
return code ?? 1;
}
const { handleLogin } = await import("../oauth/login-cli");
await handleLogin(positional[0], {}, { codeMode, acceptAntigravityRisk });
return 0;
},
logout: async deps => {
const { handleLogoutCommand } = await import("./logout-command");
return handleLogoutCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
sync: async deps => (await import("./sync-update-guard")).withSyncUpdateGuard(async () => (await import("./sync-command")).runSyncCommand(deps), deps.args),
v2: async deps => {
const { cmdV2 } = await import("./v2");
return await cmdV2(deps.args.slice(1), { runtimeApi: { findLiveProxy: deps.findLiveProxy } }, async () => (await deps.findLiveProxy())?.port);
},
connect: async deps => {
const { isGatewayClientOperand, runGatewayClientFromArgs } = await import("./gateway-client-command");
if (isGatewayClientOperand(deps.args[1])) return await runGatewayClientFromArgs("connect", deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
const { handleConnectCommand } = await import("./connect");
return await handleConnectCommand(deps.args.slice(1));
},
link: async deps => {
const { runLinkCommand } = await import("./link");
return await runLinkCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
"remote-workspace": async deps => {
const { runRemoteWorkspaceCommand } = await import("./remote-workspace");
return await runRemoteWorkspaceCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
disconnect: async deps => {
const { isGatewayClientOperand, runGatewayClientFromArgs } = await import("./gateway-client-command");
if (isGatewayClientOperand(deps.args[1])) return await runGatewayClientFromArgs("disconnect", deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
const { handleDisconnectCommand } = await import("./connect");
const code = await handleDisconnectCommand(deps.args.slice(1));
// Token recovery refuses any live client runtime and leaves nothing to restart.
if (code !== 0 || deps.args.includes("--orphaned-token")) return code;
const { bindRestartToRuntime, restartRuntimeAfterDisconnect } = await import("./disconnect-runtime");
const { observeProxyLiveness } = await import("../server/proxy-liveness");
const { readClientConnectionStateWithEvidence } = await import("../client/state");
const { readRuntimePort } = await import("../config/process-state");
const { requestBoundSystemRestart } = await import("./system-restart-client");
return await restartRuntimeAfterDisconnect({
observe: () => observeProxyLiveness({ attempts: 2 }),
capture: live => {
if (live.pid === null) return null;
const record = readRuntimePort(live.pid);
return record?.attestationSecret && record.pid === live.pid && record.port === live.port
? { ...record, attestationSecret: record.attestationSecret } : null;
},
connectionState: () => {
const state = readClientConnectionStateWithEvidence();
return state.kind === "invalid" || state.kind === "mismatched" ? { kind: state.kind, reason: state.reason } : { kind: state.kind };
},
restart: async target => {
let refusedBy: "service-unproven" | undefined;
const ok = await deps.handleProxyRestart(deps.handleRestartStartWhenStopped, supervisor => { if (supervisor === "service-unproven") refusedBy = supervisor; }, (io, deadlineAt) =>
bindRestartToRuntime(io, target, (previous, readRuntime) =>
requestBoundSystemRestart(previous as Parameters<typeof requestBoundSystemRestart>[0], deadlineAt, { readRuntime: readRuntime as typeof readRuntimePort })));
return { ok, ...(refusedBy ? { refusedBy } : {}) };
},
json: deps.args.includes("--json"),
});
},
catalog: async deps => {
const { handleCatalogCommand } = await import("./catalog");
return await handleCatalogCommand(deps.args.slice(1));
},
"sync-cache": async deps => {
const cacheArgs = deps.args.slice(1);
const restartScope = readRestartScope(cacheArgs, console);
const { withCatalogWriteSerialization } = await import("../codex/catalog-write-serialization");
const { invalidateCodexModelsCacheWithPermitOutcome } = await import("../codex/catalog/sync");
const { getCodexHome } = await import("../codex/paths");
const owningCodexHome = getCodexHome();
const cacheGateSnapshot = deps.loadConfig();
const desiredDisabled = !shouldSyncCodexOnStart(cacheGateSnapshot);
const invalidated = withCatalogWriteSerialization(owningCodexHome, permit =>
invalidateCodexModelsCacheWithPermitOutcome(permit, owningCodexHome, { allowWhenDesiredDisabled: true }),
{ intent: "cache", writer: "sync-cache" });
const cacheJson = cacheArgs.includes("--json");
const jsonSafeLog = cacheJson
? { log: (...values: unknown[]) => console.error(...values), error: (...values: unknown[]) => console.error(...values) }
: console;
// Only warn/restart when models_cache was actually rewritten from a readable catalog.
if (invalidated.kind === "completed" && invalidated.value === "written") {
await handleRestartScopeAfterWrite(restartScope, jsonSafeLog);
} else if (!cacheJson && invalidated.kind === "completed" && invalidated.value === "desired_disabled") {
// Only when the OFF gate itself stopped the write does OFF explain the outcome. An
// explicit sync-cache refreshes regardless of the toggle, so an unchanged cache, a
// missing catalog, or a contended writer is reported below on its own terms.
// Under --json this belongs on the envelope, not as a second stdout line.
console.log(localClientSkipMessage(
cacheGateSnapshot,
"Codex integration is OFF; no catalog or cache write resulted.",
"No catalog or cache write resulted.",
));
}
// An identical cache is a successful no-op, not a failed refresh. Only a real write
// should restart Codex; a missing catalog or contended writer is also a benign skip.
//
// Losing the catalog write lock to another process is a skip, not a failure:
// serialization working as designed is the expected outcome under concurrency, and a
// proxy startup holding the permit would otherwise make a perfectly healthy
// `ocx sync-cache` exit 1 and fail the pipeline that called it -- intermittently, so it
// would read as a flake rather than a bug. `codex-retained-root-serialization.test.ts`
// pins exactly that: contended lock, no cache write, exit 0.
//
// `desiredDisabled` is deliberately NOT part of the success test, which is the subtle
// part. This call passes `allowWhenDesiredDisabled: true`, so the OFF gate inside the
// refresh never fires and the work is genuinely attempted -- an explicit `ocx sync-cache`
// means the user asked for it regardless of the toggle. Treating OFF as automatic success
// would report exit 0 and `skipped: true` for a refresh that actually failed.
//
// The detailed outcome distinguishes an unchanged cache from a failed rewrite while
// the boolean wrapper remains available to callers that only care whether bytes changed.
const wrote = invalidated.kind === "completed" && invalidated.value === "written";
const unchanged = invalidated.kind === "completed" && invalidated.value === "unchanged";
const contended = invalidated.kind === "unavailable" && invalidated.reason === "busy";
const noCatalog = invalidated.kind === "completed" && invalidated.value === "missing_catalog";
const ok = wrote || unchanged || contended || noCatalog;
if (cacheJson) {
console.log(JSON.stringify({
schemaVersion: 1,
ok,
wrote,
skipped: unchanged || contended || noCatalog,
outcome: invalidated.kind,
// `outcome` alone cannot separate a contended lock from a hard serialization
// failure -- both are `unavailable`. Carry the reason so a caller can.
reason: invalidated.kind === "unavailable" ? invalidated.reason : undefined,
// Which of the three benign skips this was, so `skipped: true` is never opaque.
skippedReason: unchanged ? "unchanged" : contended ? "contended" : noCatalog ? "no_catalog" : undefined,
desiredDisabled,
codexHome: owningCodexHome,
}, null, 2));
} else if (contended) {
console.log("Another process owns the catalog write; cache sync skipped.");
} else if (noCatalog) {
console.log("No Codex catalog to derive a cache from; nothing to sync.");
} else if (unchanged) {
console.log("Codex model cache is already current; nothing to sync.");
} else if (invalidated.kind === "unavailable"
&& (invalidated.reason === "foreign-owner" || invalidated.reason === "owner-unknown")) {
const { FOREIGN_CODEX_HOME_OWNER_MESSAGE, UNKNOWN_CODEX_HOME_OWNER_MESSAGE } = await import("../codex/catalog/routed-removal");
console.error(invalidated.reason === "foreign-owner" ? FOREIGN_CODEX_HOME_OWNER_MESSAGE : UNKNOWN_CODEX_HOME_OWNER_MESSAGE);
} else if (!ok) {
console.error(`Cache refresh did not complete (${invalidated.kind}). The Codex model cache was not rewritten.`);
}
return ok ? 0 : 1;
},
gui: async deps => {
const { runGuiCommand } = await import("./gui");
return runGuiCommand(deps.args.slice(1), {
loadConfig: deps.loadConfig,
findLiveProxy: deps.findLiveProxy,
openDefaultGui: async () => {
const config = deps.loadConfig();
// Identity-checked liveness (not the pid file + a fixed sleep): finds a fallback-port
// proxy and waits until the spawned one actually answers before opening the browser.
let live = await deps.findLiveProxy();
if (!live) {
console.log("Proxy not running. Starting...");
deps.spawnDetached(deps.startArgv((config.port ?? 10100) > 0 ? (config.port ?? 10100) : undefined));
live = await deps.waitForProxy();
if (!live) {
console.error("❌ Proxy did not become healthy after starting. Not opening the GUI.");
return 1;
}
}
const guiUrl = selectDefaultGuiUrl(config, live, deps.probeHostname);
console.log(`Opening ${guiUrl}`);
const { openUrl } = await import("../lib/open-url");
// Awaited so a launcher that never opened anything is said out loud (#5261). Still exit
// 0: the proxy is serving and the URL above is reachable, only the launch did not happen.
if ((await openUrl(guiUrl)).status === "failed") {
console.error("⚠️ No browser could be opened here; open the URL above yourself.");
}
return 0;
},
});
},
hub: async deps => {
const { runHubCommand } = await import("./hub");
return runHubCommand(deps.args.slice(1), {
loadConfig: deps.loadConfig,
findLiveProxy: deps.findLiveProxy,
});
},
service: async deps => {
process.exitCode = 0;
await deps.serviceCommand(...deps.args.slice(1));
// serviceCommand uses process.exitCode for recoverable install/stop failures
// that must finish cleanup before the single top-level process.exit runs.
return Number(process.exitCode ?? 0);
},
tray: async deps => {
const { windowsTrayCommand } = await import("../tray/windows");
// windowsTrayCommand reports failure through process.exitCode (tray/windows.ts sets
// it for bad usage and for a failed install/start/stop/uninstall) and returns void,
// so a literal 0 here made `ocx tray install` print an error and exit 0 (#2697).
process.exitCode = 0;
await windowsTrayCommand(deps.args.slice(1));
return Number(process.exitCode ?? 0);
},
"codex-shim": async deps => {
const { codexShimStatus, diagnoseCodexShim, installCodexShimAsync, uninstallCodexShimAsync } = await import("../codex/shim");
switch (deps.args[1]) {
case "install": {
const r = await installCodexShimAsync();
const { healthy, runnable, active, summary } = diagnoseCodexShim();
const success = !r.refused && (runnable ?? healthy);
const { collectCodexShimReadinessWarnings } = await import("./codex-shim-readiness");
const warnings = success
? collectCodexShimReadinessWarnings()
: [];
console.log(`${success && healthy && warnings.length === 0 ? "✅ " : "⚠️ "}${r.message}`);
for (const warning of warnings) console.warn(` ${warning}`);
if (success && active !== undefined && active !== true) {
const { overlayActivationHint } = await import("../codex/shim-overlay");
console.warn(` ${overlayActivationHint()}`);
}
if (!success) console.error(`${r.refused ? "Codex shim installation was refused" : "Codex shim installation is unhealthy"}: ${summary}`);
return success ? 0 : 1;
}
case "status": {
const extra = deps.args.slice(2);
if (extra.length > 0) {
console.error(extra.some(isJsonOption)
? "ocx codex-shim status does not support --json; use ocx status --json (codexShim)."
: "ocx codex-shim status does not accept arguments or options.");
console.error("Usage: ocx codex-shim status");
return 2;
}
console.log(codexShimStatus());
break;
}
case "uninstall":
case "remove": {
const r = await uninstallCodexShimAsync();
console.log(r.removed ? `✅ ${r.message}` : `⚠️ ${r.message}`);
if (r.refused) return 1;
break;
}
default:
console.error("Usage: ocx codex-shim <install|status|uninstall|remove>");
return 1;
}
return 0;
},
update: async deps => {
// #8246: the headless Windows Desktop updater has its own grammar (including --json) and never
// reaches the package or orchestrated updater.
if (deps.args.slice(1).includes("--desktop") && !hasHelpFlag(deps.args.slice(1))) {
return (await import("../desktop-update/cli")).runHeadlessDesktopUpdateCommand(deps.args.slice(1));
}
const { isOrchestratedUpdateArgv, parseOrchestratedChildArgs } = await import("../update/orchestrated-arguments.mjs");
if (process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1" && deps.args.slice(1).some(arg => /^--orchestrated-(expect|result)(?:=|$)/.test(arg))) {
const child = parseOrchestratedChildArgs(deps.args.slice(1), process.env);
if (!child.ok) return 64;
await (await import("../update")).runUpdate(child);
return Number(process.exitCode ?? 0);
}
if (isOrchestratedUpdateArgv(deps.args.slice(1))) return (await import("../update/orchestrated-entry")).runOrchestratedUpdate(deps.args.slice(1));
// `ocx update --help` must print usage and exit WITHOUT side effects — running the
// real self-update stops the proxy and drops in-flight routed streams (issue #168).
if (hasHelpFlag(deps.args.slice(1))) {
printSubcommandUsage("update");
return 0;
}
const { runUpdate } = await import("../update");
await runUpdate();
return Number(process.exitCode ?? 0);
},
"__refresh-version": async deps => {
// Hidden, detached helper spawned by the update prompt to refresh the
// cached latest version without blocking the foreground start. Not in help.
const { refreshVersionCache } = await import("../update/notify");
const channel = deps.args[1] === "preview" ? "preview" : "latest";
await refreshVersionCache(channel);
return 0;
},
"__update-badge": async deps => {
if (deps.args.length !== 1) {
console.error("Usage: ocx __update-badge");
return 64;
}
const { readUpdateBadge } = await import("../update/badge");
console.log(JSON.stringify(readUpdateBadge()));
return 0;
},
"__tray-start": async deps => {
return (await deps.handleTrayProxyStart()) ? 0 : 1;
},
"__tray-restart": async deps => {
await deps.handleTrayProxyRestart();
return Number(process.exitCode ?? 0);
},
"__startup-health": async deps => {
const { collectStartupHealth } = await import("../codex/autostart-health");
console.log(JSON.stringify(collectStartupHealth(deps.loadConfig())));
return 0;
},
"__tray-host": async () => {
const { runWindowsTrayHost } = await import("../tray/windows");
await runWindowsTrayHost();
return 0;
},
"__gui-update-worker": async deps => {
const jobId = deps.args[1];
if (!jobId) return 1;
const channel = normalizeUpdateChannel(deps.args[2]);
await runGuiUpdateWorker(jobId, channel, deps.args[3] === "restart");
return 0;
},
restart: async deps => {
// The running proxy owns its drain and replacement through /api/system/restart.
// If nothing is live, restart degrades to the documented `ensure` start behavior.
await deps.handleProxyRestart(deps.handleRestartStartWhenStopped);
return Number(process.exitCode ?? 0);
},
capabilities: async deps => {
const { runCapabilities } = await import("./capabilities-command");
return await runCapabilities(deps.args.slice(1));
},
health: async deps => {
const healthArgs = deps.args.slice(1);
if (healthArgs.length > 1 || (healthArgs.length === 1 && healthArgs[0] !== "--json")) {
console.error("Usage: ocx health [--json]\nSee: ocx help health");
return 2;
}
const wantsHealthJson = healthArgs.includes("--json");
// A proxy that has only just bound can miss a single probe while its event loop
// is still settling startup work — the same just-started race the stop paths
// already retry for (#764, SERVICE_STOP_LIVENESS). Without this, `ocx health`
// run seconds after a service restart reports a false negative on a proxy that
// is in fact serving.
const live = await deps.findLiveProxy({ attempts: 3 });
if (wantsHealthJson) {
console.log(JSON.stringify({ ok: !!live, pid: live?.pid ?? null, port: live?.port ?? null }));
} else {
console.log(live ? `Proxy healthy (PID ${live.pid}, port ${live.port})` : "Proxy not healthy");
}
return live ? 0 : 1;
},
ready: async deps => {
// Fail-closed impossible-state guard: readyArgs is populated by the
// preparse block in src/cli/root.ts before maybeAutoRestoreCodexShimAsync, so
// reaching here without it means dispatch diverged. Refuse with code 64
// and perform NO I/O (no discovery/probe). process.exit is `never`,
// narrowing below.
const readyArgs = deps.head.readyArgs;
if (!readyArgs) return 64;
return await deps.handleReady(readyArgs);
},
provider: async deps => {
const { handleProviderCommand } = await import("./provider");
// Reset first, like the service runner below: reading process.exitCode only
// reports THIS command's outcome if nothing earlier in the process set it.
process.exitCode = 0;
const code = await runCliAction(() => handleProviderCommand(deps.args.slice(1)));
// handleProviderCommand reports failure through process.exitCode, which it sets
// from handleProviderRuntimeCommand. Returning a literal 0 here made index.ts
// call process.exit(0) and erase it, so `ocx provider quota` against a stopped
// proxy printed an error and still exited 0 (#2697).
return code || Number(process.exitCode ?? 0);
},
account: async deps => {
const { cmdAccount } = await import("./account");
return await cmdAccount(deps.args.slice(1));
},
models: async deps => {
const { handleModels } = await import("./models");
process.exitCode = 0;
const code = await runCliAction(() => handleModels(deps.args.slice(1)));
// Same as the provider runner above: handleModels sets process.exitCode from
// handleModelsRuntimeCommand, and a literal 0 discarded it (#2697).
return code || Number(process.exitCode ?? 0);
},
alias: async deps => {
const { handleAliasCommand } = await import("./alias");
return await handleAliasCommand(deps.args.slice(1));
},
combo: async deps => {
const { handleComboCommand } = await import("./combo");
return await handleComboCommand(deps.args.slice(1));
},
advisor: async deps => {
const { handleAdvisorCommand } = await import("./advisor");
return await handleAdvisorCommand(deps.args.slice(1));
},
companion: async deps => {
const { handleCompanionCommand } = await import("./companion");
return await handleCompanionCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
route: async deps => {
if (deps.args[1] === "to") {
const { handleRouteToCommand } = await import("./route-to");
return await handleRouteToCommand(deps.args.slice(2), { findLiveProxy: deps.findLiveProxy });
}
if (deps.args[1] !== "combo" && deps.args[1] !== "policy") {
console.error("Usage: ocx route <to|combo|policy> <subcommand>");
return 2;
}
if (deps.args[1] === "combo") {
const { handleComboCommand } = await import("./combo");
return await handleComboCommand(deps.args.slice(2));
} else {
const { handleRoutePolicyCommand } = await import("./route-policy");
return await handleRoutePolicyCommand(deps.args.slice(2));
}
},
effort: async deps => {
const { handleEffortCommand } = await import("./effort");
return await handleEffortCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
fallback: async deps => {
const { handleFallbackCommand } = await import("./fallback");
return await handleFallbackCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
agent: async deps => {
const { handleAgentCommand } = await import("./agent");
return await handleAgentCommand(deps.args.slice(1));
},
observe: async deps => {
const { handleObserveCommand } = await import("./observe");
return await handleObserveCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
inspect: async deps => {
const { handleInspectCommand } = await import("./inspect");
return await handleInspectCommand(deps.args.slice(1));
},
logs: async deps => {
const { handleObserveCommand } = await import("./observe");
return await handleObserveCommand([deps.command!, ...deps.args.slice(1)], { findLiveProxy: deps.findLiveProxy });
},
usage: async deps => {
const { handleObserveCommand } = await import("./observe");
return await handleObserveCommand([deps.command!, ...deps.args.slice(1)], { findLiveProxy: deps.findLiveProxy });
},
storage: async deps => {
// `ocx storage` used to be a pure alias of `observe storage`, which reached only the report
// route. wp7 gave it cleanup, trash, and policy subcommands, so it dispatches to its own
// module -- with `report` as the default subcommand, so a bare `ocx storage` still prints
// the same thing it printed before.
const { handleStorageCommand } = await import("./storage");
return await handleStorageCommand(deps.args.slice(1));
},
memory: async deps => {
const { handleObserveCommand } = await import("./observe");
return await handleObserveCommand([deps.command!, ...deps.args.slice(1)]);
},
access: async deps => {
const { handleAccessCommand } = await import("./access");
return await handleAccessCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
"api-key": async deps => {
const { handleAccessCommand } = await import("./access");
return await handleAccessCommand(["key", ...deps.args.slice(1)], { findLiveProxy: deps.findLiveProxy });
},
api: async deps => {
const { handleApiCommand } = await import("./api-protocols");
return await handleApiCommand(deps.args.slice(1));
},
export: async deps => {
const { handleExportCommand } = await import("./export-command");
return await handleExportCommand(deps.args.slice(1));
},
grok: async deps => {
const { handleGrokCommand } = await import("./integrations");
return await handleGrokCommand(deps.args.slice(1));
},
integration: async deps => {
const integration = deps.args[1];
if (integration === "grok") {
const { handleGrokCommand } = await import("./integrations");
return await handleGrokCommand(deps.args.slice(2));
} else if (integration === "native") {
// The native client toggles are a separate server surface from the reversible file
// integrations `client` manages, so they get their own subcommand rather than being
// folded into one that means something else.
const { handleIntegrationCommand } = await import("./inspect");
return await handleIntegrationCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
} else if (integration === "claude") {
const { handleClaudeConfigCommand } = await import("./integrations");
return await handleClaudeConfigCommand(deps.args.slice(2));
} else if (integration === "client") {
const { handleClientIntegrationCommand } = await import("./integrations");
return await handleClientIntegrationCommand(deps.args.slice(2), { findLiveProxy: deps.findLiveProxy });
} else {
console.error("Usage: ocx integration <claude|grok|client|native> <subcommand>\nSee: ocx help integration");
return 2;
}
},
system: async deps => {
const { handleSystemCommand } = await import("./system-command");
return await handleSystemCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
},
config: async deps => {
const { handleConfigCommand } = await import("./config-command");
return await handleConfigCommand(deps.args.slice(1));
},
lab: async deps => {
const { handleLabCommand } = await import("./lab");
return await handleLabCommand(deps.args.slice(1));
},
"codex-provider": async deps => {
const { handleCodexProviderCommand } = await import("./codex-provider");
return await handleCodexProviderCommand(deps.args.slice(1));
},
chatgpt: async deps => {
const { handleChatgptCommand } = await import("./chatgpt-command");
return await handleChatgptCommand(deps.args.slice(1));
},
claude: async deps => {
const { cmdClaude } = await import("./claude");
// "ocx claude desktop" → write Desktop 3P config
if (deps.args[1] === "desktop") {
const { handleClaudeDesktopCommand } = await import("./claude-desktop");
const exitCode = await handleClaudeDesktopCommand(deps.args.slice(2), { findLiveProxyImpl: deps.findLiveProxy });
if (exitCode !== 0) return exitCode;
return 0;
}
if (deps.args[1] === "intercept") {
const { handleClaudeInterceptCommand } = await import("./integrations");
return await handleClaudeInterceptCommand(deps.args.slice(2));
}
if (deps.args[1] === "config") {
const { handleClaudeConfigCommand } = await import("./integrations");
return await handleClaudeConfigCommand(deps.args.slice(2));
}
return await cmdClaude(deps.args.slice(1));
},
codex: async deps => {
const { cmdCodex } = await import("./codex-launcher");
return await cmdCodex(deps.args.slice(1));
},
opencode: async deps => {
const { cmdOpencode } = await import("./opencode");
return await cmdOpencode(deps.args.slice(1));
},
mcode: async deps => {
const { cmdMcode } = await import("./minimax");
return await cmdMcode(deps.args.slice(1));
},
mmx: async deps => {
const { cmdMmx } = await import("./minimax");
return await cmdMmx(deps.args.slice(1));
},
zcode: async deps => {
const { handleZcodeCommand } = await import("./integrations");
return await handleZcodeCommand(deps.args.slice(1));
},
commandcode: async deps => {
const { handleCommandcodeCommand } = await import("./integrations");
return await handleCommandcodeCommand(deps.args.slice(1));
},
cmd: async deps => {
const { handleCommandcodeCommand } = await import("./integrations");
return await handleCommandcodeCommand(deps.args.slice(1));
},
telemetry: async deps => {
const { handleTelemetryCommand } = await import("./telemetry");
return await handleTelemetryCommand(deps.args.slice(1));
},
help: async () => {
printUsage();
return 0;
},
"--help": async () => {
printUsage();
return 0;
},
"-h": async () => {
printUsage();
return 0;
},
};
/** Registry alias pairs → canonical dispatch name (init/setup, restore/eject, …). */
const aliasTargets = new Map<string, string>();
for (const entry of CLI_COMMANDS) {
for (const alias of entry.aliases ?? []) aliasTargets.set(alias, entry.name);
}
export const DISPATCH_COMMANDS: ReadonlySet<string> = new Set(Object.keys(commandRunners));
export const DISPATCH_ALIASES: ReadonlyMap<string, string> = aliasTargets;
/** Resolve the runner key for a command, following registry aliases to the
* canonical runner. Returns undefined when the command is unknown. */
/** What `handleStart` does about a live proxy it found before binding. */
export type StartOwnerDecision = "refuse" | "service-stay-out" | "sibling" | "await-parent";
/**
* Pure decision for `handleStart` when the pre-bind probe found a live proxy.
*
* The #3106 guard exists so a bare `start` cannot shadow a healthy configured-port
* proxy with an ephemeral-port copy. An interactive `--port X` naming a DIFFERENT
* port than the live proxy's is an explicit sibling request, not that shadow. The
* state-directory spend-ledger lease makes the final same-home refusal; keeping this
* decision allows isolated homes on one machine to remain independent.
* The service wrapper always passes the configured port and keeps its exact
* stay-out-of-the-way semantics: it never takes the sibling path.
*
* `"await-parent"` comes first and only for an exact pid match: the live proxy is the draining
* process that spawned this start as its restart replacement (`OCX_RESTART_PARENT_PID`, already
* checked against the real parent pid). Refusing it would leave no proxy once that parent exits,
* so the caller waits for it instead (`src/cli/restart-handoff.ts`). Every other owner, and a
* live proxy whose pid could not be verified, keeps the table above.
*/
export function decideStartWithLiveOwner(input: {
livePort: number;
requestedPort: number | undefined;
ocxService: string | undefined;
livePid?: number | null;
restartParentPid?: number | null;
}): StartOwnerDecision {
if (input.restartParentPid != null && input.livePid === input.restartParentPid) return "await-parent";
const sibling = input.requestedPort !== undefined
&& input.requestedPort !== input.livePort
// Only the exact "1" sentinel is service context — the same check the exit teardown
// uses — so an env value like "0" or "false" cannot reach the stay-out path.
&& input.ocxService !== "1";
if (sibling) return "sibling";
return input.ocxService === "1" ? "service-stay-out" : "refuse";
}
/** Which shared client state `handleStart`'s exit cleanup tears down. */
export interface StartExitTeardown {
revertSystemEnv: boolean;
restoreNativeCodex: boolean;
stripGrokConfig: boolean;
}
/**
* Pure exit-teardown decision for `handleStart`'s `syncCleanup`.
*
* A sibling instance tears down nothing: the Codex routing, the Grok fence and the system env
* belong to the live proxy it runs beside, and restoring them would take Codex off a proxy that
* is still serving it (`src/codex/sibling-start.ts`). A dashboard drain-and-restart (#563) keeps
* everything for the replacement process. Under a service manager — only the exact `"1"`
* sentinel — a crash/respawn keeps routing and the fence, and only the environment comes down.
* The caller still applies its own external-provider and service-ownership checks.
*/
export function decideStartExitTeardown(input: {
sibling: boolean;
recycling: boolean;
ocxService: string | undefined;
}): StartExitTeardown {
if (input.sibling || input.recycling) {
return { revertSystemEnv: false, restoreNativeCodex: false, stripGrokConfig: false };
}
const preserveRouting = input.ocxService === "1";
return { revertSystemEnv: true, restoreNativeCodex: !preserveRouting, stripGrokConfig: !preserveRouting };
}
/**
* The one startup line for "nothing was written to Codex".
*
* Three very different facts reach it: the user's own OFF switch, a hub declining to rewrite its
* own local clients, and a sibling instance leaving the live proxy's routing alone. Printing the
* toggle's wording for the gate is what made operators hunt for a switch they never set (#4236).
* `port` is the sibling's own bound port, named in its line.
*/
export function startupLeftCodexNativeLine(reason: LocalClientSkipReason, port?: number): string {
if (reason === "sibling") return ` ${siblingSkipMessage(port)}`;
return reason === "hub-gated"
? ` ${HUB_GATED_SKIP_MESSAGE} Startup left Codex native.`
: " Codex integration OFF; startup left Codex native.";
}
/** What `chooseListenPort` does when the preferred port stayed busy through prefer-retry. */
export type BusyPreferredPortDecision =
| "hop"
| "refuse-live-proxy"
| "service-stay-out"
| "refuse-unidentified-holder";
/**
* Pure decision for a soft `start` whose preferred port is busy and whose only remaining
* option is an ephemeral port.
*
* The hop exists so a first start is not defeated by a port this machine happens to be
* using. What it must never be is a silent answer to "someone is already here": a start
* that hops takes over this home's pid and runtime-port records and re-points Codex at
* itself, so hopping past a live opencodex leaves two proxies running and the editor
* talking to the one the user did not mean (#5004). The hop path never asked who held the
* port, and `findLiveProxy` returning null — a stale record, a probe that lost a race, a
* loopback family split — was enough to reach it.
*
* So the decision is made from the holder's own answer rather than from this home's
* bookkeeping, and both outcomes stop the start. An opencodex answer is the duplicate this
* closes. A holder that does not answer as opencodex is deliberately NOT called foreign:
* an identity probe returns the same nothing for a foreign server, an unreachable one, and
* one that lost a race, so all the start can honestly say is that the port it was told to
* use is taken by something it could not identify — and moving to an arbitrary port is the
* one response that hides that from the user while re-pointing Codex. An explicit
* `--port` never reaches here (`findAvailablePort` refuses the fallback instead), and a
* configured port of 0 is a request for an ephemeral port, not a collision.
*
* Service-wrapper context keeps the semantics `decideStartWithLiveOwner` gives it: a
* healthy proxy on the port means the port is served, and the wrapper's
* retry loop must receive the intentional stay-out signal rather than respawn every 5 seconds.
*/
export function decideBusyPreferredPort(input: {
preferredPort: number;
selectedPort: number;
hardPin: boolean;
holderIsOpencodex: boolean;
ocxService: string | undefined;
}): BusyPreferredPortDecision {
// Port 0 (or an unusable preference) asked the OS to choose; nothing was taken away.
if (input.preferredPort <= 0) return "hop";
// The preferred port was obtained — no hop happened, nothing to decide.
if (input.selectedPort === input.preferredPort) return "hop";
// Defensive: a hard pin cannot reach a different port, and if it ever did, the pin is
// the user's explicit instruction and not something to answer with a refusal here.
if (input.hardPin) return "hop";
if (input.holderIsOpencodex) {
// Same sentinel rule as decideStartWithLiveOwner: only the exact "1" is service context.
return input.ocxService === "1" ? "service-stay-out" : "refuse-live-proxy";
}
return "refuse-unidentified-holder";
}
export function resolveDispatchCommand(command: string | undefined): string | undefined {
if (command === undefined) return undefined;
if (Object.prototype.hasOwnProperty.call(commandRunners, command)) return command;
return aliasTargets.get(command);
}
export async function dispatchCommand(head: CliHead, deps: CliDispatchDeps): Promise<number> {
const command = head.command;
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
printUsage();
return 0;
}
if (command === "internal") {
// Routed here rather than as a runner key so it stays out of DISPATCH_COMMANDS and
// therefore out of the registry-parity gate. See src/cli/internal-command.ts.
const { handleInternalCommand } = await import("./internal-command");
return await handleInternalCommand(deps.args.slice(1));
}
const runner = commandRunners[resolveDispatchCommand(command) ?? ""];
if (!runner) {
printUnknownCommand(command);
return 1;
}
return await runner(deps);
}
async function reconcileClientJournalBeforeLifecycle(
state: ClientConnectionState,
): Promise<void> {
if (state.kind === "disconnected") return;
const { reconcileJournal } = await import("../codex/journal");
reconcileJournal(state.kind === "connected"
? { activeClientApiKeyId: state.value.apiKeyId }
: undefined);
}