> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orchagent.io/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI Commands

> Complete reference for the orchagent CLI

The orchagent CLI lets you interact with the platform from your terminal.

## Installation

```bash theme={null}
npm install -g @orchagent/cli
```

<Tip>
  The CLI also installs `orch` as a shorthand alias. All commands work with either `orchagent` or `orch`.
</Tip>

***

## Understanding the Four Types

Before diving into commands, understand the four types on orchagent:

| Type         | What it does                        | How to use           |
| ------------ | ----------------------------------- | -------------------- |
| **`prompt`** | Single LLM call (prompt + schema)   | `orch run`           |
| **`tool`**   | Your code runs in a sandbox         | `orch run`           |
| **`agent`**  | LLM tool-use loop with custom tools | `orch run`           |
| **`skill`**  | Passive knowledge (markdown)        | `orch skill install` |

**Simple rule:**

* Want a single LLM answer? Use `type: "prompt"`
* Want your code to execute? Use `type: "tool"`
* Want the LLM to iterate with tools? Use `type: "agent"`
* Want to share knowledge? Use `type: "skill"`

***

## Quick Reference

| Command                                   | What It Does                                           | Where It Runs                  |
| ----------------------------------------- | ------------------------------------------------------ | ------------------------------ |
| `orch run <agent>`                        | Execute agent                                          | Cloud (E2B sandbox) by default |
| `orch run --local <agent>`                | Download and execute agent locally                     | Your machine                   |
| `orch scaffold orchestration <agents...>` | Generate an orchestrator scaffold from existing agents | Local files                    |
| `orch install <agent>`                    | Export agent as sub-agent                              | Local files (for AI tools)     |
| `orch skill install <skill>`              | Download skill files                                   | Local files (for AI tools)     |
| `orch list`                               | List locally installed agents                          | -                              |
| `orch agents`                             | List your published agents                             | -                              |
| `orch info <agent>`                       | Show agent details and schemas                         | -                              |
| `orch tree <agent>`                       | Show agent dependency tree                             | -                              |
| `orch transfer <agent>`                   | Transfer agent to another workspace                    | Cloud                          |
| `orch dev`                                | Start local dev server with hot-reload                 | Your machine                   |
| `orch test`                               | Run agent tests locally                                | Your machine                   |
| `orch update`                             | Update installed agents                                | -                              |
| `orch formats`                            | List available export formats                          | -                              |
| `orch secrets list/set/delete`            | Manage workspace secrets                               | Cloud                          |
| `orch agent-keys list/create/delete`      | Manage agent service keys                              | Cloud                          |
| `orch env list/create/delete`             | Manage custom Docker environments                      | Cloud                          |
| `orch github connect/import/scan`         | GitHub integration                                     | Cloud                          |
| `orch logs [target]`                      | View execution logs                                    | -                              |
| `orch security test <agent>`              | Run vulnerability scan                                 | Cloud                          |
| `orch schedule create`                    | Create cron or webhook schedule                        | Cloud                          |
| `orch schedule list`                      | List schedules                                         | -                              |
| `orch schedule trigger`                   | Manually trigger a schedule                            | Cloud                          |
| `orch schedule info`                      | View schedule details and events                       | -                              |
| `orch schedule runs`                      | View schedule run history                              | -                              |
| `orch service deploy`                     | Deploy agent as always-on service                      | Cloud (Cloud Run)              |
| `orch service list`                       | List running services                                  | -                              |
| `orch service logs`                       | View service logs                                      | -                              |
| `orch service info`                       | Get service details                                    | -                              |
| `orch service restart`                    | Restart a service                                      | Cloud                          |
| `orch service delete`                     | Delete a service                                       | Cloud                          |
| `orch service env set`                    | Set env vars on a running service                      | Cloud                          |
| `orch service env unset`                  | Remove env vars from a service                         | Cloud                          |
| `orch service env list`                   | List env vars on a service                             | -                              |
| `orch service secret add`                 | Attach workspace secrets                               | Cloud                          |
| `orch service secret remove`              | Detach workspace secrets                               | Cloud                          |
| `orch replay <run-id>`                    | Re-execute a previous run from snapshot                | Cloud                          |
| `orch trace <run-id>`                     | View execution trace timeline                          | -                              |
| `orch health <agent>`                     | Smoke test an agent                                    | Cloud                          |
| `orch estimate <agent>`                   | Show estimated run cost                                | -                              |
| `orch diff <ref1> [ref2]`                 | Compare two agent versions                             | -                              |
| `orch pull <agent>`                       | Reconstruct a local project from a published agent     | -                              |
| `orch fork <agent>`                       | Fork a public agent into your workspace                | -                              |
| `orch metrics`                            | Show agent performance metrics                         | -                              |
| `orch dag <run-id>`                       | Visualize orchestration call graph                     | -                              |
| `orch status`                             | Check platform service status                          | -                              |
| `orch docs [topic]`                       | Open documentation in browser                          | -                              |
| `orch logout`                             | Log out and revoke API key                             | -                              |
| `orch billing`                            | Open billing portal                                    | -                              |
| `orch completion <shell>`                 | Generate shell completion script (bash, zsh, fish)     | -                              |

### When to Use What

```
Want AI to DO something now?
  |-- Need it local/private? --> orch run --local
  \-- Want managed infra?    --> orch run

Want AI to KNOW something?
  \-- Download knowledge     --> orch skill install

Want to DELEGATE to sub-agents?
  \-- Export for AI tools    --> orch install

Building an agent locally?
  \-- HTTP dev server        --> orch dev

Want to RECONSTRUCT a local project?
  \-- Pull published source    --> orch pull

Want to CUSTOMIZE an existing agent?
  \-- Copy into your workspace --> orch fork

Managing agents?
  |-- List your agents       --> orch agents
  |-- Inspect details        --> orch info / orch tree
  \-- Move between workspaces --> orch transfer

Managing secrets & keys?
  |-- Workspace secrets      --> orch secrets
  \-- Agent service keys     --> orch agent-keys

Connecting GitHub?
  \-- Import from repos      --> orch github

Debugging a run?
  |-- View execution logs    --> orch logs
  |-- Replay a failed run    --> orch replay
  |-- Inspect trace timeline --> orch trace
  \-- View call graph        --> orch dag

Checking platform health?
  \-- Service status         --> orch status
```

***

## Running Agents

### run

Execute an agent. By default, agents run on the cloud (E2B sandbox). Use `--local` to download and run on your machine instead.

```bash theme={null}
# Run agent with a URL input
orch run joe/leak-finder https://github.com/user/repo

# Run with JSON input
orch run joe/summarizer --data '{"text": "..."}'

# Just download without running
orch run joe/leak-finder --download-only

# Auto-download all dependencies
orch run joe/security-review --with-deps https://github.com/user/repo

# Override LLM provider and model
orch run joe/summarizer --data '{"text":"..."}' --provider openai --model gpt-4o-mini
```

**Options:**

