Metadata-Version: 2.4
Name: context-bus
Version: 0.1.1
Summary: Automatic model switching for AI coding agents with full context preservation
Author-email: Rajath KM <rajathkm@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/rajathkm/context-bus
Project-URL: Documentation, https://github.com/rajathkm/context-bus#readme
Project-URL: Repository, https://github.com/rajathkm/context-bus
Project-URL: Issues, https://github.com/rajathkm/context-bus/issues
Keywords: ai,llm,claude,codex,gemini,model-switching,context
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=6.0
Requires-Dist: click>=8.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Dynamic: license-file

# Context Bus

**Seamless multi-model orchestration for OpenClaw agents.**

Automatically switch between Claude Opus, Codex, and Gemini when you hit usage limits — without losing context. Your agent keeps working, you get notified, and everything Just Works™.

[![PyPI](https://img.shields.io/pypi/v/context-bus)](https://pypi.org/project/context-bus/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux-blue)]()

---

## What Is This?

Context Bus solves a common problem for AI power users:

> **You're deep in work with Claude Opus. You hit the usage limit. Now what?**

Without Context Bus:
- ❌ Switch to another model manually
- ❌ Re-explain everything to the new model
- ❌ Lose track of decisions and progress
- ❌ Waste time catching up

With Context Bus:
- ✅ Automatic switch when limits approach
- ✅ Full context preserved in shared files
- ✅ Get notified on Telegram/Discord/Slack
- ✅ Auto-switch back when limits reset

---

## Quick Start (OpenClaw Users)

### 1. Install

```bash
pip install context-bus
context-bus init
```

Or just tell your Clawdbot:
```
"Install Context Bus for automatic model switching"
```

### 2. That's It

The installer automatically:
- ✅ Creates shared context files (`AGENTS.md`, `MEMORY.md`)
- ✅ Adds usage monitoring rules to your `HEARTBEAT.md`
- ✅ Sets up a background monitor (every 10 minutes)
- ✅ Initializes state tracking (`~/.context-bus/handoff.json`)

Your Clawdbot will now:
1. Check usage on every heartbeat
2. Update the handoff file with current usage %
3. Auto-switch at 95% usage
4. Notify you when switching
5. Switch back when limits reset

---

## How It Works

### The Flow

```
┌─────────────────────────────────────────────────────────────┐
│                    YOUR CLAWDBOT                            │
│                                                             │
│  Heartbeat fires every ~30 min                              │
│       ↓                                                     │
│  Reads HEARTBEAT.md → sees Context Bus rules                │
│       ↓                                                     │
│  Runs session_status → "Usage: 87%"                         │
│       ↓                                                     │
│  Runs: ~/.context-bus/update-usage.sh 87                    │
│       ↓                                                     │
│  handoff.json updated: usage_percent = 87                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│               BACKGROUND MONITOR (every 10 min)             │
│                                                             │
│  Reads handoff.json → usage = 87%                           │
│  87% < 95% threshold → no action                            │
│                                                             │
│  [Next check: usage = 96%]                                  │
│  96% >= 95% → TRIGGER SWITCH                                │
│       ↓                                                     │
│  Update handoff.json: model = "codex"                       │
│  Send notification: "🔄 Switched to Codex (96%)"            │
│                                                             │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                     MODELS                                  │
│                                                             │
│   Opus (Primary) ←→ Codex (Secondary) ←→ Gemini (Tertiary) │
│                                                             │
│   All models read the same context files:                   │
│   • AGENTS.md — project context, current task               │
│   • MEMORY.md — long-term memory, decisions                 │
│   • handoff.json — structured state                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### Shared Context Files

All models read from the same files, so context is never lost:

**AGENTS.md** — Project context that every model sees:
```markdown
# AGENTS.md

## Project Context
Building a task management API with PostgreSQL.

## Current Task  
Implementing OAuth authentication.

## Key Constraints
- Use TypeScript
- Write tests for all endpoints
- Follow existing patterns

## Decisions Made
- JWT tokens with 1-hour expiry
- Refresh tokens in httpOnly cookies
```

**MEMORY.md** — Long-term memory across sessions:
```markdown
# MEMORY.md

## Lessons Learned
- Always run migrations before testing
- User prefers concise responses

## User Preferences
- TypeScript over JavaScript
- Prefers functional patterns
```

**handoff.json** — Machine-readable state:
```json
{
  "model": {
    "current": "codex",
    "previous": "opus",
    "usage_percent": 96,
    "switch_reason": "auto_threshold"
  },
  "task": {
    "description": "Implementing OAuth",
    "status": "in_progress"
  },
  "next_steps": ["Add token refresh", "Write tests"]
}
```

---

## Installation

### For OpenClaw/Clawdbot Users

```bash
pip install context-bus
context-bus init
```

The installer will:
1. Create `~/.context-bus/` with scripts and state
2. Create `~/.config/context-bus/config.yaml`
3. Add `AGENTS.md` and `MEMORY.md` to your workspace (if they don't exist)
4. **Augment** your `HEARTBEAT.md` with usage monitoring rules (won't overwrite existing content)
5. Set up background monitor (launchd on macOS, cron on Linux)

### For Other Agents (Claude Code, Cursor, etc.)

```bash
pip install context-bus
context-bus init
```

Then add to your agent's system prompt:
```
Before starting work, read AGENTS.md and MEMORY.md for context.
After significant work, update these files.
Periodically check ~/.context-bus/handoff.json for model state.
```

---

## Configuration

Edit `~/.config/context-bus/config.yaml`:

```yaml
# Models
models:
  primary: opus        # Your main model
  secondary: codex     # Fallback when primary hits limits
  tertiary: gemini     # Optional third fallback

# Thresholds
thresholds:
  switch_to_secondary: 95    # Switch at 95% usage
  switch_back: 50            # Switch back when usage drops below 50%

# Notifications
notifications:
  enabled: true
  channel: telegram          # telegram | discord | slack | none
  telegram:
    chat_id: "YOUR_CHAT_ID"  # Get from @userinfobot on Telegram
```

---

## CLI Commands

```bash
# Initialize in a workspace
context-bus init

# Check current status
context-bus status

# Manual model switching
context-bus switch codex
context-bus switch opus

# View/edit configuration
context-bus config --show
context-bus config --edit
```

---

## What Gets Installed

```
~/.context-bus/
├── handoff.json           # Current state (model, usage, task)
├── rolling-summary.md     # Human-readable session summary
├── usage-monitor.sh       # Background monitor script
├── update-usage.sh        # Update usage percentage
├── context-handoff.sh     # Generate handoff for model switch
└── monitor.log            # Monitor logs

~/.config/context-bus/
└── config.yaml            # Your configuration

~/your-workspace/
├── AGENTS.md              # Shared project context
├── MEMORY.md              # Long-term memory
└── HEARTBEAT.md           # + Context Bus monitoring rules
```

---

## Safety Features

Context Bus includes safeguards to prevent issues:

| Feature | What It Does |
|---------|--------------|
| **Safe augment** | Never overwrites existing files, only adds to them |
| **Task check** | Won't switch back to primary if a task is in progress |
| **Cooldown** | Minimum 5 minutes between switches |
| **Notifications** | Always notifies you when switching |

---

## Notifications

### Telegram (Recommended for OpenClaw)

1. Message [@userinfobot](https://t.me/userinfobot) to get your chat ID
2. Add to config:
```yaml
notifications:
  channel: telegram
  telegram:
    chat_id: "123456789"
```

You'll get messages like:
```
🔄 [Context Bus] Opus → Codex
   Usage: 96%
   Context preserved ✓

🔄 [Context Bus] Codex → Opus  
   Limits reset (usage: 12%)
   Welcome back!
```

### Discord

```yaml
notifications:
  channel: discord
  discord:
    webhook_url: "https://discord.com/api/webhooks/..."
```

### Slack

```yaml
notifications:
  channel: slack
  slack:
    webhook_url: "https://hooks.slack.com/services/..."
```

---

## Troubleshooting

### Auto-switch didn't trigger

**Cause:** Usage wasn't being updated in handoff.json

**Fix:** Ensure your HEARTBEAT.md has the Context Bus rules. Check:
```bash
grep "Context Bus" ~/your-workspace/HEARTBEAT.md
```

If missing, re-run `context-bus init` or manually add the rules.

### Notifications not sending

**Fix:** Verify your chat ID:
```bash
cat ~/.config/context-bus/config.yaml | grep chat_id
```

### Check monitor status

```bash
# macOS
launchctl list | grep contextbus

# View logs
tail -20 ~/.context-bus/monitor.log
```

---

## Uninstall

```bash
pip uninstall context-bus

# Remove files
rm -rf ~/.context-bus ~/.config/context-bus

# macOS: remove launchd job
launchctl unload ~/Library/LaunchAgents/com.contextbus.monitor.plist
rm ~/Library/LaunchAgents/com.contextbus.monitor.plist
```

---

## Links

- **PyPI:** https://pypi.org/project/context-bus/
- **GitHub:** https://github.com/rajathkm/context-bus
- **Issues:** https://github.com/rajathkm/context-bus/issues
- **OpenClaw:** https://github.com/openclaw/openclaw

---

## License

MIT License - see [LICENSE](LICENSE)

---

## Contributing

Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md)
