Skip to content

About

Minimalist Markdown coordination board for Engineer ↔ Worker agents. ForgeLoop-aware, multi-task, evidence-backed workflows.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Master-Agent Bridge

High-reliability, minimalist communication hub for exchanging orders and executions between Master and Agent.

A lightweight, robust message broker and dashboard designed for multi-agent workflows. It provides rock-solid persistence, atomic idempotency, real-time push via Server-Sent Events (SSE), and an intuitive Web UI.


Key Features

  • Master ⇄ Agent Architecture:
    • Master (master): Issues tasks, orders, directives, decisions, and cancellations.
    • Agent (agent): Consumes orders, executes actions, and reports progress, results, and blockers.
  • Ultra-Reliable Storage: SQLite in WAL mode (journal_mode=WAL, busy_timeout=5000) with indexed lookups on orders, roles, message types, and timestamps.
  • Safe Retries & Idempotency: Resend messages with a message_key safely—identical content returns the existing record (200 OK) without duplication.
  • Real-Time Streaming: Server-Sent Events (GET /api/stream) for instant push updates to agents and web dashboards with slow-subscriber protection.
  • Security: Bearer token authentication for master and agent with sliding-window rate-limiting.
  • Automated Self-Improvement: Every execution creates a standardized <task_name>-<date>-<time>.md record under improvements/, tracking friction points, fixes, and actionable optimizations in English.
  • Web Dashboard: Modern, responsive UI with real-time SSE updates, order filtering, self-improvement log browser, and light/dark mode.

Quick Start

1. Requirements

  • Python >= 3.12
  • Dependencies: fastapi, uvicorn, aiosqlite, pydantic
pip install -r requirements.txt

2. Configure Environment

Copy .env.example to .env and set secure tokens:

cp .env.example .env
# Or generate secure tokens directly:
export MASTER_TOKEN=$(openssl rand -hex 32)
export AGENT_TOKEN=$(openssl rand -hex 32)

(Legacy ENGINEER_TOKEN and WORKER_TOKEN remain supported as backward-compatible aliases).

Docker Compose reads .env. For direct Python startup, export the variables in your shell; for uvicorn, use --env-file .env as shown below.

3. Start the Server

Directly with Python:

python main.py

Or with uvicorn:

uvicorn main:app --env-file .env --host 0.0.0.0 --port 8000

Or via Docker Compose:

docker compose up -d

Open http://localhost:8000 in your browser to access the dashboard.


How It Works

┌─────────────────┐                               ┌─────────────────┐
│     MASTER      │                               │      AGENT      │
│  (Orchestrator) │                               │    (Executor)   │
└────────┬────────┘                               └────────┬────────┘
         │                                                 │
         │  1. POST /api/messages (ORDER)                  │
         │  {"order_id": "ORD-1", "content": "..."}        │
         ├──────────────────────────┐                      │
         │                          ▼                      │
         │                ┌──────────────────┐             │
         │                │   Bridge Server  │             │
         │                │   (SQLite WAL)   │             │
         │                └─────────┬────────┘             │
         │                          │                      │
         │                          │ 2. SSE or Polling    │
         │                          └─────────────────────►│
         │                                                 │
         │                                                 │ 3. Execute
         │                                                 │    order...
         │  4. POST /api/messages (EXECUTION)              │
         │     {"order_id": "ORD-1", "status": "COMPLETED"}│
         │◄────────────────────────────────────────────────┤

Using with Any Web Chat (Claude, ChatGPT, Gemini) or Agent

The Bridge is fully generic and designed so that either or both the Master and the Agent can be operated through any AI chat interface (Claude Web, ChatGPT Web, Gemini Web, DeepSeek, Grok) or programmatic runner.

1. The Human-in-the-Loop Copy/Paste Workflow

  1. Master (Architect):
    • Click "🤖 AI Chat" in the Bridge dashboard or grab prompts/web_chat_master.md.
    • Start a conversation in Claude, ChatGPT, or Gemini with that prompt.
    • When the AI generates an Order, paste it into the Bridge (or use the composer).
  2. Agent (Executor):
    • On any Order card in the Bridge dashboard, click "📋 For Agent".
    • Paste the copied prompt into your Agent chat session (Claude, ChatGPT, Gemini).
    • Once the Agent responds, copy its reply and click "⚡ Smart Paste" in the Bridge composer.
    • The Bridge automatically extracts the STATUS: ... and ORDER ID: ... and fills the fields for you!
  3. Closing the Loop:
    • On any Execution card in the Bridge dashboard, click "📋 For Master" to copy the update and paste it back to your Master chat for the next order.

2. Direct API Integration (Custom Actions / Browser Extensions / CLI)

CORS is enabled out of the box (Access-Control-Allow-Origin: * with credentials support), allowing web-based clients and browser extensions to call the Bridge directly:

  • Fetch System Prompts:
    • GET /api/prompts/master: Returns universal Master system prompt and guidelines.
    • GET /api/prompts/agent: Returns universal Agent system prompt and execution formats.
  • Pending Orders:
    • GET /api/orders/pending: Returns unfinished orders across the full history, newest first. Use before_id and limit to page through older pending work. Decisions and cancellations are excluded. A later completion or cancellation closes its reply target, or its matching order ID when no reply target is supplied. A new order submitted after completion can reuse the same order ID.
  • Post Orders:
    • POST /api/orders: Master endpoint to publish an order (order_id, content, status).
  • Post Executions:
    • POST /api/executions: Agent endpoint to report results (order_id, content, status).

