Desktop Companion CLI
Command reference for the signed macOS Desktop Companion CLI, including Gateway Key connections, profile management, sync, diagnostics, and secret handling across stage and dev channels.
The signed macOS Desktop Companion exposes ai-gateway-stage and ai-gateway-dev through separate
managed symlinks. Each CLI shares its own channel’s Profile JSON, Keychain records, and recovery
journal with its GUI. Agent configuration stays inside that channel’s managed home; Companion does
not write ~/.zshrc or any other shell startup file. Managed agent configuration changes only
through explicit Apply, except the one-time legacy cleanup described under
Launching agents. The launcher injects environment only into the launched child
process and does not modify the caller’s shell. The old
ai-gateway link is not claimed by either channel.
The channels start with separate empty app data and Keychain namespaces; no old shared-identity
Profile or credential is imported. Configure Profiles with a Gateway origin and Gateway Key in each newly installed app.
# Run once from the installed stage app; use ai-gateway-dev for the dev appai-gateway-stage cli install
ai-gateway-stage profile create --origin 'https://<gateway-host>' --name "Work"ai-gateway-stage profile list --jsonai-gateway-stage status <profile-id> --jsonai-gateway-stage sync <profile-id> --json # read-only Previewai-gateway-stage sync <profile-id> --apply --yes # explicit non-interactive Applyai-gateway-stage profile assign codex <profile-id> # immediate journaled assignment Applyai-gateway-stage run codex # recent selection, legacy binding, or the only Profileai-gateway-stage recover --yesai-gateway-stage logs # latest 100 validated JSONL recordsai-gateway-stage logs --lines 250 # choose 1 through 1000 recordsai-gateway-stage diagnostics export --output ./diagnostics.zipai-gateway-stage cli uninstallDesktop app
Section titled “Desktop app”The first screen is the Launchpad. It lists one row per vendor, Codex and Claude, and each row states which client forms it can start — the vendor’s CLI and its Desktop app — with that form’s installation state; the row’s Launch starts the chosen client. Each row selects a Profile inline and launches from the same row; no separate console or sidebar navigation is involved. Global navigation is limited to Launchpad, Profiles, and Settings. No other agent is supported.
- An unselected row disables Launch and asks you to select a Profile.
- Add new Profile starts Profile creation from that row. On success, the app returns to the same Launchpad row, selects and focuses the new Profile, and allows Launch without selecting again.
- Cancelling creation or failing to create a Profile with an invalid key returns to the same row and keeps the previous valid selection.
- A row that needs action offers Replace key, Choose another Profile, or Open Profile next to the reason. Details, Models, and MCP open the Sheet for the selected Profile.
- Launch resolution uses the explicit selection first, then that target’s last successful start, then the legacy binding, then the only enabled Profile. A deleted or disabled selection is shown as unavailable rather than silently replaced. If the stored selection’s Profile is deleted or disabled, the row shows the unavailable state and selects the channel’s only usable Profile, if there is one. With no usable Profile, Launch is replaced by Create Profile.
Settings contains Profile, language, app information, diagnostics, and Advanced
Activity; /history only redirects there. Advanced Activity lists committed Applies and lets Roll back this Apply restore an
eligible recorded pre-Apply state without fetching policy. An update check starts with the app. Its
progress, failure, retry, installed state, and Restart now action appear in the update item on the
bottom status bar; completion waits for any open Sheet or dialog to close.
Create a Profile by choosing or entering a Gateway origin and pasting the key into Gateway Key. Project name and ID are optional display metadata. The Companion does not compare these values with the Key’s Project or refresh them. The Project ID also builds the console’s MCP catalog link; Profile creation, sync, and launch work without it.
The Companion validates the Gateway Key and fetches callable models through GET /v1/models.
It stores the raw Key in a Profile-specific Keychain record. Replace key validates the new Key
and updates the stored Key and prefix while preserving the Project name and ID you entered.
Commands
Section titled “Commands”| Command | Arguments | Mutating |
|---|---|---|
profile list [--json] | Lists locally stored Profile metadata: ID, name, environment origin. | No |
profile create [--origin <origin>] [--name <name>] [--project <id>] [--stdin] | Creates a Profile from a Gateway origin and Gateway Key. The origin defaults to the Dev environment. --name sets the Profile name; without it, the normalized origin’s host is used. --project records optional Project ID (UUID) metadata. Supply the Key through hidden TTY input or --stdin. | Yes |
profile assign <target> <profile-id> [--overwrite-connection-settings] [--json] | Binds one target (codex or claudeCode) to a Profile through the same immediate journaled Apply the GUI uses: binding metadata and the managed agent configuration commit together. The overwrite flag is valid only for Codex. Assigning the same Codex Profile explicitly reactivates this app’s provider. | Yes |
profile unassign <target> | Removes a target binding through the immediate Apply: the app-owned configuration fields are removed locally, without any upstream fetch. | Yes |
status <profile-id> [--json] | Read-only check of the Profile. Runs the runtime-verification stage before configuration planning, then prints per-target state; --json also includes any attributed runtime errors. | No |
sync <profile-id> [--apply] [--yes] [--json] [--overwrite-connection-settings] | Read-only Preview without --apply; otherwise builds a fresh Preview and applies it in the same process. The overwrite flag requires --apply and applies only to a Codex review. Normal sync registration preserves a different active provider. | Only with --apply |
mcp-headers <profile-id> --target <codex|claudeCode> | Machine helper for managed MCP clients. Emits one compact JSON object with the current Authorization header and a trailing newline. Do not run it in a terminal or capture its output in logs. | No |
recover [--finalize] [--yes] | Completes a pending Apply journal or finalizes a committed one. | Yes |
logs [--lines <1..1000>] | Writes up to the requested number of latest validated diagnostic JSON Lines records for this channel to stdout; default: 100. Authentication is not required. | No |
run <codex|claude|codex-desktop|claude-desktop> [--profile <profile-id>] [--import-auth] [--activate-desktop] | Starts the vendor client with the launch resolution shared with the GUI: explicit Profile, then the target’s recent successful selection, then the legacy binding, then the only enabled Profile. --import-auth copies a supported vendor credential file into the managed home before starting. --activate-desktop is valid only for claude-desktop and approves switching the shared Claude Desktop entry to the launched Profile. | Yes (records the launch selection after a successful start; may run the one-time legacy cleanup first) |
diagnostics export --output <path> | Writes the same sanitized diagnostic ZIP as the GUI to a new output path for this channel. Authentication is not required. | Yes (new ZIP only) |
cli install / cli uninstall | Manages this channel’s ~/.local/bin/ai-gateway-stage or ai-gateway-dev link. Install reports whether ~/.local/bin is on PATH. The directory is created with owner-only permissions when absent. | Yes (link only) |
sync --apply reconciles only the targets assigned to that Profile. If no targets are assigned,
the command is refused with exit code 2 and a bounded list of the excluded targets and reasons.
mcp-headers is invoked by a channel-owned, argument-free MCP wrapper. It reads the current
Profile key locally each time and emits exactly {"Authorization":"Bearer <current-key>"}\n on
success. It requires the committed target/Profile assignment, the exact helper ownership record
for that target/Profile, and at least one recorded owned MCP registration. A model-only setup,
legacy environment-variable registration, all-off MCP selection, stale wrapper after reassignment,
or missing ownership is refused before key access. A pending recovery journal blocks the read.
The guarded read takes no mutation lock at all, so a concurrent Companion change (Apply, Profile
edit, another launch) neither blocks nor fails it. Failure leaves stdout empty and uses the
existing bounded CLI exit categories on stderr.
The command starts no window and never needs an upstream request. It does not check
wrapper file contents; owned wrapper creation and file verification occur during provisioning.
The older credential <profile-id> command still prints its bare key for existing shell consumers;
MCP header JSON requires the explicit mcp-headers command. Restart/reload a client to discard
headers it has already cached after removing a registration or rotating a key.
Launching agents
Section titled “Launching agents”run <agent> [--profile <profile-id>] [--import-auth] [--activate-desktop] starts a
vendor client with the selected Profile’s managed home, environment, and agent
configuration. GUI and CLI resolve managed paths, argv, and environment through the same
launch service; only the child attachment and reporting differ.
The agent names are codex, claude, codex-desktop, and claude-desktop. They behave
differently:
- CLI agents (
codex,claude): the command attaches the terminal’s stdin, stdout, and stderr, waits for the vendor process, and then exits0while printing the child’s exit code on stdout, orterminated by signalwhen a signal ended it. The child’s own output goes straight to the terminal. - Desktop agents (
codex-desktop,claude-desktop): the command asks macOS to open the app and returns once that request succeeds, printingstarted <client>. It attaches no child and waits for no process.
--activate-desktop is valid only for claude-desktop; every other agent name rejects it with
exit code 2 before starting anything. Claude Desktop reads one shared configuration entry, so
starting it with a Profile other than the one that entry names means rewriting that entry — a
change visible inside Claude Desktop. The launch therefore refuses without the flag whenever it
would have to rewrite that entry: it reports the
desktop.sync.claudeDesktopActivationRequired condition, prints
Claude Desktop does not currently apply this Profile; pass --activate-desktop to launch with it
on stderr, writes no configuration, and starts nothing. With the flag, that entry is switched to the launched
Profile through the same journaled Apply the GUI runs, and the launch continues. The Desktop app
asks for the same consent in its switch confirmation dialog; the flag is that confirmation for the
CLI.
Profile resolution:
- An explicit
--profilealways wins. The Profile must exist and be enabled; otherwise the command fails with exit code2and starts no vendor process. - Without
--profile, the command reuses the last Profile that successfully started that exact launch target. A selection is scoped to one target: acodexselection never answers forcodex-desktop, and aclaudeselection never answers forclaude-desktop. - When the target has no recent selection, the legacy persisted binding for
codexorclaudeis used once as migration input. Desktop targets never inherit that binding. - When the channel has exactly one enabled Profile, the command selects it automatically.
- A stored selection whose Profile is now disabled or deleted is a dead end: it reports selection-required and does not fall back to the legacy binding or to the only enabled Profile.
- Otherwise the command reports that a Profile selection is required (exit code
2,no Profile is selected for this launch target; pass --profile <profile-id>) and starts nothing. It never picks a Profile at random. - The selection is recorded only after a successful start. A failed start keeps the previous selection, and a selection write that cannot take the mutation lock is logged and dropped instead of failing a launch that already started.
Launch resolution itself writes only that recent selection. It never assigns the Profile to a
configuration target, rewrites canonical agent configuration, or edits shell startup files. A
pending one-time legacy cleanup, which runs only while this channel’s cleanup marker is absent,
can still remove artifacts this app previously wrote (an owned ~/.zshrc marker block, the
channel shell source, and owned Codex/Claude entries) before the launch.
ai-gateway-stage run codex # recent selection, legacy binding, or the only Profileai-gateway-stage run codex --profile <profile-id> # explicit choiceai-gateway-stage run claude --import-auth # copy a supported vendor credential firstai-gateway-stage run claude-desktop --activate-desktop # switch the shared Desktop entry to the launched ProfileClaude Code personal subscription settings
Section titled “Claude Code personal subscription settings”Existing configurations default to Provider API key authentication. To use your own Claude subscription, open Claude Code authentication in Companion’s Settings and select Personal Claude subscription. Enter a <subscription-provider>/<raw-claude-model-id> allowed by the selected Profile’s Project in Gateway model ID, then select Save Claude Code settings. This choice applies to Claude Code launched by that Companion channel. Claude Desktop and Profile assignments remain unchanged. Claude Desktop does not support a personal subscription and keeps connecting with the Gateway Key.
An administrator must first create an Anthropic subscription Provider and allow its registered models in the Project. You cannot forward a personal subscription token to a Provider that uses a server API key.
For the first login, launch the Profile’s isolated Claude Code from a terminal:
ai-gateway-stage run claude --profile <profile-id>Use ai-gateway-dev for the dev channel and ai-gateway-local for the local channel. In the launched Claude Code, run /login to sign in with your own subscription account, then check a response. Personal subscription mode rejects --import-auth. Companion does not copy existing Claude authentication files or OAuth caches. Official Claude Code manages login and renewal.
Personal subscription mode sends the Gateway Key in a separate custom header. Companion adds no API-key authentication override and merges the header with custom headers from the inherited environment. Because env.ANTHROPIC_CUSTOM_HEADERS in settings.json overrides that value, Companion reports it as a conflict. Move any required custom headers to the launch environment and resolve that settings-file entry yourself. MCP settings and other user settings are preserved.
Active apiKeyHelper, ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, other cloud authentication, or model overrides also appear as conflicts in Launchpad. Check Technical details for the setting location and field name, resolve it yourself, then check again. Companion does not delete user settings to resolve conflicts.
An ANTHROPIC_DEFAULT_*_MODEL value such as ANTHROPIC_DEFAULT_SONNET_MODEL is applied as is when it uses the <subscription-provider>/<model-id> form, and appears as a conflict when it has no Provider name. To use Sonnet for the auto mode pre-run check, see the Claude Code connection guide. Set the value in either the launch environment or env in settings.json.
Claude Code may skip model discovery with custom-header authentication, so specify the model ID explicitly. Gateway model ID is a channel-wide launch setting. When switching to a Profile in another Project, check that the same model ID is allowed there and update it if needed. Subscription costs shown in the Gateway are API-list-price estimates for comparison and are not deducted from Project budgets. Check your Claude account for actual subscription charges and limits.
For ordinary terminal setup and authentication conflict checks, see the Claude Code connection guide.
Check stages and retry scope
Section titled “Check stages and retry scope”status runs one read-only runtime-verification stage before configuration planning. Preview
and Apply perform the same observation before inspecting configuration; Apply also revalidates it
before mutation. Attribution uses these stage names:
discoverExecutable: resolve the required client executable. DirectPATHlookup is tried first. If that fails and the managed paths pass validation, one bounded login-shell observation (/bin/zsh -lic, 2-second limit) captures the executable plus an allowlisted environment (PATHandNODE); malformed, oversized, or unsafe output falls back to one directPATHlookup.verifyVersion: for Codex only, run the discovered absolute executable with--versionunder that same observation, with a 2-second deadline and a 4096-byte cap on each output stream. Claude Code stops at discovery and is not version-probed. The Codex Desktop embedded host is probed the same way; without a CLI observation it inherits the current environment. The capturedPATHandNODEare passed only to this child process;HOMEand the working directory stayHOME, and the GUI process environment is unchanged.validateApply: Apply revalidates before mutation. It assigns this stage only when the error has no stage.
A check never writes agent configuration, Profile data, or journal/history. It does not edit
shell startup files, persist a PATH, initialize mise or nvm,
or install software. In addition to the observation and version probes, it may run bounded
read-only Claude Desktop process/readiness checks; none of these change configuration.
Runtime-verification failures are reported independently of configuration validation. Lookup
failure, missing-Node evidence, timeout, output-limit, invalid version output, and process launch
failure use codes such as executableLookupFailed, executableLookupInvalid,
requiredRuntimeUnavailable, versionCommandFailed, versionOutputInvalid, processTimeout,
processOutputLimit, and processLaunchFailed. They are not drift or configuration conflict.
Unsafe or symlinked managed paths, unsupported structure, invalid TOML, and MCP-helper
incompatibility remain configuration conflicts. A failed runtime verification blocks only
operations that need the unverified client; cleanup, removal, and unassignment remain available.
A check that proceeds past a blocking recovery short-circuit performs exactly one runtime observation. Plan construction, Claude observation, agent summaries, and the Codex projection consume it, so a check does not repeat shell discovery. Preview likewise detects once.
Retry scope: after fixing the external cause (install or expose the client, repair the runtime
manager so the login shell resolves it, or correct its version output), rerun status or the
Preview/Apply. A check does not repair PATH or install software, and rerunning it unchanged
repeats the same checks rather than changing the environment.
Codex channel namespace and active state
Section titled “Codex channel namespace and active state”Provider identity comes from the app/CLI channel, never from a Profile’s Gateway URL:
| App channel | Codex provider ID | Availability |
|---|---|---|
| Local | ai_gateway_local | Local development identity |
| Dev | ai_gateway_dev | Dev app identity |
| Stage | ai_gateway_stage | Stage app identity |
| Prod | ai_gateway | Reserved name only |
There is no Prod app identity or release/updater channel today. An existing
unsuffixed ai_gateway is therefore legacy/unknown unless ownership metadata proves otherwise; it
is not presumed to be Prod. A Local Profile that points at a Dev Gateway still uses
ai_gateway_local.
Codex MCP IDs use ai-gateway-<channel>-<slug>-<server-id-prefix> for Local, Dev, and Stage. Multiple
channel provider tables and MCP registrations coexist in config.toml, while top-level
model_provider and model are one HOME-shared active pair. A Profile assignment records this
app’s intended binding; it does not prove that its provider is actually active. Status reports the
actual active provider separately. Checks, background drift detection, and normal sync registration
do not switch away from another active provider. profile assign codex <profile-id> is the CLI’s
explicit switch action, including when that same Profile is already assigned. The GUI shows the
current-to-requested switch for confirmation. Model selection and clear are disabled while this
app’s provider is inactive.
Codex Gateway connectivity requires web_search = "disabled" before the first TOML
table. Native web search has caused session failures with non-OpenAI Gateway models;
keep it disabled after setup. Confirmed assignment, activation and sync repair missing,
cached or live search values. Read-only checks report repair needed without writing.
Codex 0.160 --profile <name> layers ~/.codex/<name>.config.toml over base config,
so Gateway profiles must also keep search disabled. Avoid --search and search-enabling
-c overrides. Ordinary function and configured MCP tools remain available.
The current build loads supported Profile document versions 1–8 and writes version 8 on the next successful metadata commit. Reads and cancelled reviews leave the original bytes intact. Version 8 retains channel ownership/fingerprints, historical Codex discovery ownership, Claude Desktop ownership, exact MCP helper ownership, and target-specific MCP choices. Legacy proxy metadata remains readable but does not select an endpoint or make a listener ready. Older builds that cannot read version 8 must not share the store; do not manually downgrade its version or remove ownership fields. Supported valid documents need no backup-and-reset on upgrade.
Codex connects directly to the assigned Profile’s Gateway: provider base_url is its upstream
/v1/, and model_catalog_url is /v1/codex/models. The destination Gateway must provide that
catalog endpoint. Provisioning requires detected Codex and completed recovery, with the existing
policy, ownership and file checks; it does not require a GUI listener or the old exact 0.160.0 POC
version. CLI status compares the direct desired configuration without starting a listener or
claiming the client has refreshed its catalog. Every MCP URL retains its original Gateway origin.
Existing owned loopback configurations appear as drift. Confirm sync to replace their endpoint
fields and commit new ownership through the journal; startup and checks do not rewrite them.
Unexpected edits still require the scoped keep/overwrite review. Restart Codex after sync; when
using its app-server daemon, restart it with the same CODEX_HOME after active work completes.
Managed MCP registrations use http_headers_helper to obtain the current Gateway Key at
connection time. The older owned bearer_token_env_var field is removed when migrating that
registration so two credential sources do not compete. http_headers.Authorization,
env_http_headers.Authorization, auth/oauth, and transport settings in the same owned table
can provide a different credential or override the helper, depending on the client configuration.
The app reports these sources by field name for scoped review even when the URL and helper still
match. A catalog removal of that table also requires review. Keep leaves configuration and
history unchanged; Overwrite applies the reviewed fields only. Inspect any custom Codex profile
or command-line overrides separately, since they can take precedence over the base config.
Historical rollback preserves recorded pre-state and can restore an old loopback URL. Such a
restoration needs confirmed sync again because this build no longer serves Codex /profiles/*.
Claude Code and Claude Desktop connect directly to the assigned Profile’s Gateway origin plus
/anthropic. The Gateway must provide GET /anthropic/v1/models and
POST /anthropic/v1/messages with Gateway Key authentication in x-api-key (including the
Anthropic catalog support from Gateway PR #853). Companion provides no inference listener,
catalog conversion, or auth translation. A successful configuration check establishes local
configuration only; verify catalog discovery, ordinary inference, and streamed inference in each
installed client separately. Desktop host verification does not establish Cowork VM support.
To migrate an existing owned Claude connection, check the intended channel/Profile, quit Claude
Desktop if its entry is activated, then review and confirm sync <profile-id> --apply. Explicit CLI
assignment and legacy-repair operations also review their Claude changes. Only exact channel-owned shell
content and matching Desktop ownership fingerprints are eligible. Check, startup, and cancelled
reviews leave legacy files unchanged. A Codex or MCP-only change preserves unreviewed legacy
Claude connectivity. Migration preserves Profile IDs/origin, stored key references, assignments,
MCP selections/helpers, unknown fields, and other channels’ artifacts. It does not activate an
unowned or inactive Desktop entry. Shell prerequisites and
Desktop quit, managed-policy, helper, and path checks still apply without a GUI listener.
Open a new terminal after Claude Code migration and restart Claude Desktop after its configuration
changes. Inspect externally supplied ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY,
ANTHROPIC_BASE_URL, and client settings overrides if the client still uses an old endpoint or
returns 401. Resolve those overrides in their owning shell/settings configuration; the launcher
injects environment only into the launched child process and does not unset or otherwise modify
caller-owned values. Restarting only a child shell can retain inherited values. Credential and
endpoint selection must be verified in the actual client request.
Exact-owned unassignment and eligible history rollback remain available offline, even without the Claude executable, Gateway, or inference listener. Removing or rolling back a Codex channel preserves API-key discovery needed by another direct or legacy loopback catalog provider. If the original value cannot be proven, Preview reports preservation and only this channel’s ownership is released.
A failed migration restores journaled pre-state under the existing path/hash and ownership
checks; a retained journal can still require recovery/finalization before another mutation.
Use the channel’s recover command and the reported finalization flow; do not delete its journal.
In Settings → Advanced Activity, Roll back this Apply restores eligible recorded owned bytes
and metadata without fetching policy, while protecting later foreign edits. A restored legacy Claude loopback URL or
Bearer field is historical pre-state, reported as drift requiring another confirmed sync. It
cannot provide connectivity in this build. If rollback is rejected because owned fields changed,
resolve that conflict through the normal review flow before retrying.
Known limitation: if an inactive Profile’s stored Codex default model is obsolete and absent from a
fresh policy, the current API cannot activate or clear that model from its row. The app returns a
generic Profile error; it does not silently fall back to another model. Continuing requires choosing
a different Profile or externally corrected metadata. Do not edit the live TOML model field as a
recommended workaround.
Other channels’ MCP entries remain registered after a switch. Registration does not guarantee that
their credentials are available, and a client may keep a cached Authorization header until it is
restarted or reloaded.
The launcher injects the selected Profile’s runtime environment into the child process only. For
Codex it sets the Profile’s AI_GATEWAY_BASE_URL_<profile-id> and Gateway key environment; for
Claude Code it sets AI_GATEWAY_CLAUDE_BASE_URL_<profile-id>, points ANTHROPIC_BASE_URL at the
Profile’s direct /anthropic base, references the Profile-keyed credential with
ANTHROPIC_API_KEY, and sets CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1. It does not generate
ANTHROPIC_AUTH_TOKEN, write a shell source, or change the caller’s shell. Claude Desktop uses
inferenceGatewayAuthScheme set to "x-api-key" with its existing guarded credential helper; no
raw key is written into its entry.
Local diagnostics
Section titled “Local diagnostics”Diagnostics are local to the channel represented by the command you run. ai-gateway-stage reads
only the stage app configuration directory and ai-gateway-dev reads only the dev directory; neither
command reads the other channel. The installed CLI name or the app’s bundle identifier is authoritative;
an app display name or Finder folder name is only a hint. Confirm the CLI name before inspecting,
exporting, or deleting diagnostics. For a GUI app, confirm its identifier with
mdls -name kMDItemCFBundleIdentifier -raw "/path/to/installed-app.app".
| Channel | Authoritative identity | app_config_dir/logs on macOS |
|---|---|---|
| Stage | ai-gateway-stage / io.querypie.ai-gateway.desktop-companion.stage | ~/Library/Application Support/io.querypie.ai-gateway.desktop-companion.stage/logs/ |
| Dev | ai-gateway-dev / io.querypie.ai-gateway.desktop-companion.dev | ~/Library/Application Support/io.querypie.ai-gateway.desktop-companion.dev/logs/ |
| Local development | io.querypie.ai-gateway.desktop-companion.local | ~/Library/Application Support/io.querypie.ai-gateway.desktop-companion.local/logs/ |
Logs are owner-only JSON Lines files. Each record contains timestamp, level, component, and
event, plus optional validated error_code, correlation_id, failure_code, stage,
target, client, exit_code, and os_error_code. Levels are info, warn, and
error; components are auth, profile, sync, recovery, agent, and updater. The fixed
event and error-code vocabularies deliberately exclude free-form diagnostic text.
Retention applies whichever bound is reached first: each file is at most 5 MiB; records are retained for at most 14 days; no more than 5 files and 25 MiB total are retained. Logging or cleanup failures do not stop normal workflows.
Read recent records
Section titled “Read recent records”logs prints revalidated JSON Lines to stdout, oldest to newest within the requested recent set.
It defaults to 100 lines; --lines accepts whole-number values from 1 through 1000. Invalid line
counts fail with exit category 2. Malformed records, records with unknown fields, and records from
other channels are never emitted.
ai-gateway-stage logsai-gateway-stage logs --lines 1000Export a support bundle
Section titled “Export a support bundle”Choose an output path that does not already exist. The command creates one ZIP and deliberately
prints neither its absolute destination nor bundle contents on success. Existing output paths and
storage/export failures use exit category 6 and do not overwrite the existing file.
ai-gateway-stage diagnostics export --output ./ai-gateway-diagnostics.zipThe ZIP contains:
diagnostics.json: schema version; app version; build value; OS/architecture; channel; bounded Profile/agent state counts and flags; recent error timestamps, codes, and events; and the count of dropped malformed log lines. The build value can be"unavailable"because the packaging pipeline does not currently supply a separate build identifier.logs/diagnostics-0.jsonl: retained records reconstructed from the approved diagnostics schema.
The ZIP excludes Gateway Keys, Keychain data, sessions, cookies, Authorization values, Profile secrets or names, environment variables, personal paths, raw Profile/agent/policy/configuration files, arbitrary response/error text, and malformed or unknown log fields. Review the ZIP and its intended recipient before sharing: version, platform, channel, and state summaries can still reveal device or deployment context.
Remove diagnostics safely
Section titled “Remove diagnostics safely”After fully quitting the channel’s GUI app and waiting for all CLI commands for that same channel to
stop, delete only these app-owned files if present inside the matching logs/ directory above:
diagnostics-0.jsonl, diagnostics-1.jsonl, diagnostics-2.jsonl, diagnostics-3.jsonl, and
diagnostics-4.jsonl. Leave .lock and every other directory entry untouched; do not use a wildcard
or recursive directory deletion. Do not delete the parent app_config_dir; it also holds Profile data,
and Keychain data is managed separately. This does not affect another channel. The app recreates its
own log directory when it next needs to write diagnostics.
Confirmation rules
Section titled “Confirmation rules”- For
sync,--yesrequires--apply. sync <profile-id> --applyon an interactive TTY asks for confirmation; without a TTY it requires--yes.recoverfollows the same confirmation rules as Apply.--finalizeretires a journal whose changes were already committed.
Secret handling
Section titled “Secret handling”The Gateway Key is never accepted as a command-line argument. A global --key option is defined
only so it can be rejected with guidance before any network or filesystem access: use the hidden
TTY prompt, or pipe one line with profile create --stdin.
Keys, session IDs, authorization codes, PKCE values, and absolute local paths are removed from all human and JSON output.
Conflicts
Section titled “Conflicts”For a safely editable Codex same-name collision, unexpected edit to owned connection fields, or
recorded legacy migration, profile assign codex and sync --apply return a redacted review and
exit code 4 without changing files, assignment metadata, ownership, or history. The review lists
bounded file/table/field provenance, never raw values, headers, tokens, or full TOML.
To accept the listed scope, rerun exactly one of these forms:
ai-gateway-stage profile assign codex <profile-id> --overwrite-connection-settingsai-gateway-stage sync <profile-id> --apply --yes --overwrite-connection-settingsThe flag is not available for profile unassign, non-Codex assignment, or read-only sync. It does
not replay an earlier process’s approval. Each invocation freshly prepares one review, approves
only that scope, and revalidates immediately before mutation. Overwrite changes only the reviewed
known provider connection fields, exact MCP entries, managed agent configuration, assignment, and
ownership, and records redacted apply history. For explicit assignment/activation it also switches top-level
model_provider to this channel and applies a valid selected model, or preserves the existing
model when no model is selected; normal sync preserves a different active provider. Unknown
fields and foreign-channel entries are preserved. In the GUI, Keep existing, Escape, backdrop,
close, and dismissal all cancel the whole operation with no change.
If revalidation produces a different conflict scope, the CLI returns kind: "refreshed" and exit
code 4; inspect it and make a new decision in another invocation. If the conflict disappeared and
preparation is now ordinary, it returns kind: "ready" and exit code 4; retry without the
overwrite flag so the ordinary confirmation path applies. These are bounded decision retries, not
authentication or upstream retry behavior.
The flag never bypasses invalid TOML/non-table structure, unsafe or symlinked paths, file hashes, policy validation, shared mutation locking, or pending recovery. Those remain blocked. Other target conflicts continue to print their bounded cause and fail without overwrite.
Legacy data, versions, and concurrent writers
Section titled “Legacy data, versions, and concurrent writers”An unowned unsuffixed ai_gateway provider or old MCP entry is left untouched. The current channel
can register and activate its suffixed entries beside it. If this app has recorded legacy ownership,
migration happens only after a redacted review that includes the old entries, their destination,
and any destination collision. Startup and reads never relabel ownership, rewrite agent files, or
reset live configuration automatically.
Current documents use Profile schema 8 and history schema 3. Supported history schemas 1–3 and journal schemas 3–4 remain readable with their existing recovery safeguards. Older readers that do not support these versions must reject them. Before a binary downgrade, close clients, resolve pending recovery, and restore a complete, mutually compatible Profile/configuration backup set. Do not delete ownership or pending-recovery metadata to make an old app accept a file. Upgrading does not require deleting or changing the permissions of old proxy port files.
New builds serialize Codex writes across channels with a private HOME-scoped shared lock and revalidate the file and metadata before commit. A channel recovers its own journal and defers when another known channel has unresolved shared-target recovery; it does not steal the foreign journal. Old installed builds do not participate in this lock, so cooperative concurrent-write safety is guaranteed only among new builds. Their external writes can still be detected as changed state and returned for review.
Exit categories
Section titled “Exit categories”0 success, 2 invalid input, 3 authentication, 4 conflict, 5 upstream unavailable,
6 local storage, 7 recovery required, and 8 another mutation is in progress.
Output contract
Section titled “Output contract”Successful output goes to stdout; diagnostics go to stderr. --json prints a bounded,
secret-free JSON model suitable for scripts. Terminal CLI output is English-only; the GUI
application keeps its own localized strings.
Structured operation errors
Section titled “Structured operation errors”Native application failures include a required serialized cause, including unknown failures.
Domain wrappers retain original sources. Cause chains are redacted and bounded to eight nodes,
2048 characters per message and less than 16 KiB overall; terminal conditions have no child.
GUI technical details and explicit copy include these causes. Automatic diagnostics never persist
raw causes, stderr, PATH or private configuration. Manifest schema 2 carries the allowlisted
failure metadata and the same operation ID shown in the GUI; older retained records remain valid.
Each external retry receives a new operation ID; nested rollback retains the original attempt ID.
An unverified runtime blocks only dependent writes without claiming a proven incompatible
version; cleanup and removal remain available. Checks never initialize mise, install software,
edit shell startup files, or repair PATH. Recovery status comes from the actual journal; after
restart, an initial cause absent from that journal is explicitly unavailable.