# CLI Reference

Complete reference for the Agents CLI commands and options.

## Global Options

These options apply to all commands:

```bash
agents-exe [GLOBAL_OPTS] COMMAND [COMMAND_OPTS]
```

| Option | Default | Description |
|--------|---------|-------------|
| `--api-keys FILE` | `~/.config/agents-exe/secret-keys` | Path to API keys JSON file |
| `--agent-file FILE` | (from config) | Agent configuration file(s) |
| `--agent SLUG` | - | Select agent by slug instead of file path |
| `--log-file FILE` | `agents-logfile` | Raw log output file |
| `--log-http URL` | - | HTTP endpoint for JSON logs |
| `--log-json-file FILE` | - | Local JSON log file |

## Commands

### check

Validate agent configuration and display loaded tools.

```bash
agents-exe check [--tools MODE]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--tools MODE` | Tool display mode: `none`, `list`, `agents-exe`, `openai` (default: `none`) |

**Output:**
```
my-agent: A helpful file assistant (12 tools)
```

**Exit codes:**
- `0` - All agents loaded successfully
- `1` - Configuration errors found

**Example:**
```bash
# Check default agents
agents-exe check

# Check specific agent
agents-exe check --agent-file ./custom-agent.json

# List tools in agents-exe format
agents-exe check --tools agents-exe
```

### run

Execute a one-shot agent conversation.

```bash
agents-exe run [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--session-file FILE` | Resume from existing session |
| `--thinking TARGET` | Output thinking: `none`, `stdout`, `stderr` (default: `none`) |
| `-m, --media MEDIA` | Attach media file (can be specified multiple times) |
| `--prompt TEXT` | Initial prompt text |
| `--file FILE` | Read prompt from file |
| `--shell COMMAND` | Use shell command output as prompt |
| `--alias NAME` | Use predefined prompt alias |
| `--sep4 TEXT` | Short separator (4 chars) |
| `--sep40 TEXT` | Long separator (40 chars) |
| `--session-xs FILE` | Inject session at minimal verbosity |
| `--session-s FILE` | Inject session at low verbosity |
| `--session-m FILE` | Inject session at medium verbosity |
| `--session-l FILE` | Inject session at high verbosity |
| `--session-xl FILE` | Inject session at maximum verbosity |

**Media Attachment Format:**

The `-m, --media` option accepts file paths with optional MIME type:

```bash
# Auto-detect MIME type from extension
agents-exe run -m /path/to/image.png --prompt "Describe this image"

# Explicit MIME type (semicolon separator)
agents-exe run -m "image/jpeg;/path/to/photo.jpg" --prompt "Analyze this photo"
```

**Supported Media Types:**

| Category | Extensions | MIME Types |
|----------|------------|------------|
| **Images** | `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg` | `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/svg+xml` |
| **Documents** | `.pdf`, `.txt`, `.md`, `.json`, `.xml` | `application/pdf`, `text/plain`, `text/markdown`, `application/json`, `application/xml` |
| **Audio** | `.mp3`, `.wav`, `.ogg`, `.aac`, `.flac` | `audio/mp3`, `audio/wav`, `audio/ogg`, `audio/aac`, `audio/flac` |
| **Video** | `.mp4`, `.webm`, `.mov`, `.avi` | `video/mp4`, `video/webm`, `video/quicktime`, `video/avi` |

**Size Limit:** 50MB per file

**Examples:**

```bash
# Simple prompt
agents-exe run --agent-file agent.json --prompt "Hello!"

# Read from file
agents-exe run --agent-file agent.json --file prompt.txt

# Shell command output as prompt
agents-exe run --agent-file agent.json --shell "git diff"

# Resume session
agents-exe run --agent-file agent.json --session-file session.json

# Use alias
agents-exe run --agent-file agent.json --alias code-review --file changes.patch

# Multi-part prompt with separators
agents-exe run \
  --prompt "Review this code:" \
  --sep4 "----" \
  --file code.py \
  --sep40 "========================================" \
  --prompt "What improvements can be made?"

# Inject previous session at medium verbosity
agents-exe run \
  --agent-file agent.json \
  --session-m previous-session.json \
  --prompt "Continue from where we left off"

# Attach single image
agents-exe run \
  --agent-file vision-agent.json \
  -m ./screenshot.png \
  --prompt "What do you see in this image?"

# Attach multiple images
agents-exe run \
  --agent-file vision-agent.json \
  -m ./image1.png \
  -m ./image2.jpg \
  -m "image/gif;./animation.gif" \
  --prompt "Compare these images"

# Attach document for analysis
agents-exe run \
  --agent-file document-agent.json \
  -m ./report.pdf \
  --prompt "Summarize the key findings"

# Combine media with text from file
agents-exe run \
  --agent-file multimodal-agent.json \
  --prompt "Analyze this diagram and code:" \
  -m ./diagram.png \
  --sep4 "----" \
  --file ./source-code.py
```