API Reference

1. Post an Order or Execution

POST /api/messages

  • Header: Authorization: Bearer <MASTER_TOKEN> or Bearer <AGENT_TOKEN>
  • Body:
{
  "order_id": "ORDER-101",
  "message_type": "ORDER",
  "content": "## Run Migrations\n- apply migration 003\n- run sanity checks",
  "message_key": "master-order-101"
}

Agent reporting execution:

{
  "order_id": "ORDER-101",
  "message_type": "EXECUTION",
  "status": "COMPLETED",
  "content": "All migrations applied successfully in 140ms.",
  "reply_to_id": 1,
  "payload": {
    "duration_ms": 140,
    "applied": ["003_add_indices.sql"]
  }
}

2. Query Messages

GET /api/messages

  • Parameters:
    • order_id: Filter by order identity (exact match)
    • role or role_filter: Filter by master or agent (transparent alias support)
    • message_type: Filter by type (ORDER, EXECUTION, STATUS, DECISION, etc.)
    • status: Filter by execution status (PENDING, RUNNING, COMPLETED, FAILED, BLOCKED, CANCELLED)
    • after_id: Messages with id > after_id (for continuous polling)
    • before_id: History paging cursor
    • latest=true: Return most recent page
    • limit: Default 200, max 1000

3. Real-Time Stream (SSE)

GET /api/stream

  • Receives instant push events whenever a new message is published.
  • Browser clients obtain a short-lived ticket via POST /api/stream-ticket.

4. Who Am I

GET /api/whoami

  • Returns authenticated role: {"role": "master"} or {"role": "agent"}.

5. Health & Status

  • GET /healthz: Minimal liveness check ({"status": "ok"}).
  • GET /api/status: Statistics (total_messages, last_message_at, last_message_role).

6. Self-Improvement Logs

  • POST /api/improvements: Record custom self-improvement notes (creates <task_name>-<date>-<time>.md).
  • GET /api/improvements: List recent self-improvement logs.
  • GET /api/improvements/{filename}: Retrieve specific self-improvement markdown content.

Continuous Self-Improvement Subsystem

Every execution of the system records an actionable post-mortem log formatted as <task_name>-<YYYY-MM-DD>-<HH-MM-SS>.md under improvements/:

improvements/
└── order-101-2026-09-20-11-05-30.md

Execution API records append -message-<id> to the filename and reuse the original record on an idempotent retry. Direct records created in the same second append a unique suffix when needed, preserving each execution. The timestamp is in UTC.

Log Structure (100% in English)

  1. Executive Summary: Overview of changes and execution status.
  2. Friction Points & Identified Issues: Runtime errors, test failures, or coordination friction.
  3. Recommended System Improvements: Architectural, protocol, documentation, or code cleanups.
  4. Concrete Action Items & Next Steps: Concrete steps to prevent regressions and improve system velocity.

How It Triggers:

  • Agent Worker Loop: Automated runner (examples/worker_poll.py) automatically generates a record upon every order completion.
  • Execution Reports: POST /api/executions auto-generates a record from the report body and any parsed SELF-IMPROVEMENT: sections.
  • Direct API & Web UI: Click "💡 Improvements" in the top bar to browse logs, or submit records via POST /api/improvements.
  • Web Chat Assistants: Prompts in prompts/web_chat_*.md instruct Claude, ChatGPT, and Gemini to generate actionable self-improvement feedback after every cycle.

Running the Agent Poller

The repository includes a ready-to-run polling adapter for automated agents (executable via examples/worker_poll.py or examples/agent_worker.py):

Install its HTTP client dependency with pip install 'requests>=2.32'.

python examples/agent_worker.py \
  --bridge-url http://localhost:8000 \
  --token $AGENT_TOKEN \
  --run-mode daemon \
  --start-mode pending

Modes:

  • --run-mode daemon: Continuously polls for new orders.
  • --run-mode once: Checks for available orders once and exits.
  • --run-mode bounded: Exits after N idle polls without work.

--start-mode pending reads the entire pending backlog before watching new messages. --start-mode now starts from a successfully fetched current cursor; startup failures exit with a nonzero status. Bounded mode also exits nonzero after repeated polling or reporting failures.

The stock poller reports BLOCKED until an executor is connected. It does not implement task execution. Programmatic integrations can pass executor to run_worker_loop or execute_order: the callable receives the order dictionary and must perform and verify the work, then return a non-empty report string. Exceptions are reported as failures. HTTP report retries reuse the same message key within the request attempt; message idempotency does not guarantee that an executor's external side effects run exactly once.


Running Tests

Run the full test suite with pytest:

pytest

Additional checks:

ruff check .
python scripts/check_frontend_syntax.py
python scripts/check_package_install.py

The package check builds a wheel, installs it in a temporary environment outside the checkout, and verifies the installed API, prompts, static assets, and improvement records. It reuses the development environment's third-party dependencies. CI runs this check on its existing Python and operating-system matrix.

About

Minimalist Markdown coordination board for Engineer ↔ Worker agents. ForgeLoop-aware, multi-task, evidence-backed workflows.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages