UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

715 lines (683 loc) • 36.2 kB
import { existsSync, lstatSync, readFileSync } from "node:fs"; import { DEFAULT_CATALOG_PATH } from "../codex/paths"; import { codexSupportedReasoningEfforts } from "../codex/catalog/effort"; import { resolveCodexRuntime, type ResolvedCodexRuntime } from "../codex/runtime"; import { inspectClientCatalogReadiness, type CatalogCompatibilityDeps, type ClientCatalogFileState, type ClientCatalogReadiness, } from "../client/catalog-compatibility"; import { assertDisconnectExpectation, disconnectClient, revokeConnectedClientKey, rotateConnectedClientKey, connectClient, } from "../client/connect"; import { inspectClientRotationRecoveryGate, readClientConnectionState } from "../client/state"; import { readClientLinkState } from "../client/link-state"; import { probeLinkTunnelStatus, type LinkTunnelStatus } from "../client/link-tunnel-status"; import { teardownClientLink, type ClientLinkTeardownResult } from "../client/link-teardown"; import { ClientSyncExpectationError } from "../client/sync-expectation"; import { SYNC_EXPECTATION_MISMATCH_EXIT } from "./sync-expectation"; import { reapOrphanTunnel } from "../client/link-tunnel"; import { readServiceApiTokenState } from "../lib/service-secrets"; import { readHubCredential, type HubCredentialOwner } from "../client/hub-session"; import type { ClientLifecycleLockDeps } from "../client/lifecycle-lock"; import { recoverOrphanedTokens, type OrphanTokenRecoveryDeps } from "../client/orphan-token-recovery"; import { linkKnownHostsPath } from "../link/paths"; import { createSshRunner, type SshRunner } from "../link/ssh-runner"; import type { OrphanTunnelResult } from "../client/link-tunnel"; import { inspectRemoteDesktopStore } from "../claude/desktop-remote-store"; import type { OcxConnectedClientId } from "../types"; import { ROUTE_CLIENT_IDS, isRouteClientId } from "../link/route-intent"; import { CliUsageError, csv, printData, readSecretBytes, readSecretLine, rejectArgs, runCliAction, takeFlag, takeIntegerOption, takeOption, terminalSafeError, terminalSafeText, type RuntimeApiDeps, } from "./runtime-api"; import { inspectCodexShimForConnect, type CodexConnectShimReadiness, } from "./codex-shim-readiness"; export interface ClientCommandDeps extends RuntimeApiDeps { lifecycleLockDeps?: ClientLifecycleLockDeps; catalogProbeDeps?: ClientCatalogProbeDeps; linkTeardownDeps?: { runner?: Pick<SshRunner, "run">; reapOrphanTunnel?: () => Promise<OrphanTunnelResult>; knownHostsFile?: string; timeoutMs?: number; }; /** Injected in tests; defaults to asking the running Child's /readyz. */ probeLinkTunnel?: () => Promise<LinkTunnelStatus>; } export interface ClientCatalogProbeDeps extends CatalogCompatibilityDeps { /** Injected in tests; defaults to reading the materialized client catalog off disk. */ readCatalogBody?: () => string | null; /** * The Codex runtime the caller already resolved, handed over so readiness skips resolving it * again. General `ocx status` resolves the full runtime for its diagnostics block; the resolver * memo is keyed by discovery scope and holds one entry, so a priority-only readiness resolve * and the full one miss each other and re-probe the same command with `--version` — up to eight * seconds apiece. Passing the selection across adds no cache state, and it cannot disagree with * what status prints because it is the selection status is printing. */ selectedCodexRuntime?: ResolvedCodexRuntime; } export const CONNECT_USAGE = `Usage: ocx connect --link --key-stdin --tunnel-port <port> --link-id <id> [--clients <id,...>] [--catalog-timeout <seconds>] [--no-sync] ocx connect <url> [--management-url <url>] (--pairing-code-stdin | --admin-token-stdin) [--clients codex,claude] [--management-transport direct|relay] [--catalog-timeout <seconds>] [--no-sync] ocx connect status [--json] ocx connect rotate (--pairing-code-stdin | --admin-token-stdin) [--json] ocx connect revoke --admin-token-stdin [--json] Link client ids: ${ROUTE_CLIENT_IDS.join(", ")}`; export const DISCONNECT_USAGE = `Usage: ocx disconnect [--keep-catalog] [--recover-config --yes] [--json] [--expect-link <link id>] ocx disconnect --orphaned-token --yes [--json]`; const DISCONNECT_LINK_ID = /^lnk_[0-9a-f]{16}$/; /** --expect-link <id> or --expect-link=<id>, given at most once; removed from args. */ function takeExpectLink(args: string[]): string | undefined { let found: string | undefined; for (let index = 0; index < args.length;) { const arg = args[index]!; let value: string | undefined; if (arg === "--expect-link") { value = args[index + 1] ?? ""; args.splice(index, 2); } else if (arg.startsWith("--expect-link=")) { value = arg.slice("--expect-link=".length); args.splice(index, 1); } else { index += 1; continue; } if (found !== undefined || !DISCONNECT_LINK_ID.test(value)) { throw new CliUsageError("--expect-link needs one link id of the form lnk_ followed by 16 hex digits (see ocx connect status --json).", DISCONNECT_USAGE); } found = value; } return found; } /** Describes the local credential file without probing the lease at the Hub. */ function managementCredentialState(owner: HubCredentialOwner): "session" | "missing" | "unsafe" { const state = readHubCredential(owner); if (state.kind === "present") return "session"; return state.kind === "unsafe" ? "unsafe" : "missing"; } export type ClientConnectionStatus = { state: "disconnected" | "connected" | "invalid" | "mismatched"; reason?: string; serverUrl?: string; managementUrl?: string; managementTransport?: "direct" | "relay"; transport?: "hub" | "link"; link?: { tunnelPort: number; linkId: string }; protocolVersion?: number; apiKeyId?: string; selectedClients?: OcxConnectedClientId[]; connectedAt?: string; catalogSyncedAt?: string; catalogAgeSeconds?: number; catalog: "present" | "missing" | "unsafe"; token: "owned" | "missing" | "changed" | "unsafe"; rotation: "clean" | "orphan-cleaned" | "recovery-required" | "unsafe"; /** The stored hub management credential the loopback relay stamps; its expiry is the hub's. */ managementCredential?: "session" | "missing" | "unsafe"; /** * Whether the selected local Codex CLI can actually launch against this connection (#4207). * * `state: "connected"` proves the hub answered and the credential works. It never proved the * local runtime could consume what was downloaded, which is how a connection kept reporting * itself healthy while `codex exec` exited on `unknown variant` before its first request. * * Reported only while connected, and reported as its own field rather than as a fourth * `catalog` value: the status JSON is documented additive-only, so widening an existing * field's value domain would change what `catalog: "present"` means for every consumer that * already reads it. */ readiness?: ClientCatalogReadiness["kind"]; /** Present whenever readiness is not `ready`; names the fault and the way out. */ readinessReason?: string; /** * A Remote Link Child's tunnel as its running runtime sees it (#8470). `state: "connected"` is * the durable link record; this says whether a request can cross it now. Additive, and only on * `ocx connect status` for `transport: "link"`. */ linkTunnel?: LinkTunnelStatus; }; function readInstalledCatalogBody(): string | null { try { return readFileSync(DEFAULT_CATALOG_PATH, "utf8"); } catch { return null; } } /** * The ladder the selected Codex CLI accepts, observed without persisting anything. * * `codexSupportedReasoningEfforts()` with no deps reaches `resolveAndPersistCodexRuntime`, which * writes codex-runtime.json. `ocx status` deliberately resolves without persisting, and a * read-only diagnostics command should not start writing runtime selection state because a * readiness check was added to it. Stop at the first valid runtime, then hand only that command * to the catalog probe: readiness does not consume alternative-runtime diagnostics. The resolver * keeps this priority-only cache separate from the full discovery used by `ocx status`. * * A caller that has already resolved passes its selection in through `selectedCodexRuntime` rather * than paying for a second `--version` probe of the command it just resolved. */ function observeLocalCodexEffortLadder(selected?: ResolvedCodexRuntime): ReadonlySet<string> | null { const runtime = selected ?? resolveCodexRuntime({ discoverAlternatives: false }).runtime; // The selection travels with its command so the probe can tell an unresolved sentinel, which may // fall back to the ChatGPT.app CLI on macOS (#8360), from a bare command that actually ran. return codexSupportedReasoningEfforts({ commandCandidates: () => [runtime.command], selectedRuntime: runtime }); } /** * One observer per command, for the write-time gate and the readiness check alike. Built even * when nothing was injected, so production does not silently fall back to the default inside * {@link assertClientCatalogCompatible} — that default persists runtime selection state and * would run its own probe, which is how the two checks could disagree about the ladder within * a single `ocx connect`. */ export function catalogObserver(deps: ClientCatalogProbeDeps | undefined): CatalogCompatibilityDeps { const selected = deps?.selectedCodexRuntime; return { supportedEfforts: deps?.supportedEfforts ?? (() => observeLocalCodexEffortLadder(selected)) }; } /** The stat half of the catalog verdict, shared by the status collector and `ocx connect`. */ function installedCatalogFileState(): ClientCatalogFileState { if (!existsSync(DEFAULT_CATALOG_PATH)) return "missing"; try { const stat = lstatSync(DEFAULT_CATALOG_PATH); return !stat.isSymbolicLink() && stat.isFile() ? "present" : "unsafe"; } catch { return "unsafe"; } } /** * Observing the runtime spawns `codex debug models`, so this runs only for a connected client — * the one configuration that installs hub bytes the local clamp never touched. A standalone or * hub install pays nothing for it. * * Never throws. A status command that dies because a Codex probe failed would replace one wrong * answer with a worse one. */ function inspectInstalledCatalogReadiness( file: ClientCatalogFileState, deps: ClientCatalogProbeDeps, ): ClientCatalogReadiness { try { const read = deps.readCatalogBody ?? readInstalledCatalogBody; return inspectClientCatalogReadiness(file, file === "present" ? read() : null, catalogObserver(deps)); } catch { return { kind: "unverified", reason: "the selected local Codex runtime could not be inspected" }; } } export function collectClientConnectionStatus( now = Date.now(), lifecycleLockDeps?: ClientLifecycleLockDeps, catalogProbeDeps: ClientCatalogProbeDeps = {}, ): ClientConnectionStatus { const state = readClientConnectionState(); const tokenState = readServiceApiTokenState(); const rotation = inspectClientRotationRecoveryGate(state, lifecycleLockDeps).kind; const catalog = installedCatalogFileState(); if (state.kind !== "connected") { return { state: state.kind, ...(state.kind === "invalid" || state.kind === "mismatched" ? { reason: state.reason } : {}), catalog, token: tokenState.kind === "absent" ? "missing" : tokenState.kind === "unsafe" ? "unsafe" : "changed", rotation, }; } const catalogAgeSeconds = state.value.catalogSyncedAt ? Math.max(0, Math.floor((now - Date.parse(state.value.catalogSyncedAt)) / 1000)) : undefined; const token = tokenState.kind === "absent" ? "missing" : tokenState.kind === "unsafe" ? "unsafe" : tokenState.fingerprint === state.value.tokenFingerprint ? "owned" : "changed"; const readiness = inspectInstalledCatalogReadiness(catalog, catalogProbeDeps); return { state: "connected", serverUrl: state.value.serverUrl, managementUrl: state.value.managementUrl, managementTransport: state.value.managementTransport, ...(state.value.transport ? { transport: state.value.transport } : {}), ...(state.value.link ? { link: { ...state.value.link } } : {}), protocolVersion: state.value.protocolVersion, apiKeyId: state.value.apiKeyId, selectedClients: [...state.value.selectedClients], connectedAt: state.value.connectedAt, ...(state.value.catalogSyncedAt ? { catalogSyncedAt: state.value.catalogSyncedAt } : {}), ...(catalogAgeSeconds !== undefined ? { catalogAgeSeconds } : {}), catalog, token, rotation, // Account and usage reads use a paired session independently of the inference token. ...(state.value.transport === "link" ? {} : { managementCredential: managementCredentialState(state.value) }), readiness: readiness.kind, ...(readiness.kind === "ready" ? {} : { readinessReason: readiness.reason }), }; } function parseClients(raw: string | undefined): OcxConnectedClientId[] { const values = csv(raw) ?? ["codex", "claude"]; if (values.length < 1 || values.some(value => !isRouteClientId(value))) { throw new CliUsageError(`--clients must contain route client ids: ${ROUTE_CLIENT_IDS.join(", ")}`, CONNECT_USAGE); } return values as OcxConnectedClientId[]; } async function readLinkCredential(deps: ClientCommandDeps): Promise<{ apiKeyId: string; key: string }> { const raw = await readSecretBytes(deps, "link credential"); try { const text = new TextDecoder("utf-8", { fatal: true }).decode(raw).trim(); const parsed: unknown = JSON.parse(text); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("shape"); const record = parsed as Record<string, unknown>; if (Object.keys(record).some(key => key !== "apiKeyId" && key !== "key") || typeof record.apiKeyId !== "string" || !record.apiKeyId.trim() || record.apiKeyId.length > 256 || typeof record.key !== "string" || !/^ocx_data_[0-9a-f]{40}$/.test(record.key)) { throw new Error("shape"); } return { apiKeyId: record.apiKeyId, key: record.key }; } catch { throw new CliUsageError("invalid link credential", CONNECT_USAGE); } finally { raw.fill(0); } } /** Reads as a verdict, not a field dump: "ready" is the only word that means the client works. */ function readinessLine(status: ClientConnectionStatus): string { const label = status.readiness === "ready" ? "ready" : status.readiness === "incompatible" ? "not ready" : "unverified"; return `Local Codex CLI: ${label}${status.readinessReason ? ` (${terminalSafeText(status.readinessReason)})` : ""}`; } export type ConnectCompletionReport = { readonly lines: readonly string[]; /** Non-null when `ocx connect` must exit non-zero rather than report success. */ readonly failure: string | null; }; export function codexShimReadinessLine( selectedClients: readonly OcxConnectedClientId[], inspect: () => CodexConnectShimReadiness = inspectCodexShimForConnect, ): string | null { if (!selectedClients.includes("codex")) return null; return `Codex autostart shim: ${terminalSafeText(inspect().message)}`; } function printCodexShimReadiness(selectedClients: readonly OcxConnectedClientId[]): void { const line = codexShimReadinessLine(selectedClients); if (line) console.log(line); } /** * What `ocx connect` says once the hub and the credential are settled, and whether the command * still fails (#4207). * * Pure so the fail-closed decision can be exercised without a hub. Two rules it encodes: * * On a proven incompatibility the verdict is printed FIRST and the `Connected to …` line is * withheld, because a caller grepping for that phrase would otherwise read a catalog the local * CLI cannot parse as a success. The connection really was saved, so the replacement line says * where to see it. * * And that failure applies only when this connection selected Codex. A Claude-only connection * never launches the Codex CLI, so an old binary somewhere on PATH is not a reason to fail the * operator's Claude Desktop setup — it is still worth saying, which is why the line survives * without the exit code. */ export function connectCompletionReport( connection: { serverUrl: string; apiKeyId: string }, selectedClients: readonly OcxConnectedClientId[], readiness: ClientCatalogReadiness, ): ConnectCompletionReport { const connected = `Connected to ${connection.serverUrl} as key ${connection.apiKeyId}.`; if (readiness.kind === "ready") { return { lines: [connected, "Local Codex CLI: ready (it accepts every reasoning level in the installed catalog)."], failure: null }; } if (readiness.kind === "unverified") { // Not a failure. A client with no observable Codex CLI is a working configuration, and the // write-time gate deliberately lets it through; saying so is the honest middle report. return { lines: [connected, `Local Codex CLI: unverified (${terminalSafeText(readiness.reason)}).`], failure: null }; } const safeReason = terminalSafeText(readiness.reason); const verdict = `Local Codex CLI: not ready (${safeReason})`; if (!selectedClients.includes("codex")) { return { lines: [connected, `${verdict} This connection selected ${selectedClients.join(", ")}, so nothing here launches Codex.`], failure: null, }; } return { lines: [verdict, `The connection to ${connection.serverUrl} as key ${connection.apiKeyId} was saved; run 'ocx connect status' to see it.`], failure: `client_not_ready: ${safeReason}`, }; } /** * Adds the tunnel verdict (#8470) only for a connected Remote Link Child, the one case with a * runtime verdict to read; a hub client or a disconnected machine is returned untouched, unprobed. */ export async function withLinkTunnelStatus( status: ClientConnectionStatus, probe: () => Promise<LinkTunnelStatus>, ): Promise<ClientConnectionStatus> { if (status.state !== "connected" || status.transport !== "link") return status; // An optional diagnostic: a probe that fails must not take the durable status down with it. let linkTunnel: LinkTunnelStatus; try { linkTunnel = await probe(); } catch { linkTunnel = { state: "unknown", reason: "runtime_unreadable" }; } return { ...status, linkTunnel }; } function linkTunnelLine(tunnel: LinkTunnelStatus): string { return tunnel.state === "up" ? "Link tunnel: up" : `Link tunnel: ${tunnel.state} (${terminalSafeText(tunnel.reason)})`; } export function clientConnectionStatusLines(status: ClientConnectionStatus): string[] { if (status.state !== "connected") { return [`Connection: ${status.state}${status.reason ? ` (${status.reason})` : ""}`]; } return [ "Connection: connected", // Second line on purpose. The whole of #4207 is that a reader stopped at "connected" and // believed the client was usable, so the local verdict has to arrive before the hub detail. readinessLine(status), // #8470: the same holds for a link Child whose tunnel is down; say so before the detail. ...(status.linkTunnel ? [linkTunnelLine(status.linkTunnel)] : []), `Transport: ${status.transport ?? "hub"}`, ...(status.link ? [`Link: ${status.link.linkId} via tunnel port ${status.link.tunnelPort}`] : []), `Hub: ${status.serverUrl}`, `Management: ${status.managementUrl} (${status.managementTransport})`, `Protocol: ${status.protocolVersion}`, `API key id: ${status.apiKeyId}`, `Clients: ${status.selectedClients?.join(", ")}`, `Token file: ${status.token}`, `Key rotation: ${status.rotation}`, ...(status.managementCredential ? [`Management credential: ${status.managementCredential}${status.managementCredential !== "session" ? " (run 'ocx connect rotate' with a fresh pairing code)" : ""}`] : []), `Catalog: ${status.catalog}${status.catalogAgeSeconds !== undefined ? ` (${status.catalogAgeSeconds}s old)` : ""}`, ]; } async function runRotate(argv: string[], deps: ClientCommandDeps): Promise<void> { const args = [...argv]; const wantsJson = takeFlag(args, "--json"); const pairing = takeFlag(args, "--pairing-code-stdin"); const admin = takeFlag(args, "--admin-token-stdin"); if (Number(pairing) + Number(admin) !== 1) { throw new CliUsageError("choose exactly one of --pairing-code-stdin or --admin-token-stdin", CONNECT_USAGE); } rejectArgs(args, CONNECT_USAGE, { redactValues: true }); const value = new TextEncoder().encode(await readSecretLine(deps, pairing ? "pairing code" : "admin token")); const connection = await rotateConnectedClientKey({ credential: { kind: pairing ? "pairing-grant" : "admin", value }, }, { fetchImpl: deps.fetchImpl, lifecycleLockDeps: deps.lifecycleLockDeps }); const restartRequired = inspectRemoteDesktopStore({ serverUrl: connection.serverUrl, apiKeyId: connection.apiKeyId, connectedAt: connection.connectedAt }).kind !== "absent"; printData({ apiKeyId: connection.apiKeyId, rotation: connection.rotationOutcome, restartRequired }, wantsJson, [ connection.rotationOutcome === "committed" ? `Rotated connected API key ${connection.apiKeyId}; the previous key is no longer admitted.` : `Rotation rolled back for API key ${connection.apiKeyId}; the previous key was retained or restored.`, ...(restartRequired ? ["Fully quit and reopen Claude Desktop; a running app may still hold the previous credential."] : []), ]); } async function runHubConnect(argv: string[], deps: ClientCommandDeps): Promise<void> { const args = [...argv]; const serverUrl = args.shift(); if (!serverUrl || serverUrl.startsWith("--")) throw new CliUsageError("hub URL is required", CONNECT_USAGE); const managementUrl = takeOption(args, "--management-url"); const clients = parseClients(takeOption(args, "--clients")); if (clients.some(client => client !== "codex" && client !== "claude")) { throw new CliUsageError("Hub connections support only codex and claude; use Link for other clients", CONNECT_USAGE); } const catalogTimeoutSeconds = takeIntegerOption(args, "--catalog-timeout", { min: 1 }); if (catalogTimeoutSeconds !== undefined && catalogTimeoutSeconds > 120) { throw new CliUsageError("--catalog-timeout must be an integer between 1 and 120", CONNECT_USAGE); } const managementTransport = takeOption(args, "--management-transport") ?? "direct"; if (managementTransport !== "direct" && managementTransport !== "relay") { throw new CliUsageError("--management-transport must be direct or relay", CONNECT_USAGE); } const pairing = takeFlag(args, "--pairing-code-stdin"); const admin = takeFlag(args, "--admin-token-stdin"); const noSync = takeFlag(args, "--no-sync"); if (Number(pairing) + Number(admin) !== 1) { throw new CliUsageError("choose exactly one of --pairing-code-stdin or --admin-token-stdin", CONNECT_USAGE); } rejectArgs(args, CONNECT_USAGE, { redactValues: true }); const secret = await readSecretLine(deps, pairing ? "pairing code" : "admin token"); const value = new TextEncoder().encode(secret); const connection = await connectClient({ serverUrl, ...(managementUrl ? { managementUrl } : {}), credential: { kind: pairing ? "pairing-grant" : "admin", value }, selectedClients: clients, managementTransport, noSync, ...(catalogTimeoutSeconds === undefined ? {} : { catalogTimeoutMs: catalogTimeoutSeconds * 1_000 }), }, { fetchImpl: deps.fetchImpl, lifecycleLockDeps: deps.lifecycleLockDeps, // Same observer the readiness check below uses. Passed unconditionally: leaving it out in // production would let the gate fall back to its own probing, persisting default, so one // command could run two probes and act on two different ladders. catalogCompatibility: catalogObserver(deps.catalogProbeDeps), }).catch((error: unknown) => { // Compatibility refusals happen before the completion report and reach stderr. // Keep the domain error untouched; render its message only at the CLI boundary. throw terminalSafeError(error); }); // The hub and the credential are proven at this point; the local runtime is not. Reporting // only the first half is what #4207 was filed for, so the catalog now on disk is checked // against the Codex CLI that will read it. const readiness = inspectInstalledCatalogReadiness(installedCatalogFileState(), deps.catalogProbeDeps ?? {}); const report = connectCompletionReport(connection, connection.selectedClients, readiness); for (const line of report.lines) console.log(line); printCodexShimReadiness(connection.selectedClients); if (report.failure) throw new Error(report.failure); } async function runLinkConnect(argv: string[], deps: ClientCommandDeps): Promise<void> { const args = [...argv]; const keyStdin = takeFlag(args, "--key-stdin"); const rawPort = takeIntegerOption(args, "--tunnel-port", { min: 1024 }); const linkId = takeOption(args, "--link-id"); const managementUrl = takeOption(args, "--management-url"); const managementTransport = takeOption(args, "--management-transport"); const pairing = takeFlag(args, "--pairing-code-stdin"); const admin = takeFlag(args, "--admin-token-stdin"); const rawClients = takeOption(args, "--clients"); const clients = parseClients(rawClients); const catalogTimeoutSeconds = takeIntegerOption(args, "--catalog-timeout", { min: 1 }); if (catalogTimeoutSeconds !== undefined && catalogTimeoutSeconds > 120) { throw new CliUsageError("--catalog-timeout must be an integer between 1 and 120", CONNECT_USAGE); } const noSync = takeFlag(args, "--no-sync"); if (!keyStdin || rawPort === undefined || !linkId) { throw new CliUsageError("link connect requires --key-stdin, --tunnel-port, and --link-id", CONNECT_USAGE); } if (managementUrl || managementTransport !== undefined || pairing || admin || args.some(value => !value.startsWith("--"))) { throw new CliUsageError("link connect accepts no hub URL, management URL, management transport, pairing code, or admin token", CONNECT_USAGE); } if (rawPort > 65535 || !/^lnk_[0-9a-f]{16}$/.test(linkId)) { throw new CliUsageError("invalid link transport", CONNECT_USAGE); } rejectArgs(args, CONNECT_USAGE, { redactValues: true }); const credential = await readLinkCredential(deps); const connection = await connectClient({ serverUrl: `http://127.0.0.1:${rawPort}`, managementUrl: `http://127.0.0.1:${rawPort}`, credential: { kind: "link", ...credential }, selectedClients: clients, selectedClientsExplicit: rawClients !== undefined, managementTransport: "direct", transport: "link", link: { tunnelPort: rawPort, linkId }, noSync, ...(catalogTimeoutSeconds === undefined ? {} : { catalogTimeoutMs: catalogTimeoutSeconds * 1_000 }), }, { fetchImpl: deps.fetchImpl, lifecycleLockDeps: deps.lifecycleLockDeps, catalogCompatibility: catalogObserver(deps.catalogProbeDeps), }).catch((error: unknown) => { throw terminalSafeError(error); }); const readiness = inspectInstalledCatalogReadiness(installedCatalogFileState(), deps.catalogProbeDeps ?? {}); const report = connectCompletionReport(connection, connection.selectedClients, readiness); for (const line of report.lines) console.log(line); printCodexShimReadiness(connection.selectedClients); if (report.failure) throw new Error(report.failure); } async function runConnect(argv: string[], deps: ClientCommandDeps): Promise<void> { const args = [...argv]; if (takeFlag(args, "--link")) { await runLinkConnect(args, deps); return; } await runHubConnect(argv, deps); } async function runRevoke(argv: string[], deps: ClientCommandDeps): Promise<void> { const args = [...argv]; const wantsJson = takeFlag(args, "--json"); const admin = takeFlag(args, "--admin-token-stdin"); if (!admin) throw new CliUsageError("revoke requires --admin-token-stdin", CONNECT_USAGE); rejectArgs(args, CONNECT_USAGE, { redactValues: true }); const value = new TextEncoder().encode(await readSecretLine(deps, "admin token")); const result = await revokeConnectedClientKey({ kind: "admin", value }, { fetchImpl: deps.fetchImpl, lifecycleLockDeps: deps.lifecycleLockDeps }); printData(result, wantsJson, [`Revoked connected API key ${result.apiKeyId}. Disconnect this client next.`]); } export async function handleConnectCommand(argv: string[], deps: ClientCommandDeps = {}): Promise<number> { return runCliAction(async () => { if (argv[0] === "status") { const args = argv.slice(1); const wantsJson = takeFlag(args, "--json"); rejectArgs(args, CONNECT_USAGE, { redactValues: true }); const status = await withLinkTunnelStatus( collectClientConnectionStatus(Date.now(), deps.lifecycleLockDeps, deps.catalogProbeDeps ?? {}), deps.probeLinkTunnel ?? probeLinkTunnelStatus, ); printData(status, wantsJson, clientConnectionStatusLines(status)); return; } if (argv[0] === "revoke") { await runRevoke(argv.slice(1), deps); return; } if (argv[0] === "rotate") { await runRotate(argv.slice(1), deps); return; } await runConnect(argv, deps); }); } export async function handleDisconnectCommand( argv: string[], deps: Pick<ClientCommandDeps, "lifecycleLockDeps" | "linkTeardownDeps"> & { orphanRecoveryDeps?: OrphanTokenRecoveryDeps } = {}, ): Promise<number> { let mismatch: { phase: string; reason: string } | null = null; const code = await runCliAction(async () => { const args = [...argv]; const keepCatalog = takeFlag(args, "--keep-catalog"); const wantsJson = takeFlag(args, "--json"); const orphanedToken = takeFlag(args, "--orphaned-token"); const recoverConfig = takeFlag(args, "--recover-config"); const yes = takeFlag(args, "--yes"); const expectLink = takeExpectLink(args); rejectArgs(args, DISCONNECT_USAGE, { redactValues: true }); if (recoverConfig && (!yes || orphanedToken)) throw new CliUsageError("--recover-config requires --yes and cannot be combined with --orphaned-token", DISCONNECT_USAGE); // A Home's link-bound disconnect never asks for config recovery; that stays a person's own plain disconnect. if (recoverConfig && expectLink !== undefined) throw new CliUsageError("--recover-config cannot be combined with --expect-link", DISCONNECT_USAGE); if (orphanedToken) { if (!yes || keepCatalog || expectLink !== undefined) throw new CliUsageError("--orphaned-token requires --yes and cannot be combined with --keep-catalog or --expect-link", DISCONNECT_USAGE); const backup = await recoverOrphanedTokens({ ...deps.orphanRecoveryDeps, lifecycleLockDeps: deps.lifecycleLockDeps }); const restore = "Stop OpenCodex and move the saved files back into its config directory only if the destination names are absent."; printData({ ...backup, restore }, wantsJson, [ `Preserved token files in ${backup.backupDir}.`, `To restore: ${restore}`, ]); return; } if (yes && !recoverConfig) throw new CliUsageError("--yes requires --orphaned-token or --recover-config", DISCONNECT_USAGE); // A Home's revoke names the link it means; checked before the client-link teardown touches anything, // and again inside disconnectClient under the locks it writes under. A client-initiated link (its sidecar, or the // marker that survives a lost sidecar, names this link) needs the client-link teardown this path skips, so the // same check refuses it before anything changes. if (expectLink !== undefined) { try { assertDisconnectExpectation(expectLink, deps); } catch (error) { if (error instanceof ClientSyncExpectationError) { mismatch = error; return; } throw error; } } // A Home's link-bound disconnect (--expect-link) comes from the Home that owns that link's tunnel and record, // and it is sent only for Home-initiated links, which have no client-link sidecar. Running this Child's // client-link teardown there would only open a gap between the identity check and the locked disconnect. const teardown: ClientLinkTeardownResult = expectLink !== undefined ? { linkId: null, homeRevoke: "not_applicable", tunnel: null } : await teardownClientLink({ readSidecar: readClientLinkState, connectedLinkId: () => { const state = readClientConnectionState(); return state.kind === "connected" && state.value.transport === "link" ? state.value.link?.linkId ?? null : null; }, reapOrphanTunnel: deps.linkTeardownDeps?.reapOrphanTunnel ?? (() => reapOrphanTunnel()), runner: deps.linkTeardownDeps?.runner ?? createSshRunner(), knownHostsFile: deps.linkTeardownDeps?.knownHostsFile ?? linkKnownHostsPath(), timeoutMs: deps.linkTeardownDeps?.timeoutMs, }); const result = await disconnectClient({ keepCatalog, recoverConfig, ...(expectLink !== undefined ? { expectLink } : {}) }, deps).catch((error: unknown) => { if (error instanceof ClientSyncExpectationError) { mismatch = error; return null; } // The bare code left a Home-driven leave with nothing to act on; the remedy already exists. if (error instanceof Error && error.message === "client_catalog_ownership_changed") { throw new Error("client_catalog_ownership_changed: the Codex model catalog (opencodex-catalog.json in the Codex home) matches neither the catalog this connection wrote nor the one recorded before it connected, so something changed it after connecting and disconnect will not overwrite it. To disconnect and leave that file as it is, run: ocx disconnect --keep-catalog"); } throw error; }); if (!result) return; if (result.nativeIntentOnly) { printData(result, wantsJson, [ "Not connected; restored the standalone native switches an interrupted Remote Link enrollment had changed.", ...(result.tokenRemoved ? ["Removed the service token that enrollment left behind."] : []), ]); return; } const payload = { ...result, homeRevoke: teardown.homeRevoke, tunnel: teardown.tunnel, revoke: { apiKeyId: result.apiKeyId, location: "Integrations → API Keys", }, }; printData(payload, wantsJson, [ "Disconnected locally; native Codex state was restored.", ...(result.recoveryBackupDir ? [`Codex recovery snapshot: ${result.recoveryBackupDir}/snapshot.json (private; retained for manual inspection).`] : []), ...(result.desktopRestoration === "standard_fallback" ? ["Previous Desktop settings were not recorded; the managed profile was switched to standard mode."] : []), ...(result.restartRequired ? ["Fully quit and reopen Claude Desktop; local cleanup cannot revoke an in-memory credential."] : []), ...(teardown.homeRevoke === "failed" && teardown.linkId ? [`Home revoke failed; run ocx link revoke --link-id ${teardown.linkId} on the home.`] : []), ...(teardown.tunnel?.tunnel === "unresolved" ? [`A link tunnel (pid ${teardown.tunnel.pid}) may still be running; stop it if it is.`] : []), teardown.homeRevoke === "revoked" ? `The home revoked link ${teardown.linkId} and its key ${result.apiKeyId}.` : `The hub key ${result.apiKeyId} is still valid. Revoke it from Integrations → API Keys.`, ]); }); if (mismatch) { // As ocx sync --expect-link: one human line, then the JSON a Home parses as the last stderr line. const refused: { phase: string; reason: string } = mismatch; console.error(`Disconnect refused (${refused.phase}: ${refused.reason}); nothing was changed.${refused.reason === "client_initiated_link" ? " This machine joined its Home itself; run ocx disconnect without --expect-link." : ""}`); console.error(JSON.stringify({ phase: refused.phase, reason: refused.reason })); return SYNC_EXPECTATION_MISMATCH_EXIT; } return code; }