### tui

Start the interactive Terminal UI.

```bash
agents-exe tui [--agent-file FILE...]
```

**Features:**
- Real-time streaming responses
- Multiple agent support (Tab to switch)
- Tool call visualization
- Session persistence
- Turn navigation and forking
- Message queue management
- File attachments (Ctrl+F)
- Clipboard paste support (Ctrl+V)

**Keyboard Shortcuts:**
- `Tab` / `Shift+Tab` - Switch between agents
- `Enter` - Send message
- `Ctrl+C` - Quit
- `Up/Down` - Scroll history
- `Ctrl+[` / `Ctrl+]` - Previous/Next tab
- `Ctrl+E` - Pause/unpause conversation
- `Ctrl+D` (when paused) - Clear queued messages
- `Ctrl+F` - Attach file
- `Ctrl+Shift+F` - Clear all attachments
- `Ctrl+V` - Paste from clipboard

**Examples:**

```bash
# Single agent TUI
agents-exe tui --agent-file agent.json

# Multi-agent TUI
agents-exe tui \
  --agent-file coder.json \
  --agent-file reviewer.json \
  --agent-file tester.json
```

### mcp-server

Start an MCP (Model Context Protocol) server.

```bash
agents-exe mcp-server [--agent-file FILE...]
```

**Description:**
Exposes loaded agents as MCP tools for integration with MCP clients like Claude Desktop.

**Examples:**

```bash
# Single agent MCP server
agents-exe mcp-server --agent-file agent.json

# Multi-agent MCP server
agents-exe mcp-server \
  --agent-file research-agent.json \
  --agent-file writing-agent.json
```

### echo-prompt

Process and echo the prompt without calling the LLM.

```bash
agents-exe echo-prompt [OPTIONS]
```

**Options:** Same as `run` command.

**Use case:** Verify prompt construction before sending to LLM.

**Example:**
```bash
agents-exe echo-prompt \
  --prompt "Context:" \
  --file context.txt \
  --prompt "Question:" \
  --file question.txt
```

### session-print

Display a session file in markdown format.

```bash
agents-exe session-print [OPTIONS] SESSIONFILE
```

**Options:**

| Option | Description |
|--------|-------------|
| `--show-tool-call-results MODE` | Display mode: `hidden`, `shown`, `elided` (default: `hidden`) |
| `--show-tool-call-arguments MODE` | Display mode: `hidden`, `shown`, `elided` (default: `hidden`) |
| `--n-turns N` | Limit to last N turns |
| `--repeat-system-prompt` | Show system prompt each turn |
| `--repeat-tools` | Show available tools each turn |
| `--antichronological` | Newest first (default: oldest first) |
| `--no-funny-stamp` | Skip the ASCII art logo |

**Examples:**

```bash
# Print full session
agents-exe session-print session.json

# Print with tool results visible
agents-exe session-print --show-tool-call-results shown session.json

# Elide long outputs (show first/last 10 lines)
agents-exe session-print --show-tool-call-results elided session.json

# Last 5 turns only
agents-exe session-print --n-turns 5 session.json

# Reverse order
agents-exe session-print --antichronological session.json
```

### session-edit

Edit a session file (reads JSON from STDIN, writes JSON to STDOUT).

```bash
agents-exe session-edit [OPTIONS] < input.json > output.json
```

**Options:**

| Option | Description |
|--------|-------------|
| `--take` | Take first N turns (use with `--count`) |
| `--take-tail` | Take last N turns (use with `--count`) |
| `--drop` | Drop first N turns (use with `--count`) |
| `--drop-tail` | Drop last N turns (use with `--count`) |
| `--count N`, `-n N` | Number of turns for take/drop operations |
| `--censor-tool-calls` | Remove all tool calls |
| `--censor-thinking` | Remove all thinking content |

**Examples:**

```bash
# Keep only first 10 turns
agents-exe session-edit --take --count 10 < session.json > trimmed.json

# Keep only last 5 turns
agents-exe session-edit --take-tail --count 5 < session.json > recent.json

# Remove first 2 turns
agents-exe session-edit --drop --count 2 < session.json > dropped.json

# Remove all tool calls
agents-exe session-edit --censor-tool-calls < session.json > no-tools.json

# Remove thinking content
agents-exe session-edit --censor-thinking < session.json > no-thinking.json
```

### session-index

Manage the SQLite FTS5 search index for session files.

