Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build & Run Commands

```bash
npm install # Install dependencies
npm run build # Full build (main TypeScript + visualizer)
npm run build:main # Build queue processor & channels only (tsc)
npm run build:visualizer # Build team visualizer only (separate tsconfig)

./tinyclaw.sh start # Launch tmux session with all components
./tinyclaw.sh stop # Kill tmux session and cleanup
./tinyclaw.sh restart # Stop and start
./tinyclaw.sh status # Show running processes

./tinyclaw.sh logs all # Tail all logs (also: queue, discord, telegram, whatsapp)
```

Run individual components directly:
```bash
npm run queue # Queue processor only
npm run discord # Discord client only
npm run telegram # Telegram client only
npm run whatsapp # WhatsApp client only
npm run visualize # Team visualizer TUI
```

No test suite exists yet. Verify changes by building (`npm run build`) and running locally (`./tinyclaw.sh start`).

## Architecture

TinyClaw is a multi-agent, multi-channel AI assistant platform that runs 24/7 via tmux. Messages flow through a **file-based queue system** (no database):

```
Channel Clients (Discord/Telegram/WhatsApp)
→ ~/.tinyclaw/queue/incoming/ (JSON message files)
→ Queue Processor (routing + invocation)
→ ~/.tinyclaw/queue/outgoing/ (response files)
→ Channel Clients deliver response
```

### Two Language Layers

- **TypeScript (`src/`)**: Core runtime — queue processor, channel clients, routing, agent invocation, team visualizer
- **Bash (`lib/`)**: CLI and daemon management — startup/shutdown, setup wizard, agent/team CRUD commands, heartbeat cron

The main CLI entry point is `tinyclaw.sh` which loads bash libraries from `lib/` and dispatches commands. The TypeScript runtime compiles to `dist/` (ES2020, CommonJS).

### Key TypeScript Files

| File | Role |
|------|------|
| `src/queue-processor.ts` | Main loop — polls incoming queue, routes messages, tracks conversations, aggregates team responses |
| `src/lib/routing.ts` | Parses `@agent_id` prefixes and `[@teammate: message]` mention tags |
| `src/lib/invoke.ts` | Spawns Claude/Codex/OpenCode CLI processes per agent |
| `src/lib/config.ts` | Loads `~/.tinyclaw/settings.json`, resolves model names |
| `src/lib/types.ts` | All TypeScript interfaces (AgentConfig, TeamConfig, MessageData, Conversation) |
| `src/channels/*-client.ts` | Channel integrations — read outgoing queue, write to incoming queue |
| `src/visualizer/team-visualizer.ts` | React + Ink TUI dashboard for team collaboration |

### Key Bash Files

| File | Role |
|------|------|
| `lib/daemon.sh` | tmux session management, pane layout, process lifecycle |
| `lib/agents.sh` | Agent CRUD (add, remove, reset, list, provider switch) |
| `lib/teams.sh` | Team CRUD and visualization |
| `lib/messaging.sh` | CLI `send` command, log viewing |
| `lib/setup-wizard.sh` | First-run interactive configuration |
| `lib/common.sh` | Shared utilities, channel registry, settings loading |

### Core Design Patterns

- **Agent isolation**: Each agent has its own workspace directory (`~/tinyclaw-workspace/{agent_id}/`) with independent `.claude/` config and conversation history
- **Parallel-per-agent, sequential-per-conversation**: Different agents process concurrently; messages to the same agent are serialized
- **Actor model for teams**: Agents communicate via `[@agent_id: message]` tags parsed from responses, spawning new queue messages. No central orchestrator
- **Atomic file operations**: Queue uses filesystem move operations to prevent race conditions and message loss
- **Three-state queue**: `incoming/` → `processing/` → `outgoing/`, with recovery for orphaned files

### Runtime Data

All runtime state lives under `~/.tinyclaw/` (overridable via `TINYCLAW_HOME`):
- `settings.json` — agents, teams, channels, models config
- `pairing.json` — sender allowlist state
- `queue/{incoming,processing,outgoing}/` — message pipeline
- `logs/` — per-component log files
- `chats/` — team conversation history
- `events/` — real-time event files for visualizer

### AI Provider Support

Three providers with CLI-based invocation: Anthropic Claude (`claude`), OpenAI Codex (`codex`), and OpenCode (`opencode`). Model aliases are resolved in `src/lib/config.ts` (e.g., `sonnet` → `claude-sonnet-4-5`, `opus` → `claude-opus-4-6`). Each agent can use a different provider/model.

### Visualizer

The team visualizer (`src/visualizer/`) is a separate TypeScript build target (`tsconfig.visualizer.json`) that outputs ESM. It uses React + Ink for a terminal UI showing real-time team collaboration.
167 changes: 167 additions & 0 deletions docs/bug-fixes/PATCHES-README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# TinyClaw Bug Fix Patches

This directory contains patches to fix three critical bugs in tinyClaw.

## Bug Summary

