import type { Capability, HeadCapability } from "./capability-types";

export const HEAD_CAPABILITIES: readonly HeadCapability[] = [
  {
    invocations: ["--version", "-v", "version"],
    summary: "Print the CLI version and exit.",
    bannerLine: "ocx --version | -v          Print version",
  },
  {
    invocations: ["help", "--help", "-h"],
    summary: "Print the command list, or one command's usage with `ocx help <command>`.",
    bannerLine: "ocx help [command]          Show help for a command",
  },
];

/**
 * Capabilities declared so far. Incomplete by design: later phases add verbs.
 * `ocx capabilities` is the index of what is listed here, not of every CLI command.
 * A capability must not name a route the command does not actually fetch.
 */
export const CAPABILITIES: readonly Capability[] = [
  {
    command: ["codex-provider"],
    bannerLines: ["ocx codex-provider <sub>    Confirm custom Codex provider routing: status|allow|revoke"],
    summary: "Inspect, allow or revoke custom Codex provider routing consent.",
    routes: [], flags: [{ name: "--yes", value: "boolean", summary: "Explicitly approve the named provider without an interactive prompt." }],
    mutates: true, json: "none",
    usage: "ocx codex-provider <status|allow <id> [--yes]|revoke <id>>",
    details: ["Only local loopback routing for Responses providers using OpenAI authentication is supported. No custom credentials/headers, authless mode or client compaction. Unapproved providers are never changed."],
  },
  {
    command: ["chatgpt"],
    summary: "Experimental ChatGPT app-server shim: launch, restore or status (macOS only).",
    routes: [], flags: [], mutates: true, json: "none",
    bannerLines: ["ocx chatgpt <sub>          Experimental app-server shim: launch|restore|status (macOS)"],
    details: ["Default off; launch requires chatgptDesktop.appServerShim: true. Restore removes the generated launcher."],
  },
  {"command": ["link","probe"],"summary": "Probe an SSH host fingerprint and OpenCodex version without trusting it.","routes": [{"method": "POST","path": "/api/link/probe"}],"flags": [{"name": "--proxy-command","value": "string","summary": "Explicit ProxyCommand for the alias, passed to ssh on the command line: an absolute path, then words of letters, digits and . _ / : @ + , = - separated by single spaces. Needs --ssh-user, --ssh-port and --exclusive. The link then reads no ssh_config (-F none): the Home offers its SSH agent's keys or a default ~/.ssh/id_* key, or only the --ssh-identity-file key when one is given."},{"name": "--ssh-user","value": "string","summary": "SSH user of the explicit route: a letter or _ then up to 31 letters, digits, ., _ or -."},{"name": "--ssh-port","value": "number","summary": "SSH port of the explicit route, 1 to 65535."},{"name": "--ssh-identity-file","value": "string","summary": "The private key the link authenticates with (link.route/2): an absolute path of letters, digits and . _ + - /. Needs the explicit route. ssh then offers that key alone (IdentitiesOnly=yes, IdentityAgent=none) for every command and tunnel of the link. The Home refuses a missing, symlinked, unreadable or group- or other-accessible file, and a Windows Home refuses the flag; it never reads the key. The key's directory and every directory above it must be owned by this user or root and not writable by group or others (a sticky directory above the key, such as /tmp, excepted), and every symlink on the path must be owned by this user or root; a folder created under umask 002 is group-writable and is refused. Use a path that passes, or run chmod go-w on a private folder this user owns (its own, or one a tool made for it); never change a shared or system directory such as /tmp or another user's symlink, even as root (hints identity_file_directory, identity_file_ancestor)."},{"name": "--exclusive","value": "boolean","summary": "The link keeps exactly its alias as its one route and refuses route edits."},{"name": "--json","value": "boolean","summary": "Emit alias, fingerprint, key type and version as JSON."}],"mutates": true,"json": "payload","usage": "ocx link probe <alias> [--proxy-command <cmd> --ssh-user <user> --ssh-port <port> [--ssh-identity-file <path>]] [--exclusive] [--json]","details": ["Requires loopback admin authority on the Home. Stores only a temporary pending offer; does not persist host trust or issue a link key."]},
  {"command": ["link","add"],"summary": "Connect an SSH Child to this Home after confirming its fingerprint.","routes": [{"method": "POST","path": "/api/link/probe"},{"method": "POST","path": "/api/link/confirm-host"},{"method": "POST","path": "/api/link/apply"}],"flags": [{"name": "--expect-fingerprint","value": "string","summary": "Exact SHA256 host fingerprint; required without an interactive TTY."},{"name": "--proxy-command","value": "string","summary": "Explicit ProxyCommand for the alias, passed to ssh on the command line: an absolute path, then words of letters, digits and . _ / : @ + , = - separated by single spaces. Needs --ssh-user, --ssh-port and --exclusive. The link then reads no ssh_config (-F none): the Home offers its SSH agent's keys or a default ~/.ssh/id_* key, or only the --ssh-identity-file key when one is given."},{"name": "--ssh-user","value": "string","summary": "SSH user of the explicit route: a letter or _ then up to 31 letters, digits, ., _ or -."},{"name": "--ssh-port","value": "number","summary": "SSH port of the explicit route, 1 to 65535."},{"name": "--ssh-identity-file","value": "string","summary": "The private key the link authenticates with (link.route/2): an absolute path of letters, digits and . _ + - /. Needs the explicit route. ssh then offers that key alone (IdentitiesOnly=yes, IdentityAgent=none) for every command and tunnel of the link. The Home refuses a missing, symlinked, unreadable or group- or other-accessible file, and a Windows Home refuses the flag; it never reads the key. The key's directory and every directory above it must be owned by this user or root and not writable by group or others (a sticky directory above the key, such as /tmp, excepted), and every symlink on the path must be owned by this user or root; a folder created under umask 002 is group-writable and is refused. Use a path that passes, or run chmod go-w on a private folder this user owns (its own, or one a tool made for it); never change a shared or system directory such as /tmp or another user's symlink, even as root (hints identity_file_directory, identity_file_ancestor)."},{"name": "--exclusive","value": "boolean","summary": "The link keeps exactly its alias as its one route and refuses route edits."},{"name": "--operation-id","value": "string","summary": "Journal the enrollment under this id (1-128 letters, digits, . _ : -): reserved ids, a mark per Home effect and the outcome; a repeat with the same id and parameters replays it. Needs --expect-fingerprint."},{"name": "--require-ephemeral","value": "boolean","summary": "Refuse (409 full_install_present) a Child where any runnable full ocx exists, before any plant, key or Child change."},{"name": "--json","value": "boolean","summary": "Emit the verified link result as JSON."}],"mutates": true,"json": "payload","usage": "ocx link add <alias> [--expect-fingerprint SHA256:…] [--proxy-command <cmd> --ssh-user <user> --ssh-port <port> [--ssh-identity-file <path>]] [--exclusive] [--operation-id <id>] [--require-ephemeral] [--json]","details": ["Requires loopback admin authority on the Home. Without a fingerprint, requires a TTY and explicit yes after showing the offered fingerprint. Never prints the link key.","Preflights bound Child restart support and curl, connects, restarts once and verifies a fresh authenticated catalog relay before success. Post-connect failures can leave Child config; the failure names the attempt's link id. Before retrying, on a full install run ocx disconnect --expect-link <id> and, if it disconnected, ocx restart. A lightweight Child has no ocx: run its planted ocx-child's detach --expect-link <id> instead (~/.cache/opencodex/bin/ocx-child; in Command Prompt on Windows %LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe, or %USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe where LOCALAPPDATA is not set; a copy placed by hand in ~/.local/bin, or %USERPROFILE%\\.local\\bin on Windows; none need be on PATH). Either acts only while the Child belongs to that link. A build older than --expect-link refuses it before it acts: then leave a lightweight Child as it is, and on a full install run ocx disconnect and ocx restart only if ocx connect status --json shows that id, right after that check, and otherwise leave it as it is."]},
  {
    command: ["link","port"],
    summary: "Allocate a free loopback port for a remote home link.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the selected port as JSON."}],
    mutates: false,
    json: "envelope",
    usage: "ocx link port [--json]",
    details: ["Local temporary loopback socket allocation; no management API request.","Always emits a CLI-shaped {port} JSON object, even without --json."],
  },
  {
    command: ["link","issue"],
    summary: "Issue one link credential and record its tunnel metadata.",
    routes: [{"method":"POST","path":"/api/link/issue"}],
    flags: [{"name":"--clients","value":"string","summary":"Initial device selection: listed clients start on for this device, and Codex and Claude Code start off unless listed; other clients inherit Home defaults. Omitted, the device inherits every Home default, including an off Codex or Claude Code."},{"name":"--alias","value":"string","required":true,"summary":"SSH host alias for the linked machine."},{"name":"--tunnel-port","value":"number","required":true,"summary":"Remote loopback port for the reverse tunnel."},{"name":"--json","value":"boolean","summary":"Emit the issue result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Human-only handoff: issues a credential and prints its plaintext once. Never capture it in an agent transcript. Requires loopback admin authority; tunnel port must be 1024-65535."],
  },
  {
    command: ["link","status"],
    summary: "Read link listener and tunnel status.",
    routes: [{"method":"GET","path":"/api/link/status"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the K16 status payload as JSON."}],
    mutates: false,
    json: "payload",
    usage: "ocx link status [--json]",
    details: ["Reads live listener/tunnel metadata; when no proxy is found, falls back to the local link store. Always emits JSON.","Home-initiated links report recent authenticated HTTP delivery in relayHealth, with inference readiness reported as unknown."],
  },
  {
    command: ["link","diagnostics"],
    summary: "Read this computer's bounded Remote Link diagnostics file.",
    routes: [],
    flags: [{"name":"--limit","value":"number","summary":"Newest records to show, 1-1000; default 200."},{"name":"--since","value":"string","summary":"Only records at or after this ISO time or epoch-millisecond timestamp."},{"name":"--json","value":"boolean","summary":"Emit the ocx.link.diagnostics/1 document as JSON."}],
    mutates: false,
    json: "envelope",
    usage: "ocx link diagnostics [--limit <n>] [--since <iso-time|epoch-ms>] [--json]",
    details: ["Reads <configDir>/link/diagnostics.jsonl and its backup diagnostics.jsonl.1 directly, oldest first, without the proxy or a management route. Never creates, hardens or writes a file, and skips the Codex-shim repair preflight.","Reads only regular files (never through a symlink, FIFO or symlinked link directory), at most the newest 256 KiB of each. Every line is re-checked against the writer's allowlist: tunnel and relay event/outcome/state words, generated UUIDs, numbers and timestamps. Lines that fail are counted in skipped, never printed.","Exit 0 including when nothing is recorded yet, which prints the file path. The dashboard reads the same records through GET /api/link/diagnostics."],
  },
  {
    command: ["link","revoke"],
    summary: "Revoke a link credential and remove its link record.",
    routes: [{"method":"DELETE","path":"/api/link/{id}"}],
    flags: [{"name":"--link-id","value":"string","required":true,"summary":"Link id to revoke."},{"name":"--json","value":"boolean","summary":"Emit the revoked link id as JSON."},{"name":"--force","value":"boolean","summary":"Explicitly skip remote disconnect while retiring the local link; requires --yes."},{"name":"--yes","value":"boolean","summary":"Confirms force only; refused without --force."},{"name":"--operation-id","value":"string","summary":"Journal the revoke under this id; a purge records the Child's purged:true as its receipt, and a repeat replays the outcome even after the link is gone."}],
    mutates: true,
    json: "envelope",
    details: ["Requires a valid link ID and loopback admin authority. Explicit force additionally requires --yes.","Ordinary revoke always emits {linkId} JSON; forced revoke has human output or a JSON cleanup receipt. Already-revoked link_not_found is idempotent success.","Ordinary revoke retains its no-body and idempotent behavior. Forced success reports remoteCleanup:skipped from invocation intent; already-missing link reports unverified. Neither proves the remote client disconnected.","After a forced revoke of a full install, run ocx disconnect --expect-link <id> on the machine, which acts only while it is connected to this link; an OpenCodex older than that flag refuses it as a usage error before it acts on the link, and then run ocx disconnect only if ocx connect status --json there shows this link's id or no connection, right after that check (an enrollment that lands between the two commands would be removed); if it shows another link, a hub or another Home, or its state cannot be read, leave it. For a lightweight (ocx-child) Child, use ocx link recover --link-id <id>, which acts only when the machine's records name this link or nothing at all, and refuses a machine another link owns. No new enrollment, SSH trust or credential action is implied."],
    usage: "ocx link revoke --link-id <id> [--force --yes] [--operation-id <id>] [--json]",
  },
  {
    command: ["link","recover"],
    summary: "Clean an ephemeral Child that a forced revoke or an interrupted enrollment left behind.",
    routes: [{"method":"POST","path":"/api/link/recover"},{"method":"GET","path":"/api/link/recover"}],
    flags: [{"name":"--link-id","value":"string","summary":"Force-revoked ephemeral link whose tombstone names the machine; exactly one of --link-id or --operation-id."},{"name":"--operation-id","value":"string","summary":"Link operation whose journal entry names the machine; needs the link operation journal."},{"name":"--list","value":"boolean","summary":"List the forced revokes still waiting for cleanup (link id, alias, revokedAt); takes no other option."},{"name":"--forget","value":"boolean","summary":"Drop the tombstone for --link-id without contacting its machine, for a machine gone for good; runs on the Home, refused while the link exists and from an agent or CI runner."},{"name":"--yes","value":"boolean","summary":"Confirms --forget."},{"name":"--json","value":"boolean","summary":"Emit the {linkId, outcome, purged} receipt, the {tombstones} list or the {linkId, outcome} forget answer as JSON."}],
    mutates: true,
    json: "envelope",
    usage: "ocx link recover (--link-id <id> | --operation-id <id>) [--json] | --list [--json] | --forget --link-id <id> --yes [--json]",
    details: ["Runs the managed planted ocx-child's disconnect --purge --expect-link <id> over the link's alias with its pinned host key, never a sibling route. The Child restores only when its state and its CODEX_HOME ownership record both name that link.","Succeeds only on the Child's receipt naming that link with purged:true, or purged:false when the binary stays for another home's running relay; then the tombstone (or journal entry) is settled. residual and conflict answers (409) change nothing on the Child; do not answer a residual one with a plain ocx-child detach on the machine, which would also restore and remove a link an interrupted attach left; a person on the Home can forget the tombstone of a machine that is gone or whose cleanup cannot be proven.","A forced revoke of a Home-initiated ephemeral link writes the tombstone; a link that still exists answers link_present, and any other Home-initiated link naming the same alias (case-insensitive) answers alias_linked before the machine is contacted. Without a link operation journal, --operation-id answers operation_journal_unavailable."],
  },
  {
    command: ["link","reconnect"],
    summary: "Restart a Home-initiated link's SSH tunnel now.",
    routes: [{"method":"POST","path":"/api/link/{id}/reconnect"}],
    flags: [{"name":"--link-id","value":"string","required":true,"summary":"Home-initiated link id whose tunnel to restart."},{"name":"--json","value":"boolean","summary":"Emit the restarted link id as JSON."}],
    mutates: true,
    json: "envelope",
    usage: "ocx link reconnect --link-id <id> [--json]",
    details: ["Requires a valid link ID and loopback admin authority. Stops the current ssh child, clears any backoff or failed state and starts a fresh attempt; read ocx link status for the outcome.","A Child-initiated link is refused with link_not_home_initiated: its own computer owns and retries that tunnel.","A link that an unsettled journalled revoke keeps down (ocx link status: failed, reason revoke_unsettled) is refused with link_suspended (exit 5) and nothing is stopped; the message names the revoke's operation id and the next step (ocx link operations resolve, or first repeat a revoke that did not record its outcome).","Emits {linkId} JSON when the tunnel was restarted."],
  },
  {
    command: ["link","cleanup"],
    summary: "Inspect Remote Link Child platforms and show disconnect guidance.",
    routes: [],
    flags: [{"name":"--link-id","value":"string","summary":"Check only this link."},{"name":"--json","value":"boolean","summary":"Emit {links, changed:false} as JSON."}],
    mutates: false,
    json: "payload",
    usage: "ocx link cleanup [--link-id <id>] [--json]",
    details: ["Runs on the Home from its local link store. Asks each Home-initiated Child for its platform over the link's pinned SSH trust (the fixed %OS% probe, then uname -s) and reports Windows Children with disconnect guidance.","Never revokes, disconnects or edits a link. An ordinary ocx link revoke --yes disconnects a Windows Child through PowerShell over the recorded SSH trust."],
  },
  {
    command: ["remote-workspace","pair"],
    summary: "Enroll this executor with one Hub using a one-time code from stdin and locally approved roots.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the public local executor status."},{"name":"--pairing-code-stdin","value":"boolean","summary":"Read the one-time pairing code from stdin."},{"name":"--root","value":"string","summary":"Approve an absolute workspace directory; repeatable."},{"name":"--toolchain-root","value":"string","summary":"Approve a read-only toolchain directory; repeatable."},{"name":"--executor-helper","value":"string","summary":"Select a reviewed native helper file."},{"name":"--name","value":"string","summary":"Name this executor."}],
    mutates: true,
    json: "payload",
    details: ["Executor-local state/control; no Hub management API routes.","Pairing consumes a human-provided one-time code from stdin and persists enrollment; approved roots and platform confinement determine capabilities."],
    usage: "ocx remote-workspace pair <hub-url> --pairing-code-stdin --root <absolute-path> [--root <absolute-path> ...] [--toolchain-root <absolute-directory> ...] [--executor-helper <absolute-file>] [--name <device-name>] [--json]",
  },
  {
    command: ["remote-workspace","agent"],
    summary: "Keep the paired executor connected to its Hub.",
    routes: [],
    flags: [],
    mutates: true,
    json: "none",
    details: ["Executor-local state/control; no Hub management API routes.","Maintains the enrolled executor connection to the Hub until interrupted."],
    usage: "ocx remote-workspace agent",
  },
  {
    command: ["remote-workspace","status"],
    summary: "Read local executor enrollment and available capabilities without printing credentials.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the public local executor status."}],
    mutates: false,
    json: "payload",
    details: ["Executor-local state/control; no Hub management API routes.","Reports local enrollment and platform/helper capabilities without credentials; not Hub device/runtime/session inventory."],
    usage: "ocx remote-workspace status [--json]",
  },
  {
    command: ["models","price"],
    summary: "Read the saved manual price for an exact provider/model selector.",
    routes: [{"method":"GET","path":"/api/providers/{provider}/model-costs"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit provider, modelId, and cost (null for automatic pricing)."}],
    mutates: false,
    json: "envelope",
    details: ["The provider must be configured; everything after the first slash is the exact upstream model ID."],
    usage: "ocx models price <provider/model> [--json]",
  },
  {
    command: ["models","set-price"],
    summary: "Save four manual USD-per-1M-token rates, or restore automatic pricing for one model.",
    routes: [{"method":"PUT","path":"/api/providers/{provider}/model-costs"}],
    flags: [{"name":"--input","value":"number","summary":"Input rate; required unless --auto is used."},{"name":"--output","value":"number","summary":"Output rate; required unless --auto is used."},{"name":"--cache-read","value":"number","summary":"Cache read rate; defaults to 0."},{"name":"--cache-write","value":"number","summary":"Cache write rate; defaults to 0."},{"name":"--auto","value":"boolean","summary":"Remove this model's override; cannot be combined with rates."},{"name":"--json","value":"boolean","summary":"Emit the saved price or reset result as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Uses the exact upstream model ID after the first slash. Omitted cache rates default to zero; sibling model prices are preserved."],
    usage: "ocx models set-price <provider/model> (--input <N> --output <N> [--cache-read <N>] [--cache-write <N>]|--auto) [--json]",
  },
  {
    command: ["models","set"],
    summary: "Save per-model overrides for a routed model, or clear them back to the computed values.",
    routes: [{"method":"PUT","path":"/api/model-settings"}],
    flags: [{"name":"--context-window","value":"string","summary":"Context window in tokens; 0 or - clears the override."},{"name":"--modalities","value":"string","summary":"Comma-separated text,image,audio; - clears the override."},{"name":"--reasoning-efforts","value":"string","summary":"Comma-separated ladder; \"\" for no reasoning, - to inherit."},{"name":"--default-reasoning-effort","value":"string","summary":"Ladder member a request inherits when it omits one; - to inherit."},{"name":"--reset","value":"boolean","summary":"Clear every override on this model; cannot be combined with the options above."},{"name":"--json","value":"boolean","summary":"Emit the saved state as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Only routed provider/model selectors are supported. At least one option or --reset is required.","Context 0 or - and modalities/default effort - clear to null; reasoning efforts - restores inheritance while an empty string stores an empty ladder.","--reset clears every override (including the API-only responsesCustomTools) with null and cannot be combined with other settings. A saved-but-catalog-refresh-failed receipt must not be mistaken for an unsaved change."],
    usage: "ocx models set <provider/model> [--context-window <tokens|0|->] [--modalities <text,image,audio|->] [--reasoning-efforts <levels|->] [--default-reasoning-effort <level|->] [--reset] [--json]",
  },
  {
    command: ["status"],
    summary: "Proxy status, injection state, and version skew between this CLI and the running proxy.",
    // No management route: `collectStatus` identity-probes `/healthz` through
    // `findLiveProxy` and reads local config. Declaring `GET /api/status` here was wrong
    // -- that route does not exist, and the registry cross-check caught it.
    routes: [],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the status envelope as JSON." }],
    mutates: false,
    json: "envelope",
    details: ["Reads /healthz plus local config; drives no management API route.", "--json includes install: {method: bun|npm|pnpm|mise|source|standalone|unknown, evidence: {basis, mise?, error?}} from the updater's install detector."],
  },
  {
    command: ["resolve"],
    summary: "One JSON document naming the config home, the effective port, and the identity-checked proxy liveness verdict.",
    // No management route, same split as status: discovery is the identity-checked
    // /healthz probe inside findLiveProxy plus local config and the home from
    // src/config/paths.ts.
    routes: [],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the resolve document as JSON (the shell contract)." }],
    mutates: false,
    json: "envelope",
    details: [
      "Exit 0 carries a trustworthy verdict (live or proven absent); exit 1 means the CLI could not resolve and a caller must refuse to guess — unknown liveness never reads as absent.",
      "Built for embedding shells (desktop app): the liveness budgets stay owned by src/server/proxy-liveness.ts.",
    ],
  },
  {
    command: ["hub","invite"],
    summary: "Mint a single-use pairing code on a hub and print the exact `ocx connect` line for one more machine.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit code, expiresAt, dataUrl, managementUrl, and command."},{"name":"--data-url","value":"string","summary":"Advertise this data origin instead of hub.dataPublicOrigin or the bind address."},{"name":"--management-url","value":"string","summary":"Confirm the management origin; it must equal hub.managementPublicOrigin."},{"name":"--clients","value":"string","summary":"Pre-select codex and/or claude in the printed connect command."}],
    mutates: true,
    json: "envelope",
    details: ["Hub only: refuses when runtimeRole is not hub, and requires a running attested proxy.","The code is secret, single-use and short-lived; it is bound to hub.managementPublicOrigin and to the connecting machine's loopback browser origin.","The bound browser origin is always printed; when it is not http://localhost:10100 the warning names the port the connecting machine must use.","Refuses when the advertised data origin would be loopback (a loopback or wildcard bind with no hub.dataPublicOrigin and no --data-url) rather than printing a line that dials the other machine itself.","Prints no data-plane token. Remote machines receive their own revocable per-client key from the exchange.","Mints through the attested local pairing-grant route, the same one ocx gui pair uses; no admin token is read."],
  },
  {
    command: ["connect", "rotate"],
    summary: "Rotate the connected client's data key against the hub, with commit and abort.",
    // One command drives all three: start returns the new secret once, commit promotes it,
    // and abort unwinds a rotation that could not be confirmed. They are not separate verbs
    // because a half-rotation is not a state an operator should be able to leave behind.
    routes: [
      { method: "POST", path: "/api/keys/rotate" },
      { method: "POST", path: "/api/keys/rotate/commit" },
      { method: "DELETE", path: "/api/keys/rotate" },
    ],
    flags: [
      { name: "--pairing-code-stdin", value: "boolean", summary: "Read a one-time pairing code from stdin as the rotation authority." },
      { name: "--admin-token-stdin", value: "boolean", summary: "Read the hub admin token from stdin as the rotation authority." },
      { name: "--json", value: "boolean", summary: "Emit the rotation result as JSON." },
    ],
    mutates: true,
    json: "payload",
    details: [
      "Requires transient authority on stdin; the credential is never persisted or echoed.",
      "A rotation left pending by a crash is resumed here — startup and status stop rather than guess which key generation is live.",
    ],
  },
  {
    command: ["update"],
    summary: "Plan or apply an OpenCodex update.",
    routes: [],
    flags: [
      { name: "--plan", value: "boolean", summary: "Preview an orchestrated update with --json." },
      { name: "--yes", value: "boolean", summary: "Apply an orchestrated update with --json." },
      { name: "--json", value: "boolean", summary: "Emit a versioned plan or result." },
      { name: "--tag", value: "string", summary: "Select latest or preview for the legacy update or plan." },
      { name: "--version", value: "string", summary: "Select an exact version for a plan or apply." },
      { name: "--expect-plan", value: "string", summary: "Require the apply plan to match this planToken." },
      { name: "--not-after", value: "string", summary: "Refuse mutation after this Unix millisecond deadline." },
      { name: "--desktop", value: "boolean", summary: "Update a Windows Desktop installation headlessly (signature-verified MSI)." },
      { name: "--check", value: "boolean", summary: "With --desktop, report the published and serving versions without installing." },
    ],
    mutates: true,
    json: "envelope",
    details: [
      "Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 previous version verified; 12 uncertain; 64 usage.",
      "--desktop exit codes: 0 done or up to date; 1 nothing installed; 2 old runtime still serving or reboot pending; 3 installer uncertain; 64 usage.",
    ],
  },
  {
    command: ["capabilities"],
    summary: "List the declared CLI capabilities and the management routes they drive.",
    routes: [],
    flags: [
      { name: "--json", value: "boolean", summary: "Emit the full capability table as JSON." },
      { name: "--contracts", value: "boolean", summary: "List supported versioned contracts." },
      { name: "--mutating-only", value: "boolean", summary: "Restrict output to capabilities that mutate state." },
      { name: "--route", value: "string", summary: "Show which capabilities drive a management route." },
    ],
    mutates: false,
    json: "envelope",
    details: ["Start here when driving ocx programmatically: it is the declared surface index, not a complete verb list."],
  },
  {
    command: ["provider","list"],
    summary: "Configured providers with connectivity and selected models.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the provider list as JSON."},{"name":"--jsonl","value":"boolean","summary":"Emit one configured provider per JSON line."}],
    mutates: false,
    json: "envelope",
    details: [
      "Local config and registry read, not GET /api/providers. --json and --jsonl are mutually exclusive.",
      "Each configured row carries active: false while this device is linked to a Home (a Remote Link Child or a Hub-mode client), whose providers serve instead; true when the row serves. Credential values are never printed.",
    ],
    usage: "ocx provider list [--json|--jsonl]",
  },
  {
    command: ["provider","resets"],
    summary: "Recently detected quota resets and whether reset notifications are enabled.",
    routes: [{"method":"GET","path":"/api/quota-resets"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit reset events as JSON."},{"name":"--limit","value":"number","summary":"Limit returned events; defaults to 20, capped at 100."}],
    mutates: false,
    json: "payload",
    usage: "ocx provider resets [--limit <n>] [--json]",
    details: [],
  },
  {
    command: ["provider","keychain"],
    summary: "Move a provider's API key into the OS keychain, restore it, or report where it lives.",
    routes: [{"method":"GET","path":"/api/providers/keychain"},{"method":"POST","path":"/api/providers/keychain"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the keychain status or result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["status reads by provider name; store/restore POST {name,action}. These move an existing secret between config and OS keychain; keep credential material out of transcripts."],
    usage: "ocx provider keychain <name> [status|store|restore] [--json]",
  },
  {
    command: ["companion"],
    summary: "Inspect companion settings, filtered usage and timeline, and configure preferences.",
    routes: [{"method":"GET","path":"/api/companion/settings"},{"method":"PUT","path":"/api/companion/settings"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit companion settings as JSON."}],
    mutates: true,
    json: "payload",
    details: ["show/default reads settings; set key=value and reset write settings. Values parse as JSON when valid.","usage reads today and 30-day totals using saved display filters; partial range failure returns exit1 and keeps available results.","timeline is a separate read of the usage timeline with explicit model selection/provider exclusion and completeness metadata; it does not change settings."],
    usage: "ocx companion show [--json] | ocx companion set <key>=<value> [...] [--json] | ocx companion reset [--json]",
  },
  {
    command: ["account","login"],
    summary: "Log in to an OAuth provider; Kiro can add a native device account.",
    routes: [{"method":"POST","path":"/api/oauth/login"},{"method":"GET","path":"/api/oauth/status"},{"method":"POST","path":"/api/oauth/login/code"},{"method":"POST","path":"/api/codex-auth/login"},{"method":"GET","path":"/api/codex-auth/login-status"},{"method":"POST","path":"/api/codex-auth/login/code"}],
    flags: [{"name":"--id","value":"string","summary":"Account ID; provider OAuth requires --reauth when supplied."},{"name":"--reauth","value":"boolean","summary":"Reauthenticate an existing account."},{"name":"--device","value":"boolean","summary":"Codex device flow or xAI device authorization; a no-op for already-device-native kimi, nous and github-copilot."},{"name":"--method","value":"string","summary":"Kiro only: builder-id, google or github; add-only and incompatible with --reauth, --id, --device or --code."},{"name":"--code","value":"string","summary":"Use - to read authorization material from stdin."},{"name":"--no-wait","value":"boolean","summary":"Return after flow start."},{"name":"--json","value":"boolean","summary":"Emit the command result as JSON; xAI --device requires --no-wait."},{"name":"--open-browser","value":"string","summary":"on or off for browser-capable login; rejected for explicit/native device flows."},{"name":"--add-account","value":"string","summary":"Fresh generic OAuth login only: on forces a fresh flow, off permits existing import preference. Not supported with reauth/Codex/Kiro method."},{"name":"--accept-antigravity-risk","value":"boolean","summary":"google-antigravity only: accept the Google account-ban risk without the interactive y/N prompt."}],
    mutates: true,
    json: "payload",
    usage: "ocx account login <provider> [--id <account-id>] [--reauth] [--device] [--method <builder-id|google|github>] [--code -] [--no-wait] [--open-browser <on|off>] [--add-account <on|off>] [--accept-antigravity-risk] [--json]",
    details: ["openai, codex and chatgpt address the Codex pool. Native main uses the separate account main reauth flow.","google-antigravity (login and reauth) prints an account-ban warning and needs a y answer on a terminal or --accept-antigravity-risk; otherwise it is refused before any request. Agent-driven runs are refused even with the flag (AGENTS_INSTALL.md).","Login is a human authorization handoff. Codes, verification material and credentials must not be copied into agent transcripts. Legacy argv code input warns about exposure; use stdin.","No --live flag is implemented. Provider OAuth --id requires --reauth; --method is Kiro add-only.","Omitted options preserve each flow's existing defaults. Explicit browser flags are refused for Codex device, known native-device providers and native Kiro method; add-account is refused for reauth/Codex/Kiro method.","Start/code/poll are pinned; human verification remains required. Only public handoff/flow/state fields are printed. Completed-but-validation/catalog-pending outcomes remain visible and nonzero."],
  },
  {
    command: ["account","history"],
    summary: "Cached quota observations for one stored Codex pool account.",
    routes: [{"method":"GET","path":"/api/codex-auth/quota/history"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the bounded observation history."},{"name":"--limit","value":"number","summary":"Return the newest 1 to 200 observations."}],
    mutates: false,
    json: "payload",
    details: ["Use account history openai <pool-account-id>. Reads cached observations only; no refresh or warmup. Native main is not included."],
    usage: "ocx account history openai <pool-account-id> [--limit <1-200>] [--json]",
  },
  {
    command: ["account","main","reauth"],
    summary: "Reauthenticate the native main Codex login with a device code (#3898); headless hubs need no Codex App or keyring.",
    routes: [{"method":"POST","path":"/api/codex-auth/main/reauth-device"},{"method":"GET","path":"/api/codex-auth/main/reauth-device"},{"method":"DELETE","path":"/api/codex-auth/main/reauth-device"}],
    flags: [{"name":"--device","value":"boolean","summary":"Run the device-code flow (the only reauth mode)."},{"name":"--no-wait","value":"boolean","summary":"Print the flow handle and code without waiting for completion."},{"name":"--flow","value":"string","summary":"Flow id for status and cancel."},{"name":"--json","value":"boolean","summary":"Emit the flow status as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Same-identity native main device reauthentication; pool login endpoints are separate. Human authorization is required and credentials are never printed.","Start requires --device; --no-wait returns a flow handle. Follow with account main reauth status --flow <id> or account main reauth cancel --flow <id>. Status/cancel require --flow and reject --device/--no-wait.","Returned verification URLs and device codes are human handoff material; keep them out of agent transcripts."],
    usage: "ocx account main reauth --device [--no-wait] [--json]",
  },
  {
    command: ["account","list"],
    summary: "List live Codex, OAuth and API-key accounts with optional quota observations.",
    routes: [{"method":"GET","path":"/api/oauth/providers"},{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"GET","path":"/api/codex-auth/active"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"GET","path":"/api/providers/keys"}],
    flags: [{"name":"--all","value":"boolean","summary":"Include notes for providers with no stored accounts."},{"name":"--quota","value":"boolean","summary":"Include quota observations; OAuth and supported API-key providers may probe upstream."},{"name":"--refresh","value":"boolean","summary":"With --quota, bypass quota cache; otherwise has no effect."},{"name":"--json","value":"boolean","summary":"Emit the command result as JSON."}],
    mutates: false,
    json: "envelope",
    details: ["Omitting provider discovers OAuth providers and includes configured families. JSON is {accounts,notes}, not a raw server account array.","Default listing is observational. --quota can probe provider quotas; --refresh is only acted on together with --quota. A refresh observation is not pending-account validation consent."],
    usage: "ocx account list [provider] [--all] [--quota [--refresh]] [--json]",
  },
  {
    command: ["account","import-orca"],
    summary: "Preview or register read-only links to Orca-managed Codex accounts without another login.",
    routes: [],
    flags: [{"name":"--source","value":"string","required":true,"summary":"Orca data directory containing codex-accounts."},{"name":"--registry","value":"string","required":true,"summary":"The chosen Orca profile's orca-data.json account registry."},{"name":"--apply","value":"boolean","summary":"Register new accounts; requires a stopped proxy. Default is preview."},{"name":"--json","value":"boolean","summary":"Emit counts and fixed invalid-reason codes without credentials or source paths."}],
    mutates: true,
    json: "envelope",
    details: ["Local files only; never copies refresh tokens or changes Orca authentication files.","Skips existing ChatGPT identities. New accounts remain pending until dashboard validation.","Orca must keep the source login available and refreshed; a missing or expired source fails closed.","Mixed eligible and invalid entries exit successfully; an all-invalid result exits nonzero."],
    usage: "ocx account import-orca --source <orca-data-directory> --registry <orca-data.json> [--apply] [--json]",
  },
  {
    command: ["account","refresh"],
    summary: "Refresh account quotas without model validation; pending Codex accounts require dashboard consent.",
    routes: [{"method":"POST","path":"/api/codex-auth/accounts/refresh"},{"method":"GET","path":"/api/codex-auth/active"},{"method":"GET","path":"/api/provider-quotas"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the refresh result as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["CLI/admin-token refreshes only observe usage. After quota recovery, a human must click Refresh quotas in the dashboard to authorize model validation. Do not mint a GUI session to work around this consent boundary."],
    usage: "ocx account refresh <provider> [--json]",
  },
  {
    command: ["account","grok-reset-coupons"],
    summary: "Inspect or redeem Grok billing reset coupons; redemption is journaled and idempotent.",
    routes: [{"method":"GET","path":"/api/grok/reset-coupons"},{"method":"POST","path":"/api/grok/reset-coupons/consume"}],
    flags: [{"name":"--consume","value":"boolean","summary":"Redeem one reset coupon; requires --yes."},{"name":"--yes","value":"boolean","summary":"Explicit confirmation required by --consume."},{"name":"--token-id","value":"string","summary":"Redeem a specific reset token instead of the default selection."},{"name":"--operation-id","value":"string","summary":"UUIDv4 making a redemption idempotent: retries replay the journaled outcome."},{"name":"--json","value":"boolean","summary":"Emit the coupon list or redemption result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Without --consume this is a read: remaining coupons and their validity windows.","The operation is journaled before the upstream call, so retrying the same --operation-id replays the recorded outcome instead of spending a second coupon."],
    usage: "ocx account grok-reset-coupons [account-id] [--consume --yes [--token-id <token-id>] [--operation-id <uuid>]] [--json]",
  },
  {
    command: ["usage"],
    summary: "Token and estimated-cost report over a time range.",
    routes: [{"method":"GET","path":"/api/usage"}],
    flags: [{"name":"--range","value":"string","summary":"today | 1d | 7d | 30d | all; default 30d."},{"name":"--surface","value":"string","summary":"all | codex | claude | grok; default all."},{"name":"--since","value":"string","summary":"Inclusive epoch milliseconds or ISO datetime with timezone; requires --until."},{"name":"--until","value":"string","summary":"Inclusive end; requires --since. Custom bounds override --range."},{"name":"--provider","value":"string","summary":"Filter provider."},{"name":"--model","value":"string","summary":"Filter model."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."},{"name":"--api-key-id","value":"string","summary":"Exact nonblank management key scope; connected clients refuse this before reading their enrolled key."},{"name":"--search","value":"string","summary":"Model-row substring view over model/provider/resolvedModel; top100 by tokens. Whole-report totals stay unchanged."}],
    mutates: false,
    json: "payload",
    details: ["Alias of observe usage. Connected clients read only their enrolled-key Hub report through /v1/usage; caller --api-key-id is refused before key read/transport and never grants management authority.","Nonclient --api-key-id uses /api/usage and requires matching filter acknowledgment. An unknown acknowledged key is empty/matched:false, not404. Custom-window acknowledgment remains required.","--search filters only returned model rows after scope acknowledgment. Blank search selects the top100 model rows; modelView reports match/return counts without recomputing totals.","Nested compare reads the named range and the previous equal window; --range all is refused."],
    usage: "ocx usage [--range <today|1d|7d|30d|all>] [--surface <all|codex|claude|grok>] [--since <epoch-ms|ISO-datetime>] [--until <epoch-ms|ISO-datetime>] [--provider <name>] [--model <id>] [--api-key-id <id>] [--search <text>] [--json]",
  },
  {
    command: ["account","pause"],
    summary: "Exclude one account in a Codex, Anthropic, generic OAuth or API-key pool from automatic selection.",
    routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"},{"method":"GET","path":"/api/providers/keys"},{"method":"PUT","path":"/api/providers/keys/pause"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the pause result as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Codex pause unbinds pinned threads and selects a fallback when possible; with no fallback, the paused account cannot dispatch until resumed. Anthropic and generic OAuth pause exclude the account from new requests, failover and refresh, and an all-paused pool answers 403. Credentials and health are preserved; already-sent turns are not cancelled."],
    usage: "ocx account pause <provider> <account-id|alias|main> [--json]",
  },
  {
    command: ["account","resume"],
    summary: "Return a paused account to a Codex, Anthropic, generic OAuth or API-key pool.",
    routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"},{"method":"GET","path":"/api/providers/keys"},{"method":"PUT","path":"/api/providers/keys/pause"}],
    flags: [{"name":"--if-healthy","value":"boolean","summary":"Resume only after a fresh account-bound health read succeeds; Codex and Anthropic pools."},{"name":"--json","value":"boolean","summary":"Emit the resume result as JSON."}],
    mutates: true,
    json: "envelope",
    usage: "ocx account resume <provider> <account-id|alias|main> [--if-healthy] [--json]",
    details: [],
  },
  {
    command: ["account","pause-exhausted"],
    summary: "Pause every Codex account whose quota is spent.",
    routes: [{"method":"PUT","path":"/api/codex-auth/accounts/pause-exhausted"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit paused ids and the checked/failed counts as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Only Codex account pools are supported. Refreshes quota and may partially fail; nonzero failedAccountCount exits 1 and sets ok:false."],
    usage: "ocx account pause-exhausted <provider> [--json]",
  },
  {
    command: ["account","strategy"],
    summary: "Show or set how an account pool picks the next account.",
    routes: [{"method":"GET","path":"/api/pool/settings"},{"method":"PUT","path":"/api/pool/settings"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the applied strategy and sticky limit as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["A bare invocation reads and never writes.","The APPLIED value is echoed, not the requested one, so a server-side normalization stays visible.","Values are not re-validated in the CLI: the server owns the strategy names and the 1-100 sticky bound.","One route answers for every pool kind and declares which fields that kind honours in `supported`, so an unsupported field is a stated null rather than an absence. `anthropic` alone carries `quotaWindow`. Generic-provider settings steer selection only while `pool.kernel` is on. The legacy per-pool paths still work and are unchanged."],
    usage: "ocx account strategy <provider> [quota|round-robin|fill-first|reset-near-weighted|least-loaded|reset-first] [--json]",
  },
  {
    command: ["account","sticky"],
    summary: "Show or set how many consecutive requests stay on one account.",
    routes: [{"method":"GET","path":"/api/pool/settings"},{"method":"PUT","path":"/api/pool/settings"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the applied strategy and sticky limit as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Only meaningful under the sticky-capable strategies; the pool strategy is the other half of this setting."],
    usage: "ocx account sticky <provider> [1-100] [--json]",
  },
  {
    command: ["account","routes"],
    summary: "Read, replace, or clear Anthropic OAuth model account routes.",
    routes: [{"method":"GET","path":"/api/pool/settings"},{"method":"PUT","path":"/api/pool/settings"}],
    flags: [{"name":"--file","value":"string","summary":"Read a bounded JSON route array from a local file."},{"name":"--clear","value":"boolean","summary":"Remove the stored routes."},{"name":"--json","value":"boolean","summary":"Emit the unified settings response as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Only anthropic is supported. Omitted --file/--clear reads. --clear sends routes:null; file and clear are mutually exclusive. The local JSON file must be a regular file of at most 64 KiB; the server validates its route array."],
    usage: "ocx account routes anthropic [--file <json-file>|--clear] [--json]",
  },
  {
    command: ["account","auto-switch"],
    summary: "Show or set the usage percentage at which a pool moves to another account.",
    routes: [{"method":"GET","path":"/api/codex-auth/active"},{"method":"PUT","path":"/api/codex-auth/auto-switch"},{"method":"GET","path":"/api/oauth/accounts/pool"},{"method":"PUT","path":"/api/oauth/accounts/pool"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/auto-switch"},{"method":"GET","path":"/api/codex-auth/accounts"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the stored threshold and whether it is applied."},{"name":"--account","value":"string","summary":"Per-account scope for openai or anthropic; openai resolves main/exact ID/unambiguous alias from the selected runtime."}],
    mutates: true,
    json: "envelope",
    details: ["Without --account the existing pool-wide operation remains. OpenAI per-account status reads override plus effective threshold; on writes80, off0, inherit null, threshold a validated0–100 integer.","New OpenAI policy writes require successful unambiguous roster evidence and never fall back to a raw unresolved selector. These are routing thresholds, not pool enablement or paid-credit permission."],
    usage: "ocx account auto-switch <provider> <status|on|off|threshold <0-100>|inherit> [--account <id>] [--json]",
  },
  {
    command: ["logs"],
    summary: "Recent request log rows, filterable by provider, model, conversation, account, and status.",
    routes: [{"method":"GET","path":"/api/logs"}],
    flags: [{"name":"--provider","value":"string","summary":"Filter provider, including failover attempts."},{"name":"--model","value":"string","summary":"Filter model, including failover attempts."},{"name":"--status","value":"string","summary":"Filter status code."},{"name":"--conversation","value":"string","summary":"Filter conversation ID."},{"name":"--conversationId","value":"string","summary":"Alias of --conversation."},{"name":"--account","value":"string","summary":"Filter stable account log label."},{"name":"--limit","value":"number","summary":"Positive row limit; default 200."},{"name":"--follow","value":"boolean","summary":"Poll for new rows; add --jsonl to emit JSONL."},{"name":"-f","value":"boolean","summary":"Alias of --follow."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."},{"name":"--jsonl","value":"boolean","summary":"Emit one row per JSON line; exclusive with --json."},{"name":"--events","value":"boolean","summary":"Versioned snapshot/append JSONL; requires --follow, conflicts with --json. Redundant --jsonl is accepted."}],
    mutates: false,
    json: "payload",
    details: ["Follow uses the server cursor and a bounded ordered window, preserving same-ID amendments and repeated row occurrences. It never enables logging.","--events emits version1 snapshots/appends with cursor and limit for observed-window reconstruction. Legacy row JSONL cannot express removals or resets exactly; neither mode promises lossless history between polls.","Follow limit is1–2000, default200. Polling is serial and cancellable; SIGINT exits130 and SIGTERM143. Malformed/oversized/unavailable responses stop without a fabricated empty snapshot or retry.","Nested history pages the derived index and get reads one canonical row; explain reads recorded decisions; rebuild-index and index-status touch the local derived index and retain separate declarations."],
    usage: "ocx logs [--provider <name>] [--model <id>] [--status <code>] [--conversation <id>] [--account <label>] [--limit <n>] [--follow] [--json|--jsonl]; ocx logs --follow --events [--limit <1-2000>]",
  },
  {
    command: ["storage","report"],
    summary: "Disk usage under CODEX_HOME, with the log-guard protection report.",
    routes: [{"method":"GET","path":"/api/storage"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the storage report as JSON."}],
    mutates: false,
    json: "payload",
    bannerLines: ["ocx storage                 Storage report (default subcommand)"],
    usage: "ocx storage report [--json]",
    details: [],
  },
  {
    command: ["storage","cleanup"],
    summary: "Preview or delete the oldest archived sessions by percentage.",
    routes: [{"method":"POST","path":"/api/storage/cleanup/preview"},{"method":"POST","path":"/api/storage/cleanup"}],
    flags: [{"name":"--percent","value":"number","summary":"Portion of the oldest archived sessions to target (0-100)."},{"name":"--mode","value":"string","summary":"quarantine (recoverable from trash) or permanent."},{"name":"--yes","value":"boolean","summary":"Required to actually delete; without it this is a preview."},{"name":"--json","value":"boolean","summary":"Emit the preview or result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Without `--yes` it prints what WOULD be freed and exits 0 having changed nothing.","There is no interactive confirmation: a prompt an agent can answer is not a safety boundary.","`--mode quarantine` moves files to trash, so `storage trash restore` can undo it; `permanent` cannot be undone."],
    usage: "ocx storage cleanup --percent <0-100> [--mode <quarantine|permanent>] [--yes] [--json]",
  },
  {
    command: ["storage","trash"],
    summary: "List quarantined cleanup batches, or restore one.",
    routes: [{"method":"GET","path":"/api/storage/trash"},{"method":"POST","path":"/api/storage/trash/restore"}],
    flags: [{"name":"--yes","value":"boolean","summary":"Required for restore, which moves files and reconciles database rows."},{"name":"--json","value":"boolean","summary":"Emit the trash list or restore result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Restore fails with a named 409 when the destination already exists, rather than overwriting it.","Mixed family: list/default reads quarantine batches; restore moves files and reconciles database rows only with --yes."],
    usage: "ocx storage trash [list] [--json] | ocx storage trash restore <entry-id> --yes [--json]",
  },
  {
    command: ["storage","policy"],
    summary: "Show, change, or run the automatic archived-session cleanup policy.",
    routes: [{"method":"GET","path":"/api/storage/cleanup-policy"},{"method":"PUT","path":"/api/storage/cleanup-policy"},{"method":"POST","path":"/api/storage/cleanup-policy/run"}],
    flags: [{"name":"--enabled","value":"string","summary":"true or false."},{"name":"--percent","value":"number","summary":"Portion of oldest archived sessions each run targets."},{"name":"--mode","value":"string","summary":"quarantine or permanent."},{"name":"--schedule","value":"string","summary":"startup, daily, weekly, or manual."},{"name":"--yes","value":"boolean","summary":"Required for `policy run`, which deletes immediately."},{"name":"--json","value":"boolean","summary":"Emit the policy or run state as JSON."}],
    mutates: true,
    json: "payload",
    details: ["`policy set` never enables implicitly: omitting `--enabled` keeps the stored value.","`policy run` forces a run regardless of schedule, so it needs `--yes`.","Mixed family: show/default reads; set persists submitted fields; run requires --yes and starts immediate cleanup. At least one setting is required by set."],
    usage: "ocx storage policy [show] [--json] | ocx storage policy set [--enabled <true|false>] [--percent <1-100>] [--mode <quarantine|permanent>] [--schedule <startup|daily|weekly|manual>] [--json] | ocx storage policy run --yes [--json]",
  },
  {
    command: ["inspect", "config"],
    summary: "The effective merged configuration the proxy is running.",
    routes: [{ method: "GET", path: "/api/config" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the config as JSON." }],
    mutates: false,
    json: "payload",
  },
  {
    command: ["inspect", "catalog"],
    summary: "The generated model catalog served to clients.",
    routes: [{ method: "GET", path: "/api/catalog" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the catalog as JSON." }],
    mutates: false,
    json: "payload",
  },
  {
    command: ["inspect", "routing-analytics"],
    summary: "Aggregate routing outcomes per provider and model.",
    routes: [{ method: "GET", path: "/api/routing-analytics" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the analytics payload as JSON." }],
    mutates: false,
    json: "payload",
  },
  {
    command: ["inspect", "pacing"],
    summary: "Request-pacing state for one provider or all of them.",
    routes: [{ method: "GET", path: "/api/provider-request-pacing" }],
    flags: [
      { name: "--name", value: "string", summary: "Restrict to one provider; omitted means every provider." },
      { name: "--json", value: "boolean", summary: "Emit the pacing state as JSON." },
    ],
    mutates: false,
    json: "payload",
    details: ["An unknown provider name is a 404 rather than an empty result."],
  },
  {
    command: ["inspect", "key-providers"],
    summary: "Providers that authenticate with an API key rather than OAuth.",
    routes: [{ method: "GET", path: "/api/key-providers" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the provider list as JSON." }],
    mutates: false,
    json: "payload",
  },
  {
    command: ["inspect", "codex-prompt"],
    summary: "The Codex system prompt state, or the prompt text itself.",
    routes: [
      { method: "GET", path: "/api/codex-prompt" },
      { method: "GET", path: "/api/codex-prompt/text" },
    ],
    flags: [
      { name: "--text", value: "boolean", summary: "Print the prompt body verbatim instead of its metadata." },
      { name: "--json", value: "boolean", summary: "Emit the prompt metadata as JSON." },
    ],
    mutates: false,
    json: "payload",
    details: ["Read-only by design: the six mutating prompt routes require a dashboard session."],
  },
  {
    command: ["inspect", "client-config"],
    summary: "The generated configuration snippet for a supported client.",
    routes: [{ method: "GET", path: "/api/client-config" }],
    flags: [
      { name: "--client", value: "string", summary: "Required client id; the route names every accepted value on error." },
      { name: "--json", value: "boolean", summary: "Emit the snippet payload as JSON." },
    ],
    mutates: false,
    json: "payload",
  },
  {
    command: ["inspect", "star"],
    summary: "Whether this repository is starred by the signed-in GitHub account.",
    // GET only, permanently. The POST spends the operator identity and requires a dashboard
    // session precisely so an agent cannot answer that question for them.
    routes: [{ method: "GET", path: "/api/github/star" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the star status as JSON." }],
    mutates: false,
    json: "payload",
    details: ["Starring is never available from the CLI; the verb says so rather than offering a flag that cannot work."],
  },
  {
    command: ["inspect", "windows-tray"],
    summary: "Windows tray helper state.",
    routes: [{ method: "GET", path: "/api/windows-tray" }],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the tray state as JSON." }],
    mutates: false,
    json: "payload",
  },
  {
    command: ["system","codex-app-server"],
    summary: "Codex app-server reachability and process state, as the dashboard sees it.",
    routes: [{"method":"GET","path":"/api/system/codex-app-server"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the app-server state as JSON."}],
    mutates: false,
    json: "payload",
    details: ["The GUI reads this state directly; without a verb an agent could not tell whether the Codex app-server was reachable at all."],
    usage: "ocx system codex-app-server [--json]",
  },
  {
    command: ["system","codex-cli-update","check"],
    summary: "Inspect a configured Codex CLI candidate and its ownership provenance.",
    routes: [],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the redacted provenance report as JSON."}],
    mutates: false,
    json: "envelope",
    details: ["Proof-bound published-launcher context authenticates the configured candidate snapshot, not successful Codex execution; the selection is attested only when the runtime resolver picks the same canonical path, and even then this check reports rather than admits a runtime.","On Windows this first slice performs no candidate or configuration filesystem I/O: only a proof-captured absolute environment candidate can receive lexical app-bundle or version-manager labels; every other Windows candidate fails closed.","Makes no package-registry request.","Does not execute Codex or npm, install or repair software, control a process, or write configuration or cache state."],
    usage: "ocx system codex-cli-update check [--json]",
  },
  {
    command: ["system","codex-cli-update","attest"],
    summary: "Observe the selected or explicitly named Windows npm Codex installation files without enabling updates.",
    routes: [],
    flags: [{"name":"--candidate","value":"string","summary":"Absolute npm codex.cmd or package bin/codex.js path; all four paths are all-or-none."},{"name":"--npm-prefix","value":"string","summary":"Absolute prefix containing node_modules/@openai/codex."},{"name":"--npm-cli","value":"string","summary":"Absolute node_modules/npm/bin/npm-cli.js path."},{"name":"--node","value":"string","summary":"Absolute node.exe path; observed, never executed."},{"name":"--json","value":"boolean","summary":"Emit the path-free installation identity observation."}],
    mutates: false,
    json: "envelope",
    details: ["Opt-in Windows x64 local-volume inspection using held native file handles; refuses reparse points, active writers and unsupported layouts.","Without explicit paths, the proof-bound launcher snapshot identifies the selected candidate: the configured CODEX_CLI_PATH or the first codex on the captured PATH, with an OpenCodex wrapper resolving to its codex.opencodex-real backing. Discovery only proposes paths; the held-handle observation remains the authority.","Success binds observed file identities and bytes, not selected-runtime admission or installer ownership.","selectionAttested, managed and applyAllowed remain false. The digest is an observation, not a durable update permit.","Does not run the named Codex/npm/Node files, query a registry, install software, control processes or persist state."],
    usage: "ocx system codex-cli-update attest [--candidate <absolute-path> --npm-prefix <absolute-path> --npm-cli <absolute-path> --node <absolute-path>] [--json]",
  },
  {
    command: ["system", "codex-cli-update", "plan"],
    summary: "Dry-run a Codex CLI update and print the plan id binding the decision's evidence.",
    routes: [],
    flags: [
      { name: "--channel", value: "string", summary: "Registry channel to resolve. Only the stable latest channel is offered." },
      { name: "--json", value: "boolean", summary: "Emit the plan as JSON." },
    ],
    mutates: false,
    json: "envelope",
    details: [
      "Local counterpart of GET /api/codex/cli-update/plan: runs the same proof-bound plan builder without HTTP transport.",
      "Adds the three inputs check leaves out: an exact registry version with its sha512 integrity, a fail-closed process-table read, and a decision.",
      "The registry evidence is pinned to the official npm registry with project/user npm configuration isolated, so a redirected .npmrc cannot supply the answer.",
      "Installs nothing and mutates no application state; registry evidence is gathered under an isolated temporary npm root (npmrc, cwd, cache and logs) removed best-effort afterwards. A refusal is a normal dry-run answer and still exits 0.",
      "The plan id is a digest of the evidence; apply re-observes it before any mutation.",
      "Apply durably admits a bounded, same-user job before running; request IDs deduplicate retries and a conflicting payload is rejected. Unresolved records are retained rather than expired.",
      "An unreadable process table refuses rather than reading as no live session.",
    ],
    usage: "ocx system codex-cli-update plan [--channel latest] [--json]",
  },
  {
    command: ["system", "codex-cli-update", "apply"],
    summary: "Apply a confirmed Codex CLI update as a durable job.",
    routes: [],
    flags: [{ name: "--plan-id", value: "string", summary: "Required 32-hex id from the current plan." }, { name: "--yes", value: "boolean", summary: "Required confirmation." }, { name: "--request-id", value: "string", summary: "Optional stable retry key." }, { name: "--json", value: "boolean", summary: "Emit the public job status." }],
    mutates: true, json: "envelope",
    details: ["Local counterpart of POST /api/codex/cli-update/apply: invokes the same durable job owner with --yes confirmation; HTTP admission separately requires a current paired dashboard session on trusted loopback ingress, matching origin, CSRF and confirmed: true.", "Standalone HTTP pairing requires the configured literal 127.0.0.1 or ::1 origin; localhost aliases, wildcard binds and connected-client roles use the local CLI --yes path instead.", "Admission is stored under the protected current-user config root before the installer can run.", "Exit 0 requires an applied job; refused, not_applied, ambiguous and pending duplicate jobs exit 1, including with --json.", "Only POSIX npm-global managed installs are currently supported; Windows, shims and other managers remain refused."],
    usage: "ocx system codex-cli-update apply --plan-id <32-hex> --yes [--request-id <key>] [--json]",
  },
  {
    command: ["system", "codex-cli-update", "status"],
    summary: "Read a Codex CLI update job by opaque id.", routes: [], flags: [{ name: "--json", value: "boolean", summary: "Emit the path-free job status." }],
    mutates: false, json: "envelope", details: ["Local counterpart of GET /api/codex/cli-update/jobs/{jobId}: reads the same path-free job status without HTTP transport.", "Reads the protected job record directly; the job id is not an authorization credential."],
    usage: "ocx system codex-cli-update status <job-id> [--json]",
  },
  {
    command: ["system","codex-restart"],
    summary: "Restart the Codex app-servers, and the desktop app when its model picker predates the catalog.",
    routes: [{"method":"POST","path":"/api/system/codex-restart"}],
    flags: [{"name":"--yes","value":"boolean","summary":"Required: restarts the Codex app-servers, interrupting running turns, and fully quits and relaunches the operator's Codex desktop app when its model picker predates the current catalog or that cannot be determined, which may discard unsaved composer drafts, model-picker selections, and pending approval prompts."},{"name":"--json","value":"boolean","summary":"Emit the restart result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["`sync --restart-codex` is not a substitute: it restarts only as a side effect after a catalog, cache, or changed configuration write, so it cannot restart a healthy install on request.","Restarts the app-servers through the same module the CLI uses. The desktop app is quit and relaunched when its model picker predates the current catalog or this request changes the `model_catalog_json` binding, because the picker is built at launch; otherwise it is left running and respawns its own app-server, keeping unsaved client state. An unreadable desktop or catalog state falls back to the full restart. When the proxy itself runs inside the Codex app the desktop restart is refused, because restarting the app would kill the request.","--yes is mandatory because this interrupts a running editor session and may discard unsaved composer drafts, model-picker selections, and pending approval prompts; it must never happen because an agent guessed a subcommand."],
    usage: "ocx system codex-restart --yes [--json]",
  },
  {
    command: ["claude","config"],
    summary: "Read or update Claude Code settings, including independent CLI first-party routing.",
    routes: [{"method":"GET","path":"/api/claude-code"},{"method":"PUT","path":"/api/claude-code"}],
    flags: [{"name":"--enabled","value":"string","summary":"on or off."},{"name":"--auth-mode","value":"string","summary":"auto, proxy or subscription."},{"name":"--system-env","value":"string","summary":"on or off."},{"name":"--fast-mode","value":"string","summary":"on or off."},{"name":"--auto-context","value":"string","summary":"on or off."},{"name":"--compact-window","value":"string","summary":"Positive token count or default to clear."},{"name":"--context-accounting","value":"string","summary":"1m (default) or 200k."},{"name":"--inject-agents","value":"string","summary":"on or off."},{"name":"--native-passthrough","value":"string","summary":"on or off; off routes bare Claude models through opencodex instead of Claude Code's own login."},{"name":"--small-fast-model","value":"string","summary":"Model ID; - clears."},{"name":"--model-map","value":"string","summary":"Comma-separated from=to mappings; - clears."},{"name":"--blocked-skills","value":"string","summary":"Comma-separated names; - clears."},{"name":"--web-model","value":"string","summary":"Model ID; - clears."},{"name":"--web-backend","value":"string","summary":"openai, anthropic, xai, gemini, exa or -."},{"name":"--vision-model","value":"string","summary":"Model ID; - clears."},{"name":"--vision-backend","value":"string","summary":"openai, anthropic or -."},{"name":"--first-party","value":"string","summary":"on or off; must be the only setting."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["At least one setting is required. --first-party must be set alone and writes Claude settings immediately.","Clear both helper model and backend with - to restore inheritance. Preserve shared_proxy_retained warnings."],
    usage: "ocx claude config status [--json]; ocx claude config set [--enabled <on|off>] [--auth-mode <auto|proxy|subscription>] [--system-env <on|off>] [--fast-mode <on|off>] [--auto-context <on|off>] [--compact-window <tokens|default>] [--context-accounting <1m|200k>] [--inject-agents <on|off>] [--native-passthrough <on|off>] [--small-fast-model <id|->] [--model-map <from=to,...|->] [--blocked-skills <name,name|->] [--web-model <id|->] [--web-backend <openai|anthropic|xai|gemini|exa|->] [--vision-model <id|->] [--vision-backend <openai|anthropic|->] [--json]; or ocx claude config set --first-party <on|off> [--json]",
  },
  {
    command: ["claude","intercept","start"],
    summary: "Start the local Claude interception pair on demand.",
    routes: [{"method":"POST","path":"/api/claude-intercept/start"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the management response as JSON."}],
    mutates: true,
    json: "payload",
    usage: "ocx claude intercept start [--json]",
    details: [],
  },
  {
    command: ["claude","desktop","status"],
    summary: "Applied-vs-desired Claude Desktop state, including staleness, drift, and health.",
    routes: [{"method":"GET","path":"/api/claude-desktop/status"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the live status as JSON."}],
    mutates: false,
    json: "payload",
    details: ["Distinct from `claude desktop show`, which reports what this machine WOULD write; this reports what is actually in effect, which only the running proxy knows."],
    usage: "ocx claude desktop status [--json]",
  },
  {
    command: ["claude","desktop","bind"],
    summary: "First-party: serve a Claude Desktop Code tab picker model with an opencodex route.",
    routes: [{"method":"PUT","path":"/api/claude-desktop/first-party-bindings"}],
    flags: [],
    mutates: true,
    json: "none",
    details: ["Takes a picker model id (claude-sonnet-4-6) and a route in the Desktop route vocabulary (provider/model or native/<slug>); the route must be one the Desktop profile can offer.","Only Claude Code traffic that reaches the proxy through the first-party intercept (Desktop's Code tab, the claude CLI) honours it; ocx claude and the public Messages endpoint are unaffected.","The Desktop picker keeps Anthropic's label; the binding changes which model answers, starting with the next request."],
    usage: "ocx claude desktop bind <picker-model-id> <provider/model|native/slug>",
  },
  {
    command: ["claude","desktop","unbind"],
    summary: "Remove a first-party Claude Desktop Code tab picker binding.",
    routes: [{"method":"PUT","path":"/api/claude-desktop/first-party-bindings"}],
    flags: [],
    mutates: true,
    json: "none",
    details: ["Removing an id that is not bound is a no-op; the remaining bindings are printed."],
    usage: "ocx claude desktop unbind <picker-model-id>",
  },
  {
    command: ["claude","desktop","picker","status"],
    summary: "First-party picker mode: whether Claude Desktop's Code tab lists opencodex models, and what is missing if not.",
    routes: [{"method":"GET","path":"/api/claude-desktop/picker"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the result as JSON."}],
    mutates: false,
    json: "payload",
    details: ["Reads the live picker when available; otherwise reports local offline picker state. JSON emits the picker DTO, not the enclosing API response. No trust mutation."],
    usage: "ocx claude desktop picker status [--json]",
  },
  {
    command: ["claude","desktop","picker","on"],
    summary: "Turn first-party picker mode on and remember the choice.",
    routes: [{"method":"PUT","path":"/api/claude-desktop/picker"}],
    flags: [],
    mutates: true,
    json: "none",
    details: ["Needs a running proxy, first-party mode and macOS or Windows. The first time, the OS asks to trust a local certificate authority limited to claude.ai; when the server cannot show that prompt the command runs the trust step in this terminal.","Claude Desktop then reaches the network through opencodex; fully quit and reopen Desktop afterwards."],
    usage: "ocx claude desktop picker on",
  },
  {
    command: ["claude","desktop","picker","off"],
    summary: "Turn first-party picker mode off, remove its Desktop egress profile and certificate trust, and remember the choice.",
    routes: [{"method":"PUT","path":"/api/claude-desktop/picker"}],
    flags: [],
    mutates: true,
    json: "none",
    details: ["Works without a running proxy: the preference is saved and the picker profile and trust are removed locally."],
    usage: "ocx claude desktop picker off",
  },
  {
    command: ["claude","desktop","picker","trust"],
    summary: "Run the OS certificate trust step for picker mode in this terminal, then ask the server to finish enabling it.",
    routes: [{"method":"GET","path":"/api/claude-desktop/picker"},{"method":"PUT","path":"/api/claude-desktop/picker"}],
    flags: [],
    mutates: true,
    json: "none",
    details: ["The server removes trust this command added if the enable is refused; if the request is lost, trust is left alone and picker status tells what happened."],
    usage: "ocx claude desktop picker trust",
  },
  {
    command: ["integration","native"],
    summary: "Read native integration state or toggle Claude, Claude Desktop, Codex and Grok.",
    routes: [{"method":"GET","path":"/api/native-integrations"},{"method":"PUT","path":"/api/native-integrations/claude"},{"method":"PUT","path":"/api/native-integrations/claude-desktop"},{"method":"PUT","path":"/api/native-integrations/codex"},{"method":"PUT","path":"/api/native-integrations/grok"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the client rows or toggle result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Each on/off writes the Home's native switch, recording no route intent for the Home, and applies it through the client's runtime owner, including Claude Desktop's first-party transition; Children keep inheriting their saved default. Refused disables remain failures. On a Child it is refused with the exact Home command. Cursor status and local-installer are separate read-only subcommands; they do not toggle or install Cursor."],
    usage: "ocx integration native [list] [--json]; ocx integration native <claude|claude-desktop|codex|grok> <on|off> [--json]",
  },
  {
    command: ["integration","client"],
    summary: "Inspect and toggle file integrations and Aside profiles, read journals, and restore selected operations.",
    routes: [{"method":"GET","path":"/api/client-integrations"},{"method":"GET","path":"/api/client-integrations/{clientId}"},{"method":"GET","path":"/api/client-integrations/aside/profiles"},{"method":"GET","path":"/api/client-integrations/aside/profiles/{profileId}"},{"method":"GET","path":"/api/client-integrations/journal"},{"method":"GET","path":"/api/client-integrations/aside/profiles/journal"},{"method":"GET","path":"/api/client-integrations/aside/profiles/{profileId}/journal"},{"method":"PUT","path":"/api/client-integrations/{clientId}"},{"method":"PUT","path":"/api/client-integrations/aside/profiles"},{"method":"PUT","path":"/api/client-integrations/aside/profiles/{profileId}"},{"method":"POST","path":"/api/client-integrations/restore"},{"method":"POST","path":"/api/client-integrations/aside/profiles/{profileId}/restore"}],
    flags: [{"name":"--model-names","value":"string","summary":"Hermes/Command Code apply or overwrite only: alias or routed; omission preserves managed policy."},{"name":"--client","value":"string","summary":"File integration ID, including gentle-shell; aside selects profiles."},{"name":"--profile","value":"number","summary":"Aside nonnegative integer account ID; requires --client aside."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."},{"name":"--overwrite-conflict","value":"boolean","summary":"Explicitly permit replacing a conflicting block."},{"name":"--op","value":"string","summary":"Operation ID; --op-id is an alias."},{"name":"--confirm-drift","value":"boolean","summary":"Explicitly allow replacing edits made after the snapshot."}],
    mutates: true,
    json: "payload",
    details: ["status/show/list reads all clients, one client or Aside profiles. history/journal reads rollback records; expired snapshots stay visible.","enable/disable requires --client; an omitted Aside --profile toggles all profiles. Each toggle is this Home's own decision, like the dashboard: once the Home uses route intent it is recorded so ocx sync keeps it, and linked Children keep their defaults (ocx route to <client> on|off changes those). --overwrite-conflict applies only to enable.","restore requires --op (alias --op-id); --client requires --profile and only Aside supports that profile selector. --confirm-drift is an explicit user waiver, never auto-retried. Use client preview or restore --preview to inspect a change, history remove --op ID --yes to retire a journal row, and sync --client aside to refresh managed profiles."],
    usage: "ocx integration client status [--client <id>] [--profile <id>] [--json]; ocx integration client history [--client <id>] [--profile <id>] [--json]; ocx integration client enable --client <id> [--profile <id>] [--overwrite-conflict] [--model-names <alias|routed>] [--json]; ocx integration client disable --client <id> [--profile <id>] [--json]; ocx integration client restore --op <opId> [--client aside --profile <id>] [--confirm-drift] [--json]",
  },
  {
    command: ["sync"],
    summary: "Synchronize client catalogs, including Aside profiles and Pi through the running server's mutation owner.",
    routes: [{ method: "POST", path: "/api/client-integrations/aside/sync" }, { method: "POST", path: "/api/client-integrations/pi/sync" }],
    flags: [
      { name: "--overwrite-conflict", value: "boolean", summary: "Allow conflicting route materialization only for this explicit sync." },
      { name: "--overwrite-client", value: "string", summary: "Restrict takeover to one client; requires --overwrite-conflict." },
      { name: "--local-only", value: "boolean", summary: "Do not fan out the Home sync to linked Children." },
      { name: "--json", value: "boolean", summary: "Emit the sync fan-out result as JSON." },
      { name: "--restart-codex", value: "boolean", summary: "Restart the Codex app-servers and fully quit and relaunch the Codex desktop app after a catalog, cache, or changed configuration write, on macOS, Linux and Windows." },
      { name: "--restart-app-server-only", value: "boolean", summary: "Restart only the Codex app-servers and leave the desktop app running; wins over --restart-codex when both are given." },
      { name: "--restart-desktop-app", value: "boolean", summary: "Deprecated alias of --restart-codex." },
      { name: "--expect-link", value: "string", summary: "Sync only when this machine is a connected Remote Link Child of this link id; otherwise exit 5 with nothing changed." },
      { name: "--expect-hub-key", value: "string", summary: "Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed." },
      { name: "--child", value: "string", summary: "Fan out only to this link id; repeatable. Other links report not-selected." },
      { name: "--restart-children", value: "string", summary: "After each selected Child's sync, restart its Codex: app-server or codex (codex needs --yes); bare means app-server. Withheld per Child while a relayed model request is in flight." },
      { name: "--yes", value: "boolean", summary: "Confirms --restart-children=codex, which quits and relaunches the Codex app and ends live conversations on each selected Child." },
    ],
    mutates: true,
    json: "payload",
    details: [
      "The Aside refresh uses the live server; other catalog synchronization also performs local work.",
      "An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.",
      "A current Home catalog fans out to linked Children; --child <linkId> (repeatable) limits it to those links. Fan-out requests no Codex restart on a Child unless --restart-children[=app-server|codex] is given (codex also needs --yes); the Home then skips the restart, never the sync, for a Child with a model request in flight (restart-skipped:link-active), on Windows Children, and on ocx-child, and exits 6. Applying changed Home settings may restart the Child's own OpenCodex client runtime.",
      "After a successful Home sync, a connected Child skipped during fan-out, a failed or timed-out Child, a synced Child whose requested restart did not certainly happen (restart-skipped:*, restart-unsupported:ocx-child, restart-not-run, restart-result-unknown), or an unreadable link store yields partial exit 6. Skipped connected Children and withheld restarts include an actionable hint; update an outdated ocx through its owning installer, with the Desktop tray as an option for Desktop installs. Intentional skips, including client-initiated links, --local-only, not-selected (outside --child) and child-busy (a Child operation holds the Child), keep their existing exit behavior.",
      "--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.",
    ],
    usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--overwrite-conflict [--overwrite-client <id>]] [--local-only] [--json] [--restart-codex] [--restart-app-server-only] [--child <linkId>]... [--restart-children[=app-server] | --restart-children=codex --yes]",
  },
  {
    command: ["agent","subagents","force"],
    summary: "Force Claude Code subagents onto one exposed model at the next routed launch; - clears.",
    routes: [{"method":"PUT","path":"/api/subagent-models"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the saved force setting."}],
    mutates: true,
    json: "payload",
    details: ["Requires Claude Code 2.1.257+. Plain claude, forks, inherit skills, the main model and small-fast sidecars are unaffected."],
    usage: "ocx agent subagents force <model|-> [--json]",
  },
  {
    command: ["agent","request-user-input"],
    summary: "Show or set whether default mode may ask the operator a question mid-task.",
    routes: [{"method":"GET","path":"/api/codex-auth/features/default-mode-request-user-input"},{"method":"PUT","path":"/api/codex-auth/features/default-mode-request-user-input"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the feature state as JSON."}],
    mutates: true,
    json: "payload",
    details: ["A bare invocation reads and never writes."],
    usage: "ocx agent request-user-input [on|off] [--json]",
  },
  {
    command: ["agent","roles"],
    summary: "omo (Codex / LazyCodex): show each Codex agent role's model pin, set one role's model in its TOML and in omo.jsonc, or suggest a model for every role.",
    routes: [{"method":"GET","path":"/api/codex-agent-roles"},{"method":"PUT","path":"/api/codex-agent-roles/{role}"},{"method":"POST","path":"/api/codex-agent-roles/auto-assign"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the role list, the write result or the proposals as JSON."},{"name":"--effort","value":"string","summary":"set: also write the role's reasoning effort."},{"name":"--model","value":"string","summary":"suggest: size the roles with this model instead of the Codex default model."},{"name":"--apply","value":"boolean","summary":"suggest: write every proposal through the role model write."}],
    mutates: true,
    json: "payload",
    details: ["A bare invocation reads and never writes.","Requires Codex-based omo (LazyCodex): the omo@sisyphuslabs Codex plugin enabled in config.toml and installed; otherwise status lists no roles, and set and suggest are refused.","set rewrites only the root model value of $CODEX_HOME/agents/<role>.toml, plus model_reasoning_effort with --effort; omo.jsonc gets the same model and, when LazyCodex has that level, the effort as reasoning; it is skipped when absent or when it contains comments.","suggest sizes every role with one model call and prints proposals without writing; --apply writes each proposed model and effort."],
    usage: "ocx agent roles [status] [--json]; ocx agent roles set <role> <model> [--effort <level>] [--json]; ocx agent roles suggest [--model <id>] [--apply] [--json]",
  },
  {
    command: ["agent","injection"],
    summary: "Show or set the delegation model and effort, or suggest both for a described piece of delegated work.",
    routes: [{"method":"GET","path":"/api/injection-model"},{"method":"PUT","path":"/api/injection-model"},{"method":"POST","path":"/api/injection-model/suggest"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the delegation settings, the write result or the proposal as JSON."},{"name":"--model","value":"string","summary":"set: the delegation model, - clears it. suggest: size the work with this model instead of the Codex default model."},{"name":"--effort","value":"string","summary":"set: the delegation reasoning effort, - clears it."},{"name":"--prompt","value":"string","summary":"set: a custom guidance prompt, - clears it."},{"name":"--guidance","value":"string","summary":"set: on or off for OpenCodex delegation guidance."},{"name":"--apply","value":"boolean","summary":"suggest: write the proposed model and effort through the delegation settings write."},{"name":"--sync-codex-defaults","value":"string","summary":"set only: enable/disable the existing model-dependent default-sync policy."}],
    mutates: true,
    json: "payload",
    details: ["guidance aliases injection. Bare invocation reads; use explicit status before --json. set requires at least one setting and - clears model, effort or prompt.","suggest may spend a model call; it writes no settings unless --apply is explicitly supplied. Preserve unsized/unassigned/already-set outcomes.","Default-sync edits return actual normalized model/effort/prompt/guidance/default-sync state; they do not promise a client catalog rewrite. Clearing a model also clears dependent settings under server validation."],
    usage: "ocx agent injection status [--json]; ocx agent injection set [--model <id|->] [--effort <level|->] [--prompt <text|->] [--guidance <on|off>] [--sync-codex-defaults <on|off>] [--json]; ocx agent injection suggest <work description> [--model <id>] [--apply] [--json]",
  },
  {
    command: ["api","protocols"],
    summary: "Read the protocol contract version, API surfaces, protocol settings and feature vocabulary.",
    routes: [{"method":"GET","path":"/api/protocols"}],
    flags: [{"name":"--provider","value":"string","summary":"Add one configured provider's upstream wire and who decided it."},{"name":"--json","value":"boolean","summary":"Emit the GET /api/protocols body."}],
    mutates: false,
    json: "payload",
    usage: "ocx api protocols [--provider <name>] [--json]",
    details: [],
  },
  {
    command: ["combo","test"],
    summary: "Run one JEV decision probe through a decision method: TypeSafe, a System One row, or an opencodex model.",
    routes: [{"method":"GET","path":"/api/combos"},{"method":"POST","path":"/api/combos/decision-test"}],
    flags: [{"name":"--combo","value":"string","summary":"Combo id whose saved decision method is probed and whose recursion rules apply."},{"name":"--decision-provider","value":"string","summary":"Probe a jev-decision provider row (or jev for TypeSafe) instead of the saved method."},{"name":"--decision-model","value":"string","summary":"Probe an opencodex-routed model instead of the saved method."},{"name":"--decision-timeout","value":"number","summary":"Decision deadline in milliseconds (1000-120000)."},{"name":"--json","value":"boolean","summary":"Emit the probe result."}],
    mutates: true,
    json: "payload",
    details: ["--combo without an explicit decision override reads the saved combo first. The synthetic decision probe may spend a backend call; a failed-open receipt is not an applied decision."],
    usage: "ocx combo test [--combo <id>] [--decision-provider <provider|jev> | --decision-model <route>] [--decision-timeout <ms>] [--json]",
  },
  {
    command: ["combo","discover"],
    summary: "List configured System One decision rows and catalog models that look like decision services.",
    routes: [{"method":"GET","path":"/api/combos/decision-discovery"}],
    flags: [{"name":"--query","value":"string","summary":"Match catalog rows by this text instead of the built-in decision-model hint."},{"name":"--json","value":"boolean","summary":"Emit the discovery payload."}],
    mutates: false,
    json: "payload",
    details: ["Read-only: nothing is probed and no provider row is created."],
    usage: "ocx combo discover [--query <text>] [--json]",
  },
  {
    command: ["api","explain"],
    summary: "Preview the request path a model would take from one inbound API, computed from config.",
    routes: [{"method":"POST","path":"/api/protocols/plan"}],
    flags: [{"name":"--model","value":"string","required":true,"summary":"Model selector as a client would send it."},{"name":"--inbound","value":"string","required":true,"summary":"Inbound API: responses, chat or messages."},{"name":"--feature","value":"string","summary":"Request feature key to judge; repeatable or comma-separated."},{"name":"--json","value":"boolean","summary":"Emit the ProtocolPlanV1 preview."}],
    mutates: false,
    json: "payload",
    details: ["A read-only POST: nothing is sent upstream, no combo state advances and the input is not logged."],
    usage: "ocx api explain --model <id> --inbound <responses|chat|messages> [--feature <key>[,<key>]]... [--json]",
  },
  {
    command: ["api","policy"],
    summary: "Read the protocol policy, or change the Messages surface, unrepresentable policy and rollout switches.",
    routes: [{"method":"GET","path":"/api/protocols"},{"method":"PATCH","path":"/api/protocols/settings"}],
    flags: [{"name":"--messages","value":"string","summary":"Open or close the Messages API: on or off. Off also turns the Claude integration off."},{"name":"--unrepresentable","value":"string","summary":"legacy keeps today's behavior; reject refuses a request its path cannot carry."},{"name":"--rollout","value":"string","summary":"One switch as name=on or name=off; repeatable. Every switch defaults off except antigravityDirect."},{"name":"--json","value":"boolean","summary":"Emit the resulting GET /api/protocols body."}],
    mutates: true,
    json: "payload",
    details: ["A bare invocation reads and never writes.","A setting flag changes the operator's config; run it only when the operator asks for that change."],
    usage: "ocx api policy [--messages <on|off>] [--unrepresentable <legacy|reject>] [--rollout <switch>=<on|off>]... [--json]",
  },
];