```bash
agents-exe session-index [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--build` | Build the search index from scratch |
| `--update` | Incrementally update the search index |
| `--status` | Show index status (default) |
| `--clean` | Remove the search index |
| `--db-path PATH` | Path to search index database (default: `.agents-search.db`) |
| `--include-tool-outputs` | Include tool outputs in the index |

**Description:**
The `session-index` command manages a SQLite FTS5-based search index for fast fuzzy text search across session files. The index uses trigram tokenization to enable fuzzy matching (e.g., "error" matches "errors", "erroring").

**Index Schema:**
- `session_index` - Session metadata cache (path, mtime, agent, turn count)
- `search_content` - FTS5 virtual table with trigram tokenizer
- `tool_index` - Tool call index for filtering by tool name

**Examples:**

```bash
# Build the search index
agents-exe session-index --build

# Check index status
agents-exe session-index --status

# Update index incrementally
agents-exe session-index --update

# Remove the index
agents-exe session-index --clean

# Build with tool outputs included
agents-exe session-index --build --include-tool-outputs

# Custom database location
agents-exe session-index --build --db-path ~/.config/agents-exe/search.db
```

### session-search

Search session files with fuzzy text matching and filtering.

```bash
agents-exe session-search [OPTIONS] "QUERY"
```

**Arguments:**

| Argument | Description |
|----------|-------------|
| `QUERY` | Search query text (supports fuzzy matching) |

**Options:**

| Option | Description |
|--------|-------------|
| `--db-path PATH` | Path to search index database |
| `--after DATE` | Filter sessions after date (YYYY-MM-DD) |
| `--before DATE` | Filter sessions before date (YYYY-MM-DD) |
| `--tool TOOLNAME` | Filter by tool name (can specify multiple) |
| `--agent SLUG` | Filter by agent slug |
| `--include-tool-outputs` | Include tool outputs in search |
| `--json` | Output results as JSON |
| `--preview N` | Show N lines of context around matches |
| `--limit N` | Limit to N results |
| `--auto` | Auto-update index if stale before searching |

**Description:**
Performs fast fuzzy text search across session files using an SQLite FTS5 index. The search supports trigram-based fuzzy matching, allowing queries like "error" to match "errors", "erroring", "terror", etc.

**Search Features:**
- **Fuzzy matching**: Trigram tokenizer handles typos and variations
- **Metadata filtering**: Filter by date, tool usage, or agent
- **Incremental indexing**: Only re-indexes changed sessions
- **JSON output**: Machine-readable format for scripting

**Examples:**

```bash
# Basic fuzzy search
agents-exe session-search "database error"

# Search with auto-update
agents-exe session-search "migration" --auto

# Include tool outputs in search
agents-exe session-search "config.yaml" --include-tool-outputs

# Filter by date and tool
agents-exe session-search "auth" --after 2024-01-01 --tool write-file

# Filter by agent
agents-exe session-search "refactor" --agent my-coder

# JSON output for scripting
agents-exe session-search "TODO" --json

# Show context lines
agents-exe session-search "deploy" --preview 5

# Combined filters
agents-exe session-search "fix" --after 2024-01-01 --before 2024-12-31 --tool bash_write-file --json
```

**JSON Output Format:**
```json
{
  "resultItems": [
    {
      "resultMetadata": {
        "resultSessionId": "550e8400-e29b-41d4-a716-446655440000",
        "resultFilePath": "/path/to/session.json",
        "resultAgentSlug": "my-agent",
        "resultTurnCount": 15,
        "resultRank": 0.5
      },
      "resultPreview": "...context around match...",
      "resultMatchedTerms": ["error", "database"]
    }
  ],
  "resultTotalMatches": 42,
  "resultQueryTimeMs": 15.3,
  "resultIndexWasUpdated": false
}
```

### list-tool-calls

Extract and list all tool calls from a session file.

```bash
agents-exe list-tool-calls [OPTIONS] SESSIONFILE
```

**Options:**

| Option | Description |
|--------|-------------|
| `-f, --format FORMAT` | Output format: `human`, `json`, `brief` (default: `human`) |

**Description:**
Parses a session file and extracts all tool calls made during the conversation.
Useful for debugging, auditing, and replaying specific tool calls.

**Output formats:**
- `human` - Detailed human-readable format with indices, turn numbers, and arguments
- `json` - JSON array for machine processing
- `brief` - Compact tabular format (index, name, arguments preview)

**Examples:**

```bash
# List tool calls in human-readable format
agents-exe list-tool-calls session.json

# Output as JSON
agents-exe list-tool-calls session.json --format json

# Brief format for quick overview
agents-exe list-tool-calls session.json --format brief
```

