# TypeAgent CLI

Command-line interface for executing type-safe AI agents defined in MDX format.

## Installation

```bash
cargo install --path crates/typedialog-agent/typedialog-ag
```text

Or build from source:

```bash
cargo build --release --package typedialog-ag
```text

## Setup

Set your API key:

```bash
export ANTHROPIC_API_KEY=your-api-key-here
```text

## Usage

### Execute an Agent

Run an agent with interactive prompts for inputs:

```bash
typeagent agent.mdx
```text

Or use the explicit `run` command:

```bash
typeagent run agent.mdx
```text

Skip input prompts (use defaults):

```bash
typeagent agent.mdx --yes
```text

Verbose output (show Nickel code):

```bash
typeagent agent.mdx --verbose
```text

### Validate an Agent

Check syntax, transpilation, and type checking without executing:

```bash
typeagent validate agent.mdx
```text

Output:
```text
✓ Validating agent

✓ MDX syntax valid
✓ Transpilation successful
✓ Type checking passed
✓ Evaluation successful

Agent Summary:
  Role: creative writer
  Model: claude-3-5-haiku-20241022
  Max tokens: 4096
  Temperature: 0.7

✓ Agent is valid and ready to execute
```text

### Transpile to Nickel

Convert MDX to Nickel configuration code:

```bash
# Output to stdout
typeagent transpile agent.mdx

# Save to file
typeagent transpile agent.mdx -o agent.ncl
```text

Output:
```nickel
{
  config = {
    role = "creative writer",
    llm = "claude-3-5-haiku-20241022",
  },
  inputs = {},
  template = "Write a haiku about {{ topic }}.",
}
```text

## Example Session

### 1. Create an Agent File

Create `haiku.agent.mdx`:

```markdown
---
@agent {
  role: creative writer,
  llm: claude-3-5-haiku-20241022
}

@input topic: String
---

Write a haiku about {{ topic }}. Return only the haiku, nothing else.
```text

### 2. Validate the Agent

```bash
$ typeagent validate haiku.agent.mdx

✓ Validating agent

✓ MDX syntax valid
✓ Transpilation successful
✓ Type checking passed
✓ Evaluation successful

Agent Summary:
  Role: creative writer
  Model: claude-3-5-haiku-20241022
  Max tokens: 4096
  Temperature: 0.7

✓ Agent is valid and ready to execute
```text

### 3. Execute the Agent

```bash
$ typeagent haiku.agent.mdx

🤖 TypeAgent Executor

✓ Parsed agent definition
✓ Transpiled to Nickel
✓ Evaluated agent definition

Agent Configuration:
  Role: creative writer
  Model: claude-3-5-haiku-20241022
  Max tokens: 4096
  Temperature: 0.7

topic (String): programming in Rust

Inputs:
  topic: "programming in Rust"

⠋ Executing agent with LLM...
════════════════════════════════════════════════════════════
Response:
════════════════════════════════════════════════════════════

Memory safe code flows,
Ownership ensures no woes,
Concurrency glows.

════════════════════════════════════════════════════════════

Metadata:
  Duration: 1234ms
  Tokens: 87
  Validation: ✓ PASSED
```text

## Agent File Format

### Basic Structure

```markdown
---
@agent {
  role: <role>,
  llm: <model-name>
}

@input <name>: <type>
@input <name>?: <type>  # Optional input

@validate output {
  must_contain: ["pattern1", "pattern2"],
  format: markdown
}
---

Your template content with {{ variables }}.
```text

### Directives

#### `@agent` (Required)

Defines the agent configuration.

```markdown
@agent {
  role: creative writer,
  llm: claude-3-5-haiku-20241022,
  tools: []  # Optional
}
```text

**Supported models:**
- `claude-3-5-haiku-20241022` - Fast, cheap
- `claude-3-5-sonnet-20241022` - Balanced
- `claude-opus-4` - Most capable

#### `@input` (Optional)

Declares inputs that will be prompted to the user.

