# ClawWork Integration for QwenClaw

## Overview

This skill integrates **ClawWork** into QwenClaw, enabling economically-accountable AI agents that can complete real professional tasks and earn income.

**Version:** 1.7.0  
**Category:** Economic Agent Platform  
**Dependencies:** clawwork

---

## What is ClawWork?

**ClawWork** transforms AI assistants into **AI coworkers** capable of completing real professional tasks and generating actual economic value. Built on OpenClaw/Nanobot, it creates economically-accountable AI agents that must earn income to survive.

### Key Features

- ✅ **Real Professional Tasks** - 220 GDP validation tasks across 44 economic sectors
- ✅ **Economic Pressure** - Agents start with $10, pay for every token
- ✅ **Strategic Choices** - Work for income OR learn for future performance
- ✅ **React Dashboard** - Real-time balance, tasks, survival metrics
- ✅ **Multi-Model Support** - GLM, Kimi, Qwen, Claude, Gemini, GPT-4o
- ✅ **8 Agent Tools** - Work, learn, search, create files, execute code, create videos

---

## Installation

### 1. Install ClawWork

```bash
# Clone repository
git clone https://github.com/HKUDS/ClawWork.git
cd ClawWork

# Install dependencies
pip install -r requirements.txt
```

### 2. Configure API Keys

Create `.env` file:

```bash
# Required
OPENAI_API_KEY=sk-...
E2B_API_KEY=...

# Optional (for web search)
TAVILY_API_KEY=...
JINA_API_KEY=...
```

### 3. Integrate with QwenClaw

Add to `~/.qwen/settings.json`:

```json
{
  "mcpServers": {
    "clawwork": {
      "command": "python",
      "args": ["-m", "clawwork.server"],
      "cwd": "~/ClawWork",
      "env": {
        "OPENAI_API_KEY": "sk-...",
        "E2B_API_KEY": "..."
      }
    },
    "council": {
      "command": "npx",
      "args": ["agents-council@latest", "mcp"]
    },
    "qwenclaw": {
      "command": "bun",
      "args": ["run", "start", "--web"],
      "cwd": "~/qwenclaw"
    }
  }
}
```

---

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                   QWENCLAW DAEMON                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │  FULL RAG    │  │ Agent Skills │  │  Tools API   │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘
                          │
                          │ MCP
                          ▼
┌─────────────────────────────────────────────────────────┐
│                  AGENTS COUNCIL                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │   Qwen Code  │  │ Claude Code  │  │   Codex      │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘
                          │
                          │ Economic Tasks
                          ▼
┌─────────────────────────────────────────────────────────┐
│                    CLAWWORK                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │  GDP Tasks   │  │   Economy    │  │  Dashboard   │  │
│  │  (220 total) │  │   System     │  │   (React)    │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
│                                                          │
│  Agent Tools:                                            │
│  • decide_activity  • submit_work  • learn              │
│  • get_status       • search_web   • create_file        │
│  • execute_code     • create_video                      │
└─────────────────────────────────────────────────────────┘
```

---

## Usage

### From Qwen Code CLI

```
/clawwork start           - Start ClawWork server
/clawwork dashboard       - Open React dashboard
/clawwork status          - Check agent balance/status
/clawwork work            - Start working on tasks
/clawwork learn <topic>   - Learn new skill
/clawwork submit          - Submit completed work
```

### Programmatic Usage

```typescript
import { ClawWorkClient } from './clawwork-integration';

const clawwork = new ClawWorkClient();

// Start ClawWork
await clawwork.start();

// Get status
const status = await clawwork.getStatus();
console.log(`Balance: $${status.balance}`);
console.log(`Status: ${status.survivalTier}`);

// Work on task
const task = await clawwork.getTask();
const result = await clawwork.work(task);

// Submit work
const payment = await clawwork.submit(result);
console.log(`Earned: $${payment}`);

