# QwenClaw Rig Integration

## Overview

QwenClaw now integrates with **Rig** (https://github.com/0xPlaygrounds/rig), a high-performance Rust AI agent framework, providing:

- 🤖 **Multi-Agent Orchestration** - Agent councils for complex tasks
- 🛠️ **Dynamic Tool Calling** - Context-aware tool resolution
- 📚 **RAG Workflows** - Vector store integration for semantic search
- ⚡ **High Performance** - Rust-native speed and efficiency

---

## Architecture

```
┌─────────────────┐     ┌─────────────────┐
│  QwenClaw       │────▶│  Rig Service    │
│  (TypeScript)   │◀────│  (Rust + Rig)   │
│  - Daemon       │     │  - Agents       │
│  - Web UI       │     │  - Tools        │
│  - Scheduling   │     │  - Vector Store │
└─────────────────┘     └─────────────────┘
         │                       │
         ▼                       ▼
    Qwen Code              OpenAI/Anthropic
    Telegram               SQLite Vectors
```

---

## Quick Start

### 1. Start Rig Service

```bash
cd rig-service

# Set environment variables
export OPENAI_API_KEY="your-key-here"
export RIG_HOST="127.0.0.1"
export RIG_PORT="8080"

# Build and run
cargo build --release
cargo run
```

### 2. Use Rig in QwenClaw

```typescript
import { initRigClient, executeWithRig } from "./src/rig";

// Initialize Rig client
const rig = initRigClient("127.0.0.1", 8080);

// Check if Rig is available
if (await rig.health()) {
  console.log("✅ Rig service is running!");
}

// Create an agent
const sessionId = await rig.createAgent({
  name: "researcher",
  preamble: "You are a research specialist.",
  model: "gpt-4",
});

// Execute prompt
const result = await executeWithRig(sessionId, "Research AI trends in 2026");
console.log(result);
```

---

## API Reference

### Agents

```typescript
// Create agent
const sessionId = await rig.createAgent({
  name: "assistant",
  preamble: "You are a helpful assistant.",
  model: "gpt-4",
  provider: "openai",
  temperature: 0.7,
});

// List agents
const agents = await rig.listAgents();

// Execute prompt
const response = await rig.executePrompt(sessionId, "Hello!");

// Get agent details
const agent = await rig.getAgent(sessionId);

// Delete agent
await rig.deleteAgent(sessionId);
```

### Multi-Agent Councils

```typescript
// Create council with multiple agents
const councilId = await rig.createCouncil("Research Team", [
  {
    name: "researcher",
    preamble: "You are a research specialist.",
    model: "gpt-4",
  },
  {
    name: "analyst",
    preamble: "You are a data analyst.",
    model: "gpt-4",
  },
  {
    name: "writer",
    preamble: "You are a content writer.",
    model: "gpt-4",
  },
]);

// Execute task with council
const result = await rig.executeCouncil(councilId, "Write a research report on AI");
console.log(result);
// Output includes responses from all agents
```

### Tools

```typescript
// List all available tools
const tools = await rig.listTools();

// Search for relevant tools
const searchTools = await rig.searchTools("research", 5);
// Returns: web_search, academic_search, etc.
```

### RAG (Retrieval-Augmented Generation)

```typescript
// Add document to vector store
const docId = await rig.addDocument(
  "AI agents are transforming software development...",
  { source: "blog", author: "admin" }
);

// Search documents semantically
const results = await rig.searchDocuments("AI in software development", 5);

// Get specific document
const doc = await rig.getDocument(docId);

// Delete document
await rig.deleteDocument(docId);
```

---

## HTTP API

### Agents

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/agents` | Create agent |
| GET | `/api/agents` | List agents |
| GET | `/api/agents/:id` | Get agent |
| POST | `/api/agents/:id/prompt` | Execute prompt |
| DELETE | `/api/agents/:id` | Delete agent |

### Councils

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/councils` | Create council |
| GET | `/api/councils` | List councils |
| POST | `/api/councils/:id/execute` | Execute council task |

### Tools

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/tools` | List all tools |
| POST | `/api/tools/search` | Search tools |

### Documents

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/documents` | Add document |
| GET | `/api/documents` | List documents |
| POST | `/api/documents/search` | Search documents |
| GET | `/api/documents/:id` | Get document |
| DELETE | `/api/documents/:id` | Delete document |

---

## Configuration

### Environment Variables

```bash
# Rig Service Configuration
RIG_HOST=127.0.0.1
RIG_PORT=8080
RIG_DATABASE_PATH=rig-store.db

# Model Providers
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
QWEN_API_KEY=...

# Defaults
RIG_DEFAULT_PROVIDER=openai
RIG_DEFAULT_MODEL=gpt-4
```

### Rig Service Config

Edit `rig-service/.env`:

```env
RIG_HOST=127.0.0.1
RIG_PORT=8080
RIG_DATABASE_PATH=./data/rig-store.db
OPENAI_API_KEY=your-key-here
```

---

## Use Cases

### 1. Research Assistant

```typescript
const researcher = await rig.createAgent({
  name: "researcher",
  preamble: "You are a research specialist. Find accurate, up-to-date information.",
  model: "gpt-4",
});

// Add research papers to vector store
await rig.addDocument("Paper: Attention Is All You Need...", { type: "paper" });
await rig.addDocument("Paper: BERT: Pre-training...", { type: "paper" });

// Search and execute
const context = await rig.searchDocuments("transformer architecture", 3);
const result = await rig.executePrompt(
  researcher,
  `Based on this context: ${context.map(d => d.content).join("\n")}, explain transformers.`
);
```

### 2. Code Review Council

```typescript
const councilId = await rig.createCouncil("Code Review Team", [
  {
    name: "security",
    preamble: "You are a security expert. Review code for vulnerabilities.",
  },
  {
    name: "performance",
    preamble: "You are a performance expert. Identify bottlenecks.",
  },
  {
    name: "style",
    preamble: "You are a code style expert. Ensure clean, maintainable code.",
  },
]);

const review = await rig.executeCouncil(councilId, `
Review this code:
\`\`\`typescript
${code}
\`\`\`
`);
```

### 3. Content Creation Pipeline

```typescript
// Create specialized agents
const researcher = await rig.createAgent({
  name: "researcher",
  preamble: "Research topics thoroughly.",
});