```markdown
@input name: String          # Required input
@input description?: String  # Optional input
```text

#### `@validate` (Optional)

Defines output validation rules.

```markdown
@validate output {
  must_contain: ["Security", "Performance"],
  must_not_contain: ["TODO", "FIXME"],
  format: markdown,
  min_length: 100,
  max_length: 5000
}
```text

**Supported formats:**
- `markdown` (default)
- `json`
- `yaml`
- `text`

#### `@import` (Optional)

Import file content into template variables.

```markdown
@import "./docs/**/*.md" as documentation
@import "https://example.com/schema.json" as schema
```text

#### `@shell` (Optional)

Execute shell commands and inject output.

```markdown
@shell "git diff HEAD~1" as recent_changes
@shell "cargo tree" as dependencies
```text

### Template Syntax

Uses [Tera template engine](https://tera.netlify.app/):

```markdown
# Variables
{{ variable_name }}

# Conditionals
{% if condition %}
  content
{% endif %}

# Filters
{{ name | upper }}
{{ value | default(value="fallback") }}
```text

## Commands

### `typeagent [FILE]`

Execute an agent (default command).

**Options:**
- `-y, --yes` - Skip input prompts
- `-v, --verbose` - Show Nickel code
- `-h, --help` - Show help

**Example:**
```bash
typeagent agent.mdx --yes --verbose
```text

### `typeagent run <FILE>`

Explicit execute command (same as default).

**Options:**
- `-y, --yes` - Skip input prompts

**Example:**
```bash
typeagent run agent.mdx
```text

### `typeagent validate <FILE>`

Validate agent without execution.

**Example:**
```bash
typeagent validate agent.mdx
```text

### `typeagent transpile <FILE>`

Transpile MDX to Nickel.

**Options:**
- `-o, --output <FILE>` - Output file (default: stdout)

**Example:**
```bash
typeagent transpile agent.mdx -o agent.ncl
```text

### `typeagent cache`

Cache management (not yet implemented).

**Subcommands:**
- `clear` - Clear cache
- `stats` - Show cache statistics

## Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `ANTHROPIC_API_KEY` | Yes | Anthropic API key for Claude models |
| `RUST_LOG` | No | Logging level (default: `info`) |

## Error Handling

### Missing API Key

```text
Error: ANTHROPIC_API_KEY environment variable not set
Set ANTHROPIC_API_KEY to use Claude models
```text

**Solution:** Export your API key:
```bash
export ANTHROPIC_API_KEY=sk-ant-...
```text

### Invalid Agent File

```text
Error: Failed to parse agent MDX
```text

**Solution:** Validate your agent file:
```bash
typeagent validate agent.mdx
```text

### Validation Failures

```text
Validation: ✗ FAILED
  - Output must contain: Security
  - Output too short: 45 chars (minimum: 100)
```text

The agent executed successfully but output validation failed. Adjust your `@validate` rules or improve your prompt.

## Examples

See [`typedialog-ag-core/tests/fixtures/`](../typedialog-ag-core/tests/fixtures/) for example agent files:

- `simple.agent.mdx` - Basic hello world agent
- `architect.agent.mdx` - Architecture design agent with inputs
- `code-reviewer.agent.mdx` - Code review agent with shell commands

## Troubleshooting

### Command not found

Make sure the binary is in your PATH:

```bash
export PATH="$HOME/.cargo/bin:$PATH"
```text

Or use the full path:

```bash
./target/release/typeagent
```text

### Permission denied

Make the binary executable:

```bash
chmod +x ./target/release/typeagent
```text

### Slow compilation

Use release mode for better performance:

```bash
cargo build --release --package typedialog-ag
./target/release/typeagent agent.mdx
```text

## Development

Run from source:

```bash
cargo run --package typedialog-ag -- agent.mdx
```text

Run with logging:

```bash
RUST_LOG=debug cargo run --package typedialog-ag -- agent.mdx
```text

## License

MIT