| Bug | Description | Severity | Files Affected |
|-----|-------------|----------|----------------|
| **Bug 1** | Channel clients (Telegram/Discord/WhatsApp) randomly fail to return responses due to non-atomic send-then-ack flow | Critical | `db.ts`, `telegram-client.ts`, `discord-client.ts`, `whatsapp-client.ts`, `server/index.ts` |
| **Bug 2** | Inter-agent mentions fail silently due to validation issues (case sensitivity, typos, cross-team) | High | `routing.ts` |
| **Bug 3** | Multi-agent conversations lose replies due to race condition on `conv.pending` counter | Critical | `conversation.ts`, `queue-processor.ts` |

## Patch Files

```
patches/
├── README.md # This file
├── bug1-db.patch # Database changes for delivering status
├── bug1-telegram.patch # Telegram client fix (claim-before-send pattern)
├── bug2-routing.patch # Routing improvements (logging, case-insensitive matching)
├── bug3-conversation.patch # Conversation locking mechanism
├── bug3-queue-processor.patch # Queue processor integration with locking
└── server-api.patch # New API endpoints for claim/unclaim
```

## Installation Order

Apply patches in this order to avoid conflicts:

### Phase 1: Database and Core Infrastructure

```bash
# 1. Database changes (adds 'delivering' status)
patch -p1 < patches/bug1-db.patch

# 2. Server API endpoints (claim/unclaim)
patch -p1 < patches/server-api.patch
```

### Phase 2: Core Logic Fixes

```bash
# 3. Conversation locking mechanism
patch -p1 < patches/bug3-conversation.patch

# 4. Queue processor integration
patch -p1 < patches/bug3-queue-processor.patch

# 5. Routing improvements (logging, case-insensitive matching)
patch -p1 < patches/bug2-routing.patch
```

### Phase 3: Channel Clients

```bash
# 6. Telegram client (as proof of concept)
patch -p1 < patches/bug1-telegram.patch

# Note: Discord and WhatsApp clients need similar fixes
# Apply the same pattern from bug1-telegram.patch to:
# - src/channels/discord-client.ts
# - src/channels/whatsapp-client.ts
```

## Manual Application (If Patches Fail)

If `patch` command fails due to line number differences, apply changes manually by referencing the solution document:

1. See `/mnt/okcomputer/output/tinyclaw-bug-solutions.md` for detailed code changes
2. Copy the relevant sections into your files
3. Ensure all imports are updated

## Verification

After applying patches, verify the fixes:

### Bug 1 Verification

```bash
# Check that the delivering status exists in the database
sqlite3 .tinyclaw/tinyclaw.db ".schema responses"
# Should show: status TEXT CHECK(status IN ('pending', 'delivering', 'acked'))
```

### Bug 2 Verification

```bash
# Check logs for mention validation messages
tail -f .tinyclaw/logs/queue.log | grep -i "mention"
# Should see: "Valid mention: @agent1 → @agent2" or "Invalid mention ..."
```

### Bug 3 Verification

```bash
# Check for race condition debug messages
tail -f .tinyclaw/logs/queue.log | grep -i "pending"
# Should see: "Conversation X: pending incremented to N" and "decremented to N"
```

## Rollback

If you need to rollback, restore from git:

```bash
git checkout -- src/lib/db.ts
git checkout -- src/lib/routing.ts
git checkout -- src/lib/conversation.ts
git checkout -- src/queue-processor.ts
git checkout -- src/channels/telegram-client.ts
# ... restore other modified files
```

## Testing Recommendations

### Test Bug 1 Fix

1. Send a message through Telegram
2. Verify response is received
3. Simulate network failure (if possible)
4. Verify no duplicate responses are sent

### Test Bug 2 Fix

1. Configure a team with multiple agents
2. Send message with mixed-case mention: `[@Coder: help]` where agent ID is `coder`
3. Check logs for validation messages
4. Verify mentioned agent is activated

### Test Bug 3 Fix

1. Configure a team with 2+ agents
2. Send message: `[@agent1,agent2: task]`
3. Both agents should respond
4. Final aggregated response should be sent to user

## Additional Notes

### Discord/WhatsApp Client Fixes

The same pattern from `bug1-telegram.patch` should be applied to:

- `src/channels/discord-client.ts` (lines ~369-455)
- `src/channels/whatsapp-client.ts` (lines ~369-445)

Key changes needed:
1. Add `inFlightResponses` tracking Set
2. Add `deliveringResponses` Map for retry tracking
3. Claim response before sending
4. Track delivery attempts
5. Handle max retry exceeded

### Database Migration

The patches add a new column `delivering_at` to the responses table. For existing databases:

```sql
-- Run this if you get schema errors
ALTER TABLE responses ADD COLUMN delivering_at INTEGER;
```

## Support

For questions or issues with these patches:
1. Check the detailed solution document: `tinyclaw-bug-solutions.md`
2. Review the original bug investigation in the GitHub issue
3. Test changes in a development environment first
Loading