**Example output (human format):**
```
Found 3 tool call(s):

[0] bash_read-file
  Turn: 1
  Arguments: 
    {"filepath":"./src/Main.hs"}

[1] bash_grep-files
  Turn: 2
  Arguments: 
    {"pattern":"TODO","filepath":"./src"}

[2] bash_write-file
  Turn: 2
  Arguments: 
    {"filepath":"./src/Main.hs","content":"..."}

To replay a tool call:
  agents-exe replay-tool-call --session <file> --tool-call <index> --tool <tool-path>
```

### replay-tool-call

Replay a specific tool call from a session file, with validation.

```bash
agents-exe replay-tool-call --session FILE --tool-call INDEX --tool TOOLPATH [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `-s, --session FILE` | Path to the session file containing the tool call |
| `-i, --tool-call INDEX` | Index of the tool call to replay (0-based) |
| `-t, --tool TOOLPATH` | Path to the tool script to execute |
| `--validate-only` | Only validate arguments, don't execute |
| `--raw` | Show raw output instead of formatted |

**Description:**
Extracts a tool call from a session file, validates its arguments against the tool's schema,
and optionally executes the tool with the same arguments. This is useful for:

- Debugging failed tool calls
- Reproducing tool execution for testing
- Validating historical tool calls against updated schemas

**Exit codes:**
- `0` - Validation passed (and tool executed if not --validate-only)
- `1` - Validation failed or tool execution failed

**Examples:**

```bash
# First, list tool calls to find the index
agents-exe list-tool-calls session.json

# Validate and execute a tool call
agents-exe replay-tool-call \
  --session session.json \
  --tool-call 0 \
  --tool ./tools/read-file.sh

# Only validate without executing
agents-exe replay-tool-call \
  --session session.json \
  --tool-call 1 \
  --tool ./tools/grep-files.sh \
  --validate-only

# Execute and show raw output
agents-exe replay-tool-call \
  --session session.json \
  --tool-call 2 \
  --tool ./tools/write-file.sh \
  --raw
```

**Example output:**
```
✓ Tool call validation passed
Tool: read-file
Arguments: {"filepath":"./src/Main.hs"}

Executing tool...

=== Tool Output ===
module Main where

main :: IO ()
main = putStrLn "Hello, World!"
===================
```

### tool-call

Call a tool from the first loaded agent with JSON payload from stdin.

```bash
echo '{}' | agents-exe tool-call TOOLNAME [OPTIONS]
```

**Arguments:**

| Argument | Description |
|----------|-------------|
| `TOOLNAME` | Name of the tool to call |

**Options:**

| Option | Description |
|--------|-------------|
| `-l, --log-file FILE` | Optional log file for tracing tool execution |

**Description:**
Executes a single tool directly without involving the LLM. Useful for:

- Testing tool implementations
- Scripting tool usage
- Debugging tool behavior

**Examples:**

```bash
# Call a tool with arguments
echo '{"filepath": "./README.md"}' | \
    agents-exe tool-call read-file --agent-file ./agent.json

# Call with logging
echo '{"command": "ls -la"}' | \
    agents-exe tool-call bash --log-file ./tool-debug.log
```

### check-tool-call

Validate a tool call payload against a tool schema (reads JSON from stdin).

```bash
cat payload.json | agents-exe check-tool-call --tool TOOLPATH
```

**Options:**

| Option | Description |
|--------|-------------|
| `-t, --tool TOOLPATH` | Path to the tool script to validate against |

**Description:**
Validates that a JSON payload from stdin matches the tool's declared schema.
Returns exit code 0 if valid, 1 if invalid with detailed error messages.

**Example:**
```bash
# Create a test payload
echo '{"filepath": "/path/to/file"}' | agents-exe check-tool-call --tool ./tools/read-file.sh

# Validate from file
cat payload.json | agents-exe check-tool-call --tool ./tools/my-tool.sh
```

**Example output (valid):**
```
✓ Tool call payload is valid
```

**Example output (invalid):**
```
Tool call validation failed for './tools/my-tool.sh (my-tool)' with 2 errors:

1. filepath: Required property missing

2. content: Required property missing

