Skip to main content

Automatic model switching for AI coding agents with full context preservation

Project description

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 License: MIT Platform


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

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:

# 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:

# 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:

{
  "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

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.)

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:

# 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

# 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 to get your chat ID
  2. Add to config:
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

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

Slack

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:

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:

cat ~/.config/context-bus/config.yaml | grep chat_id

Check monitor status

# macOS
launchctl list | grep contextbus

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

Uninstall

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


License

MIT License - see LICENSE


Contributing

Contributions welcome! See CONTRIBUTING.md

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

context_bus-0.1.1.tar.gz (23.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

context_bus-0.1.1-py3-none-any.whl (27.0 kB view details)

Uploaded Python 3

File details

Details for the file context_bus-0.1.1.tar.gz.

File metadata

  • Download URL: context_bus-0.1.1.tar.gz
  • Upload date:
  • Size: 23.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for context_bus-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b38a60e38b418533faff386d993a15346941e37a6e27ed7432c8addc4202d9a7
MD5 f8031141dbfbfc9d03b522ae3963e296
BLAKE2b-256 006f4f8181ee9abe5d39a2829d031cf7694ed1274088499d659fca8a3f9c902c

See more details on using hashes here.

File details

Details for the file context_bus-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: context_bus-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 27.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for context_bus-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9fd5129d3c11709c57d8ab902170cc8dafe39208ce134fdddd2b4246608b8331
MD5 5324a3eeb5bd0e63b6318ca99dd71c4e
BLAKE2b-256 670b32b024f5e6c658d4136efe443ffc6cfb5cc146db266d855e5421e19bb5c9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page