| Flag                   | Description                                                    |
| ---------------------- | -------------------------------------------------------------- |
| `--data <json>`        | JSON payload (string or @file, @- for stdin)                   |
| `--local`              | Run on your machine instead of cloud                           |
| `--file <path>`        | Pass file content to agent (repeatable for multiple files)     |
| `--file-field <name>`  | Schema field to map file content to (auto-detected if omitted) |
| `--provider <name>`    | LLM provider (openai, anthropic, gemini, ollama)               |
| `--model <model>`      | LLM model to use (overrides agent default)                     |
| `--download-only`      | Download agent without executing                               |
| `--with-deps`          | Auto-download all dependencies                                 |
| `--endpoint <name>`    | Override agent endpoint                                        |
| `--output <file>`      | Save response to file                                          |
| `--json`               | Raw JSON output                                                |
| `--verbose`            | Show sandbox stdout/stderr and debug info (cloud only)         |
| `--estimate`           | Show cost estimate before running and ask for confirmation     |
| `--no-stream`          | Disable real-time streaming for sandbox runs                   |
| `--skills <refs>`      | Add skills (comma-separated)                                   |
| `--skills-only <refs>` | Use ONLY these skills (replaces agent's default\_skills)       |
| `--no-skills`          | Ignore all default skills                                      |
| `--key <key>`          | LLM API key (overrides env vars)                               |
| `--tenant <id>`        | Tenant identifier for multi-tenant callers (cloud only)        |
| `--mount <field=dir>`  | Mount a local directory as a JSON field map (repeatable)       |
| `--path <dir>`         | Shorthand for `--data '{"path": "<dir>"}'` (local only)        |
| `--here`               | Scan current directory as input (local only)                   |
| `--metadata <json>`    | JSON metadata to send with file uploads (cloud only)           |
| `--input <json>`       | Alias for `--data`                                             |

**What happens (cloud, default):**

1. CLI sends request to gateway (`api.orchagent.io`)
2. Gateway spins up an E2B sandbox (ephemeral, isolated)
3. Agent runs with your stored LLM keys
4. Response returned through gateway

**What happens (with `--local`):**

1. CLI downloads agent code from orchagent registry
2. Agent runs locally on your machine
3. Agent calls LLM API using YOUR environment keys
4. Results returned to terminal

**When to use `--local`:**

* Development and testing
* Keep data on your machine (privacy)
* Try agents without an account
* Debug agent behavior

**Requirements for `--local`:**

* LLM API key in environment (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.)
* Agent must be downloadable (has `source_url` in manifest)

<Note>
  **Dependency handling:** If an agent has dependencies, the CLI prompts you to choose between server execution or downloading available dependencies. Use `--with-deps` to auto-download.
</Note>

***

## Agent Management

### agents

List your published agents.

```bash theme={null}
# List latest version of each agent
orch agents

# Filter by name
orch agents --filter scanner

# Show all versions
orch agents --all-versions

# JSON output
orch agents --json
```

**Options:**

| Flag              | Description                              |
| ----------------- | ---------------------------------------- |
| `--filter <text>` | Filter agents by name                    |
| `--all-versions`  | Show all versions (default: latest only) |
| `--json`          | Output raw JSON                          |

By default, shows only the latest version of each agent grouped by name. Displays a table with columns: Agent, Version, Type, Description. When in latest-only mode, the version column shows the count (e.g., `v3 (5 total)`). Respects workspace context.

### info

Show agent details including schemas, dependencies, and configuration.

```bash theme={null}
# Show agent info
orch info joe/code-reviewer

# Show specific version
orch info joe/code-reviewer@v2

# JSON output
orch info joe/code-reviewer --json
```

**Options:**

| Flag     | Description    |
| -------- | -------------- |
| `--json` | Output as JSON |

Displays: type, callable status, supported providers, server URL (for tool types), source URL, run command, local-ready status, input/output schemas, dependencies, skills, custom tools, and environment pinning. For GitHub-linked agents, fetches and displays the repository README.

### tree

Show the dependency tree for an agent, including skills and nested sub-agents.

```bash theme={null}
# Show dependency tree
orch tree joe/security-review

# JSON output
orch tree joe/security-review --json

# Disable colors
orch tree joe/security-review --no-color
```

**Options:**

| Flag         | Description            |
| ------------ | ---------------------- |
| `--json`     | Output as JSON         |
| `--no-color` | Disable colored output |

Renders an ASCII tree showing the agent, its skills (tagged with `(skill)`), and nested dependency agents. Inaccessible nodes are dimmed. Locked skills show a lock icon. Summary line shows total agents, total skills, and max depth.

### transfer

Transfer an agent to another workspace. Moves all versions, revokes existing grants, and disables schedules.

```bash theme={null}
# Transfer agent to another workspace
orch transfer my-agent --to team-workspace

# Transfer from a specific source workspace
orch transfer my-agent --to team-workspace --workspace my-team

# Preview what would happen
orch transfer my-agent --to team-workspace --dry-run

# Skip confirmation prompt
orch transfer my-agent --to team-workspace --yes
```

**Options:**

| Flag                     | Description                                  |
| ------------------------ | -------------------------------------------- |
| `--to <workspace-slug>`  | **(Required)** Target workspace slug         |
| `-w, --workspace <slug>` | Source workspace (default: active workspace) |
| `-y, --yes`              | Skip confirmation prompt                     |
| `--dry-run`              | Preview transfer without making changes      |
| `--json`                 | Output result as JSON                        |

The pre-transfer check shows: version count, grants to revoke, keys to delete, schedules to disable, warnings, and blockers. In interactive mode, you must type the agent name to confirm.

***

## Installing Agents as Sub-Agents

### install

Export an agent as a sub-agent for AI coding tools (Claude Code, Cursor, etc.). This writes configuration files that your AI tool reads — **not** the agent's source code.

<Warning>
  **`install` ≠ `pull`.** `orch install` writes a single IDE config file (e.g. `.claude/agents/my-agent.md`). It does **not** write `orchagent.json`, `prompt.md`, `schema.json`, or code bundles. If you want the agent's source files, use `orch pull` instead. See the [FAQ](/troubleshooting#whats-the-difference-between-pull-install-and-fork) for a full comparison.
</Warning>

```bash theme={null}
# Install to home directory (available in all projects)
orch install joe/code-reviewer

# Install to current project only
orch install joe/code-reviewer --scope project

# Same as --scope user (matches skill install syntax)
orch install joe/code-reviewer --global

# Specify format (default: claude-code)
orch install joe/code-reviewer --format cursor

# Install to multiple formats
orch install joe/code-reviewer --format claude-code,cursor

# Preview what would be installed
orch install joe/code-reviewer --dry-run

# Specify version
orch install joe/code-reviewer@v2
```

**What happens:**

1. CLI downloads agent metadata from registry
2. Converts to target format (Claude Code, Cursor, AGENTS.md)
3. Writes configuration file to AI tool directory
4. Tracks installation for updates

**Install locations by format:**

| Format        | User Scope (`--scope user`) | Project Scope (`--scope project`) |
| ------------- | --------------------------- | --------------------------------- |
| `claude-code` | `~/.claude/agents/`         | `./.claude/agents/`               |
| `cursor`      | `~/.cursor/rules/`          | `./.cursor/rules/`                |
| `agents-md`   | `~/AGENTS.md`               | `./AGENTS.md`                     |

**When to use `install`:**

* You want Claude Code or Cursor to delegate tasks to specialized agents
* You want sub-agents available across all your projects
* You're building a team workflow with shared agents

<Tip>
  **Set default format:** Run `orch config set default-format claude-code,cursor` to install to multiple formats automatically.
</Tip>

### update

Update installed agents to their latest versions.

```bash theme={null}
# Update all installed agents
orch update

# Update specific agent
orch update joe/code-reviewer

# Check for updates without installing
orch update --check

# Force update even if locally modified
orch update --force
```

**What happens:**

1. CLI reads `~/.orchagent/installed.json` to find installed agents
2. Checks registry for newer versions
3. Downloads and writes updated files
4. Preserves local modifications (unless `--force`)

<Note>
  If you've manually edited an installed agent file, `orch update` will skip it to preserve your changes. Use `--force` to overwrite.
</Note>

### formats

List available export formats for agents.

```bash theme={null}
# List formats
orch formats

# JSON output
orch formats --json
```

**Example output:**

```
Available export formats:

  claude-code    Claude Code Sub-Agent
                 Supports: agent, skill
                 Format version: 2026-01
                 user: ~/.claude/agents/
                 project: ./.claude/agents/

  cursor         Cursor Rules
                 Supports: agent, skill
                 Format version: 2026-01
                 user: ~/.cursor/rules/
                 project: ./.cursor/rules/

  agents-md      AGENTS.md (Universal)
                 Supports: agent, skill
                 Format version: 1.0
                 project: ./AGENTS.md

Use with: orch install <agent> --format <id>
Set default: orch config set default-format <ids>
```

### list

List locally installed agents and skills.

```bash theme={null}
# List installed agents
orch list

# Show format details for each installation
orch list --verbose

# Clean up orphaned entries (tracked files that no longer exist)
orch list --verify

# JSON output
orch list --json
```

**Options:**

| Flag            | Description                                           |
| --------------- | ----------------------------------------------------- |
| `-v, --verbose` | Show format and path details for each installation    |
| `--verify`      | Check tracked files exist and remove orphaned entries |
| `--json`        | Output as JSON                                        |

Also available as `orch ls`.

***

## Working with Skills

Skills are passive knowledge files that enhance AI tools. Install them locally to give your AI assistant domain expertise.

### skill install

Install a skill to your local AI tool directories.

```bash theme={null}
# Install to current directory (project-specific)
orch skill install yourorg/react-best-practices

# Install to home directory (global)
orch skill install yourorg/react-best-practices --global

# Specify version
orch skill install yourorg/react-best-practices@v2

# Specify format(s)
orch skill install yourorg/react-best-practices --format claude-code,cursor

# Install to all supported AI tool directories
orch skill install yourorg/react-best-practices --all-formats

# Preview what would be installed
orch skill install yourorg/react-best-practices --dry-run

# JSON output for scripting
orch skill install yourorg/react-best-practices --json
```

**Options:**

| Flag                 | Description                                             |
| -------------------- | ------------------------------------------------------- |
| `--global`           | Install to home directory (default: current directory)  |
| `--scope <scope>`    | Install scope: `user` or `project`                      |
| `--format <formats>` | Comma-separated format IDs (e.g., `claude-code,cursor`) |
| `--all-formats`      | Install to all supported AI tool directories            |
| `--dry-run`          | Show what would be installed without making changes     |
| `--json`             | Output result as JSON                                   |

**Install locations (current directory):**

```
./.claude/skills/react-best-practices.md
./.cursor/skills/react-best-practices.md
./.codex/skills/react-best-practices.md
./.agent/skills/react-best-practices.md
```

**Install locations (with `--global`):**

```
~/.claude/skills/react-best-practices.md
~/.cursor/skills/react-best-practices.md
~/.codex/skills/react-best-practices.md
~/.agent/skills/react-best-practices.md
```

### Using Skills with Agents

When running orchagent agents, you can compose skills:

```bash theme={null}
# Add skills to an agent run
orch run acme/code-reviewer code.py --skills yourorg/react-best-practices

# Use ONLY specific skills (ignore agent's default_skills)
orch run acme/code-reviewer code.py --skills-only yourorg/react-rules

# Ignore all skills
orch run acme/code-reviewer code.py --no-skills
```

***

## Authentication

### login

Authenticate and store your API key.

```bash theme={null}
# Interactive mode (recommended)
orch login

# Non-interactive mode (for CI/CD)
orch login --key sk_live_xxx
```

<Warning>
  The `--key` flag exposes the key in shell history. For CI/CD, use the `ORCHAGENT_API_KEY` environment variable instead.
</Warning>

### logout

Log out of orchagent. Revokes the API key server-side and clears local credentials.

```bash theme={null}
orch logout
```

Preserves user preferences (default formats, scope) while clearing authentication fields. If the `ORCHAGENT_API_KEY` environment variable is set, a warning is printed since the env var will continue to authenticate requests.

### whoami

Show current user and organization info.

```bash theme={null}
orch whoami
```

***

## Workspaces

Workspaces let you organize agents by team, share agents privately, and manage billing.

### How Workspaces Affect Commands

When you set an active workspace, CLI commands will look for agents there by default:

```bash theme={null}
# Set active workspace
orch workspace use marketing-team

# These now look in marketing-team workspace:
orch run my-agent --data '{}'         # → marketing-team/my-agent
orch run --local my-agent --input '{}' # → marketing-team/my-agent
orch install my-agent                 # → marketing-team/my-agent
orch skill install my-skill           # → marketing-team/my-skill

# Explicit org always overrides workspace:
orch run other-team/my-agent --data '{}' # → other-team/my-agent
```

**Resolution order:** Explicit `org/agent` → Active workspace → Default org (from login)

### workspace list

```bash theme={null}
# List workspaces (→ marks active)
orch workspace list

# JSON output
orch workspace list --json
```

### workspace create

```bash theme={null}
# Create a workspace (slug auto-generated)
orch workspace create "My Team"

# Create with custom slug
orch workspace create "My Team" --slug my-team
```

### workspace use

Set the active workspace for agent lookups.

```bash theme={null}
orch workspace use my-team
```

After this, `orch run agent` will look for `my-team/agent`.

### workspace members

```bash theme={null}
# List members of current workspace
orch workspace members

# List members of specific workspace
orch workspace members my-team
```

### workspace invite

```bash theme={null}
# Invite with default role (member)
orch workspace invite alice@example.com

# Invite as owner
orch workspace invite alice@example.com --role owner
```

### workspace leave

```bash theme={null}
orch workspace leave
```

***

## Agent Development

### init

Initialize a new agent or skill project.

```bash theme={null}
# Create an agent (default: direct LLM, on-demand)
orch init my-agent

# Create a JavaScript tool agent
orch init my-tool --type tool --language javascript

# Create a JavaScript Discord bot from template
orch init my-bot --template discord-js

# Create an agent with a specific run mode
orch init my-agent --run-mode always_on

# Create a skill
orch init my-skill --type skill

# Initialize in the current directory (no subdirectory created)
orch init
```

**Options:**

| Flag                | Description                                                                                                         |
| ------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `--type <type>`     | `prompt` (default), `tool`, `agent`, or `skill`. Legacy values `code` and `agentic` are accepted for compatibility. |
| `--run-mode <mode>` | `on_demand` (default) or `always_on`                                                                                |
| `--language <lang>` | `python` (default) or `javascript`. Scaffolds `main.js` + `package.json` instead of `main.py` + `requirements.txt`. |
| `--template <name>` | Start from a template: `support-agent`, `discord`, `discord-js`, `github-weekly-summary`                            |

When a name is provided, `init` creates a subdirectory with that name and writes all files there. Without a name, files are written to the current directory.

The generated `orchagent.json` uses the specified type (defaulting to `"prompt"`) with the canonical `run_mode` field.

<Note>
  `--language javascript` is supported for `tool` types. `agent` types (managed loop) currently require Python — the managed loop runner is Python-only.
</Note>

### scaffold orchestration

Generate a managed-loop orchestrator scaffold from existing dependency agents.

```bash theme={null}
# Scaffold in current directory
orch scaffold orchestration acme/scanner acme/auditor@v2

# Scaffold into a new directory with an explicit orchestrator name
orch scaffold orchestration acme/scanner --output ./security-orch --name security-orchestrator

# Overwrite existing scaffold files
orch scaffold orchestration acme/scanner --force
```

**What it generates:**

* `orchagent.json` with:
  * `manifest.dependencies` pinned to concrete versions
  * `custom_tools` commands wired to `orch_call.py`
  * managed-loop defaults (`max_turns`, provider + orchestration settings)
* `prompt.md` starter prompt with dependency tool catalog
* `schema.json` starter input/output schema

**Validation behavior:**

* Resolves each dependency ref and pins `latest` to a concrete version
* Rejects dependencies that are skills or `callable: false`
* Detects conflicting versions for the same dependency
* Deduplicates repeated dependency refs

Use this command when you already have worker agents and want a ready-to-publish orchestrator quickly.

### publish

Publish an agent or skill from the current directory.

```bash theme={null}
# Preview what would be published
orch publish --dry-run

# Publish your agent
orch publish

# Publish all agents in subdirectories (dependency order)
orch publish --all

# Preview batch publish plan
orch publish --all --dry-run

# Publish with default skills
orch publish --skills yourorg/style@v1,yourorg/rules@v1

# Publish with local download enabled (allows orch run --local)
orch publish --local-download
```

The publish command validates the `type` field, infers the `execution_engine` from the type (with optional `runtime`/`loop` overrides), and validates all fields. The dry-run output shows: Type, Run mode, Execution engine, Callable, Providers, and Visibility.

The `--all` flag scans immediate subdirectories for `orchagent.json` or `SKILL.md` files, builds a dependency graph from `manifest.dependencies` and `custom_tools` references, and publishes in topological order (leaf-first). If any agent fails to publish, the batch stops to prevent publishing agents whose dependencies are missing.

### pull

Reconstruct a local agent project from a published version. This is the reverse of `orch publish` — it downloads the full agent source and reconstructs `orchagent.json`, `prompt.md`, `schema.json`, and code bundle files into a local directory.

<Tip>
  **`pull` gives you source files. `install` gives you IDE config.** Use `pull` when you want to edit and republish an agent. Use `install` when you just want your AI tool to delegate to it. See the [FAQ](/troubleshooting#whats-the-difference-between-pull-install-and-fork).
</Tip>

```bash theme={null}
# Pull an agent into a local directory
orch pull acme/my-agent

# Pull a specific version
orch pull acme/my-agent@v2

# Pull using short ref (uses workspace/default-org)
orch pull my-agent

# Pull into a custom directory
orch pull acme/my-agent --output ./custom-dir

# Overwrite an existing directory
orch pull acme/my-agent --overwrite

# Machine-readable output (still writes files)
orch pull acme/my-agent --json
```

**Options:**

| Flag                  | Description                                                     |
| --------------------- | --------------------------------------------------------------- |
| `-o, --output <path>` | Output directory (default: `./<agent-name>/`)                   |
| `--overwrite`         | Replace existing output directory contents                      |
| `--json`              | Print machine-readable result summary (files are still written) |

**What happens:**

1. CLI resolves the agent from the public registry (or falls back to authenticated owner/private lookup)
2. Reconstructs `orchagent.json` manifest with canonical fields
3. Writes `prompt.md` if the agent has a prompt (direct LLM and managed loop engines)
4. Writes `schema.json` if input or output schemas exist
5. For code runtime agents, downloads and extracts the code bundle
6. Prints a summary of written files

**Agent resolution:**

The CLI resolves agent refs using the same fallback logic as `run`:

1. Tries the public download endpoint first
2. If the agent is server-only (403) and you're the owner, falls back to authenticated access
3. If the agent is private (404) and you're authenticated, resolves from your own agents

**When to use:**

* Reconstruct a local project from a published agent (e.g., lost source, new machine)
* Review the contents of a published agent version
* Set up a local development environment from a deployed agent

**Requirements:**

* No login required for public, source-available agents
* Login required for private agents or server-only agents you own

<Note>
  `pull` is for agents only. If the target is a skill, you'll be directed to use `orch skill install` instead.
</Note>

### delete

Delete an agent or skill you own. By default, deletes the latest version only. Requires the full `org/agent` reference. Use the `@version` syntax to delete a specific version.

```bash theme={null}
# Delete latest version (prompts for confirmation)
orch delete yourorg/my-agent

# Delete a specific version
orch delete yourorg/my-agent@v2

# Skip confirmation prompt
orch delete yourorg/my-agent -y

# Preview what would be deleted
orch delete yourorg/my-agent --dry-run
```

**Options:**

| Flag        | Description                                       |
| ----------- | ------------------------------------------------- |
| `-y, --yes` | Skip confirmation prompt                          |
| `--dry-run` | Show what would be deleted without making changes |

Deleted data is retained for 30 days before permanent removal.

### fork

Fork a public, source-available agent into your workspace. This creates a private copy you can customize and deploy independently.

```bash theme={null}
# Fork latest version into your current workspace
orch fork orchagent/security-agent

# Fork a specific version into a target workspace
orch fork orchagent/security-agent@v2 --workspace acme-corp

# Fork with a custom name
orch fork orchagent/security-agent --name my-security-scanner

# JSON output for scripting
orch fork orchagent/security-agent --json
```

**Options:**

| Flag                     | Description                                        |
| ------------------------ | -------------------------------------------------- |
| `--name <new-name>`      | Rename the forked agent                            |
| `-w, --workspace <slug>` | Target workspace slug (default: current workspace) |
| `--json`                 | Raw JSON output                                    |

**What happens:**

1. CLI resolves the source agent from the public registry
2. If `--workspace` is specified, resolves and verifies workspace membership
3. Creates a private copy in the target workspace via `POST /agents/{id}/fork`
4. Returns the new agent reference and a service key (if the agent has dependencies)

**What gets copied:**

The fork copies everything needed to customize and deploy: name, description, tags, type, prompt, schemas, manifest, code bundle, default skills, supported providers, default models, timeout, and execution config. The forked agent resets to **private** (`is_public = false`) and records a `forked_from` link to the source.

**Not copied:** run history, deploy state, schedules, stats, or services.

**When to use:**

* Start from a template instead of building from scratch
* Customize an existing public agent for your team
* Copy an agent into a different workspace

**Requirements:**

* Must be logged in (`orch login`)
* Source agent must be public and source-available (`allow_local_download = true`)
* `--workspace` requires browser-auth login (`orch login` without `--key`) so workspace membership can be verified

<Note>
  If a name collision occurs in the target workspace, the server auto-increments the version number.
</Note>

### test

Run tests for your agent locally. Supports Python (pytest), JavaScript/TypeScript (vitest/npm test), and fixture-based testing for direct LLM agents.

```bash theme={null}
# Run tests in current directory
orch test

# Run tests in a specific directory
orch test ./my-agent

# Verbose output
orch test --verbose

# Watch mode - re-run on file changes
orch test --watch
```

**Options:**

| Flag            | Description                             |
| --------------- | --------------------------------------- |
| `-v, --verbose` | Show detailed test output               |
| `-w, --watch`   | Watch for file changes and re-run tests |

**Test Discovery:**

The CLI automatically discovers tests based on file patterns:

| Type                  | Patterns                                           |
| --------------------- | -------------------------------------------------- |
| Python                | `test_*.py`, `*_test.py`                           |
| JavaScript/TypeScript | `*.test.ts`, `*.test.js`, `*.spec.ts`, `*.spec.js` |
| Fixtures              | `tests/fixture-*.json` (for direct LLM agents)     |

**Fixture Format:**

For prompt and skill agents, create fixture files in `tests/` to test your prompts against an LLM:

```json theme={null}
{
  "input": {"text": "Hello world"},
  "expected_output": {"greeting": "Hello!"},
  "expected_contains": ["Hello"],
  "description": "Tests greeting response"
}
```

| Field               | Required | Description                            |
| ------------------- | -------- | -------------------------------------- |
| `input`             | Yes      | Input data passed to the prompt        |
| `expected_output`   | No\*     | Exact match comparison (deep equality) |
| `expected_contains` | No\*     | Substrings that must appear in output  |
| `description`       | No       | Human-readable test description        |

\*At least one of `expected_output` or `expected_contains` is required.

**Requirements for fixture tests:**

* LLM API key in environment (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.)
* A `prompt.md` or `SKILL.md` file in the agent directory

**Mocked Orchestration Tests:**

For managed-loop orchestrator agents (type `agent` with `custom_tools`), add a `mocks` field to test the full agent loop with deterministic sub-agent responses — no live sub-agents needed:

```json theme={null}
{
  "description": "Orchestrator aggregates scan results",
  "input": {"code": "import os; os.getenv('SECRET')"},
  "mocks": {
    "scan_secrets": {"findings": [{"type": "env_access", "severity": "medium"}]},
    "scan_deps": {"vulnerabilities": []}
  },
  "expected_contains": ["env_access", "medium"]
}
```

The `mocks` field maps custom tool names to their mock responses. When the LLM calls a mocked tool during the agent loop, it receives the mock response instantly instead of executing the real sub-agent command. Built-in tools (`bash`, `read_file`, etc.) always execute normally.

| Field               | Required | Description                                   |
| ------------------- | -------- | --------------------------------------------- |
| `input`             | Yes      | Input data for the orchestrator               |
| `mocks`             | Yes      | Map of custom tool name to mock JSON response |
| `expected_output`   | No\*     | Exact match comparison                        |
| `expected_contains` | No\*     | Substrings that must appear in output         |
| `description`       | No       | Human-readable test description               |

\*At least one of `expected_output` or `expected_contains` is required.

<Tip>
  Mocked orchestration tests are ideal for CI — they test the full LLM reasoning loop (tool selection, multi-turn reasoning, result aggregation) without requiring deployed sub-agents or network access to the gateway.
</Tip>

<Tip>
  Watch mode works on all platforms (macOS, Linux, Windows) and automatically picks up new test files as you create them.
</Tip>

### dev

Start a local HTTP development server with hot-reload. The server accepts JSON input via HTTP and runs your agent locally, reloading automatically when files change.

```bash theme={null}
# Start dev server in current directory
orch dev

# Start dev server for agent in a specific directory
orch dev ./my-agent

# Use a custom port
orch dev --port 3001

# Show detailed execution output
orch dev --verbose

# Disable file watching (no hot-reload)
orch dev --no-watch
```

**Options:**

| Flag                | Description                                                |
| ------------------- | ---------------------------------------------------------- |
| `-p, --port <port>` | Server port (default: `4900`)                              |
| `-v, --verbose`     | Show detailed execution output (stderr, LLM provider info) |
| `--no-watch`        | Disable file watching (no automatic reload on changes)     |

**Endpoints:**

| Method | Path      | Description                                      |
| ------ | --------- | ------------------------------------------------ |
| `POST` | `/run`    | Execute agent with JSON body as input            |
| `POST` | `/`       | Alias for `/run`                                 |
| `GET`  | `/health` | Agent configuration info (name, version, engine) |
| `GET`  | `/`       | Usage instructions                               |

**Example:**

```bash theme={null}
# Terminal 1: Start the dev server
orch dev

# Terminal 2: Send requests
curl -X POST http://localhost:4900/run \
  -H "Content-Type: application/json" \
  -d '{"task": "summarize this text", "text": "..."}'
```

**How it works:**

1. Reads `orchagent.json` from the agent directory
2. Starts an HTTP server on the specified port
3. Watches for file changes (orchagent.json, prompt.md, schema.json, source files)
4. On each POST request, executes the agent locally and returns the JSON result
5. On file change, reloads the agent configuration automatically

The dev server supports all three execution engines:

| Engine            | How it runs                                             |
| ----------------- | ------------------------------------------------------- |
| **code\_runtime** | Spawns entrypoint (main.py/main.js) with input as stdin |
| **direct\_llm**   | Calls LLM with prompt.md + input data                   |
| **managed\_loop** | Runs agent\_runner.py with prompt, tools, and LLM       |

**Requirements:**

* `orchagent.json` in the target directory
* For LLM-based agents: API key in environment or `.env` file
* For code runtime agents: Python 3 or Node.js installed

<Tip>
  The dev server enables CORS, so you can send requests from browser-based tools or frontend apps during development.
</Tip>

<Tip>
  Use `orch dev` alongside `orch test --watch` for a full development loop: the dev server handles HTTP requests while test watch validates on every save.
</Tip>

### estimate

Show estimated cost for running an agent, based on historical run data from the last 30 days.

```bash theme={null}
# Estimate cost for an agent
orch estimate yourorg/my-agent

# Estimate a specific version
orch estimate yourorg/my-agent@v2

# JSON output for scripting
orch estimate yourorg/my-agent --json
```

**Options:**

| Flag     | Description    |
| -------- | -------------- |
| `--json` | Output as JSON |

**Output includes:**

* **Cost stats** — Average, median (p50), and 95th percentile cost per run
* **Token averages** — Average input and output tokens per run
* **Duration** — Average execution time
* **Success rate** — Percentage of runs that completed successfully
* **Provider breakdown** — Per-provider cost averages (e.g., Anthropic vs OpenAI)

**Example output:**

```
yourorg/my-agent@v1
========================================

Type: agent
Engine: managed_loop
Providers: anthropic, openai

Cost Estimate (25 runs, last 30d)
----------------------------------------
  Average:   $0.015
  Median:    $0.012
  95th pct:  $0.045

Tokens (avg per run)
  Input:  1.5k
  Output: 500

Duration
  Average: 3.2s
  Success: 96%

By Provider
  anthropic (claude-haiku-4-5-20251001): $0.012 avg · 20 runs
  openai (gpt-4o-mini): $0.020 avg · 5 runs
```

You can also use `--estimate` on the `run` command to see the estimate before executing:

```bash theme={null}
orch run yourorg/my-agent --data '{"text": "..."}' --estimate
```

This shows the cost estimate and prompts for confirmation before proceeding.

<Tip>
  If the agent has never been run before, the estimate will show "No run history available." Run the agent once and the estimate will populate from subsequent runs.
</Tip>

### diff

Compare two versions of an agent side-by-side. Shows changes in type, description, schemas, providers, dependencies, skills, custom tools, prompt, and configuration fields.

```bash theme={null}
# Compare two specific versions
orch diff yourorg/my-agent@v1 v2

# Compare against latest
orch diff yourorg/my-agent@v1

# Compare two different agents
orch diff yourorg/agent-a@v1 otherorg/agent-b@v1

# JSON output for scripting
orch diff yourorg/my-agent@v1 v2 --json
```

**Options:**

| Flag     | Description                                                              |
| -------- | ------------------------------------------------------------------------ |
| `--json` | Output diff as JSON with `from`, `to`, `identical`, and `changes` fields |

**Output format:**

Changes are shown with prefixes indicating the type of change:

* `+` — field was added
* `-` — field was removed
* `~` — field was changed (shows old and new values)

Schema and prompt changes show field-level diffs with added/removed lines.

**Version shorthand:**

The second argument can be just a version string (e.g., `v2`) — the org and agent name are inherited from the first argument. If the second argument is omitted, the first version is compared against `latest`.

***

## Secrets & Keys

### secrets

Manage workspace secrets. Secrets are injected as environment variables into agent sandboxes and always-on services.

```bash theme={null}
# List secrets (names and metadata, never values)
orch secrets list

# List secrets in a specific workspace
orch secrets list --workspace acme-team

# JSON output
orch secrets list --json

# Create or update a secret
orch secrets set ANTHROPIC_API_KEY sk-ant-xxx

# Set with a description
orch secrets set STRIPE_SECRET_KEY sk_live_xxx --description "Production Stripe key"

# Delete a secret
orch secrets delete OLD_API_KEY
```

**Subcommands:**

| Subcommand                   | Description                                     |
| ---------------------------- | ----------------------------------------------- |
| `secrets list`               | List secrets (names and metadata, never values) |
| `secrets set <name> <value>` | Create or update a secret                       |
| `secrets delete <name>`      | Delete a secret                                 |

**Options for `list`:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--json`             | Output as JSON                              |

**Options for `set`:**

| Flag                   | Description                                 |
| ---------------------- | ------------------------------------------- |
| `--description <text>` | Description of what this secret is for      |
| `--workspace <slug>`   | Workspace slug (default: current workspace) |

**Options for `delete`:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

Secret names must start with an uppercase letter, contain only uppercase letters, digits, and underscores, and be 1-128 characters (e.g., `STRIPE_SECRET_KEY`, `DISCORD_TOKEN`).

<Note>
  When you update a secret that is used by running always-on services, those services are automatically restarted.
</Note>

### agent-keys

Manage agent service keys for programmatic access to your agents.

```bash theme={null}
# List keys for an agent
orch agent-keys list my-agent

# Create a new key
orch agent-keys create my-agent

# Delete a key
orch agent-keys delete my-agent key_abc123
```

**Subcommands:**

| Subcommand                           | Description                    |
| ------------------------------------ | ------------------------------ |
| `agent-keys list <agent>`            | List service keys for an agent |
| `agent-keys create <agent>`          | Create a new service key       |
| `agent-keys delete <agent> <key-id>` | Delete a service key           |

The `list` output shows: ID, PREFIX, CREATED, LAST USED, and whether the key is SAVED locally (`~/.orchagent/keys/`).

<Note>
  Service keys are shown only once at creation time. The CLI saves them to `~/.orchagent/keys/` automatically, but if that fails, copy the key immediately — it cannot be retrieved later.
</Note>

***

## Custom Environments

Manage custom Docker environments for tool-type agents. See the [Custom Environments](/building-agents/environments) guide for details.

### env

```bash theme={null}
# List environments in your workspace
orch env list

# JSON output
orch env list --json

# Check build status
orch env status <environment-id>

# Create from Dockerfile
orch env create --file ./Dockerfile --name my-env

# Delete an environment
orch env delete <environment-id>

# Set workspace default environment
orch env set-default <environment-id>

# Clear workspace default (revert to base image)
orch env clear-default
```

**Subcommands:**

| Subcommand             | Description                         |
| ---------------------- | ----------------------------------- |
| `env list`             | List environments in workspace      |
| `env status <id>`      | Check environment build status      |
| `env create`           | Create environment from Dockerfile  |
| `env delete <id>`      | Delete an environment               |
| `env set-default <id>` | Set workspace default environment   |
| `env clear-default`    | Clear workspace default environment |

**Options for `list`:**

| Flag                     | Description    |
| ------------------------ | -------------- |
| `-w, --workspace <slug>` | Workspace slug |
| `--json`                 | Output as JSON |

**Options for `status`:**

| Flag     | Description    |
| -------- | -------------- |
| `--json` | Output as JSON |

**Options for `create`:**

| Flag                | Description                       |
| ------------------- | --------------------------------- |
| `-f, --file <path>` | **(Required)** Path to Dockerfile |
| `-n, --name <name>` | **(Required)** Environment name   |

**Options for `set-default` / `clear-default`:**

| Flag                     | Description    |
| ------------------------ | -------------- |
| `-w, --workspace <slug>` | Workspace slug |

The `list` output shows: Name, Status, Agents, Type, ID. Status is color-coded: green (ready), yellow (building), red (failed), gray (pending). The default environment is marked with `(default)`.

***

## GitHub Integration

### github

Connect your GitHub account and import agents directly from repositories.

```bash theme={null}
# Install the GitHub App
orch github connect

# Remove GitHub connection
orch github disconnect

# Check connection status
orch github status
orch github status --json

# Scan a repo for agents and skills
orch github scan owner/repo
orch github scan owner/repo --json

# Import an agent from GitHub
orch github import owner/repo
orch github import owner/repo --path agents/my-agent
orch github import owner/repo --name custom-name --json

# View or update sync configuration
orch github sync-config <agent-id>
orch github sync-config <agent-id> --set-auto-publish true

# Approve a pending sync
orch github approve <agent-id>
```

**Subcommands:**

| Subcommand                   | Description                                    |
| ---------------------------- | ---------------------------------------------- |
| `github connect`             | Install the GitHub App to connect your account |
| `github disconnect`          | Remove GitHub App installation                 |
| `github status`              | Show GitHub connection status                  |
| `github scan <repo>`         | Scan a repository for agents and skills        |
| `github import <repo>`       | Import an agent or skill from GitHub           |
| `github sync-config <agent>` | View or update sync configuration              |
| `github approve <agent-id>`  | Approve a pending GitHub sync                  |

**Options for `scan`:**

| Flag     | Description     |
| -------- | --------------- |
| `--json` | Output raw JSON |

**Options for `import`:**

| Flag            | Description                                                 |
| --------------- | ----------------------------------------------------------- |
| `--path <path>` | Path to manifest within repo (scans first if not specified) |
| `--name <name>` | Override agent name                                         |
| `--json`        | Output raw JSON                                             |

**Options for `sync-config`:**

| Flag                         | Description                           |
| ---------------------------- | ------------------------------------- |
| `--set-auto-publish <value>` | Set auto\_publish (`true` or `false`) |
| `--json`                     | Output raw JSON                       |

<Tip>
  When importing from a repo with multiple agents, omit `--path` to scan first. If only one item is found, it imports automatically. If multiple are found, you'll get an interactive selection prompt.
</Tip>

***

## Execution Logs

### logs

View execution logs. Use with no arguments to list recent runs, an agent name to filter, or a run ID for full detail.

```bash theme={null}
# List recent runs
orch logs

# Filter by agent name
orch logs scanner

# Filter by status
orch logs --status failed

# View detailed logs for a specific run
orch logs a1b2c3d4-e5f6-7890-abcd-ef1234567890

# View logs using a short run ID prefix (7+ hex chars)
orch logs a1b2c3d

# Limit results
orch logs --limit 50

# JSON output
orch logs --json
```

**Options:**

| Flag                 | Description                                                   |
| -------------------- | ------------------------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace)                   |
| `--status <status>`  | Filter by status: `running`, `completed`, `failed`, `timeout` |
| `--limit <n>`        | Number of runs to show (default: 20, max: 200)                |
| `--json`             | Output as JSON                                                |

**Modes:**

| Target                           | Behavior                                                                                        |
| -------------------------------- | ----------------------------------------------------------------------------------------------- |
| *(none)* or agent name           | Lists recent runs in a table: Run ID, Agent, Status, Duration, Source, Started, Error           |
| Full UUID                        | Shows detailed logs: agent info, status, duration, exit code, input/output data, stdout, stderr |
| Short UUID prefix (7+ hex chars) | Resolves to full run ID via prefix matching, then shows detailed logs                           |

***

## Security

### security test

Run a dynamic vulnerability scan against a deployed agent. Tests for prompt injection, persona roleplay, logic traps, and other attack categories.

```bash theme={null}
# Run security test
orch security test my-org/my-agent@latest

# Filter by attack categories
orch security test my-org/my-agent@v1 --categories persona_roleplay logic_trap

# Filter by severity
orch security test my-org/my-agent@v1 --severities critical high

# Limit number of attacks
orch security test my-org/my-agent@v1 --max-attacks 10

# Output as markdown report
orch security test my-org/my-agent@v1 --output markdown --output-file report.md

# JSON output
orch security test my-org/my-agent@v1 --output json
```

**Options:**

| Flag                     | Description                                                       |
| ------------------------ | ----------------------------------------------------------------- |
| `--categories <cats...>` | Filter by attack categories                                       |
| `--severities <sevs...>` | Filter by severities: `critical`, `high`, `medium`, `low`         |
| `--max-attacks <n>`      | Limit number of attacks                                           |
| `--output <format>`      | Output format: `json`, `markdown`, `summary` (default: `summary`) |
| `--output-file <path>`   | Write report to file                                              |
| `--key <key>`            | LLM API key (requires `--provider`)                               |
| `--provider <provider>`  | LLM provider: `openai`, `anthropic`, `gemini`                     |

Summary output includes: risk level banner, attacks tested, vulnerabilities found, breakdown by severity and category, and top 5 issues.

***

## Debugging

### replay

Re-execute a previous run using the original input and configuration captured in its snapshot. Useful for reproducing bugs, testing fixes with policy overrides, or retrying failed runs.

```bash theme={null}
# Replay a run and wait for results
orch replay a1b2c3d4-e5f6-7890-abcd-ef1234567890

# Replay using a short run ID prefix
orch replay a1b2c3d4

# Queue the replay and return immediately
orch replay a1b2c3d4 --no-wait

# Replay with a reason (stored in audit log)
orch replay a1b2c3d4 --reason "debugging timeout issue"

# Replay with a different provider policy
orch replay a1b2c3d4 --override-policy policy-abc

# JSON output
orch replay a1b2c3d4 --json
```

**Options:**

| Flag                     | Description                                 |
| ------------------------ | ------------------------------------------- |
| `--workspace <slug>`     | Workspace slug (default: current workspace) |
| `--reason <text>`        | Reason for replay (stored in audit log)     |
| `--override-policy <id>` | Override provider policy ID for this replay |
| `--no-wait`              | Queue the replay and return immediately     |
| `--json`                 | Output as JSON                              |

**What happens:**

1. CLI resolves the run ID (supports short prefix matching)
2. Submits a replay request — the gateway re-executes using the original snapshot (input data, execution config, agent version)
3. By default, polls for completion and displays the result (agent name, version, status, output, stdout/stderr, duration)
4. With `--no-wait`, returns immediately with the new run ID and job ID

**Example output:**

```
Replay bbbbbbbb-cccc-dddd-eeee-ffffffffffff
  Agent:    joe/scanner@v2
  Status:   completed
  Duration: 1.5s

── Output ─────────────────────────────────
{"findings": [], "summary": "No issues found."}

── Stdout ─────────────────────────────────
Scanning repository...
Done.

View trace: orch trace bbbbbbbb-cccc-dddd-eeee-ffffffffffff
```

<Tip>
  After a replay completes, use `orch trace` on the new run ID to inspect the full execution timeline — LLM calls, tool calls, token usage, and cost breakdown.
</Tip>

### trace

View the execution trace for a run. Shows a timeline of LLM calls, tool calls, decisions, fallbacks, policy violations, and errors — with token counts, costs, and durations.

```bash theme={null}
# View trace for a run
orch trace a1b2c3d4-e5f6-7890-abcd-ef1234567890

# View trace using a short run ID prefix
orch trace a1b2c3d4

# JSON output (includes full event details)
orch trace a1b2c3d4 --json
```

**Options:**

| Flag                 | Description                                               |
| -------------------- | --------------------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace)               |
| `--json`             | Output as JSON (includes raw trace header and all events) |

**Event types shown:**

| Event                 | What It Shows                                        |
| --------------------- | ---------------------------------------------------- |
| `llm_call_succeeded`  | Provider, model, input/output tokens, cost, duration |
| `llm_call_failed`     | Provider, model, error message, duration             |
| `tool_call_succeeded` | Tool name, duration                                  |
| `tool_call_failed`    | Tool name, error message, duration                   |
| `decision`            | Agent decision description                           |
| `fallback_transition` | Provider fallback (from → to, reason)                |
| `policy_violation`    | Policy violation type and detail                     |
| `error`               | Error type and message                               |

**Example output:**

```
Trace for a1b2c3d4-e5f6-...
  Agent:    joe/scanner@v2
  Status:   completed
  Duration: 3.2s

── Timeline ─────────────────────────────────
  # 1  ✔ LLM  anthropic / claude-haiku-4-5-20251001 │ 1,200 in, 350 out │ $0.0004 │ 1.2s
  # 2  ✔ Tool scan-repo │ 1.5s
  # 3  ✔ LLM  anthropic / claude-haiku-4-5-20251001 │ 2,100 in, 180 out │ $0.0005 │ 0.8s

── Summary ─────────────────────────────────
  LLM calls:  2
  Tool calls: 1
  Tokens:     3,300 in, 530 out
  Cost:       $0.0009
  Providers:  anthropic
```

<Tip>
  Use `orch replay` to re-execute a run, then `orch trace` on the new run to compare execution traces side-by-side.
</Tip>

### metrics

Show agent performance metrics for a workspace — success rates, latency percentiles, error rates, and per-agent breakdown.

```bash theme={null}
# Show metrics for the last 30 days (default)
orch metrics

# Show metrics for the last 7 days
orch metrics --days 7

# Filter to a specific agent
orch metrics --agent scanner

# Use a specific workspace
orch metrics --workspace acme-corp

# JSON output for scripting
orch metrics --json
```

**Options:**

| Flag                 | Description                                    |
| -------------------- | ---------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace)    |
| `--days <n>`         | Number of days to analyze (1-365, default: 30) |
| `--agent <name>`     | Filter to a specific agent                     |
| `--json`             | Output as JSON                                 |

**Output includes:**

* **Overview** — Total runs, success rate, error rate (failed + timeout), p50/p95/avg latency, runs per day
* **Per-agent table** — Each agent's run count, success rate, latency percentiles, error count, and top error message

**Example output:**

```
Agent Metrics (last 30d)
==================================================

  Total Runs:   150
  Success Rate: 93.3%
  Error Rate:   6.7% (8 failed, 2 timeout)
  p50 Latency:  1.2s
  p95 Latency:  4.5s
  Avg Latency:  1.8s
  Runs/Day:     5

Per Agent
------------------------------------------------------------------------------------------
Agent                       Runs   Success       p50       p95  Errors  Top Error
------------------------------------------------------------------------------------------
scanner                      100      96%     800ms     3.2s       4  SANDBOX_TIMEOUT
review-agent                  50      88%     2.5s     8.0s       6  LLM_RATE_LIMIT
```

The same metrics are available on the web dashboard at `orchagent.io/metrics` with interactive charts for run activity, latency trends, and success rate over time.

### dag

Visualize the orchestration call graph (DAG) for a run. Shows all agents in the chain as an ASCII tree with real-time status, cost, duration, and trace summaries per node.

```bash theme={null}
# View DAG for a run
orch dag a1b2c3d4-e5f6-7890-abcd-ef1234567890

# View DAG using a short run ID prefix
orch dag a1b2c3d4

# Live mode — polls for updates while the run is active
orch dag a1b2c3d4 --live

# Custom poll interval (default: 2 seconds)
orch dag a1b2c3d4 --live --interval 5

# JSON output
orch dag a1b2c3d4 --json
```

**Options:**

| Flag                   | Description                                         |
| ---------------------- | --------------------------------------------------- |
| `--workspace <slug>`   | Workspace slug (default: current workspace)         |
| `--live`               | Keep polling for updates while the run is active    |
| `--interval <seconds>` | Poll interval in seconds for live mode (default: 2) |
| `--json`               | Output as JSON                                      |

**Example output:**

```
Orchestration DAG [LIVE]
  Root:     a1b2c3d4...
  Agents:   3
  Duration: 8.0s
  Cost:     $0.0150
  Status:   2 completed, 1 active
  Costly:   orchestrator

  ✓ orchestrator v1
    completed | 8.0s | $0.0050 | claude-sonnet-4-20250514 (2 LLM, 1 tool, 1.2K tok)
    └── ✓ audit-agent v2
          completed | 5.0s | $0.0060 | claude-haiku-4-5-20251001 (1 LLM, 1 tool, 950 tok)
          └── ✓ scanner-tool v1
                completed | 3.0s | $0.0040 (2 tool, 600 tok)

View trace:  orch trace a1b2c3d4
View logs:   orch logs a1b2c3d4
```

**What it shows per node:**

* Status icon (`✓` completed, `✗` failed, `◉` running, `○` queued)
* Agent name and version
* Status, duration, self cost, LLM model
* Trace summary: LLM call count, tool call count, error count, total tokens

**Live mode** clears the screen and re-renders the full DAG on each poll until the execution completes. Press `Ctrl+C` to stop.

The same DAG visualization is available on the web dashboard's run detail page, rendered as an interactive graph with SVG edges and clickable nodes.

<Tip>
  Use `orch dag` during multi-agent orchestration runs to monitor which agents are active, see cost distribution across the chain, and quickly identify failed nodes.
</Tip>

***

## Configuration

### config

Manage CLI configuration.

```bash theme={null}
# Set default export format(s)
orch config set default-format claude-code,cursor

# Set default scope
orch config set default-scope user

# Set default LLM provider (used when --provider flag is omitted)
orch config set default-provider gemini

# Get current value
orch config get default-format

# List all config values
orch config list
```

### Config File

The CLI stores configuration at `~/.orchagent/config.json`:

```json theme={null}
{
  "api_key": "sk_live_xxx",
  "api_url": "https://api.orchagent.io",
  "default_org": "myorg",
  "workspace": "optional-workspace-slug",
  "profiles": {
    "staging": {
      "api_key": "sk_staging_xxx",
      "api_url": "https://staging.api.orchagent.io"
    }
  },
  "default_formats": ["claude-code", "cursor"],
  "default_scope": "user"
}
```

| Field             | Description                                         |
| ----------------- | --------------------------------------------------- |
| `api_key`         | Your orchagent API key                              |
| `api_url`         | API base URL (default: `https://api.orchagent.io`)  |
| `default_org`     | Default org from login (personal workspace)         |
| `workspace`       | Active workspace (set via `orch workspace use`)     |
| `profiles`        | Named profiles with their own api\_key and api\_url |
| `default_formats` | Default export formats for `orch install`           |
| `default_scope`   | Default install scope: `"user"` or `"project"`      |

**Agent resolution:** When you run `orch run agent`, the CLI looks for the agent in this order:

1. Explicit org if provided (`org/agent`)
2. Active `workspace` if set
3. `default_org` (your personal workspace)

### Environment Variables

| Variable                | Description                   |
| ----------------------- | ----------------------------- |
| `ORCHAGENT_API_KEY`     | API key (preferred for CI/CD) |
| `ORCHAGENT_API_URL`     | API base URL                  |
| `ORCHAGENT_DEFAULT_ORG` | Default org for agent lookups |

**Resolution order:** Command-line flags > Environment variables > Config file > Defaults

***

## Diagnostics

### doctor

Diagnose CLI setup issues.

```bash theme={null}
# Check your setup
orch doctor

# Show extra details
orch doctor --verbose

# JSON output
orch doctor --json
```

**Checks performed:**

* Environment (Node.js, CLI version, Git)
* Configuration (config file, permissions)
* Connectivity (gateway reachable, latency)
* Authentication (API key valid)
* LLM Configuration (keys configured)

### health

Smoke test an agent by running a minimal cloud execution. Useful for verifying an agent is deployed, reachable, and responding correctly.

```bash theme={null}
# Basic health check
orch health acme/my-agent

# Health check a specific version
orch health acme/my-agent@v2

# JSON output (for CI/CD pipelines)
orch health acme/my-agent --json

# Custom input instead of auto-generated
orch health acme/my-agent --data '{"query": "test"}'

# Custom timeout (default: 30s)
orch health acme/my-agent --timeout 60000
```

**Options:**

| Flag             | Description                                                   |
| ---------------- | ------------------------------------------------------------- |
| `--json`         | Output result as JSON                                         |
| `--data <json>`  | Custom input data (overrides auto-generated sample)           |
| `--timeout <ms>` | Execution timeout in milliseconds (default: 30000, min: 1000) |

**What happens:**

1. CLI resolves the agent (public or private)
2. Auto-generates minimal input from the agent's `input_schema` (fills required fields with sample values)
3. Fires a real POST to the agent's cloud endpoint
4. Reports pass/fail with latency and run ID

**Example output:**

```
✔ PASS joe/my-agent@v1 — 2340ms

  Resolve:  pass
  Execute:  pass
  Run ID:   run_abc123
  Logs:     orch logs run_abc123
```

**JSON output:**

```json theme={null}
{
  "agent": "joe/my-agent",
  "version": "v1",
  "status": "pass",
  "latency_ms": 2340,
  "run_id": "run_abc123",
  "checks": {
    "resolve": "pass",
    "execute": "pass"
  }
}
```

<Tip>
  Use `orch health` in CI/CD pipelines after deploying a new agent version to verify it's working. The `--json` flag and exit code (`0` = pass, `1` = fail) make it easy to integrate with any CI system.
</Tip>

### status

Check orchagent platform service status.

```bash theme={null}
# Check service status
orch status

# JSON output
orch status --json
```

**Options:**

| Flag     | Description     |
| -------- | --------------- |
| `--json` | Output raw JSON |

Displays overall platform status (All Systems Operational / Partial Outage / Service Outage) and per-service status with latency. Also verifies actual API connectivity and warns if the status page and API disagree.

### docs

Open orchagent documentation in your browser.

```bash theme={null}
# Open docs homepage
orch docs

# Open specific topic
orch docs cli
orch docs agents
orch docs skills
orch docs sdk
orch docs api
orch docs quickstart
```

**Topics:**

| Topic        | Opens                  |
| ------------ | ---------------------- |
| *(none)*     | Documentation homepage |
| `cli`        | CLI commands reference |
| `agents`     | Agent types guide      |
| `skills`     | Orchestration guide    |
| `sdk`        | SDK reference          |
| `api`        | API reference          |
| `quickstart` | Quickstart guide       |

### completion

Generate shell completion scripts for tab-completion of commands, subcommands, and flags.

```bash theme={null}
# Generate completions for your shell
orch completion bash
orch completion zsh
orch completion fish
```

**Setup:**

```bash theme={null}
# Bash — add to ~/.bashrc
eval "$(orch completion bash)"

# Zsh — add to ~/.zshrc
eval "$(orch completion zsh)"

# Fish — add to config.fish
orch completion fish | source
```

**Persistent install (alternative):**

```bash theme={null}
# Bash
orch completion bash > ~/.local/share/bash-completion/completions/orch

# Zsh
orch completion zsh > "${fpath[1]}/_orch"

# Fish
orch completion fish > ~/.config/fish/completions/orch.fish
```

***

## Scheduling

Automate agent execution with cron schedules or webhooks. See the full [Scheduling & Webhooks](/using-agents/scheduling) guide for detailed usage and examples.

### schedule list

List schedules in your workspace.

```bash theme={null}
# List all schedules
orch schedule list

# Filter by agent name
orch schedule list --agent report-generator

# Filter by type
orch schedule list --type cron

# JSON output
orch schedule list --json
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--agent <name>`     | Filter by agent name                        |
| `--type <type>`      | Filter by type: `cron` or `webhook`         |
| `--json`             | Output as JSON                              |

### schedule create

Create a cron or webhook schedule for an agent.

```bash theme={null}
# Cron schedule — daily at 9am UTC
orch schedule create acme/report-generator --cron "0 9 * * *"

# Cron schedule with timezone and input
orch schedule create acme/report-generator \
  --cron "0 9 * * 1-5" \
  --timezone "America/New_York" \
  --input '{"format": "pdf"}'

# Webhook schedule
orch schedule create acme/github-processor --webhook
```

**Options:**

| Flag                           | Description                                                   |
| ------------------------------ | ------------------------------------------------------------- |
| `--cron <expression>`          | Cron expression (required unless `--webhook`)                 |
| `--webhook`                    | Create webhook schedule instead of cron                       |
| `--timezone <tz>`              | Timezone for cron (default: `UTC`)                            |
| `--input <json>`               | Input data as JSON string                                     |
| `--provider <provider>`        | LLM provider: `anthropic`, `openai`, `gemini`                 |
| `--pin-version`                | Pin to current agent version (disable auto-update on publish) |
| `--alert-webhook <url>`        | Webhook URL to POST on failure (HTTPS required)               |
| `--alert-on-failure-count <n>` | Consecutive failures before alerting (default: 3)             |
| `--workspace <slug>`           | Workspace slug (default: current workspace)                   |

<Note>
  Webhook URLs contain a secret token and are shown only once at creation time. Save the URL immediately.
</Note>

### schedule update

Update an existing schedule.

```bash theme={null}
# Change cron expression
orch schedule update <schedule-id> --cron "0 10 * * 1"

# Disable a schedule
orch schedule update <schedule-id> --disable

# Re-enable
orch schedule update <schedule-id> --enable

# Update timezone and input
orch schedule update <schedule-id> \
  --timezone "America/Los_Angeles" \
  --input '{"threshold": 2000}'
```

**Options:**

| Flag                           | Description                                        |
| ------------------------------ | -------------------------------------------------- |
| `--cron <expression>`          | New cron expression                                |
| `--timezone <tz>`              | New timezone                                       |
| `--input <json>`               | New input data as JSON                             |
| `--provider <provider>`        | New LLM provider                                   |
| `--enable`                     | Enable the schedule                                |
| `--disable`                    | Disable the schedule                               |
| `--pin-version`                | Pin to current agent version (disable auto-update) |
| `--alert-webhook <url>`        | Webhook URL to POST on failure (HTTPS required)    |
| `--alert-on-failure-count <n>` | Consecutive failures before alerting               |
| `--clear-alert-webhook`        | Remove the alert webhook URL                       |
| `--workspace <slug>`           | Workspace slug (default: current workspace)        |

### schedule delete

Delete a schedule permanently.

```bash theme={null}
# Delete a schedule (prompts for confirmation)
orch schedule delete <schedule-id>

# Skip confirmation prompt
orch schedule delete <schedule-id> --yes
```

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `-y, --yes`          | Skip confirmation prompt                    |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### schedule trigger

Manually trigger a schedule execution (useful for testing).

```bash theme={null}
# Trigger with default input
orch schedule trigger <schedule-id>

# Trigger with input override
orch schedule trigger <schedule-id> --input '{"test": true}'
```

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--input <json>`     | Override input data for this execution      |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### schedule info

View schedule details and recent events.

```bash theme={null}
# View schedule details
orch schedule info <schedule-id>

# JSON output
orch schedule info <schedule-id> --json
```

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--json`             | Output as JSON                              |

Shows schedule configuration, recent run history, and event timeline.

### schedule runs

View run history for a schedule.

```bash theme={null}
# List recent runs
orch schedule runs <schedule-id>

# Filter by status
orch schedule runs <schedule-id> --status failed

# Limit results
orch schedule runs <schedule-id> --limit 50
```

| Flag                 | Description                                                   |
| -------------------- | ------------------------------------------------------------- |
| `--status <status>`  | Filter by status: `completed`, `failed`, `running`, `timeout` |
| `--limit <n>`        | Number of runs to show (default: 20)                          |
| `--workspace <slug>` | Workspace slug (default: current workspace)                   |
| `--json`             | Output as JSON                                                |

***

## Services

Deploy agents as always-on services for long-running workloads like Discord bots, webhook listeners, or background workers. See the full [Services](/using-agents/services) guide for detailed usage and examples.

### service deploy

Deploy an agent as an always-on service.

```bash theme={null}
# Deploy an agent as a service
orch service deploy acme/discord-bot

# Deploy with a custom service name
orch service deploy acme/discord-bot --name my-discord-bot

# Deploy with instance scaling
orch service deploy acme/discord-bot --min-instances 1 --max-instances 3

# Deploy with environment variables
orch service deploy acme/discord-bot \
  --env BOT_PREFIX="!" \
  --env LOG_LEVEL=debug

# Deploy with workspace secrets (for sensitive values)
orch service deploy acme/discord-bot \
  --secret DISCORD_TOKEN \
  --secret DATABASE_URL

# Deploy with a custom command and arguments
orch service deploy acme/worker --command python --arg worker.py --arg --verbose

# JSON output
orch service deploy acme/discord-bot --json
```

**Options:**

| Flag                  | Description                                  |
| --------------------- | -------------------------------------------- |
| `--workspace <slug>`  | Workspace slug (default: current workspace)  |
| `--name <name>`       | Custom service name (default: agent name)    |
| `--min-instances <n>` | Minimum number of instances                  |
| `--max-instances <n>` | Maximum number of instances                  |
| `--env <KEY=value>`   | Environment variable (repeatable)            |
| `--secret <NAME>`     | Workspace secret name (repeatable)           |
| `--command <cmd>`     | Override the default entrypoint command      |
| `--arg <arg>`         | Argument to pass to the command (repeatable) |
| `--json`              | Output as JSON                               |

<Note>
  Only agents with a `runtime.command` or `loop` config (i.e., code runtime or managed loop agents) are eligible for service deployment. Direct LLM agents cannot be deployed as services. Sensitive environment variables (e.g., API keys, tokens) are rejected by `--env` and must be passed using `--secret` instead.
</Note>

### service list

List services in your workspace.

```bash theme={null}
# List all services
orch service list

# Filter by status
orch service list --status running

# JSON output
orch service list --json
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--status <status>`  | Filter by service status                    |
| `--json`             | Output as JSON                              |

### service info

Get service details and events.

```bash theme={null}
# View service details
orch service info <service-id>

# JSON output
orch service info <service-id> --json
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--json`             | Output as JSON                              |

### service logs

View service logs.

```bash theme={null}
# View recent logs
orch service logs <service-id>

# Limit number of log lines
orch service logs <service-id> --limit 200

# View logs since a specific time
orch service logs <service-id> --since 2026-02-10T00:00:00Z

# JSON output
orch service logs <service-id> --json
```

**Options:**

| Flag                  | Description                                            |
| --------------------- | ------------------------------------------------------ |
| `--workspace <slug>`  | Workspace slug (default: current workspace)            |
| `--limit <n>`         | Number of log lines to return (default: 100, max: 500) |
| `--since <timestamp>` | Show logs since this time (ISO 8601 format)            |
| `--json`              | Output as JSON                                         |

<Note>
  Sensitive values in log output are automatically redacted.
</Note>

### service restart

Restart a service.

```bash theme={null}
# Restart a service
orch service restart <service-id>

# JSON output
orch service restart <service-id> --json
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--json`             | Output as JSON                              |

### service delete

Delete a service.

```bash theme={null}
# Delete a service
orch service delete <service-id>

# JSON output
orch service delete <service-id> --json
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |
| `--json`             | Output as JSON                              |

### service env set

Set or update environment variables on a deployed service. Merges with existing variables. Triggers a restart if the service is running.

```bash theme={null}
# Set one variable
orch service env set my-bot DEPLOY_ENV=production

# Set multiple variables
orch service env set my-bot LOG_LEVEL=debug BATCH_SIZE=100

# With workspace
orch service env set my-bot FOO=bar --workspace acme-team
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### service env unset

Remove environment variables from a service. Triggers a restart if the service is running.

```bash theme={null}
# Remove one variable
orch service env unset my-bot DEBUG_MODE

# Remove multiple
orch service env unset my-bot DEBUG_MODE VERBOSE
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### service env list

List current environment variables on a service.

```bash theme={null}
orch service env list my-bot
```

Output:

```
DEPLOY_ENV=production
LOG_LEVEL=warn
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### service secret add

Attach workspace secrets to a service. Secrets are injected as environment variables at runtime. Triggers a restart if the service is running.

```bash theme={null}
# Attach one secret
orch service secret add my-bot DISCORD_BOT_TOKEN

# Attach multiple
orch service secret add my-bot DISCORD_BOT_TOKEN DATABASE_URL
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

### service secret remove

Detach workspace secrets from a service. Triggers a restart if the service is running.

```bash theme={null}
orch service secret remove my-bot OLD_API_KEY
```

**Options:**

| Flag                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `--workspace <slug>` | Workspace slug (default: current workspace) |

***

## Billing

### billing

Open the Stripe billing portal in your browser to manage your subscription, payment methods, and invoices.

```bash theme={null}
orch billing
```

The command opens your billing portal URL directly. If the browser doesn't open automatically, the URL is printed to stdout so you can copy it.

***

## Exit Codes

| Code | Meaning               |
| ---- | --------------------- |
| `0`  | Success               |
| `1`  | General/unknown error |
| `2`  | Authentication error  |
| `3`  | Permission denied     |
| `4`  | Not found             |
| `5`  | Invalid input         |
| `6`  | Rate limited          |
| `7`  | Timeout               |
| `8`  | Server error          |
| `9`  | Network error         |

***

## Scripting Examples

```bash theme={null}
# Capture response, see errors
result=$(orch run acme/scanner doc.pdf)

# Suppress errors, check exit code
orch run acme/scanner doc.pdf 2>/dev/null && echo "success"

# Process JSON output
orch run acme/scanner doc.pdf --json | jq '.data.total'

# Install agents in CI
orch install acme/code-reviewer --format claude-code --scope project
```