Please correct these issues and try again.
```

### init

Initialize a new agent configuration.

```bash
agents-exe init [--agent-file FILE]
```

**Creates:**
- `agent.json` - Agent configuration
- `tools/` - Tool directory
- `secret-keys` - API keys file (if doesn't exist)

**Example:**
```bash
agents-exe init --agent-file ./my-agent.json
```

### new

Create scaffolding for new agents or tools.

```bash
agents-exe new (agent|tool) [OPTIONS]
```

#### new agent

Create a new agent configuration file from a template.

```bash
agents-exe new agent SLUG [FILE] [MODEL] [OPTIONS]
```

**Arguments:**

| Argument | Description |
|----------|-------------|
| `SLUG` | Unique identifier for the agent |
| `FILE` | Output file path (default: `./{slug}.json`) |
| `MODEL` | Model name (e.g., gpt-4o, mistral-large) |

**Options:**

| Option | Description |
|--------|-------------|
| `-p, --preset PRESET` | Provider preset: `openai`, `mistral`, `ollama` (default: `openai`) |
| `-f, --force` | Overwrite existing file |

**Presets:**

| Preset | Model URL | Default Model | API Key ID |
|--------|-----------|---------------|------------|
| `openai` | https://api.openai.com/v1 | gpt-4-turbo-preview | main-key |
| `mistral` | https://api.mistral.ai/v1 | mistral-large-latest | mistral-key |
| `ollama` | http://localhost:11434/v1 | llama3.2 | ollama-key |

**Examples:**

```bash
# Create agent with OpenAI preset (default)
agents-exe new agent my-assistant

# Create agent with specific preset
agents-exe new agent my-assistant --preset mistral

# Create agent with custom model
agents-exe new agent coder --preset openai --model gpt-4o

# Create agent with custom output path
agents-exe new agent my-assistant ./agents/assistant.json

# Overwrite existing
agents-exe new agent my-assistant --force
```

**Generated agent file:**
```json
{
  "agent": {
    "slug": "my-assistant",
    "apiKeyId": "main-key",
    "flavor": "OpenAIv1",
    "modelUrl": "https://api.openai.com/v1",
    "modelName": "gpt-4-turbo-preview",
    "announce": "a helpful assistant powered by gpt-4-turbo-preview",
    "systemPrompt": [
      "You are my-assistant, a helpful AI assistant.",
      "You provide clear, accurate, and concise responses.",
      "When using tools, you explain your actions to the user."
    ],
    "toolDirectory": "tools",
    "mcpServers": [],
    "openApiToolboxes": null,
    "postgrestToolboxes": null,
    "builtinToolboxes": [],
    "extraAgents": null
  }
}
```

#### new tool

Create a new tool script from a template.

```bash
agents-exe new tool SLUG LANGUAGE FILE [OPTIONS]
```

**Arguments:**

| Argument | Description |
|----------|-------------|
| `SLUG` | Unique identifier for the tool |
| `LANGUAGE` | Programming language: `bash`, `python`, `haskell`, `node` |
| `FILE` | Output file path (without extension) |

**Options:**

| Option | Description |
|--------|-------------|
| `-f, --force` | Overwrite existing file |

**Examples:**

```bash
# Create bash tool (default)
agents-exe new tool my-tool bash ./tools/my-tool

# Create Python tool
agents-exe new tool my-tool python ./scripts/my-tool

# Create Haskell tool
agents-exe new tool my-tool haskell ./tools/my-tool

# Create Node.js tool
agents-exe new tool my-tool node ./scripts/my-tool
```

**Generated bash tool:**
```bash
#!/bin/bash
# my-tool - A bash tool for agents-exe

set -euo pipefail

# Agents-exe tool protocol: describe|run
# Environment variables available during 'run':
#   AGENT_SESSION_ID      - UUID of the current session
#   AGENT_CONVERSATION_ID - UUID of the conversation
#   AGENT_TURN_ID         - UUID of the current turn
#   AGENT_AGENT_ID        - UUID of the executing agent (if available)

case "${1:-}" in
  describe)
    cat <<'DESCRIBE_EOF'
{
  "slug": "my-tool",
  "description": "Tool my-tool - describe what this tool does",
  "args": [],
  "empty-result": {
    "tag": "AddMessage",
    "contents": "--no output--"
  }
}
DESCRIBE_EOF
    ;;
  run)
    # TODO: Implement tool logic
    # Access arguments via environment or command line
    echo "Tool my-tool executed"
    ;;
  *)
    echo "Usage: my-tool <describe|run>" >&2
    exit 1
    ;;