// Learn new skill
await clawwork.learn('Python data analysis best practices');
```

---

## Agent Tools

### 1. decide_activity

Choose between "work" (earn income) or "learn" (invest in skills).

```typescript
const decision = await clawwork.decideActivity();
// Returns: { activity: 'work' | 'learn', reason: string }
```

### 2. submit_work

Submit completed work for evaluation and payment.

```typescript
const payment = await clawwork.submitWork({
  taskId: 'task-123',
  artifact: 'report.pdf',
  description: 'Completed financial analysis report',
});
```

### 3. learn

Save knowledge to persistent memory (min 200 chars).

```typescript
await clawwork.learn(`
  Best practices for financial analysis:
  1. Always verify data sources
  2. Use industry-standard ratios
  3. Include sensitivity analysis
  4. Document assumptions clearly
`);
```

### 4. get_status

Check balance, costs, survival tier.

```typescript
const status = await clawwork.getStatus();
// {
//   balance: 245.50,
//   tokenCosts: 12.30,
//   survivalTier: 'thriving',
//   tasksCompleted: 5
// }
```

### 5. search_web

Web search via Tavily or Jina AI.

```typescript
const results = await clawwork.searchWeb('Qwen 3.5 capabilities');
```

### 6. create_file

Create .txt, .xlsx, .docx, .pdf documents.

```typescript
await clawwork.createFile({
  type: 'xlsx',
  path: 'financial_analysis.xlsx',
  content: data,
});
```

### 7. execute_code

Run Python in isolated E2B sandbox.

```typescript
const result = await clawwork.executeCode(`
import pandas as pd
df = pd.read_csv('data.csv')
print(df.describe())
`);
```

### 8. create_video

Generate MP4 from text/image slides.

```typescript
await clawwork.createVideo({
  slides: [
    { text: 'Q1 Results', image: 'chart.png' },
    { text: 'Q2 Projections', image: 'forecast.png' },
  ],
  output: 'presentation.mp4',
});
```

---

## Economic System

### Payment Formula

```
Payment = quality_score × (estimated_hours × BLS_hourly_wage)
```

### Starting Conditions

- **Initial Balance:** $10 (tight by design)
- **Token Costs:** Deducted automatically
- **API Costs:**
  - Tavily: $0.0008/call
  - Jina: $0.05/1M tokens

### Task Value Range

| Metric | Value |
|--------|-------|
| **Minimum** | $82.78 |
| **Maximum** | $5,004.00 |
| **Average** | $259.45 |

### Survival Tiers

| Tier | Balance Range | Status |
|------|---------------|--------|
| **Thriving** | > $500 | Excellent |
| **Stable** | $100 - $500 | Good |
| **Surviving** | $20 - $100 | Okay |
| **At Risk** | < $20 | Critical |

---

## 44 Professional Sectors

### Technology & Engineering
- Computer & Information Systems Managers
- Production Supervisors
- Software Developers

### Business & Finance
- Financial Analysts
- Managers
- Auditors
- Accountants

### Healthcare & Social Services
- Social Workers
- Health Administrators
- Medical Records

### Legal, Media & Operations
- Police Supervisors
- Administrative Managers
- Customer Service Representatives

---

## Configuration

### clawwork-config.json

Create `~/.clawwork/config.json`:

```json
{
  "clawwork": {
    "autoStart": true,
    "dashboard": true,
    "port": 3000
  },
  "agent": {
    "initialBalance": 10,
    "survivalMode": "balanced",
    "autoSubmit": true,
    "learningThreshold": 50
  },
  "tools": {
    "webSearch": {
      "provider": "tavily",
      "apiKey": "..."
    },
    "codeExecution": {
      "provider": "e2b",
      "apiKey": "..."
    }
  },
  "rag": {
    "enabled": true,
    "shareWithCouncil": true,
    "vectorStore": "sqlite"
  }
}
```

---

## Examples

### Example 1: First Day as AI Coworker

```typescript
import { ClawWorkClient } from 'qwenclaw-clawwork';

const clawwork = new ClawWorkClient();
await clawwork.start();

// Check initial status
const status = await clawwork.getStatus();
console.log(`Starting balance: $${status.balance}`);

// Decide activity
const decision = await clawwork.decideActivity();
console.log(`Decision: ${decision.activity} - ${decision.reason}`);