const writer = await rig.createAgent({
  name: "writer",
  preamble: "Write engaging content.",
});

const editor = await rig.createAgent({
  name: "editor",
  preamble: "Edit and polish content.",
});

// Or use a council
const councilId = await rig.createCouncil("Content Team", [
  { name: "researcher", preamble: "Research topics thoroughly." },
  { name: "writer", preamble: "Write engaging content." },
  { name: "editor", preamble: "Edit and polish content." },
]);

const article = await rig.executeCouncil(councilId, "Write an article about AI agents");
```

---

## Building Rig Service

### Prerequisites

- Rust 1.70+
- Cargo

### Build

```bash
cd rig-service

# Debug build
cargo build

# Release build (optimized)
cargo build --release

# Run
cargo run
```

### Cross-Platform

```bash
# Linux/macOS
cargo build --release

# Windows (MSVC)
cargo build --release

# Cross-compile for Linux from macOS
cargo install cross
cross build --release --target x86_64-unknown-linux-gnu
```

---

## Troubleshooting

### Rig Service Won't Start

```bash
# Check if port is in use
lsof -i :8080

# Check logs
RUST_LOG=debug cargo run
```

### Connection Issues

```typescript
// Test connection
const rig = initRigClient("127.0.0.1", 8080);
const healthy = await rig.health();
console.log("Rig healthy:", healthy);
```

### Vector Store Issues

```bash
# Reset database
rm rig-store.db

# Check document count via API
curl http://127.0.0.1:8080/api/documents
```

---

## Performance

| Metric | QwenClaw (TS) | Rig (Rust) |
|--------|---------------|------------|
| Startup | ~2-3s | ~0.5s |
| Memory | ~200MB | ~50MB |
| Tool Lookup | O(n) | O(log n) |
| Concurrent | Event loop | Native threads |

---

## Next Steps

1. **Start Rig Service**: `cd rig-service && cargo run`
2. **Initialize Client**: `initRigClient()` in your code
3. **Create Agents**: Define specialized agents for tasks
4. **Use Councils**: Orchestrate multi-agent workflows
5. **Add RAG**: Store and search documents semantically

---

## Resources

- **Rig GitHub**: https://github.com/0xPlaygrounds/rig
- **Rig Docs**: https://docs.rig.rs
- **QwenClaw Repo**: https://github.rommark.dev/admin/QwenClaw-with-Auth

---

## License

MIT - Same as QwenClaw
