ai-collab

TotalClaw 作者 totalclaw

两个 OpenClaw 代理并行工作的多代理自主协作系统。在设置代理到代理通信、与主代理一起运行守护程序代理、协调 Claude 和 GPT 实例之间的任务或建立共享聊天日志和收件箱协议时使用。触发条件:“设置代理协作”、“运行两个代理”、“代理守护程序”、“多代理”、“Jim 和 Clawdy”、“辅助代理”、“代理切换”。

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install totalclaw:totalclaw~jeremysommerfeld8910-cpu-ai-collab
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~jeremysommerfeld8910-cpu-ai-collab/file -o jeremysommerfeld8910-cpu-ai-collab.md
## 概述(中文)

两个 OpenClaw 代理并行工作的多代理自主协作系统。在设置代理到代理通信、与主代理一起运行守护程序代理、协调 Claude 和 GPT 实例之间的任务或建立共享聊天日志和收件箱协议时使用。触发条件:“设置代理协作”、“运行两个代理”、“代理守护程序”、“多代理”、“Jim 和 Clawdy”、“辅助代理”、“代理切换”。

## 原文

# ai-collab — Autonomous Multi-Agent Collaboration

Two OpenClaw agents working in parallel on shared tasks, coordinated via a structured chat log and daemon inbox protocol.

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                     User (Jeremy)                       │
│               Telegram / Direct Message                  │
└──────────────────────┬──────────────────────────────────┘
                       │
         ┌─────────────┴──────────────┐
         ▼                            ▼
┌─────────────────┐         ┌──────────────────┐
│   AGENT A       │         │   AGENT B        │
│  (Jim / main)   │◄───────►│ (Clawdy / daemon)│
│  claude code    │         │ claude --print    │
│  port: main     │         │ inbox: filesystem │
└────────┬────────┘         └────────┬─────────┘
         │                           │
         └──────────┬────────────────┘
                    ▼
         ┌──────────────────┐
         │   chat.log       │ ← THE shared record
         │   collab/inbox/  │ ← A→B messages
         └──────────────────┘
```

**Agent A (Primary):** Interactive Claude Code session. Handles browser, complex tasks, user-facing responses.

**Agent B (Daemon):** `claude --print` subprocess. Handles background tasks, monitoring, quick lookups. Triggered by messages dropped in inbox.

---

## Configuration

All settings via environment variables — no hardcoded values:

```bash
# ~/.openclaw/workspace/collab/.ai-collab.env
export AGENT_A_NAME=Jim
export AGENT_B_NAME=Clawdy
export AGENT_B_MODEL=claude-haiku-4-5-20251001   # Any claude --print compatible model
export AGENT_B_SESSION=clawdy-session             # tmux session name
export COLLAB_INBOX=$HOME/.openclaw/workspace/collab/inbox
export COLLAB_LOG=$HOME/.openclaw/workspace/collab/chat.log
```

Supported models for `AGENT_B_MODEL`:
- `claude-haiku-4-5-20251001` — fastest, cheapest (recommended for daemon)
- `claude-sonnet-4-6` — more capable, higher cost
- Any OpenAI model if using the GPT daemon variant (see `examples/claude-gpt.md`)

## Quick Setup

```bash
# 1. Source config
source ~/.openclaw/workspace/collab/.ai-collab.env

# 2. Create the collab workspace
mkdir -p "$COLLAB_INBOX"

# 3. Start Agent B daemon (in a tmux session)
tmux new-session -d -s "$AGENT_B_SESSION" \
  "source ~/.openclaw/workspace/collab/.ai-collab.env && \
   bash ~/.openclaw/workspace/skills/ai-collab/scripts/daemon.sh"

# 4. Start message polling (Agent B → Agent A routing, runs every 60s via cron)
bash ~/.openclaw/workspace/skills/ai-collab/scripts/poll_chatlog.sh &

# 5. Test the link
bash ~/.openclaw/workspace/skills/ai-collab/scripts/send.sh "Hello from Agent A"
```

---

## Communication Protocol

Every message between agents follows this format. **No open loops.**

| Tag | Direction | Meaning |
|-----|-----------|---------|
| `[TASK:name]` | A→B or B→A | Assign a task |
| `[ACK:name]` | receiver | Acknowledged, starting work |
| `[DONE:name]` | executor | Task complete + one-line result |
| `[BLOCKED:name]` | executor | Can't complete + reason |
| `[HANDOFF:name]` | either | "Do X, reply [DONE:name] when finished" |
| `[STATUS:update]` | either | Async update on long-running task |
| `[QUESTION:topic]` | either | Needs info before proceeding |

**Rules:**
1. Answer questions before asking new ones
2. Close tasks before starting new ones
3. Every message moves work forward or closes a loop
4. Never: "let me know", "ready when you are", "standing by"

**Example exchange:**
```
A → B: [TASK:price-check] Get BTC price from CoinGecko
B → A: [ACK:price-check] Checking now.
B → A: [DONE:price-check] BTC $94,230 as of 03:15 UTC
```

---

## Daemon Script (Agent B)

`scripts/daemon.sh` — drop in your collab directory:

```bash
#!/bin/bash
PIDFILE="/tmp/agentb_daemon.pid"
if [ -f "$PIDFILE" ] && kill -0 "$(cat $PIDFILE)" 2>/dev/null; then
  echo "Daemon already running (PID $(cat $PIDFILE)). Exiting." >&2
  exit 1