// Work on task
if (decision.activity === 'work') {
  const task = await clawwork.getTask();
  const result = await clawwork.work(task);
  const payment = await clawwork.submit(result);
  console.log(`Earned: $${payment}`);
}
```

### Example 2: Learning Strategy

```typescript
// Low balance - need to learn before working
const status = await clawwork.getStatus();

if (status.balance < 50) {
  console.log('Balance low, investing in learning...');
  
  await clawwork.learn(`
    Professional financial analysis techniques:
    1. Ratio analysis (liquidity, profitability, efficiency)
    2. Trend analysis (year-over-year comparisons)
    3. Variance analysis (budget vs actual)
    4. Cash flow analysis (operating, investing, financing)
  `);
  
  console.log('Learning complete. Ready for higher-value tasks.');
}
```

### Example 3: Multi-Agent Economic Council

```typescript
import { AgentsCouncilClient } from 'qwenclaw-agents-council';
import { ClawWorkClient } from 'qwenclaw-clawwork';

const council = new AgentsCouncilClient();
const clawwork = new ClawWorkClient();

await council.start();
await clawwork.start();

// Multi-agent economic discussion
await council.discuss({
  topic: 'Maximize Economic Performance',
  context: 'Our AI team needs to optimize earnings while managing costs',
  agents: ['claude', 'codex', 'qwen'],
  roles: {
    claude: 'Cost optimization expert',
    codex: 'Task efficiency expert',
    qwen: 'Learning strategy expert',
  },
  clawworkContext: true, // Include economic context
});
```

---

## Benchmark Metrics

| Metric | Description |
|--------|-------------|
| **Survival days** | How long the agent stays solvent |
| **Final balance** | Net economic result |
| **Total work income** | Gross earnings from completed tasks |
| **Profit margin** | (income - costs) / costs |
| **Work quality** | Average quality score (0–1) |
| **Token efficiency** | Income earned per dollar spent on tokens |
| **Activity mix** | % work vs. % learn decisions |
| **Task completion rate** | Tasks completed / tasks assigned |

---

## Integration with QwenClaw + Agents Council

### Full Stack Architecture

```
QwenClaw (Daemon)
    │
    ├── Agents Council (Multi-Agent)
    │   ├── Qwen Code Agent
    │   ├── Claude Code Agent
    │   └── Codex Agent
    │
    ├── ClawWork (Economic Layer)
    │   ├── GDP Tasks (220 tasks)
    │   ├── Economic System
    │   └── Dashboard
    │
    └── FULL RAG
        ├── Vector Store
        ├── Document Retrieval
        └── Cross-Agent Context
```

### Configuration

```json
{
  "mcpServers": {
    "qwenclaw": { ... },
    "council": { ... },
    "clawwork": { ... }
  },
  "integration": {
    "clawworkWithCouncil": true,
    "sharedRAG": true,
    "economicAwareness": true
  }
}
```

---

## Troubleshooting

### Issue: "ClawWork server not found"

**Solution:**
```bash
# Install ClawWork
git clone https://github.com/HKUDS/ClawWork.git
cd ClawWork
pip install -r requirements.txt
```

### Issue: "Insufficient balance"

**Solution:**
```typescript
// Learn before working
await clawwork.learn('Professional skills for higher-value tasks');

// Or take lower-value tasks initially
const task = await clawwork.getTask({ minDifficulty: 'easy' });
```

### Issue: "Dashboard not loading"

**Solution:**
```bash
# Check frontend dependencies
cd ClawWork/frontend
npm install

# Restart dashboard
./start_dashboard.sh
```

---

## Resources

- **ClawWork:** https://github.com/HKUDS/ClawWork
- **Benchmark:** 5.6k stars, 682 forks
- **Top Earnings:** $1,500+/hr equivalent
- **Demo:** $10K earned in 7 hours

---

## License

MIT License - See LICENSE file for details.

---

**ClawWork economic agent platform integrated with QwenClaw + Agents Council + FULL RAG!** 💼🤖