esac
```

**Next steps after creating a tool:**
1. Edit the `args` array in the describe function
2. Implement the `run` function logic
3. Test with: `agents-exe describe-tool ./tools/my-tool`

### spec

Display embedded specification documentation.

```bash
agents-exe spec TOPIC
```

**Topics:**

| Topic | Description |
|-------|-------------|
| `bash-tools` | Binary tool protocol specification |

**Examples:**

```bash
# Display bash-tools specification
agents-exe spec bash-tools
```

**Use case:** Learn the protocol for writing bash tools without leaving the CLI.

### describe-tool

Display information about a tool script.

```bash
agents-exe describe-tool TOOL_PATH [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `-f, --format FORMAT` | Output format: `json` or `pretty` (default: `json`) |
| `--check-only` | Only check validity, don't output full description |

**Description:**
Loads and displays the tool's description (the output of `tool describe`).

**Example:**
```bash
agents-exe describe-tool ./tools/my-tool.sh

# Pretty format
agents-exe describe-tool ./tools/my-tool.sh --format pretty

# Only check validity
agents-exe describe-tool ./tools/my-tool.sh --check-only
```

**Output:**
```json
{
  "slug": "my-tool",
  "description": "What this tool does",
  "args": [...],
  "empty-result": {...}
}
```

### paths

Show important configuration paths.

```bash
agents-exe paths [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--json` | Output in JSON format |

**Description:**
Displays configuration paths including config directory, agent files, 
API keys file, and session storage configuration.

**Session Storage:**
The session storage configuration supports multiple read locations:
- **Write location**: Where new sessions are saved
- **Read locations**: Directories searched for existing sessions (includes write location by default)

**Examples:**

```bash
# Human-readable output
agents-exe paths

# JSON output
agents-exe paths --json
```

**Example output:**
```
Configuration:
  File: /home/user/project/agents-exe.cfg.json
  Directory: /home/user/project
  Default: /home/user/.config/agents-exe

Agent Files:
  - ./main-agent.json
  - ./secondary-agent.json

API Keys:
  /home/user/.config/agents-exe/secret-keys

Session Storage:
  Write location: ./sessions/
  Read locations:
    1. ./sessions/
    2. ./.agents-sessions/
    3. ~/.config/agents-exe/sessions/
```

### export

Export agent/tool configurations to archive or git.

```bash
agents-exe export [OPTIONS]
```

**Source Options:**

| Option | Description |
|--------|-------------|
| `--all` | Export all loaded agents |
| `--agent-slug SLUG` | Export specific agent by slug |
| `--tools-only` | Export only tools, not agent config |
| `--tool TOOLNAME` | Export specific tool |

**Destination Options:**

| Option | Description |
|--------|-------------|
| `-o, --output FILE` | Output file path |
| `--git-url URL` | Git remote URL |
| `--git-branch BRANCH` | Git branch |
| `--git-message MESSAGE` | Commit message |
| `--git-push` | Push after commit |
| `--git-tag TAG` | Create git tag |

**Format Options:**

| Option | Description |
|--------|-------------|
| `--format FORMAT` | Archive format: tar, tar.gz, zip |
| `--namespace NAMESPACE` | Namespace for export (e.g., "team.project") |
| `--no-tools` | Exclude tools from export |
| `--no-mcp` | Exclude MCP servers from export |

**Examples:**

```bash
# Export to tar.gz
agents-exe export --output ./my-agent.tar.gz

# Export to git
agents-exe export \
  --git-url https://github.com/user/agents-repo \
  --git-branch main \
  --git-message "Update agent" \
  --git-push

# Export tools only
agents-exe export --tools-only --output ./tools.tar.gz

# Export specific agent
agents-exe export --agent-slug my-agent --output ./agent.tar.gz

# With namespace
agents-exe export --namespace team-a.project-1 --output ./export.tar.gz
```

### import

Import agent/tool configurations from archive or git.

```bash
agents-exe import [OPTIONS]
```

**Source Options:**

| Option | Description |
|--------|-------------|
| `-f, --from-file FILE` | Import from archive file |
| `--git-url URL` | Import from git URL |
| `--git-ref REF` | Git ref (branch, tag, commit) |
| `--namespace NAMESPACE` | Namespace to import from |

**Destination Options:**

| Option | Description |
|--------|-------------|
| `--to-current` | Import to current directory |
| `--to PATH` | Import to specific path |
| `--to-config-dir` | Import to config directory |
| `--install-to-agent FILE` | Install tools to agent's tool directory |
| `--install-to-tooldir DIR` | Install tools to specific directory |

**Mode Options:**

| Option | Description |
|--------|-------------|
| `--overwrite` | Overwrite existing files |
| `--merge` | Merge with existing files |
| (default) | Fail on conflict |

**List Options:**

| Option | Description |
|--------|-------------|
| `--list-namespaces` | List available namespaces (git only) |
| `--list-tools` | List available tools (git only) |

**Examples:**

```bash
# Import from archive
agents-exe import --from-file ./agent.tar.gz

# Import from git
agents-exe import \
  --git-url https://github.com/user/agents-repo \
  --git-ref main

# Import tools to agent
agents-exe import \
  --from-file ./tools.tar.gz \
  --install-to-agent ./my-agent.json

# Import with overwrite
agents-exe import --from-file ./agent.tar.gz --overwrite

# List namespaces
agents-exe import --git-url https://github.com/user/repo --list-namespaces

# Import specific namespace
agents-exe import \
  --git-url https://github.com/user/repo \
  --namespace team-a.tools \
  --to ./tools/
```

### cowsay

Display a fun message with the agents-exe mascot.

```bash
agents-exe cowsay [MESSAGE] [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `-W, --width WIDTH` | Maximum width of speech bubble (default: 40) |

**Description:**
If no message is provided, reads from stdin.

**Example:**
```bash
agents-exe cowsay "Hello, agents!"

# With custom width
agents-exe cowsay "A much longer message that needs more space" --width 60

# Pipe from another command
echo "System ready" | agents-exe cowsay
```

### describe

Output self-describing schema for the agent.

```bash
agents-exe describe [OPTIONS]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--self-describe-slug NAME` | Override the slug field |
| `--self-describe-description DESC` | Override the description |

**Output:** JSON schema for tool calling.

**Use case:** Integration with external systems that need to understand the agent's interface.

### self-describe

Output information about the agents-exe binary itself.

```bash
agents-exe self-describe
```

**Output:** Version, build info, and available commands.

## Configuration File

Project-level configuration in `agents-exe.cfg.json`:

```json
{
  "agentsConfigDir": "/custom/config/path",
  "agentsDirectories": [
    "./agents",
    "./more-agents"
  ],
  "agentsFiles": [
    "./main-agent.json"
  ],
  "promptAliases": {
    "translate": {
      "systemPrompt": ["You are a translator..."],
      "userPromptPrefix": "Translate to English:"
    }
  },
  "selfDescribeSlug": "my-agent",
  "selfDescribeDescription": "A custom agent",
  "agentsLogs": {
    "logJsonHttpEndpoint": "http://localhost:8080/log",
    "logJsonPath": "./logs/agents.json",
    "logRawPath": "./logs/agents.log"
  },
  "sessions": {
    "writeLocation": "./sessions/",
    "readLocations": [
      "./sessions/",
      "./.agents-sessions/",
      "~/.config/agents-exe/sessions/"
    ]
  }
}
```

**Search order:**
1. Current directory
2. Parent directories (upward search)

### Sessions Configuration

The `sessions` section configures multi-location session storage:

| Field | Type | Description |
|-------|------|-------------|
| `writeLocation` | `FilePath` | Directory where new sessions are written |
| `readLocations` | `[FilePath]` | Directories to search for existing sessions |

**Key behaviors:**
- **Deduplication**: First location in `readLocations` has highest priority for duplicate session IDs
- **Auto-prepending**: If `writeLocation` is not in `readLocations`, it's automatically prepended
- **Tilde expansion**: Paths like `~/.config/agents-exe/sessions/` are resolved to the user's home directory
- **Backwards compatibility**: If `sessions` is not present, falls back to `agentsLogs.logSessionsJsonPrefix` (deprecated)

## Environment Variables

| Variable | Description |
|----------|-------------|
| `AGENTS_API_KEY` | Default API key (overrides file) |
| `AGENTS_CONFIG_DIR` | Config directory path |
| `AGENTS_LOG_LEVEL` | Logging verbosity |
| `AGENT_MD_VIEWER` | External markdown viewer for TUI session viewing |

## Exit Codes

| Code | Meaning |
|------|---------|
| `0` | Success |
| `1` | General error |
| `2` | Invalid arguments |
| `3` | Configuration error |
| `4` | Agent loading error |
| `5` | Tool execution error |
| `10` | Export error |
| `11` | Import error |

## Examples

### Complete Workflow

```bash
# 1. Initialize new agent
agents-exe new agent my-assistant

# 2. Create a custom tool
agents-exe new tool file-reader python ./tools/file-reader

# 3. Edit tool and agent configurations
# (edit files as needed)

# 4. Check configuration
agents-exe check --agent-file ./my-assistant.json

# 5. Test with one-shot
agents-exe run --agent-file ./my-assistant.json --prompt "Test"

# 6. Start interactive session
agents-exe tui --agent-file ./my-assistant.json

# 7. Export for sharing
agents-exe export --agent-file ./my-assistant.json --output ./my-assistant.tar.gz

# 8. Import elsewhere
agents-exe import --from-file ./my-assistant.tar.gz --to ./new-location/
```

### Multi-Agent Setup

```bash
# Start multi-agent TUI
agents-exe tui \
  --agent-file ./router.json \
  --agent-file ./coder.json \
  --agent-file ./reviewer.json

# Start multi-agent MCP server
agents-exe mcp-server \
  --agent-file ./router.json \
  --agent-file ./coder.json
```

### Session Management Workflow

```bash
# Run an agent session
agents-exe run \
    --agent-file ./my-agent.json \
    --session-file ./session.json \
    --prompt "Let's work on a project"

# Later, inspect the session
agents-exe session-print ./session.json

# List all tool calls from the session
agents-exe list-tool-calls ~/.config/agents-exe/sessions/session-*.json

# Replay a specific tool call for debugging
agents-exe replay-tool-call \
  --session ./session.json \
  --tool-call 0 \
  --tool ./tools/read-file.sh \
  --validate-only

# Trim to last 20 turns
agents-exe session-edit --take-tail --count 20 < ./session.json > ./trimmed.json
mv ./trimmed.json ./session.json

# Continue the session
agents-exe run \
    --agent-file ./my-agent.json \
    --session-file ./session.json \
    --prompt "Where were we?"
```

### Session Search Workflow

```bash
# Build the search index
agents-exe session-index --build

# Search for error-related sessions
agents-exe session-search "error" --json

# Find sessions using specific tool after a date
agents-exe session-search "config" --after 2024-01-01 --tool write-file

# Search with context preview
agents-exe session-search "TODO" --preview 3

# Auto-update index before searching
agents-exe session-search "refactor" --auto --limit 10
```

### Multi-Modal Workflow

```bash
# Analyze a screenshot with a vision-capable agent
agents-exe run \
    --agent-file ./vision-agent.json \
    -m ./screenshot.png \
    --prompt "What UI issues do you see in this screenshot?"

# Analyze multiple images
agents-exe run \
    --agent-file ./design-agent.json \
    -m ./mockup-v1.png \
    -m ./mockup-v2.png \
    --prompt "Compare these two design mockups and recommend which to use"

# Analyze a PDF document
agents-exe run \
    --agent-file ./document-agent.json \
    -m ./report.pdf \
    --prompt "Summarize the key findings and recommendations"

# Combine image with code for debugging
agents-exe run \
    --agent-file ./debug-agent.json \
    --prompt "This error appears in the UI:" \
    -m ./error-screenshot.png \
    --sep4 "----" \
    --prompt "Here's the relevant code:" \
    --file ./src/Main.hs
```

### Automation

```bash
# Process all files in directory
for file in *.txt; do
    agents-exe run \
        --agent-file ./processor.json \
        --prompt "Process this file:" \
        --file "$file" \
        --prompt "End of file."
done

# Git pre-commit hook
agents-exe run \
    --agent-file ./reviewer.json \
    --shell "git diff --cached" \
    --prompt "Review these changes."

# Daily summary from logs
agents-exe run \
    --agent-file ./summarizer.json \
    --shell "cat /var/log/app.log | tail -100" \
    --prompt "Summarize any errors or warnings"

# Automated image analysis with timestamp
agents-exe run \
    --agent-file ./monitor-agent.json \
    -m ./screenshots/$(date +%Y%m%d-%H%M%S).png \
    --prompt "Check for any alerts or errors in this status dashboard"
```

### Developer Workflow

```bash
# Learn the tool protocol
agents-exe spec bash-tools

# Create and validate a tool
agents-exe new tool my-validator bash ./tools/my-validator
# (edit the tool)
agents-exe describe-tool ./tools/my-validator --format pretty

# Validate a payload
echo '{"input": "test"}' | agents-exe check-tool-call --tool ./tools/my-validator

# Test the tool directly
echo '{"input": "test"}' | agents-exe tool-call my-validator

# Create agent with dev tools
agents-exe new agent dev-assistant
# (add DeveloperToolbox to builtinToolboxes)
# Now the agent can validate tools and scaffold new ones!

# Create a tool that outputs media
agents-exe new tool chart-generator bash ./tools/chart-gen
# Add to describe output:
#   "output-media-type": "image/png"
# Now the tool's output is treated as a PNG image
```

### Debugging Tool Calls

```bash
# Run an agent session
agents-exe run --agent-file ./my-agent.json --prompt "Read the README"

# Find the session file
agents-exe paths

# List all tool calls
agents-exe list-tool-calls ~/.config/agents-exe/sessions/session-*.json

# Replay with validation only
agents-exe replay-tool-call \
  --session ~/.config/agents-exe/sessions/session-xxx.json \
  --tool-call 0 \
  --tool ./tools/read-file.sh \
  --validate-only

# Actually replay the tool call
agents-exe replay-tool-call \
  --session ~/.config/agents-exe/sessions/session-xxx.json \
  --tool-call 0 \
  --tool ./tools/read-file.sh
```

## Related Documentation

- [tools.md](tools.md) - Tool system details
- [tui.md](tui.md) - Terminal UI documentation
- [sessions.md](sessions.md) - Session management
- [architecture.md](architecture.md) - System architecture

