II.
Page JSON
Structured · livepage:docs-agent-mux-reference-10-cli-reference
CLI Reference (`amux`) json
Inspect the normalized record payload exactly as the atlas UI reads it.
{
"id": "page:docs-agent-mux-reference-10-cli-reference",
"_kind": "Page",
"_file": "wiki/docs/agent-mux/reference/10-cli-reference.md",
"_cluster": "wiki",
"attributes": {
"nodeKind": "Page",
"sourcePath": "docs/agent-mux/reference/10-cli-reference.md",
"sourceKind": "repo-docs",
"title": "CLI Reference (`amux`)",
"displayName": "CLI Reference (`amux`)",
"slug": "docs/agent-mux/reference/10-cli-reference",
"articlePath": "wiki/docs/agent-mux/reference/10-cli-reference.md",
"article": "\n# CLI Reference (`amux`)\n\n**Specification v1.0** | `@a5c-ai/agent-mux-cli`\n\n> **SCOPE EXTENSION:** hermes-agent (`@NousResearch/hermes-agent`) is included as a 10th supported agent per explicit project requirements from the project owner. It extends the original scope document's 9 built-in agents. All hermes-specific content in this spec is marked with this same scope extension note.\n\n---\n\n## 1. Overview\n\nThe `amux` binary is the CLI surface of the `@a5c-ai/agent-mux` project. It exposes every capability of the SDK -- running agents, inspecting adapters, managing sessions, configuring agents, handling authentication, working with plugins, and tracking costs -- through a single command-line interface.\n\nThe CLI and SDK are co-equal surfaces that share the same core layer and behave identically. Every CLI command maps to a specific SDK method. This specification defines the CLI completely and precisely: a developer should be able to implement the binary from this document alone.\n\n### 1.1 Package Coordinates\n\n| Field | Value |\n|---|---|\n| npm package | `@a5c-ai/agent-mux-cli` |\n| Binary name | `amux` |\n| Language | TypeScript, strict mode |\n| Runtime | Node.js 20.9.0 or later |\n| License | MIT |\n\nThe binary is installed as part of `@a5c-ai/agent-mux` (the convenience meta-package) or standalone via `@a5c-ai/agent-mux-cli`. It depends on `@a5c-ai/agent-mux-core` and `@a5c-ai/agent-mux-adapters`.\n\n```bash\n# Via meta-package\nnpm install -g @a5c-ai/agent-mux\n\n# Standalone CLI\nnpm install -g @a5c-ai/agent-mux-cli\n\n# Zero-install\nnpx @a5c-ai/agent-mux\nnpx @a5c-ai/agent-mux run claude \"hello\"\n```\n\n### 1.2 Cross-References\n\n| Concept | Spec | Section |\n|---|---|---|\n| `AgentName`, `BuiltInAgentName` | `01-core-types-and-client.md` | 1.4 |\n| `ErrorCode`, `AgentMuxError` | `01-core-types-and-client.md` | 3.1 |\n| `CapabilityError` | `01-core-types-and-client.md` | 3.2 |\n| `ValidationError` | `01-core-types-and-client.md` | 3.3 |\n| Storage layout | `01-core-types-and-client.md` | 4 |\n| `createClient()`, `ClientOptions` | `01-core-types-and-client.md` | 5 |\n| `RunOptions` | `02-run-options-and-profiles.md` | 2 |\n| `ProfileManager` | `02-run-options-and-profiles.md` | 10 |\n| `RunHandle`, `RunResult` | `03-run-handle-and-interaction.md` | 2, 3 |\n| `AgentEvent` union | `04-agent-events.md` | 2 |\n| `AgentAdapter`, `BaseAgentAdapter` | `05-adapter-system.md` | 2 |\n| `AgentCapabilities`, `ModelCapabilities` | `06-capabilities-and-models.md` | 2 |\n| `SessionManager` | `07-session-manager.md` | 2 |\n| `ConfigManager`, `AuthManager` | `08-config-and-auth.md` | 2, 8 |\n| `PluginManager` | `09-plugin-manager.md` | 2 |\n| CLI commands (scope) | `agent-mux-scope.md` | 21 |\n| Process lifecycle (scope) | `agent-mux-scope.md` | 22 |\n| Package structure (scope) | `agent-mux-scope.md` | 24 |\n\n---\n\n## 2. Invocation Syntax\n\n```\namux [command] [subcommand] [positional-args...] [flags...]\n```\n\nWhen invoked without a command, `amux` prints a help summary and exits with code 0.\n\nWhen invoked with an unrecognized command, `amux` prints an error message with suggestions and exits with code 2.\n\n---\n\n## 3. Global Flags\n\nGlobal flags are accepted by every command. They are parsed before command-specific flags and override corresponding environment variables and config file values.\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--agent` | `-a` | `AgentName` | Config default | Target agent name. Accepted values: `claude`, `codex`, `gemini`, `copilot`, `cursor`, `opencode`, `pi`, `omp`, `openclaw`, `hermes`, or any plugin-registered adapter name. |\n| `--model` | `-m` | `string` | Agent default | Model ID for the target agent. Must be a model ID recognized by the agent's adapter. |\n| `--json` | -- | `boolean` | `false` | Output as machine-readable JSON or JSONL. See Section 5 for output mode details. |\n| `--debug` | -- | `boolean` | `false` | Enable debug output. Includes raw event data in JSONL output and verbose logging to stderr. |\n| `--config-dir` | -- | `string` | `~/.agent-mux/` | Override the global configuration directory. Equivalent to `createClient({ configDir })`. |\n| `--project-dir` | -- | `string` | `.agent-mux/` | Override the project-local configuration directory. Equivalent to `createClient({ projectConfigDir })`. |\n| `--no-color` | -- | `boolean` | `false` | Disable colored output. Also activated when the `NO_COLOR` environment variable is set to any non-empty value, or when stdout is not a TTY. |\n| `--version` | `-V` | `boolean` | -- | Print the `@a5c-ai/agent-mux-cli` version and exit. |\n| `--help` | `-h` | `boolean` | -- | Print help for the current command and exit. Available on every command and subcommand. |\n| `--completions` | -- | `string` | -- | Generate shell completion script: `bash`, `zsh`, `fish`, `powershell`. See Section 22. |\n\n### 3.1 Flag Parsing Rules\n\n- Long flags use `--kebab-case` (e.g., `--thinking-effort`, `--config-dir`).\n- Short flags are single-character prefixed with `-` (e.g., `-a`, `-m`, `-i`, `-q`, `-y`).\n- Boolean flags do not take a value (`--json` enables JSON mode; `--no-stream` disables streaming).\n- Repeatable flags accept multiple values by specifying the flag multiple times (e.g., `--tag build --tag test`).\n- `--env` flags use `KEY=VALUE` syntax (e.g., `--env ANTHROPIC_API_KEY=sk-...`).\n- `--` terminates flag parsing; all subsequent arguments are treated as positional.\n\n---\n\n## 4. Exit Codes\n\nThe `amux` binary uses the following exit codes. These are the only exit codes produced by the CLI itself. When `amux run` is used, the agent subprocess exit code is available in the JSONL output but does not propagate as the `amux` process exit code unless the agent crashed.\n\n| Code | Name | Description | Corresponding `ErrorCode` |\n|---|---|---|---|\n| 0 | Success | Command completed successfully. | -- |\n| 1 | General error | An error occurred during execution. | Varies (see `error` event) |\n| 2 | Usage error | Invalid command syntax, unknown flag, or missing required argument. | `VALIDATION_ERROR` |\n| 3 | Agent not found | The specified agent has no registered adapter. | `AGENT_NOT_FOUND` |\n| 4 | Agent not installed | The agent adapter exists but the CLI binary is not on `$PATH`. | `AGENT_NOT_INSTALLED` |\n| 5 | Auth error | Authentication is required but not configured or expired. | `AUTH_ERROR` |\n| 6 | Capability error | The requested operation requires a capability the agent does not support. | `CAPABILITY_ERROR` |\n| 7 | Config error | Configuration file could not be read, parsed, or written. | `CONFIG_ERROR` |\n| 8 | Session not found | The specified session does not exist. | `SESSION_NOT_FOUND` |\n| 9 | Profile not found | The specified profile does not exist. | `PROFILE_NOT_FOUND` |\n| 10 | Plugin error | Plugin operation failed (install, uninstall, search, etc.). | `PLUGIN_ERROR` |\n| 11 | Timeout | The run exceeded its timeout or inactivity timeout. | `TIMEOUT` or `INACTIVITY_TIMEOUT` |\n| 12 | Agent crashed | The agent subprocess terminated unexpectedly. | `AGENT_CRASH` |\n| 13 | Aborted | The run was aborted by the user (e.g., via SIGINT). | `ABORTED` |\n| 14 | Rate limited | The agent reported a rate limit. | `RATE_LIMITED` |\n| 15 | Context exceeded | The agent's context window was exceeded. | `CONTEXT_EXCEEDED` |\n\n### 4.1 Exit Code Mapping\n\nThe CLI maps `ErrorCode` values from the SDK to exit codes as shown above. When multiple errors occur, the exit code reflects the first fatal error. Non-fatal errors (e.g., `RATE_LIMITED` with a successful retry) do not affect the exit code.\n\nThe following `ErrorCode` values map to exit code 1 (General error) as they have no dedicated exit code:\n\n| `ErrorCode` | Rationale |\n|---|---|\n| `SPAWN_ERROR` | Agent subprocess failed to spawn (bad path, permissions, missing binary). Distinct from `AGENT_NOT_INSTALLED` (binary not found on PATH) in that the binary was found but could not be executed. |\n| `INTERNAL` | Internal agent-mux error (bug). Should not occur in normal operation. |\n| `PARSE_ERROR` | An agent's output could not be parsed. Distinct from `CONFIG_ERROR` in that it relates to runtime output, not config files. |\n\nNote: `CONFIG_LOCK_ERROR` maps to exit code 7 (same as `CONFIG_ERROR`), not exit code 1, since it is a config-related error. It is not listed in the exit code 1 table above.\n\n---\n\n## 5. Output Modes\n\nThe CLI supports three output modes, selected by flags and context.\n\n### 5.1 Human-Readable (Default)\n\nWhen stdout is a TTY and `--json` is not set, the CLI produces formatted, colored output:\n\n- **Tables**: aligned columns with headers for list commands (`adapters list`, `sessions list`, `models list`, etc.).\n- **Streaming text**: for `amux run`, agent text output is printed to stdout as it arrives. Tool calls, thinking, and file operations are printed to stderr with visual indicators.\n- **Progress indicators**: spinners and status lines for long-running operations (install, plugin operations).\n- **Color**: ANSI color codes for emphasis, status indicators, and error highlighting. Disabled by `--no-color`, `NO_COLOR` env var, or non-TTY stdout.\n\n### 5.2 JSON (`--json`)\n\nWhen `--json` is set on non-streaming commands (e.g., `adapters list --json`, `sessions list --json`, `models list --json`), the CLI outputs a single JSON object or array to stdout:\n\n```json\n{\n \"ok\": true,\n \"data\": [ ... ]\n}\n```\n\nOn error:\n\n```json\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"AGENT_NOT_FOUND\",\n \"message\": \"No adapter registered for agent 'foo'\",\n \"recoverable\": false\n }\n}\n```\n\n### 5.3 JSONL Event Stream (`amux run --json`)\n\nWhen `--json` is set on `amux run`, the CLI outputs one JSON object per line to stdout. Each line is a serialized `AgentEvent` object as defined in `04-agent-events.md`. The final line is always a `RunResult` object with `type: \"run_result\"`.\n\n```jsonl\n{\"type\":\"session_start\",\"runId\":\"01J...\",\"agent\":\"claude\",\"timestamp\":1718000000000,\"sessionId\":\"abc123\",\"resumed\":false}\n{\"type\":\"text_delta\",\"runId\":\"01J...\",\"agent\":\"claude\",\"timestamp\":1718000000100,\"delta\":\"Hello\",\"accumulated\":\"Hello\"}\n{\"type\":\"message_stop\",\"runId\":\"01J...\",\"agent\":\"claude\",\"timestamp\":1718000000200,\"text\":\"Hello, world!\"}\n{\"type\":\"run_result\",\"runId\":\"01J...\",\"agent\":\"claude\",\"model\":\"claude-sonnet-4-20250514\",\"sessionId\":\"abc123\",\"text\":\"Hello, world!\",\"exitCode\":0,\"exitReason\":\"completed\",\"durationMs\":1200,\"turnCount\":1}\n```\n\nWhen `--debug` is combined with `--json`, each event includes the `raw` field containing the unparsed agent output line.\n\nHuman-readable progress (spinners, status) is suppressed in JSONL mode. Diagnostic messages go to stderr.\n\n---\n\n## 6. `amux run` -- Run an Agent\n\nInvoke an agent with a prompt. This is the primary command.\n\n### 6.1 Syntax\n\n```\namux run [<agent>] [<prompt>] [flags...]\n```\n\nBoth `<agent>` and `<prompt>` are optional positional arguments:\n\n- If `<agent>` is omitted, the default agent from config is used (`GlobalConfig.defaultAgent` or `--agent` global flag).\n- If `--prompt` / `-p` is provided, it supplies the initial prompt and takes precedence over positional prompt text.\n- If no explicit prompt is provided and stdin is not a TTY, the prompt is read from stdin (see Section 14).\n- If no explicit prompt is provided and stdin is a TTY and `--interactive` is not set, the CLI prints an error and exits with code 2.\n- If both are provided as positionals, the first argument is parsed as an agent name if it matches a registered adapter; otherwise, the entire positional is treated as the prompt and the default agent is used.\n\n### 6.2 Flags\n\n| Flag | Short | Type | Default | Maps to `RunOptions` | Description |\n|---|---|---|---|---|---|\n| `--model` | `-m` | `string` | Agent default | `model` | Model ID. |\n| `--stream` | -- | `boolean` | `true` | `stream: true` | Enable streaming output. |\n| `--no-stream` | -- | `boolean` | -- | `stream: false` | Disable streaming; buffer all output. |\n| `--thinking-effort` | -- | `string` | -- | `thinkingEffort` | Thinking effort: `low`, `medium`, `high`, `max`. |\n| `--thinking-budget` | -- | `number` | -- | `thinkingBudgetTokens` | Thinking budget in tokens. Minimum 1024. |\n| `--temperature` | -- | `number` | -- | `temperature` | Sampling temperature (0.0–2.0). Capability-gated. |\n| `--top-p` | -- | `number` | -- | `topP` | Top-p sampling (0.0–1.0). Capability-gated. |\n| `--top-k` | -- | `number` | -- | `topK` | Top-k sampling (>= 1). Capability-gated. |\n| `--thinking-override` | -- | `string` | -- | `thinkingOverride` | Native thinking parameter override as a JSON string. Passed directly to the agent's API. Use for agent-specific thinking controls not covered by `--thinking-effort` or `--thinking-budget`. Example: `--thinking-override '{\"type\":\"enabled\",\"budget_tokens\":8192}'`. |\n| `--max-tokens` | -- | `number` | -- | `maxTokens` | Maximum output tokens. |\n| `--max-output-tokens` | -- | `number` | -- | `maxOutputTokens` | Alias for `--max-tokens`. If both are set, `--max-output-tokens` wins. |\n| `--max-turns` | -- | `number` | -- | `maxTurns` | Maximum agentic turns (tool-use loops). |\n| `--session` | -- | `string` | -- | `sessionId` | Resume session by native session ID. |\n| `--fork` | -- | `string` | -- | `forkSessionId` | Fork session by native session ID. |\n| `--no-session` | -- | `boolean` | `false` | `noSession: true` | Ephemeral run; do not persist session. |\n| `--system` | -- | `string` | -- | `systemPrompt` | System prompt text. |\n| `--system-mode` | -- | `string` | `prepend` | `systemPromptMode` | System prompt mode: `prepend`, `append`, `replace`. |\n| `--cwd` | -- | `string` | `process.cwd()` | `cwd` | Working directory for the agent subprocess. Must be an absolute path to an existing directory. |\n| `--env` | -- | `string` | -- | `env` | Environment variable in `KEY=VALUE` format. Repeatable. |\n| `--prompt` | `-p` | `string` | -- | -- | Initial prompt text. Equivalent to the positional `<prompt>`, but unambiguous in scripts. |\n| `--non-interactive` | -- | `boolean` | `false` | `nonInteractive: true` | Force headless one-shot harness mode. Harness prompt flags are only used when this is paired with `--prompt`. |\n| `--yolo` | -- | `boolean` | -- | `approvalMode: 'yolo'` | Auto-approve all tool calls and file operations. |\n| `--deny` | -- | `boolean` | -- | `approvalMode: 'deny'` | Auto-deny all actions requiring approval. |\n| `--timeout` | -- | `number` | `0` | `timeout` | Run timeout in milliseconds. 0 disables. |\n| `--inactivity-timeout` | -- | `number` | `0` | `inactivityTimeout` | Inactivity timeout in milliseconds. 0 disables. |\n| `--output-format` | -- | `string` | `text` | `outputFormat` | Agent output format: `text`, `json`, `jsonl`. |\n| `--tag` | -- | `string` | -- | `tags` | Run tag for cost roll-ups and session search. Repeatable. |\n| `--run-id` | -- | `string` | Auto ULID | `runId` | Custom run ID (must be a valid ULID). |\n| `--attach` | -- | `string` | -- | `attachments` | File path to attach. Repeatable. Supports images and text files. Capability-gated (`supportsFileAttachments`). |\n| `--skill` | -- | `string` | -- | `skills` | Skill file or directory path. Repeatable. Capability-gated (`supportsSkills`). |\n| `--agents-doc` | -- | `string` | -- | `agentsDoc` | Path to an agents.md document. Capability-gated (`supportsAgentsMd`). |\n| `--mcp-server` | -- | `string` | -- | `mcpServers` | MCP server name (must exist in config). Repeatable. Overrides the default MCP server set. Capability-gated (`supportsMCP`). |\n| `--project-id` | -- | `string` | -- | `projectId` | Project identifier for cost tracking and session grouping. Stored in `run-index.jsonl`. |\n| `--profile` | -- | `string` | -- | `profile` | Named profile to apply as the base. |\n| `--interactive` | `-i` | `boolean` | `false` | -- | Enter interactive REPL mode (see Section 13). |\n| `--json` | -- | `boolean` | `false` | -- | Emit JSONL event stream to stdout. |\n| `--quiet` | `-q` | `boolean` | `false` | -- | Suppress non-essential output (tool calls, thinking, file ops). Only print final text. |\n\n#### SDK-Only RunOptions (No CLI Flag)\n\nThe following `RunOptions` fields are intentionally not exposed as CLI flags:\n\n| `RunOptions` Field | Reason |\n|---|---|\n| `retryPolicy` | Complex `RetryPolicy` object with `maxRetries`, `baseDelay`, `maxDelay`, `backoffMultiplier` fields. Not suitable for a single CLI flag. Configure via profile or config file. |\n| `onInputRequired` | Callback function. The CLI handles input_required events internally (prompts user or auto-denies in non-interactive mode). |\n| `onApprovalRequest` | Callback function. The CLI handles approval_request events via `--yolo` / `--deny` flags or interactive prompts. |\n\n### 6.3 Mutual Exclusion\n\nThe following flag combinations are invalid and produce exit code 2:\n\n- `--session` + `--no-session`\n- `--session` + `--fork`\n- `--fork` + `--no-session`\n- `--yolo` + `--deny`\n- `--stream` + `--no-stream`\n\n### 6.4 Flag-to-RunOptions Mapping\n\nThe CLI constructs a `RunOptions` object from flags. Resolution order (highest precedence first):\n\n1. Explicit CLI flags.\n2. Profile values (if `--profile` is set).\n3. Project config values (`.agent-mux/config.json`).\n4. Global config values (`~/.agent-mux/config.json`).\n5. Adapter defaults.\n\nThis matches the resolution order defined in `02-run-options-and-profiles.md`, Section 7.\n\n### 6.5 Behavior\n\n1. The CLI calls `createClient()` with global flag overrides.\n2. Resolves the initial prompt from `--prompt`, positional args, or stdin.\n3. Constructs `RunOptions` from flags, profile, and config.\n4. Calls `mux.run(options)` to obtain a `RunHandle`.\n5. By default, the initial prompt is delivered to stdin-capable harnesses over stdin so the harness stays interactive. When `--prompt` and `--non-interactive` are both set, agent-mux instead uses the harness's one-shot prompt flag/path.\n6. Consumes events from the `RunHandle`:\n - **Human mode**: prints text deltas to stdout, tool calls and thinking to stderr.\n - **JSONL mode** (`--json`): writes each `AgentEvent` as one JSON line to stdout.\n - **Quiet mode** (`-q`): suppresses everything except the final `message_stop` text.\n7. On `approval_request` events (when `approvalMode` is `'prompt'` and not `--yolo`/`--deny`):\n - **Interactive terminal**: prompts the user on stderr, reads response from stdin.\n - **Non-interactive** (pipe, no TTY): auto-denies with a warning to stderr.\n8. On `input_required` events:\n - **Interactive terminal**: prompts on stderr, reads from stdin.\n - **Non-interactive**: emits the event in JSONL mode; otherwise errors.\n9. Awaits `RunResult`. Prints cost summary to stderr (unless `--quiet`).\n10. Exits with the appropriate exit code (see Section 4).\n\n### 6.6 API Mapping\n\n| CLI | SDK |\n|---|---|\n| `amux run claude \"hello\"` | `mux.run({ agent: 'claude', prompt: 'hello' })` |\n| `amux run --profile fast \"hello\"` | `mux.run({ profile: 'fast', prompt: 'hello' })` |\n| `amux run -a gemini --yolo \"fix tests\"` | `mux.run({ agent: 'gemini', prompt: 'fix tests', approvalMode: 'yolo' })` |\n\n### 6.7 Examples\n\n```bash\n# Basic run\namux run claude \"explain this codebase\"\n\n# Run with thinking and model override\namux run claude --model claude-sonnet-4-20250514 --thinking-effort high \"refactor auth module\"\n\n# Ephemeral run with auto-approve\namux run codex --no-session --yolo \"add unit tests for utils.ts\"\n\n# Resume session\namux run claude --session abc123 \"continue from where we left off\"\n\n# Fork session\namux run claude --fork abc123 \"try a different approach\"\n\n# JSONL output for piping\namux run gemini --json \"list all TODO items\" | jq 'select(.type == \"text_delta\") | .delta'\n\n# With tags for cost tracking\namux run claude --tag feature/auth --tag sprint-42 \"implement oauth flow\"\n\n# Using a profile\namux run --profile careful \"review this PR\"\n\n# Quiet mode -- only final text\namux run claude -q \"what is 2+2\"\n```\n\n---\n\n## 6b. `amux launch` -- Launch a Harness with Provider Flexibility\n\nStart (or resume) an interactive or non-interactive coding agent session with full stdin/stdout passthrough. Unlike `amux run`, which normalizes output into the `AgentEvent` stream, `amux launch` is a **transparent proxy** — the user interacts directly with the harness as if they invoked it natively. Its key additional capability is unified provider resolution: you can point any supported harness at any LLM provider, with `amux-proxy` bridging the gap when the harness cannot speak the provider's native wire protocol.\n\nSee [launcher](../archive/design/launcher.md) for the archived launcher specification and [provider & model configuration](../archive/design/amux-provider-config.md) for the archived provider-configuration design.\n\n| Concern | `amux run` | `amux launch` |\n|---|---|---|\n| Output format | Normalized `AgentEvent` stream | Raw harness output (bypass) |\n| Input format | `RunOptions` / SDK API | Raw stdin passthrough |\n| Provider config | N/A (each harness's own) | Unified provider/model resolution |\n| Proxy orchestration | No | Yes (`--with-proxy-if-needed`) |\n| Use case | Programmatic orchestration, multi-agent | Direct harness usage with provider flexibility |\n\n### 6b.1 Syntax\n\n```\namux launch <harness> [provider] [flags...]\n```\n\n**Positional arguments:**\n\n| Argument | Required | Description |\n|---|---|---|\n| `<harness>` | Yes | Target harness name. Registered `SubprocessAdapter.agent` values: `claude`, `codex`, `gemini`, `opencode`, `copilot`, `cursor`, `pi`, `omp`, `openclaw`, `hermes`, `droid`, `amp`, `qwen`. |\n| `[provider]` | No | Provider/backend identifier. If omitted, the harness's default native provider is used. See §6b.3 for the full taxonomy. |\n\n### 6b.2 Flags\n\n#### Provider Configuration\n\n| Flag | Short | Type | Description |\n|---|---|---|---|\n| `--model` | `-m` | `string` | Model identifier (provider-specific format). Required for non-default providers. |\n| `--api-key` | | `string` | API key for the target provider. Can also be set via provider-specific env vars. |\n| `--api-base` | | `string` | Custom API base URL. Overrides provider defaults. |\n| `--region` | | `string` | Cloud region (for Bedrock, Vertex). |\n| `--project` | | `string` | Cloud project ID (for Vertex, Foundry). |\n| `--resource-group` | | `string` | Resource group (for Azure/Foundry). |\n| `--endpoint-name` | | `string` | Named deployment/endpoint (Azure, Foundry, Bedrock). |\n| `--transport` | `-t` | `string` | Wire protocol the harness should speak. One of: `anthropic`, `openai-chat`, `openai-responses`, `google`. Default: auto-detected from harness and provider. |\n| `--profile` | | `string` | Named provider profile from `~/.amux/providers.json`. |\n| `--auth-command` | | `string` | External command that emits a bearer token on stdout. |\n\n#### Proxy Control\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--with-proxy-if-needed` | `boolean` | `false` | Launch `amux-proxy` automatically if the harness cannot speak the provider's native transport directly. |\n| `--with-proxy` | `boolean` | `false` | Force proxy launch even if the harness supports the provider natively. Useful for observability or logging. |\n| `--no-proxy` | `boolean` | `false` | Explicitly disable proxy. Errors if the harness cannot reach the provider without one. |\n| `--proxy-port` | `number` | `0` (auto) | Port for the proxy server. `0` = OS-assigned ephemeral port. |\n| `--proxy-log-level` | `string` | `warn` | Log level for the proxy process: `debug`, `info`, `warn`, `error`. |\n\n#### Session Control\n\n| Flag | Short | Type | Description |\n|---|---|---|---|\n| `--resume` | `-r` | `string` | Resume an existing session by ID or name. Passes the harness-specific resume flag through. |\n| `--session-id` | `-s` | `string` | Explicit session ID for a new session. |\n\n#### Execution Mode\n\n| Flag | Short | Type | Description |\n|---|---|---|---|\n| `--prompt` | `-p` | `string` | Initial prompt. When set, runs in **non-interactive** mode: sends the prompt, streams output, and exits when the harness exits. When omitted, runs in **interactive** mode with full stdin/stdout passthrough. |\n| `--max-turns` | | `number` | Turn limit (non-interactive mode). |\n| `--max-budget-usd` | | `number` | Cost limit (where the harness supports it). |\n\n#### Bridge Control\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--bridge-interactive` | `boolean` | `false` | Enable the interactive bridge layer, which proxies stdin/stdout through an intermediary that can inject babysitter hook responses and orchestration signals while preserving the harness's native TUI. |\n| `--bridge-hooks` | `boolean` | `false` | Enable hook bridging: the bridge intercepts hook lifecycle events (SessionStart, Stop, PreToolUse, etc.) and forwards them to the babysitter session-start hook, which can bind the session to a bare run. Requires `--bridge-interactive` or is implied by it when the harness supports hooks natively. |\n\n#### Harness Passthrough\n\n| Flag | Type | Description |\n|---|---|---|\n| `--harness-args` | `string[]` | Raw arguments forwarded verbatim to the harness CLI after all amux-managed args. Use the `--` separator: `amux launch claude api -- --bare --verbose`. |\n\n#### General\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--json` | | `boolean` | `false` | Output machine-readable JSON for launch status and proxy lifecycle events. Does not affect raw harness output. |\n| `--debug` | `-d` | `boolean` | `false` | Debug mode. Logs proxy and harness process details to stderr. |\n| `--dry-run` | | `boolean` | `false` | Print the resolved command, env vars, and proxy config as JSON without executing. |\n\n### 6b.3 Supported Provider IDs\n\n| Provider ID | Description | Default Transport | Default Auth |\n|---|---|---|---|\n| `anthropic` | Anthropic direct API | `anthropic` | API key |\n| `openai` | OpenAI direct API | `openai-responses` | API key |\n| `google` | Google AI Studio | `google` | API key |\n| `bedrock` | AWS Bedrock | `anthropic` | IAM / AWS profile |\n| `vertex` | Google Vertex AI | `google` | ADC / service account |\n| `azure` | Azure OpenAI | `openai-chat` | API key / AD token |\n| `foundry` | Azure AI Foundry | `openai-chat` | API key / AD token |\n| `ollama` | Local Ollama instance | `openai-chat` | None |\n| `local` | Generic local model server | `openai-chat` | None |\n| `openrouter` | OpenRouter | `openai-chat` | API key |\n| `groq` | Groq | `openai-chat` | API key |\n| `fireworks` | Fireworks AI | `openai-chat` | API key |\n| `together` | Together AI | `openai-chat` | API key |\n| `deepseek` | DeepSeek | `openai-chat` | API key |\n| `mistral` | Mistral AI | `openai-chat` | API key |\n| `cerebras` | Cerebras | `openai-chat` | API key |\n| `sambanova` | SambaNova | `openai-chat` | API key |\n| `custom` | User-defined endpoint | Requires `--transport` | Any (via flags) |\n\n### 6b.4 Supported Transport IDs\n\n| Transport ID | Endpoint | Wire Format | Used By |\n|---|---|---|---|\n| `anthropic` | `POST /v1/messages` | Anthropic Messages API (SSE) | Claude Code |\n| `openai-chat` | `POST /v1/chat/completions` | OpenAI Chat Completions | OpenCode, Codex (`wire_api=chat`) |\n| `openai-responses` | `POST /v1/responses` | OpenAI Responses API | Codex (default) |\n| `google` | `POST /v1beta/models/:model:generateContent` | Google GenerateContent | Gemini CLI |\n\n### 6b.5 Native Support Matrix\n\nThis matrix shows which harness+provider combinations work **without** a proxy. Use `--with-proxy-if-needed` for combinations marked with a cross.\n\n| | `anthropic` | `bedrock` | `vertex` | `azure` | `foundry` | `google` | `openai` | `ollama` |\n|---|---|---|---|---|---|---|---|---|\n| **claude** | Native | Native | Native | No | Native | No | No | Via `ANTHROPIC_BASE_URL` |\n| **codex** | No | No | No | No | No | No | Native | Native (`--oss`) |\n| **gemini** | No | No | Native (ADC) | No | No | Native | No | No |\n| **opencode** | Native | Native (SDK) | Native (SDK) | Native (SDK) | No | Native (SDK) | Native | OpenAI-compat |\n| **copilot** | No | No | No | No | No | No | No | No |\n| **cursor** | Native | No | No | No | No | No | No | No |\n\nCells marked \"No\" require `--with-proxy-if-needed`. Cells marked \"Via `ANTHROPIC_BASE_URL`\" or \"OpenAI-compat\" work with an env var workaround but a proxy is recommended for reliability.\n\n### 6b.6 Examples\n\n```bash\n# Interactive Claude Code with default provider (Anthropic direct)\namux launch claude\n\n# Interactive Claude Code via Bedrock (native, no proxy needed)\namux launch claude bedrock --region us-east-1\n\n# Interactive Claude Code via Vertex (native)\namux launch claude vertex --project my-gcp-project --region us-central1\n\n# Interactive Codex via Bedrock (proxy required: codex speaks OpenAI, bedrock speaks Anthropic)\namux launch codex bedrock --region us-east-1 \\\n --model anthropic.claude-sonnet-4-20250514-v1:0 \\\n --with-proxy-if-needed\n\n# Non-interactive (one-shot) run via Vertex\namux launch claude vertex --project my-project --region us-central1 \\\n -p \"Explain the authentication flow in this codebase\" \\\n --max-turns 3\n\n# Interactive Codex via Ollama (local, no proxy needed with --oss flag)\namux launch codex ollama --model qwen3:32b\n\n# Interactive Claude Code via Ollama (proxy bridges Ollama to Anthropic transport)\namux launch claude ollama --model qwen3:32b --with-proxy-if-needed\n\n# Use a named provider profile from ~/.amux/providers.json\namux launch claude --profile work-bedrock\n\n# Dry run: see what would be executed without running it\namux launch codex bedrock --region us-east-1 --model anthropic.claude-sonnet-4-20250514-v1:0 \\\n --with-proxy-if-needed --dry-run\n\n# Passthrough raw harness args after --\namux launch claude api -- --bare --verbose\n```\n\n### 6b.7 Non-Interactive vs Interactive Mode\n\n**Interactive mode** (default, no `--prompt`): stdin, stdout, and stderr are passed through directly to the harness. The user interacts with the harness TUI natively. `amux` only manages the proxy lifecycle and process signals.\n\n**Non-interactive mode** (`--prompt` is set): the prompt is delivered to the harness via its native mechanism (e.g., `--print` for claude, `exec` for codex, `--prompt` for gemini). stdout and stderr are still passed through raw. The process exits when the harness completes its response. Suitable for scripting and CI/CD.\n\n### 6b.8 Error Codes\n\n| Code | Condition |\n|---|---|\n| `HARNESS_NOT_FOUND` | Unknown harness name. |\n| `HARNESS_NOT_INSTALLED` | Harness binary not found on `$PATH`. |\n| `PROVIDER_UNSUPPORTED` | Harness+provider combo has no native support and proxy is not enabled. |\n| `PROXY_REQUIRED` | Proxy required but `--no-proxy` is set. |\n| `PROXY_LAUNCH_FAILED` | `amux-proxy` failed to start. Check that it is installed: `pip install amux-proxy`. |\n| `AUTH_MISSING` | Required provider auth not supplied. |\n\n---\n\n## 7. `amux install` -- Install Agent CLIs\n\nInstall or display installation instructions for agent CLI binaries.\n\n### 7.1 Syntax\n\n```\namux install <agent> [flags...]\n```\n\n`<agent>` is required. Must be one of the ten built-in agent names: `claude`, `codex`, `gemini`, `copilot`, `cursor`, `opencode`, `pi`, `omp`, `openclaw`, `hermes`.\n\n### 7.2 Flags\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--dry-run` | -- | `boolean` | `false` | Print the install commands without executing them. |\n| `--method` | -- | `string` | Auto-detected | Force a specific install method: `npm`, `pip`, `brew`, `gh-extension`, `curl`, `winget`, `scoop`, `manual`. |\n| `--yes` | `-y` | `boolean` | `false` | Non-interactive: execute install commands without confirmation prompts. |\n\n### 7.3 Behavior\n\n1. Resolves the adapter for `<agent>`.\n2. Reads `AgentCapabilities.installMethods` filtered by the current platform (`process.platform`).\n3. If `--method` is specified, selects only the matching install method. Exits with code 2 if no method matches.\n4. For each matching install method:\n a. Checks prerequisites (`InstallMethod.prerequisiteCheck`) if defined. Prints a warning if the prerequisite is not met.\n b. Prints the install command to stdout.\n c. Unless `--dry-run`: prompts for confirmation (unless `--yes`), then executes the command as a child process, streaming stdout/stderr to the terminal.\n5. After installation, runs `mux.adapters.detect(agent)` to verify the install succeeded and prints the detected version.\n\n### 7.4 Install Methods per Agent\n\n| Agent | Method | Command | Platform | Notes |\n|---|---|---|---|---|\n| `claude` | npm | `npm install -g @anthropic-ai/claude-code` | all | -- |\n| `claude` | brew | `brew install claude-code` | darwin | -- |\n| `codex` | npm | `npm install -g @openai/codex` | all | -- |\n| `gemini` | npm | `npm install -g @google/gemini-cli` | all | -- |\n| `copilot` | gh-extension | `gh extension install github/gh-copilot` | all | Requires GitHub CLI (`gh`). Prerequisite check: `gh --version`. |\n| `cursor` | manual | Opens download page | darwin, linux | No headless-only install. Full app required. |\n| `cursor` | winget | `winget install Cursor.Cursor` | win32 | -- |\n| `opencode` | npm | `npm install -g opencode` | all | -- |\n| `opencode` | brew | `brew install opencode/tap/opencode` | darwin | -- |\n| `pi` | npm | `npm install -g @mariozechner/pi-coding-agent` | all | -- |\n| `omp` | npm | `npm install -g @oh-my-pi/pi-coding-agent` | all | -- |\n| `openclaw` | npm | `npm install -g openclaw` | all | Requires Node 22.16+, 16GB RAM minimum. |\n| `hermes` | pip | `pip install hermes-agent` | all | Requires Python >= 3.11. Alternative: `uv pip install hermes-agent`. |\n\n### 7.5 API Mapping\n\n| CLI | SDK |\n|---|---|\n| `amux install claude` | `mux.adapters.installInstructions('claude', process.platform)` |\n| `amux install --dry-run gemini` | `mux.adapters.installInstructions('gemini', process.platform)` (display only) |\n\n### 7.6 Examples\n\n```bash\n# Install Claude Code\namux install claude\n\n# See what would be installed without running\namux install --dry-run gemini\n\n# Force npm method\namux install opencode --method npm\n\n# Non-interactive install\namux install codex --yes\n\n# Install hermes (Python agent)\namux install hermes\n```\n\n---\n\n## 8. `amux adapters` -- Adapter Discovery\n\nList and inspect registered adapters and their installation state.\n\n### 8.1 Syntax\n\n```\namux adapters list [flags...]\namux adapters detect <agent> [flags...]\n```\n\n### 8.2 `amux adapters list`\n\nLists all registered adapters with their installation status, version, and authentication state.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**Output columns (human mode):**\n\n| Column | Description |\n|---|---|\n| Agent | Agent name. |\n| Installed | `yes` / `no`. |\n| Version | Detected version string, or `--` if not installed. |\n| Auth | `authenticated`, `unauthenticated`, `expired`, `unknown`, or `--`. |\n| Path | Absolute path to CLI binary, or `--`. |\n\n**API mapping:** `mux.adapters.list()` combined with `mux.adapters.installed()` for the installed/version/auth columns.\n\n### 8.3 `amux adapters detect <agent>`\n\nDetect a single agent: checks installation, resolves the binary path, detects the version, and checks authentication state.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON object. |\n\n**Output (human mode):** Key-value pairs:\n\n```\nAgent: claude\nInstalled: yes\nPath: /usr/local/bin/claude\nVersion: 1.2.3\nMin version: 1.0.0\nMeets min: yes\nAuth: authenticated\nModel: claude-sonnet-4-20250514\n```\n\n**API mapping:** `mux.adapters.detect('claude')` returns `InstalledAgentInfo`.\n\n### 8.4 Error Behavior\n\n- Unknown agent name: exit code 3 (`AGENT_NOT_FOUND`).\n- Agent not installed (for `detect`): prints the detection result showing `installed: false`, exits with code 0 (detection succeeded; the result is \"not installed\").\n\n---\n\n## 9. `amux capabilities` -- Agent Capabilities\n\nDisplay the capabilities manifest for an agent, optionally scoped to a specific model.\n\n### 9.1 Syntax\n\n```\namux capabilities <agent> [flags...]\n```\n\n### 9.2 Flags\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--model` | `string` | -- | Show model-level capabilities for a specific model ID. |\n| `--json` | `boolean` | `false` | Output as JSON object. |\n\n### 9.3 Behavior\n\n- Without `--model`: prints agent-level capabilities (`AgentCapabilities`) as defined in `06-capabilities-and-models.md`, Section 2.\n- With `--model`: prints the union of agent-level and model-level capabilities (`ModelCapabilities`) for the specified model.\n\n**Output (human mode):** Grouped key-value display organized by category (session, streaming, tool calling, thinking, output, skills, plugins, process, auth, install).\n\n**API mapping:**\n\n| CLI | SDK |\n|---|---|\n| `amux capabilities claude` | `mux.adapters.capabilities('claude')` |\n| `amux capabilities claude --model claude-sonnet-4-20250514` | `mux.adapters.capabilities('claude')` + `mux.models.model('claude', 'claude-sonnet-4-20250514')` |\n\n### 9.4 Error Behavior\n\n- Unknown agent: exit code 3 (`AGENT_NOT_FOUND`).\n- Unknown model (with `--model`): exit code 1, error message listing available models.\n\n---\n\n## 10. `amux models` -- Model Registry\n\nList, inspect, and refresh model metadata for agents.\n\n### 10.1 Syntax\n\n```\namux models list <agent> [flags...]\namux models get <agent> <model-id> [flags...]\namux models refresh <agent> [flags...]\namux models current <agent> [flags...]\namux models set <agent> <model-id> [--provider <provider>] [flags...]\n```\n\n### 10.2 `amux models list <agent>`\n\nList all models available for an agent.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**Output columns (human mode):**\n\n| Column | Description |\n|---|---|\n| Model ID | The model identifier string. |\n| Display Name | Human-readable name. |\n| Provider | Normalized provider family (`anthropic`, `openai`, `configurable`, etc.). |\n| Protocol | Normalized request protocol (`messages`, `responses`, `chat`, `custom`). |\n| Deploy | Typical deployment path (`hosted`, `local`, `gateway`, `hybrid`). |\n| Context Window | Maximum context in tokens. |\n| Source | `bundled` or `remote`. |\n| Default | Whether this is the adapter's default model. |\n\n**API mapping:** `mux.models.catalog('claude')` returns the per-adapter model catalog with default-entry metadata.\n\n### 10.3 `amux models get <agent> <model-id>`\n\nShow detailed capabilities for a single model.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON object. |\n\n**Output (human mode):** Key-value display showing all `ModelCapabilities` fields.\n\n**API mapping:** `mux.models.model('claude', 'claude-sonnet-4-20250514')` returns `ModelCapabilities | null`.\n\n### 10.4 `amux models refresh <agent>`\n\nRefresh the model list from the agent's remote source (where applicable).\n\n**API mapping:** `mux.models.refresh('claude')`.\n\n### 10.5 `amux models current <agent>`\n\nShow the configured model, adapter default, and effective model selection for an agent.\n\n**API mapping:** `mux.config.getModelSelection('claude')` plus `mux.models.model(...)` for effective-model details.\n\n### 10.6 `amux models set <agent> <model-id>`\n\nValidate and persist the configured model for an agent. Optional `--provider` records the selected provider for configurable/local-provider adapters.\n\n**API mapping:** `mux.models.validate('claude', 'sonnet')` followed by `mux.config.setModelSelection('claude', { model, provider })`.\n\n### 10.7 Error Behavior\n\n- Unknown agent: exit code 3 (`AGENT_NOT_FOUND`).\n- Unknown model (for `get`): exit code 1, error message listing available models.\n\n---\n\n## 11. `amux plugin` -- Native Plugin Management\n\nUnified interface for managing native agent plugins through CLI delegation. Commands delegate to each agent's native plugin system (e.g., `claude plugins`, `copilot plugin`, `gemini extensions`). All subcommands are capability-gated: invoking on an agent where native plugin CLI commands don't exist produces exit code 6 (`CAPABILITY_ERROR`).\n\n### 11.1 Syntax\n\n```\namux plugin list <agent> [flags...]\namux plugin install <agent> <plugin-id> [flags...]\namux plugin uninstall <agent> <plugin-id> [flags...]\namux plugin update <agent> <plugin-id> [flags...]\namux plugin marketplace <agent> [subcommand] [flags...]\n```\n\n### 11.2 `amux plugin list <agent>`\n\nList installed plugins for an agent via native CLI.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**API mapping:** Delegates to agent's native command (e.g., `claude plugins list`).\n\n### 11.3 `amux plugin install <agent> <plugin-id>`\n\nInstall a plugin via agent's native CLI.\n\n**Flags:**\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--yes` | `-y` | `boolean` | `false` | Skip confirmation prompt. |\n\n**API mapping:** Delegates to agent's native install command.\n\n### 11.4 `amux plugin uninstall <agent> <plugin-id>`\n\nUninstall a plugin via agent's native CLI.\n\n**Flags:**\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--yes` | `-y` | `boolean` | `false` | Skip confirmation prompt. |\n\n**API mapping:** Delegates to agent's native uninstall command.\n\n### 11.5 `amux plugin update <agent> <plugin-id>`\n\nUpdate a plugin via agent's native CLI.\n\n**API mapping:** Delegates to agent's native update command.\n\n### 11.6 `amux plugin marketplace <agent> [subcommand]`\n\nAccess agent's native plugin marketplace commands.\n\n**API mapping:** Delegates to agent's marketplace commands (e.g., `claude plugins marketplace`).\n\n### 11.7 Plugin Support per Agent\n\n| Agent | Native Plugin Support | CLI Command |\n|---|---|---|\n| Claude | ✅ Full marketplace | `claude plugins` |\n| Gemini | ✅ Extensions | `gemini extensions` |\n| Codex | ✅ Plugin directory | `codex plugins` |\n| Copilot | ✅ Plugin marketplace | `copilot plugin` |\n| OpenCode | ✅ Three-tier system | `opencode plugins` |\n| Cursor | ❌ Hook-only (see Section 12) | N/A |\n| All others | ❌ MCP-only (see Section 12) | N/A |\n\n### 11.8 Examples\n\n```bash\n# List installed plugins via native CLI\namux plugin list claude\namux plugin list gemini\n\n# Install plugins via native marketplace\namux plugin install claude @anthropic/frontend-design\namux plugin install copilot github/copilot-agent\n\n# Access native marketplace\namux plugin marketplace claude\namux plugin marketplace copilot\n```\n\n---\n\n## 12. `amux mcp` -- MCP Server Management\n\nUnified interface for managing Model Context Protocol servers across all agents. MCP servers provide cross-agent capabilities and integrations. All agents support MCP servers.\n\n### 12.1 Syntax\n\n```\namux mcp list <agent> [flags...]\namux mcp install <agent> <mcp-server> [flags...]\namux mcp uninstall <agent> <mcp-server> [flags...]\n```\n\n### 12.2 `amux mcp list <agent>`\n\nList installed MCP servers for an agent.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON array. |\n| `--project` | `boolean` | `false` | List project-specific MCP servers only. |\n\n**Output columns (human mode):**\n\n| Column | Description |\n|---|---|\n| Server Name | MCP server identifier. |\n| Status | `enabled` / `disabled`. |\n| Command | Executable command. |\n| Scope | `global` / `project`. |\n\n### 12.3 `amux mcp install <agent> <mcp-server>`\n\nInstall an MCP server for an agent.\n\n**Flags:**\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--project` | `-p` | `boolean` | `false` | Install to project scope (vs. global). |\n| `--yes` | `-y` | `boolean` | `false` | Skip confirmation prompt. |\n\n### 12.4 `amux mcp uninstall <agent> <mcp-server>`\n\nUninstall an MCP server from an agent.\n\n**Flags:**\n\n| Flag | Short | Type | Default | Description |\n|---|---|---|---|---|\n| `--yes` | `-y` | `boolean` | `false` | Skip confirmation prompt. |\n\n### 12.5 MCP Server Registry\n\nAll MCP servers are available from the official registry at [https://modelcontextprotocol.io](https://modelcontextprotocol.io).\n\n### 12.6 Examples\n\n```bash\n# List MCP servers for an agent\namux mcp list claude\namux mcp list cursor\n\n# Install MCP server globally\namux mcp install claude filesystem\namux mcp install gemini postgres\n\n# Install MCP server to project\namux mcp install claude web-browser --project\n\n# Remove MCP server\namux mcp uninstall claude filesystem\n```\n\n---\n\n## 13. `amux sessions` -- Session Management\n\nRead-only access to agent session data. The CLI delegates to `SessionManager` (see `07-session-manager.md`, Section 2). Session data is never modified by these commands.\n\n### 12.1 Syntax\n\n```\namux sessions list <agent> [flags...]\namux sessions show <agent> <session-id> [flags...]\namux sessions search <query> [flags...]\namux sessions export <agent> <session-id> [flags...]\namux sessions diff <agent>:<id> <agent>:<id> [flags...]\namux sessions resume <agent> <session-id> [flags...]\namux sessions fork <agent> <session-id> [flags...]\n```\n\n### 12.2 `amux sessions list <agent>`\n\nList sessions for an agent.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--since` | `string` | -- | ISO 8601 date or relative (e.g., `2024-01-01`, `7d`, `1w`). Include sessions after this time. |\n| `--until` | `string` | -- | ISO 8601 date or relative. Include sessions before this time. |\n| `--model` | `string` | -- | Filter by model ID. |\n| `--tag` | `string` | -- | Filter by run tag (from `run-index.jsonl`). Repeatable. |\n| `--limit` | `number` | `50` | Maximum number of sessions to return. |\n| `--sort` | `string` | `date` | Sort order: `date`, `cost`, `turns`. |\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**Output columns (human mode):**\n\n| Column | Description |\n|---|---|\n| Session ID | Native session identifier. |\n| Model | Model ID used. |\n| Turns | Number of conversation turns. |\n| Cost | Total cost in USD. |\n| Date | Session start date. |\n| Summary | First line of the prompt (truncated). |\n\n**API mapping:** `mux.sessions.list('claude', { since, until, model, tags, limit, sort })` returns `SessionSummary[]`.\n\n### 12.3 `amux sessions show <agent> <session-id>`\n\nDisplay the full content of a session.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--format` | `string` | `markdown` | Output format: `json`, `jsonl`, `markdown`. |\n\n**API mapping:** `mux.sessions.export('claude', 'abc123', 'markdown')`.\n\n### 12.4 `amux sessions tail <agent> [session-id]`\n\nThis command is not part of the current public CLI surface.\n\n`@a5c-ai/agent-mux-core` does not currently expose a truthful live session-watch API. Earlier\ndrafts described `mux.sessions.watch()`, but that contract was removed rather than shipping\nsynthetic `AgentEvent` payloads derived from arbitrary session-file changes.\n\n### 12.5 `amux sessions search <query>`\n\nFull-text search across sessions.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--agent` | `AgentName` | All | Restrict search to a specific agent. |\n| `--since` | `string` | -- | Search sessions after this time. |\n| `--until` | `string` | -- | Search sessions before this time. |\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**API mapping:** `mux.sessions.search({ text: query, agent, since, until })` returns `SessionSummary[]`.\n\n### 12.6 `amux sessions export <agent> <session-id>`\n\nExport a session to a file or stdout.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--format` | `string` | `json` | Export format: `json`, `jsonl`, `markdown`. |\n\n**Output:** The exported session content is written to stdout. Redirect to a file as needed.\n\n**API mapping:** `mux.sessions.export('claude', 'abc123', 'json')` returns `string`.\n\n### 12.7 `amux sessions diff <agent>:<id> <agent>:<id>`\n\nCompute a structural diff between two sessions. Sessions may belong to the same or different agents.\n\n**Syntax:** Each argument uses the unified ID format `<agent>:<native-session-id>`.\n\n```bash\namux sessions diff claude:abc123 claude:def456\namux sessions diff claude:abc123 gemini:xyz789\n```\n\n**API mapping:** `mux.sessions.diff({ agent: 'claude', sessionId: 'abc123' }, { agent: 'gemini', sessionId: 'xyz789' })` returns `SessionDiff`.\n\n### 12.8 `amux sessions resume <agent> <session-id>`\n\nResume a session by starting a new interactive run that continues from the specified session.\n\n**Behavior:** Equivalent to `amux run <agent> --session <session-id> --interactive`. Enters REPL mode (see Section 13).\n\n**API mapping:** `mux.run({ agent, sessionId, ... })` with interactive REPL loop.\n\n### 12.9 `amux sessions fork <agent> <session-id>`\n\nFork a session and enter an interactive run on the new branch.\n\n**Behavior:** Equivalent to `amux run <agent> --fork <session-id> --interactive`. Enters REPL mode.\n\n**API mapping:** `mux.run({ agent, forkSessionId: sessionId, ... })` with interactive REPL loop.\n\n### 12.10 Error Behavior\n\n- Unknown agent: exit code 3 (`AGENT_NOT_FOUND`).\n- Unknown session ID: exit code 8 (`SESSION_NOT_FOUND`).\n- Corrupt session file: exit code 1 (`PARSE_ERROR`), with diagnostic message to stderr.\n\n---\n\n## 13. Interactive REPL Mode (`amux run -i`)\n\nWhen `--interactive` / `-i` is set on `amux run`, the CLI enters a Read-Eval-Print Loop for multi-turn conversation with the agent.\n\n### 13.1 Entry Conditions\n\nREPL mode is entered when:\n- `amux run -i` is invoked (with or without an initial prompt).\n- `amux sessions resume` is invoked.\n- `amux sessions fork` is invoked.\n\n### 13.2 REPL Behavior\n\n1. If an initial prompt is provided, it is sent as the first turn.\n2. After the agent completes its response, the CLI prints a prompt indicator (for example, `amux>`) and waits for user input on stdin.\n3. User input is sent to the running agent via `RunHandle.continue(prompt)`.\n4. Tool approval requests are handled inline: the CLI prints the request and prompts for `[y]es / [n]o / [a]lways` on stderr.\n5. The loop continues until:\n - The user types `/exit` or `/quit`.\n - The user presses Ctrl+D (EOF on stdin).\n - The user presses Ctrl+C twice within 1 second.\n - The agent terminates.\n\n### 13.3 REPL Commands\n\nThe following slash commands are recognized within the REPL:\n\n| Command | Description |\n|---|---|\n| `/exit`, `/quit` | End the session and exit. |\n| `/abort` | Abort the current agent operation. |\n| `/interrupt` | Send interrupt (SIGINT) to the agent. |\n| `/pause` | Pause agent execution. |\n| `/resume` | Resume paused execution. |\n| `/status` | Print current run state, session ID, model, and cost. |\n| `/cost` | Print accumulated cost for this run. |\n| `/session` | Print the current session ID. |\n| `/help` | Print REPL command reference. |\n\nSDK frontends built on the same live-run surface can also defer follow-up\nprompts with `RunHandle.queue()` and `RunHandle.steer()`. The bundled TUI maps\n`/queue ...`, `/steer ...`, and `/steer-tool ...` onto those APIs when a run\nis already active.\n\n### 13.4 REPL + JSONL\n\nWhen `-i` and `--json` are combined, the REPL reads prompts from stdin (one per line) and emits JSONL events to stdout. This enables programmatic multi-turn conversation. The REPL terminates on stdin EOF.\n\n---\n\n## 14. Pipe and Stdin Support\n\nThe CLI supports pipe-based workflows for composability with Unix tools.\n\n### 14.1 Reading Prompt from Stdin\n\nWhen `amux run` is invoked without a prompt argument and stdin is not a TTY, the entire stdin is read and used as the prompt:\n\n```bash\necho \"refactor this function\" | amux run claude\ncat prompt.txt | amux run gemini --json\ngit diff | amux run codex \"review this diff\"\n```\n\nWhen both a positional prompt and stdin are provided, the positional prompt takes precedence and stdin is ignored.\n\n### 14.2 JSONL Output for Piping\n\nJSONL output (`--json`) is designed for consumption by downstream tools:\n\n```bash\n# Extract only text deltas\namux run claude \"explain X\" --json | jq 'select(.type == \"text_delta\") | .delta'\n\n# Monitor tool calls\namux run codex \"fix tests\" --json | jq 'select(.type | startswith(\"tool_\"))'\n\n# Extract final text\namux run gemini \"summarize\" --json | jq 'select(.type == \"run_result\") | .text'\n```\n\n### 14.3 TTY Detection\n\nThe CLI detects whether stdin and stdout are TTYs using `process.stdin.isTTY` and `process.stdout.isTTY`:\n\n| stdin | stdout | Behavior |\n|---|---|---|\n| TTY | TTY | Full interactive mode: colors, spinners, approval prompts. |\n| TTY | Pipe | Colors disabled, spinners disabled, approval prompts still on stderr. |\n| Pipe | TTY | Prompt read from stdin pipe. Approval prompts on stderr. |\n| Pipe | Pipe | Full non-interactive: `--json` implied if not set, approvals auto-denied. |\n\n---\n\n## 15. `amux cost` -- Cost Reporting\n\nAggregate and display cost data across runs.\n\n### 15.1 Syntax\n\n```\namux cost report [flags...]\n```\n\n### 15.2 Flags\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--agent` | `AgentName` | All | Filter by agent. Repeatable. |\n| `--since` | `string` | -- | Include runs after this time. ISO 8601 or relative. |\n| `--until` | `string` | -- | Include runs before this time. |\n| `--model` | `string` | -- | Filter by model. |\n| `--tag` | `string` | -- | Filter by tag. Repeatable. |\n| `--group-by` | `string` | `agent` | Group results: `agent`, `model`, `day`, `tag`. |\n| `--json` | `boolean` | `false` | Output as JSON object. |\n\n### 15.3 Output (Human Mode)\n\nA formatted table showing cost breakdowns per grouping:\n\n```\nCost Report (last 30 days)\n──────────────────────────────────────────\nAgent Runs Input$ Output$ Total\nclaude 42 $1.23 $3.45 $4.68\ncodex 15 $0.50 $1.20 $1.70\ngemini 8 $0.10 $0.30 $0.40\n──────────────────────────────────────────\nTotal 65 $1.83 $4.95 $6.78\n```\n\n### 15.4 API Mapping\n\n| CLI | SDK |\n|---|---|\n| `amux cost report --agent claude --since 30d` | `mux.sessions.totalCost({ agent: 'claude', since: '30d' })` |\n| `amux cost report --group-by model` | `mux.sessions.totalCost({ groupBy: 'model' })` |\n\n---\n\n## 16. `amux config` -- Configuration Management\n\nRead, write, and validate agent configuration files through the unified `ConfigManager` interface. See `08-config-and-auth.md`, Section 2 for the full `ConfigManager` specification.\n\n### 16.1 Syntax\n\n```\namux config get <agent> [field] [--scope global|project] [--json]\namux config set <agent> <field> <value> [--scope global|project]\namux config schema <agent> [--json]\namux config validate <agent> [--json]\namux config mcp list <agent> [--json]\namux config mcp add <agent> [--scope global|project]\namux config mcp remove <agent> <server-name> [--scope global|project]\namux config reload [agent]\n```\n\n#### Common Config Flags\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--scope` | `global \\| project` | `merged` | Target a specific config file scope. `global` reads/writes only `~/.agent-mux/config.json` (or the agent's global config). `project` reads/writes only `.agent-mux/config.json` (or the agent's project config). When omitted, read commands return the merged result (project overrides global); write commands target the global file. |\n| `--json` | flag | off | Output in JSON format (single object, not JSONL). Applies to all read/query subcommands. |\n\n### 16.2 `amux config get <agent> [field]`\n\nRead configuration for an agent. If `field` is omitted, prints the full merged config. If `field` is provided (dot-notation), prints only that field's value.\n\n**API mapping:**\n\n| CLI | SDK |\n|---|---|\n| `amux config get claude` | `mux.config.get('claude')` |\n| `amux config get claude model` | `mux.config.getField('claude', 'model')` |\n| `amux config get claude permissions.allow` | `mux.config.getField('claude', 'permissions.allow')` |\n\n### 16.3 `amux config set <agent> <field> <value>`\n\nWrite a single field to the agent's native config file.\n\n`<value>` is parsed as JSON if it starts with `{`, `[`, `\"`, or is a number/boolean literal. Otherwise it is treated as a plain string.\n\n**API mapping:** `mux.config.setField('claude', 'model', 'claude-sonnet-4-20250514')`.\n\n**Error behavior:**\n- Unknown agent: exit code 3 (`AGENT_NOT_FOUND`).\n- Invalid field/value: exit code 2 (`VALIDATION_ERROR`).\n- File write failure: exit code 7 (`CONFIG_ERROR`).\n- Lock contention: exit code 7 (`CONFIG_LOCK_ERROR`), message indicates retry.\n\n### 16.4 `amux config schema <agent>`\n\nPrint the configuration schema for an agent, showing all recognized fields, their types, defaults, and valid ranges.\n\n**API mapping:** `mux.config.schema('claude')` returns `AgentConfigSchema`.\n\n### 16.5 `amux config validate <agent>`\n\nValidate the current config file(s) for an agent against the schema. Prints validation results: field-level errors and warnings.\n\n**API mapping:** `mux.config.validate('claude', mux.config.get('claude'))` returns `ValidationResult`.\n\n### 16.6 `amux config mcp list <agent>`\n\nList MCP servers configured for an agent.\n\n**API mapping:** `mux.config.getMcpServers('claude')` returns `McpServerConfig[]`.\n\n### 16.7 `amux config mcp add <agent>`\n\nAdd an MCP server to the agent's config. The CLI prompts for server name, command, args, and environment variables interactively. In non-interactive mode (piped stdin), reads a JSON `McpServerConfig` from stdin.\n\n**API mapping:** `mux.config.addMcpServer('claude', serverConfig)`.\n\n**Error behavior:**\n- Agent does not support MCP: exit code 6 (`CAPABILITY_ERROR`).\n- Server name already exists: exit code 7 (`CONFIG_ERROR`).\n\n### 16.8 `amux config mcp remove <agent> <server-name>`\n\nRemove an MCP server from the agent's config by name.\n\n**API mapping:** `mux.config.removeMcpServer('claude', 'my-server')`.\n\n### 16.9 `amux config reload [agent]`\n\n> **Spec-level addition:** This command is not in the scope document's CLI listing (scope §21) but is specified in `08-config-and-auth.md` Section 2 and Section 15.1. It maps to the `ConfigManager.reload()` method added by that spec.\n\nInvalidate the config cache and re-read from disk. If `agent` is omitted, reloads all agents.\n\nThis is useful when external processes (the agent's own CLI, manual editing) have modified config files since the last read.\n\n**API mapping:** `mux.config.reload('claude')` or `mux.config.reload()`.\n\n### 16.10 Examples\n\n```bash\n# Read full config\namux config get claude\n\n# Read single field\namux config get claude model\n\n# Set a field\namux config set claude model claude-sonnet-4-20250514\n\n# View schema\namux config schema codex\n\n# Validate current config\namux config validate gemini\n\n# List MCP servers\namux config mcp list claude\n\n# Remove an MCP server\namux config mcp remove claude my-custom-server\n\n# Reload after external edit\namux config reload claude\n```\n\n---\n\n## 17. `amux profiles` -- Profile Management\n\nManage named `RunOptions` presets. Profiles are stored as JSON files in `~/.agent-mux/profiles/` (global) or `.agent-mux/profiles/` (project). See `02-run-options-and-profiles.md`, Section 10 for the full `ProfileManager` specification.\n\n### 17.1 Syntax\n\n```\namux profiles list [flags...]\namux profiles show <name>\namux profiles set <name> [run-flags...]\namux profiles delete <name> [flags...]\namux profiles apply <name>\n```\n\n### 17.2 `amux profiles list`\n\nList all available profiles from both global and project directories.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--scope` | `string` | All | Filter by scope: `global`, `project`. |\n| `--json` | `boolean` | `false` | Output as JSON array. |\n\n**Output columns (human mode):**\n\n| Column | Description |\n|---|---|\n| Name | Profile name. |\n| Scope | `global` or `project`. |\n| Agent | Default agent in profile, or `--`. |\n| Model | Default model in profile, or `--`. |\n\n**API mapping:** `mux.profiles.list({ scope })` returns `ProfileEntry[]`.\n\n### 17.3 `amux profiles show <name>`\n\nDisplay the resolved contents of a profile (merged global + project).\n\n**API mapping:** `mux.profiles.show(name)` returns `ResolvedProfile`.\n\n### 17.4 `amux profiles set <name> [run-flags...]`\n\nCreate or update a profile. The profile data is derived from the provided run flags. Any flag accepted by `amux run` (except per-run ephemeral flags) can be used.\n\n**Per-run ephemeral flags that are rejected** (per `02-run-options-and-profiles.md`, Section 10.3):\n\n`--cwd`, `--env`, `--run-id`, `--attach`, `--fork`, `--no-session`, `--project-id`, `--interactive`, `--quiet`.\n\n> **Note:** `--system` and `--system-mode` are NOT rejected — `systemPrompt` and `systemPromptMode` are valid profile fields (spec 02 §10.2).\n\nThese flags correspond to `RunOptions` fields that are per-run ephemeral and excluded from profile storage: `cwd`, `env`, `runId`, `attachments`, `systemPrompt`, `systemPromptMode`, `forkSessionId`, `noSession`, `projectId`, plus CLI-only flags `--interactive` and `--quiet`.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--scope` | `string` | Auto | Target scope: `global` or `project`. Defaults to `project` if a project directory exists, otherwise `global`. |\n\n**API mapping:** `mux.profiles.set(name, profileData, { scope })`.\n\n**Examples:**\n\n```bash\n# Create a \"fast\" profile\namux profiles set fast --agent claude --model claude-sonnet-4-20250514 --yolo --max-turns 5\n\n# Create a \"careful\" profile\namux profiles set careful --agent claude --thinking-effort high --deny\n\n# Create global profile\namux profiles set shared-fast --scope global --agent gemini --max-tokens 4096\n```\n\n### 17.5 `amux profiles delete <name>`\n\nDelete a profile.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--scope` | `string` | Both | Scope to delete from: `global`, `project`. If omitted, deletes from both. |\n\n**API mapping:** `mux.profiles.delete(name, { scope })`.\n\n### 17.6 `amux profiles apply <name>`\n\nResolve a profile and print the resulting `RunOptions` values. Does not start a run. Useful for previewing what a profile produces.\n\n**API mapping:** `mux.profiles.apply(name)` returns `Partial<RunOptions>`.\n\n### 17.7 Error Behavior\n\n- Unknown profile: exit code 9 (`PROFILE_NOT_FOUND`).\n- Invalid profile data: exit code 2 (`VALIDATION_ERROR`).\n\n---\n\n## 18. `amux auth` -- Authentication\n\nCheck and guide authentication state for agents. The CLI never writes credentials or modifies auth state -- it only inspects and provides guidance.\n\n### 18.1 Syntax\n\n```\namux auth check [agent]\namux auth setup <agent>\n```\n\n### 18.2 `amux auth check [agent]`\n\nCheck authentication state. If `agent` is omitted, checks all agents.\n\n**Flags:**\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output as JSON. |\n\n**Output (human mode, single agent):**\n\n```\nAgent: claude\nStatus: authenticated\nMethod: api-key\nIdentity: user@example.com\nChecked: 2025-01-15T10:30:00Z\n```\n\n**Output (human mode, all agents):**\n\n| Agent | Status | Method | Identity |\n|---|---|---|---|\n| claude | authenticated | api-key | user@... |\n| codex | unauthenticated | -- | -- |\n| gemini | authenticated | oauth | user@... |\n| ... | ... | ... | ... |\n\n**API mapping:**\n\n| CLI | SDK |\n|---|---|\n| `amux auth check claude` | `mux.auth.check('claude')` returns `AuthState` |\n| `amux auth check` | `mux.auth.checkAll()` returns `Record<AgentName, AuthState>` |\n\n### 18.3 `amux auth setup <agent>`\n\nPrint setup guidance for authenticating with an agent. Does not perform authentication itself.\n\n**Output:** Structured guidance including:\n- Required steps (numbered list).\n- Environment variables to set.\n- Commands to run.\n- Documentation links.\n- Platform-specific notes.\n\n**API mapping:** `mux.auth.getSetupGuidance('claude')` returns `AuthSetupGuidance`.\n\n### 18.4 Error Behavior\n\n- Unknown agent: exit code 3 (`AGENT_NOT_FOUND`).\n- `auth check` with unauthenticated result: exits with code 0 (the check succeeded; the result is \"unauthenticated\"). The status is reported in the output.\n\n---\n\n## 18b. `amux skill` -- Skill Management\n\nFile-convention only (no native harness command). Skills are folders containing\na `SKILL.md` plus assets, installed under per-harness conventions.\n\n```bash\namux skill list <agent> [--global|--project]\namux skill add <agent> <source-folder> [--name <n>] [--force] [--global|--project]\namux skill remove <agent> <name> [--global|--project]\namux skill where <agent>\namux skill agents # list supported harnesses\n```\n\nSupported harnesses: `claude`, `codex`, `cursor`, `opencode`, `gemini`, `copilot`.\nPaths: `$HOME/.<agent>/skills/` (global) or `<cwd>/.<agent>/skills/` (project).\n\n---\n\n## 18c. `amux agent` -- Sub-agent Management\n\nFile-convention only. Copies agent definition files (markdown/yaml/json) into\nper-harness sub-agent directories.\n\n```bash\namux agent list <agent> [--global|--project]\namux agent add <agent> <source> [--name <n>] [--force] [--global|--project]\namux agent remove <agent> <name> [--global|--project]\namux agent where <agent>\namux agent agents # list supported harnesses\n```\n\nSupported: `claude`, `claude-code`, `codex`, `cursor`, `opencode`.\nPaths: `$HOME/.<agent>/agents/` (global) or `<cwd>/.<agent>/agents/` (project).\n\nReferences:\n- Claude: https://code.claude.com/docs/en/sub-agents\n- Codex: https://developers.openai.com/codex/subagents#custom-agents\n\n---\n\n## 18d. `amux hooks` -- Hook Management\n\nManage hook registrations and dispatch. Backed by `HookConfigManager` in core.\n\n```bash\namux hooks <agent> discover # native hook types\namux hooks <agent> list\namux hooks <agent> add <hookType> [--handler builtin|command|script] [--target <t>] [--id <id>] [--global]\namux hooks <agent> remove <id> [--global]\namux hooks <agent> set <id> [--priority N] [--enabled true|false] [--target <t>]\namux hooks <agent> handle <hookType> # stdin JSON → dispatch → result\n```\n\nStorage: `$HOME/.amux/hooks.json` (global), `<cwd>/.amux/hooks.json` (project).\n\n---\n\n## 19. `amux init` -- Project Initialization\n\nCreate the `.agent-mux/` directory in the current working directory with default configuration.\n\n### 19.1 Syntax\n\n```\namux init [flags...]\n```\n\n### 19.2 Behavior\n\n1. Creates `.agent-mux/` in the current directory (or the directory specified by `--project-dir`).\n2. Creates `.agent-mux/config.json` with an empty object `{}`.\n3. Creates `.agent-mux/profiles/` directory.\n4. Prints confirmation to stdout.\n5. If `.agent-mux/` already exists, prints a message and exits with code 0 (idempotent).\n\n### 19.3 Flags\n\n| Flag | Type | Default | Description |\n|---|---|---|---|\n| `--json` | `boolean` | `false` | Output result as JSON. |\n\n---\n\n## 20. Signal Handling\n\nThe CLI handles process signals for graceful shutdown and run control.\n\n### 20.1 Unix (macOS, Linux)\n\n| Signal | Behavior |\n|---|---|\n| `SIGINT` (Ctrl+C) | First: sends `interrupt()` to the active `RunHandle`. The agent may handle this gracefully (stop current tool call, remain alive). Second within 1 second: sends `abort()` to force shutdown. Third or if no active run: exits immediately. |\n| `SIGTERM` | Initiates graceful shutdown: sends `SIGINT` to all child processes, waits the grace period (default 5000ms), then sends `SIGKILL` to any remaining children. Exits with code 13 (`ABORTED`). |\n| `SIGKILL` | Cannot be caught. OS terminates the process. Child processes receive `SIGKILL` via process group. |\n| `SIGTSTP` (Ctrl+Z) | Sends `pause()` to the active `RunHandle`. |\n| `SIGCONT` | Sends `resume()` to the active `RunHandle`. |\n\n### 20.2 Windows\n\nWindows does not have POSIX signals. The CLI uses alternative mechanisms:\n\n| Event | Behavior |\n|---|---|\n| Ctrl+C | Handled via `process.on('SIGINT')` (Node.js emulation). Behavior matches Unix `SIGINT` above. |\n| Ctrl+Break | Sends `abort()` to the active `RunHandle`. Equivalent to double-SIGINT on Unix. |\n| Console close / `SIGTERM` | `process.on('SIGTERM')` triggers graceful shutdown. Child processes are terminated via `TerminateProcess` Win32 API after the grace period. |\n| `SIGTSTP` / `SIGCONT` | Not available on Windows. Pause/resume is only available through REPL commands (`/pause`, `/resume`). |\n\n### 20.3 Zombie Prevention\n\nAll spawned child processes are registered in a cleanup list. On Node.js `beforeExit` and `exit` events, the CLI sends `SIGKILL` (Unix) or `TerminateProcess` (Windows) to any still-running children. This prevents zombie processes.\n\nThe grace period for graceful shutdown is configurable via `AGENT_MUX_GRACE_PERIOD_MS` environment variable (default: 5000ms).\n\n---\n\n## 21. Environment Variables\n\nThe following environment variables are recognized by the CLI. CLI flags take precedence over environment variables.\n\n| Variable | Type | Default | Description | Equivalent Flag |\n|---|---|---|---|---|\n| `AGENT_MUX_CONFIG_DIR` | `string` | `~/.agent-mux/` | Override global config directory. | `--config-dir` |\n| `AGENT_MUX_PROJECT_DIR` | `string` | `.agent-mux/` | Override project config directory. | `--project-dir` |\n| `AGENT_MUX_DEFAULT_AGENT` | `AgentName` | -- | Default agent when none is specified. | `--agent` (global) |\n| `AGENT_MUX_GRACE_PERIOD_MS` | `number` | `5000` | Grace period in milliseconds before SIGKILL on shutdown. | -- |\n| `NO_COLOR` | any | -- | Disable colored output when set to any non-empty value. See [no-color.org](https://no-color.org/). | `--no-color` |\n| `DEBUG` | `string` | -- | When set to `amux` or `amux:*`, enables debug logging to stderr. | `--debug` |\n| `FORCE_COLOR` | any | -- | Force colored output even when stdout is not a TTY. Overridden by `NO_COLOR` and `--no-color`. | -- |\n\n### 21.1 Resolution Order\n\nFor any configuration value, the resolution order is (highest precedence first):\n\n1. CLI flags (e.g., `--config-dir`).\n2. Environment variables (e.g., `AGENT_MUX_CONFIG_DIR`).\n3. Project config file (`.agent-mux/config.json`).\n4. Global config file (`~/.agent-mux/config.json`).\n5. Adapter defaults.\n\nThis mirrors the SDK resolution order defined in `01-core-types-and-client.md`, Section 4.1.1 and `02-run-options-and-profiles.md`, Section 7.\n\n---\n\n## 22. Shell Completion\n\nThe CLI provides shell completion scripts for interactive use.\n\n### 22.1 Generating Completion Scripts\n\n```bash\n# Bash\namux --completions bash > ~/.local/share/bash-completion/completions/amux\n# or\namux --completions bash >> ~/.bashrc\n\n# Zsh\namux --completions zsh > ~/.zfunc/_amux\n# or add to .zshrc: fpath=(~/.zfunc $fpath); autoload -Uz compinit; compinit\n\n# Fish\namux --completions fish > ~/.config/fish/completions/amux.fish\n\n# PowerShell\namux --completions powershell >> $PROFILE\n```\n\n### 22.2 Completion Scope\n\nCompletions are provided for:\n- Top-level commands (`run`, `install`, `adapters`, `capabilities`, `models`, `plugin`, `mcp`, `sessions`, `cost`, `config`, `profiles`, `auth`, `init`).\n- Subcommands (e.g., `plugin list`, `mcp install`, `config mcp add`).\n- Flag names and their valid values (e.g., `--agent` completes to registered agent names, `--thinking-effort` completes to `low`, `medium`, `high`, `max`).\n- Agent names (positional argument for many commands).\n- Model IDs (for `--model` flag, dynamically queried from the model registry).\n- Profile names (for `--profile` flag).\n\n---\n\n## 23. Error Output Format\n\n### 23.1 Human-Readable Errors\n\nIn human mode, errors are printed to stderr with the following format:\n\n```\nerror: <message>\n code: <ErrorCode>\n agent: <agent> (when applicable)\n hint: <actionable guidance> (when available)\n```\n\nExample:\n\n```\nerror: Agent 'cursor' does not support native plugin CLI commands\n code: CAPABILITY_ERROR\n agent: cursor\n hint: Agents with native plugin CLI: claude, gemini, codex, copilot, opencode\n```\n\n### 23.2 JSON Errors\n\nIn JSON mode (`--json`), errors are emitted as a JSON object to stdout:\n\n```json\n{\n \"ok\": false,\n \"error\": {\n \"code\": \"CAPABILITY_ERROR\",\n \"message\": \"Agent 'cursor' does not support native plugin CLI commands\",\n \"agent\": \"cursor\",\n \"recoverable\": false\n }\n}\n```\n\n### 23.3 JSONL Run Errors\n\nDuring `amux run --json`, errors appear as typed events in the JSONL stream:\n\n```jsonl\n{\"type\":\"error\",\"runId\":\"01J...\",\"agent\":\"claude\",\"timestamp\":1718000000000,\"code\":\"AUTH_ERROR\",\"message\":\"Authentication required\",\"recoverable\":false}\n```\n\nThe `type` field matches the error event types defined in `04-agent-events.md`: `auth_error`, `rate_limit_error`, `context_exceeded`, `crash`, `error`.\n\n### 23.4 Canonical Error Codes\n\nAll error codes used by the CLI are defined in `01-core-types-and-client.md`, Section 3.1:\n\n| Error Code | Description |\n|---|---|\n| `CAPABILITY_ERROR` | Agent/model lacks required capability. |\n| `VALIDATION_ERROR` | Input fails schema or range validation. |\n| `AUTH_ERROR` | Authentication required but not configured. |\n| `AGENT_NOT_FOUND` | No adapter registered for the agent name. |\n| `AGENT_NOT_INSTALLED` | Adapter exists but CLI binary not on `$PATH`. |\n| `AGENT_CRASH` | Agent subprocess terminated unexpectedly. |\n| `SPAWN_ERROR` | Failed to spawn agent subprocess. |\n| `TIMEOUT` | Run exceeded wall-clock timeout. |\n| `INACTIVITY_TIMEOUT` | Run exceeded inactivity timeout. |\n| `PARSE_ERROR` | Failed to parse agent output or file. |\n| `CONFIG_ERROR` | Config file read/write/parse failure. |\n| `CONFIG_LOCK_ERROR` | Advisory file lock acquisition failed. |\n| `SESSION_NOT_FOUND` | Specified session does not exist. |\n| `PROFILE_NOT_FOUND` | Specified profile does not exist. |\n| `PLUGIN_ERROR` | Plugin operation failed. |\n| `RATE_LIMITED` | Agent reported rate limiting. |\n| `CONTEXT_EXCEEDED` | Agent's context window exceeded. |\n| `ABORTED` | Run was aborted by user. |\n| `INTERNAL` | Internal error in agent-mux. |\n\n---\n\n## 24. Platform-Specific Notes\n\n### 24.1 Windows\n\n- **Signal handling**: Windows lacks POSIX signals. See Section 20.2 for the alternative mechanisms used.\n- **TTY detection**: `process.stdin.isTTY` and `process.stdout.isTTY` work correctly on Windows terminals (cmd.exe, PowerShell, Windows Terminal). ConPTY is used for PTY-based agents.\n- **PTY support**: `node-pty` uses ConPTY on Windows 10 1809+ for agents requiring PTY (OpenClaw, some interactive modes).\n- **Path handling**: All internal paths use forward slashes. CLI output uses the platform-native separator. Config file paths (`--config-dir`, `--project-dir`) accept both forward and backslashes on Windows.\n- **Color support**: ANSI color codes are supported in Windows Terminal and PowerShell 7+. Legacy cmd.exe may not render colors correctly; `--no-color` is recommended in that environment.\n- **Hermes on Windows**: Hermes requires WSL2 on Windows. The hermes adapter detects whether WSL2 is available and spawns hermes through `wsl` when running on native Windows. If WSL2 is not detected, the adapter reports `installed: false` with guidance to install WSL2.\n- **omp on Windows**: omp has `partial` Windows support (see `agent-mux-scope.md`, Section 23). Some features may not work correctly on Windows.\n- **Shell completion**: PowerShell completion is supported via `Register-ArgumentCompleter`. See Section 22.1.\n\n### 24.2 macOS\n\n- **Homebrew**: Several agents offer Homebrew install methods (`claude`, `opencode`). The `amux install` command prefers Homebrew on macOS when available.\n- **Config paths**: Global config at `~/` (`$HOME`, typically `/Users/<user>/`).\n\n### 24.3 Linux\n\n- **XDG compliance**: Some agents store config in XDG-compliant locations (e.g., `~/.config/` for Gemini, Copilot, OpenCode). The adapters handle this transparently.\n- **Config paths**: Global config at `~/` (`$HOME`, typically `/home/<user>/`).\n\n---\n\n## 25. Command Summary\n\nQuick reference of all commands and their SDK method mappings.\n\n| Command | Subcommand | SDK Method |\n|---|---|---|\n| `amux run` | -- | `mux.run()` |\n| `amux install` | -- | `mux.adapters.installInstructions()` |\n| `amux adapters` | `list` | `mux.adapters.list()` + `mux.adapters.installed()` |\n| `amux adapters` | `detect` | `mux.adapters.detect()` |\n| `amux capabilities` | -- | `mux.adapters.capabilities()` + `mux.models.model()` |\n| `amux models` | `list` | `mux.models.catalog()` |\n| `amux models` | `get` | `mux.models.model()` |\n| `amux models` | `refresh` | `mux.models.refresh()` |\n| `amux models` | `current` | `mux.config.getModelSelection()` + `mux.models.model()` |\n| `amux models` | `set` | `mux.models.validate()` + `mux.config.setModelSelection()` |\n| `amux plugin` | `list` | Native CLI delegation |\n| `amux plugin` | `install` | Native CLI delegation |\n| `amux plugin` | `uninstall` | Native CLI delegation |\n| `amux plugin` | `update` | Native CLI delegation |\n| `amux plugin` | `marketplace` | Native CLI delegation |\n| `amux mcp` | `list` | `mux.mcp.list()` |\n| `amux mcp` | `install` | `mux.mcp.install()` |\n| `amux mcp` | `uninstall` | `mux.mcp.uninstall()` |\n| `amux sessions` | `list` | `mux.sessions.list()` |\n| `amux sessions` | `show` | `mux.sessions.export()` |\n| `amux sessions` | `search` | `mux.sessions.search()` |\n| `amux sessions` | `export` | `mux.sessions.export()` |\n| `amux sessions` | `diff` | `mux.sessions.diff()` |\n| `amux sessions` | `resume` | `mux.run({ sessionId })` |\n| `amux sessions` | `fork` | `mux.run({ forkSessionId })` |\n| `amux cost` | `report` | `mux.sessions.totalCost()` |\n| `amux config` | `get` | `mux.config.get()` / `mux.config.getField()` |\n| `amux config` | `set` | `mux.config.setField()` |\n| `amux config` | `schema` | `mux.config.schema()` |\n| `amux config` | `validate` | `mux.config.validate()` |\n| `amux config` | `mcp list` | `mux.config.getMcpServers()` |\n| `amux config` | `mcp add` | `mux.config.addMcpServer()` |\n| `amux config` | `mcp remove` | `mux.config.removeMcpServer()` |\n| `amux config` | `reload` | `mux.config.reload()` |\n| `amux profiles` | `list` | `mux.profiles.list()` |\n| `amux profiles` | `show` | `mux.profiles.show()` |\n| `amux profiles` | `set` | `mux.profiles.set()` |\n| `amux profiles` | `delete` | `mux.profiles.delete()` |\n| `amux profiles` | `apply` | `mux.profiles.apply()` |\n| `amux auth` | `check` | `mux.auth.check()` / `mux.auth.checkAll()` |\n| `amux auth` | `setup` | `mux.auth.getSetupGuidance()` |\n| `amux skill` | `list` / `add` / `remove` / `where` / `agents` | File-convention (copy into `.{agent}/skills/`) |\n| `amux agent` | `list` / `add` / `remove` / `where` / `agents` | File-convention (copy into `.{agent}/agents/`) |\n| `amux hooks` | `discover` / `list` / `add` / `remove` / `set` / `handle` | `HookConfigManager` (core) |\n| `amux doctor` | -- | Capability / auth / runtime diagnostics |\n| `amux tui` | -- | Launch interactive Ink UI (`@a5c-ai/agent-mux-tui`) |\n| `amux init` | -- | `createClient()` + directory creation |\n\n---\n\n## 26. Version and Help\n\n```bash\n# Print version\namux --version\namux -V\n\n# Print help\namux --help\namux -h\n\n# Command-specific help\namux run --help\namux plugin --help\namux mcp --help\n```\n\n`--version` prints the package version of `@a5c-ai/agent-mux-cli` and exits with code 0.\n\n`--help` prints the usage summary for the command or subcommand and exits with code 0. Help text includes a brief description, syntax, available flags, and examples.\n\n---\n\n## 27. Type Reference Summary\n\nThis section lists the key types referenced throughout the CLI spec and where they are defined.\n\n| Type | Spec | Section |\n|---|---|---|\n| `AgentName`, `BuiltInAgentName` | `01-core-types-and-client.md` | 1.4 |\n| `ErrorCode` | `01-core-types-and-client.md` | 3.1 |\n| `AgentMuxError` | `01-core-types-and-client.md` | 3.1 |\n| `CapabilityError` | `01-core-types-and-client.md` | 3.2 |\n| `ValidationError` | `01-core-types-and-client.md` | 3.3 |\n| `GlobalConfig` | `01-core-types-and-client.md` | 4.1.2 |\n| `ClientOptions` | `01-core-types-and-client.md` | 5.1.1 |\n| `InstalledAgentInfo` | `01-core-types-and-client.md` | 5.3.1 |\n| `InstallMethod` | `01-core-types-and-client.md` | 5.3.1 |\n| `RunOptions` | `02-run-options-and-profiles.md` | 2 |\n| `ProfileData` | `02-run-options-and-profiles.md` | 10.2 |\n| `ProfileManager` | `02-run-options-and-profiles.md` | 10 |\n| `RunHandle` | `03-run-handle-and-interaction.md` | 2 |\n| `RunResult` | `03-run-handle-and-interaction.md` | 3 |\n| `AgentEvent` | `04-agent-events.md` | 2 |\n| `AgentCapabilities` | `06-capabilities-and-models.md` | 2 |\n| `ModelCapabilities` | `06-capabilities-and-models.md` | 2 |\n| `SessionManager`, `SessionSummary`, `Session` | `07-session-manager.md` | 2 |\n| `ConfigManager`, `AgentConfig` | `08-config-and-auth.md` | 2 |\n| `AuthManager`, `AuthState` | `08-config-and-auth.md` | 8 |\n| `PluginManager`, `InstalledPlugin`, `PluginListing` | `09-plugin-manager.md` | 2 |\n| `McpServerConfig` | `02-run-options-and-profiles.md` | 4 |\n| `RetryPolicy` | `01-core-types-and-client.md` | 5.1.1 |\n| `CostRecord`, `CostSummary` | `01-core-types-and-client.md` | 4.2.3 |\n\n---\n\n## Implementation Status (2026-04-12)\n\nFive command surfaces have landed that extend the original spec. All are implemented under `packages/cli/src/commands/`.\n\n### `amux install <agent> [--version V] [--force] [--dry-run] [--json]`\n\nInvokes the adapter's `install()`. Emits an `InstallResult`. Non-zero exit if `ok` is false. Used by the Dockerfile with `HARNESSES=<csv>` to pre-install harnesses into an image.\n\n### `amux update <agent> [--dry-run] [--json]`\n\nInvokes the adapter's `update()`. Same result shape.\n\n### `amux detect [<agent> | --all] [--json]`\n\nInvokes `detectInstallation()`. With `--all` iterates every registered adapter; with a specific agent returns one record. Prints `installed`, `version`, `path`, `notes`.\n\n### `amux detect-host [--json]`\n\nCalls `client.detectHost()` and prints `HostHarnessInfo { agent, confidence, source, matchedSignals }` or \"no harness detected\". Confidence: `high` (≥ 2 env signals), `medium` (1 env signal), `low` (argv heuristic only).\n\n### `amux remote install|update <host> [--mode ssh|docker|k8s|local] [--harness <agent>] [--force] [--json]`\n\nFour-step bootstrap over the chosen invocation mode:\n\n1. Probe `amux --version` on target.\n2. If missing or `update`/`--force`: `npm install -g @a5c-ai/agent-mux-cli` (or `npm update -g`).\n3. `amux install <harness>` (or `amux update <harness>`) on target.\n4. Verify with `amux detect --all --json`.\n\nDefault `--mode` is `ssh` when `<host>` is given, else `local`. Default `--harness` is `claude-code`.\n\n### Global flags actually accepted\n\nFrom `packages/cli/src/parse-args.ts` the recognized globals are: `--agent/-a`, `--model/-m`, `--json`, `--debug`, `--config-dir`, `--project-dir`, `--no-color`, `--version/-V`, `--help/-h`, `--completions <shell>`. The top-level commands: `run`, `install`, `uninstall`, `update`, `detect`, `detect-host`, `remote`, `adapters`, `capabilities`, `models`, `plugin`, `mcp`, `sessions`, `cost`, `config`, `profiles`, `auth`, `init`, `version`, `help`.\n",
"documents": []
},
"outgoingEdges": [],
"incomingEdges": []
}