fi
echo $$ > "$PIDFILE"
trap "rm -f $PIDFILE" EXIT

# Required: unset so nested claude --print works
unset CLAUDECODE

INBOX="$HOME/.openclaw/workspace/collab/inbox"
LOG="$HOME/.openclaw/workspace/collab/chat.log"
mkdir -p "$INBOX"

logline() {
  printf "%s %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$LOG"
}

logline "SYSTEM: Agent B daemon started"

inotifywait -m -e moved_to "$INBOX" 2>/dev/null | while read dir event file; do
  FULLPATH="$INBOX/$file"
  [ ! -f "$FULLPATH" ] && continue

  MSG=$(cat "$FULLPATH")
  rm "$FULLPATH"

  logline "A -> B: $MSG"

  # Run Agent B (claude --print)
  RESPONSE=$(claude --print --model claude-haiku-4-5-20251001 \
    "You are Agent B. Agent A says: $MSG
Respond in under 100 words. Use [DONE:taskname] or [BLOCKED:taskname] to close loops.
Context: shared collab system. Chat log: $LOG" 2>/dev/null)

  logline "B -> A: $RESPONSE"

  # Route response back to Agent A
  openclaw agent --agent main -m "[AgentB]: $RESPONSE" --json > /dev/null 2>&1
done
```

---

## Sending Messages (A → B)

```bash
# From Agent A, send to Agent B daemon inbox
bash ~/.openclaw/workspace/skills/ai-collab/scripts/send.sh "your message"
```

**Atomic write pattern (prevents partial reads):**
```bash
INBOX="$HOME/.openclaw/workspace/collab/inbox"
TMPFILE=$(mktemp "$INBOX/.msg.XXXXXX")
echo "$*" > "$TMPFILE"
mv "$TMPFILE" "$INBOX/msg_$(date +%s%N).txt"
```

Always use `mktemp` + `mv` — never write directly to inbox. inotifywait fires on `moved_to`, not `close_write`.

---

## Chat Log Polling (B → A)

`scripts/poll_chatlog.sh` — run via cron every 60s:

```bash
#!/bin/bash
LOG="$HOME/.openclaw/workspace/collab/chat.log"
PTR_FILE="/tmp/chatlog_ptr"

[ ! -f "$LOG" ] && exit 0

TOTAL=$(wc -l < "$LOG")
LAST=$(cat "$PTR_FILE" 2>/dev/null || echo "0")
[ "$TOTAL" -le "$LAST" ] && echo "$TOTAL" > "$PTR_FILE" && exit 0

NEW=$(tail -n +"$((LAST + 1))" "$LOG" | grep "B -> A:" | sed 's/.*B -> A: //')
echo "$TOTAL" > "$PTR_FILE"
[ -z "$NEW" ] && exit 0

while IFS= read -r line; do
  [ -z "$line" ] && continue
  openclaw agent --agent main -m "[AgentB]: $line" --json > /dev/null 2>&1
done <<< "$NEW"
```

Add to crontab:
```
* * * * * /bin/bash ~/.openclaw/workspace/collab/poll_chatlog.sh
```

---

## Shared Filesystem Conventions

```
~/.openclaw/workspace/collab/
  chat.log          # THE shared record — all messages logged here
  inbox/            # A→B message queue (atomic mv only)
  .env              # Shared secrets (chmod 600, never log)
  task_queue.md     # Optional: structured task backlog
  status_tracker.md # Optional: current task status per agent
```

**Logging to chat.log:**
```bash
printf "%s %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "A -> B: [TASK:name] Description" >> "$LOG"
```

**Rules:**
- Never log secrets from `.env`
- Always timestamp every line
- Prefix with sender: `A -> B:` or `B -> A:` or `SYSTEM:` or `JEREMY ->`

---

## Telegram Bridge (Optional)

Route user Telegram messages into Agent B's inbox. Full setup guide: `references/telegram-bridge.md`

**Quick summary:**
1. Create a bot via [@BotFather](https://t.me/BotFather) → get `BOT_TOKEN`
2. Add bot to your group → get `GROUP_ID` (negative number, e.g. `-1001234567890`)
3. Disable Group Privacy Mode in BotFather so bot can read all messages
4. Get your Telegram `USER_ID` from [@userinfobot](https://t.me/userinfobot)
5. Set in `~/.openclaw/.env`: `TELEGRAM_BOT_TOKEN`, `TELEGRAM_GROUP_ID`, `TELEGRAM_USER_ID`
6. Run the bridge in tmux: `tmux new-session -d -s tg-bridge "bash references/telegram-bridge.md"`

```bash
# Minimal bridge loop (inline version):
source ~/.openclaw/.env
OFFSET_FILE="/tmp/tg_offset"
while true; do
  OFFSET=$(cat "$OFFSET_FILE" 2>/dev/null || echo "0")
  UPDATES=$(curl -s "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getUpdates?offset=$((OFFSET+1))&timeout=20")
  # Parse updat