ai-agent-sdk 0.5.0

Idiomatic agent sdk inspired by the claude code source leak
Documentation
# AI Agent SDK (Rust)

[![Crates.io](https://img.shields.io/crates/v/ai-agent-sdk)](https://crates.io/crates/ai-agent-sdk)
[![Rust](https://img.shields.io/badge/rust-%3E%3D1.70-blue)](https://www.rust-lang.org)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)

[English]README.md | [中文]READCN.md

One to one Rust translation of `claude code source`.

Idiomatic agent sdk inspired by the `claude code source` leak, written in Rust that runs the full agent loop **in-process** — no subprocess or CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.

## Quick Demo

```rust
use ai_agent_sdk::Agent;

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
let result = agent.prompt("List files in current directory").await?;
println!("{}", result.text);
```

> That's it! The agent automatically uses 20+ built-in tools (Bash, Read, Write, Edit, Glob, Grep, WebFetch, etc.) to accomplish tasks.

## Core Features

| Feature | Description |
|---------|-------------|
| **Agent** | Create agents with custom models, tools, and prompts |
| **Subagent** | Spawn subagents for parallel or specialized tasks |
| **Session** | Persist, resume, fork conversations on disk |
| **Skills** | Load external skills or use 15+ bundled skills |
| **Plugin** | Load plugins with commands, skills, MCP servers |
| **Hooks** | 20+ lifecycle events for custom workflows |
| **Tools** | 20+ built-in tools + custom tool registration |
| **Memory** | Automatic session memory management |

## Quick Start

Install:

```bash
cargo add ai-agent-sdk
```

Configure your API key:

```bash
export AI_AUTH_TOKEN=your-api-key
export AI_MODEL=MiniMaxAI/MiniMax-M2.5
```

Or use `.env` file:

```text
AI_AUTH_TOKEN=your-token
AI_MODEL=MiniMaxAI/MiniMax-M2.5
AI_BASE_URL=https://api.minimax.chat/v1
```

### Simple Prompt

```rust
use ai_agent_sdk::Agent;

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
let result = agent.prompt("What files are in this project?").await?;
println!("{}", result.text);
```

### Multi-turn Conversation

```rust
use ai_agent_sdk::Agent;

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 5);
let r1 = agent.prompt("Create file /tmp/hello.txt with 'Hello'").await?;
let r2 = agent.prompt("Read that file back").await?;
println!("Session messages: {}", agent.get_messages().len());
```

### Custom Tools

```rust
use ai_agent_sdk::{Agent, ToolDefinition, ToolInputSchema};

fn calculator_impl(input: serde_json::Value, _ctx: ()) -> impl std::future::Future<Output = Result<ai_agent_sdk::ToolResult, ai_agent_sdk::AgentError>> + Send {
    async move {
        let expr = input["expression"].as_str().unwrap_or("0");
        Ok(ai_agent_sdk::ToolResult {
            result_type: "tool_result".to_string(),
            tool_use_id: "".to_string(),
            content: format!("Result of {}", expr),
            is_error: None,
        })
    }
}

let calculator = ai_agent_sdk::Tool {
    name: "Calculator".to_string(),
    description: "Evaluate math expressions".to_string(),
    input_schema: ToolInputSchema::Json(serde_json::json!({
        "type": "object",
        "properties": {"expression": {"type": "string"}},
        "required": ["expression"]
    })),
    executor: Box::new(calculator_impl),
};

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Tool registration via agent tools currently uses ToolDefinition
```

### MCP Servers

```rust
use ai_agent_sdk::{Agent, McpServerConfig};

let config = McpServerConfig::Stdio(ai_agent_sdk::McpStdioConfig {
    command: "npx".to_string(),
    args: Some(vec!["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]),
    ..Default::default()
});

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: MCP servers configured via AgentOptions
```

### Subagents

```rust
use ai_agent_sdk::{Agent, AgentDefinition};

let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Subagents are used via the Agent tool at runtime
```

### Skills

```rust
use ai_agent_sdk::{Agent, load_skill_from_dir};

let skill = load_skill_from_dir("skills/debug")?;
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Skills are applied via agent configuration
```

### Plugin System

```rust
use ai_agent_sdk::{load_plugin, load_plugins_from_dir, CommandRegistry};

let plugin = load_plugin("plugins/hello-plugin").await?;
let plugins = load_plugins_from_dir("plugins").await?;
let registry = CommandRegistry::new();
```

### Hooks

```rust
use ai_agent_sdk::hooks::{HookRegistry, HookDefinition, HookInput};

let mut registry = HookRegistry::new();
registry.register("PreToolUse", HookDefinition {
    command: Some("echo pre-tool".to_string()),
    timeout: Some(5000),
    matcher: Some("Read.*".to_string()),
});

let mut input = HookInput::new("PreToolUse");
input.tool_name = Some("Read".to_string());
let results = registry.execute("PreToolUse", input).await;
```

## Configuration

### Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `model` | string | MiniMaxAI/MiniMax-M2.5 | LLM model ID |
| `api_key` | string | env var | API key |
| `base_url` | string || Custom API endpoint |
| `cwd` | string | process.cwd() | Working directory |
| `max_turns` | u32 | 10 | Max agentic turns |
| `max_budget_usd` | f64 || Spending cap |
| `max_tokens` | u32 | 16384 | Max response tokens |
| `tools` | Vec<ToolDefinition> | All built-in | Available tools |
| `allowed_tools` | Vec<String> || Tool allow-list |
| `disallowed_tools` | Vec<String> || Tool deny-list |

### Environment Variables

| Variable | Description |
|----------|-------------|
| `AI_AUTH_TOKEN` | API authentication token (required) |
| `AI_MODEL` | Model name |
| `AI_BASE_URL` | API endpoint |
| `AI_CONTEXT_WINDOW` | Override context window size |
| `AI_DISABLE_AUTO_MEMORY` | Disable auto memory |
| `AI_MEMORY_PATH_OVERRIDE` | Override memory directory |

## Built-in Tools

| Tool | Description |
|------|-------------|
| **Bash** | Execute shell commands |
| **Read** | Read files with line numbers |
| **Write** | Create / overwrite files |
| **Edit** | Precise string replacement |
| **Glob** | Find files by pattern |
| **Grep** | Search with regex |
| **WebFetch** | Fetch web content |
| **WebSearch** | Web search |
| **NotebookEdit** | Edit Jupyter cells |
| **Agent** | Spawn subagents |
| **TaskCreate/List/Update/Get** | Task management |
| **TeamCreate/Delete** | Multi-agent teams |
| **SendMessage** | Inter-agent messaging |
| **EnterWorktree/ExitWorktree** | Git worktree |
| **EnterPlanMode/ExitPlanMode** | Planning workflow |
| **AskUserQuestion** | Request user input |
| **CronCreate/Delete/List** | Scheduled tasks |
| **TodoWrite** | Session todo list |

## Architecture

```
┌─────────────────────────────────────┐
│         Your Application             │
│   use ai_agent_sdk::Agent            │
└──────────────┬──────────────────────┘
    ┌──────────▼──────────┐
    │       Agent         │  Session state, tools
    │    prompt()         │  MCP connections
    └──────────┬──────────┘
    ┌──────────▼──────────┐
    │    QueryEngine      │  Agent loop:
    │   submitMessage()   │  API → tools → repeat
    └──────────┬──────────┘
    ┌──────────┼──────────┐
    │          │          │
┌───▼───┐  ┌───▼───┐  ┌──▼────┐
│  LLM  │  │ 20+   │  │  MCP  │
│  API  │  │Tools  │  │Server │
└───────┘  └───────┘  └───────┘
```

## Examples

Run examples from `examples/` directory:

```bash
# Configure your .env first
cargo run --example 01_simple_query
cargo run --example 18_plugin
cargo run --example 19_hooks
```

## License

MIT