# codered-dev/ai-agent-bridge architecture

> Architecture diagram of the GitHub repository codered-dev/ai-agent-bridge, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-04). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/codered-dev/ai-agent-bridge
- Repository: https://github.com/codered-dev/ai-agent-bridge

## Overview

##### What this project is (type + purpose)
This is a **Python library/scaffold** for a **multi-agent communication “bridge”** that standardizes agent-to-agent interactions via a **structured message protocol** rather than freeform chat. It’s not a full-stack web app; it’s a **protocol + router + adapters** package with a local demo.

- Agents don’t talk directly; they communicate by exchanging **typed protocol envelopes** (`AgentMessage`) through a **Router/Bridge layer** that validates, enforces handshake/lifecycle transitions, and records events.
- Model execution is **decoupled** via an adapter interface: the bridge is **model-agnostic**, and concrete adapters implement the “call LLM + parse response” integration.

##### Core package: `src/bridge/`
- `protocol.py`: **domain model** (message schema, statuses, TTL, serialization) + **MessageQueue** (in-memory transport abstraction).
- `adapter.py`: **AgentAdapter (interface/base class)** that defines how an agent sends/receives intents via the bridge; declares integration points:
- `prompt_model` / `parse_response` (implemented by concrete adapters).
- `router.py`: **Router / Bridge orchestrator**
- enforces **handshake transitions**
- records **router events** (observability)
- maintains a **shared context store** (metadata/journaling per conversation)
- delivers validated requests to target agent(s)
- `local_llm.py`: **Local LLM client wrapper** (stub or Ollama runner); represents the “LLM backend” boundary.
- `local_adapter.py`: `LocalLLMAdapter` concrete adapter that:
- pulls shared context
- builds structured prompts
- sends replies back through router

##### Runtime/demo + artifacts
- `scripts/handshake_demo.py`: the **composition root** (wires planner/executor adapters + router + stubbed or real local clients).
- `logs/bridge.log`: runtime **event log** output; important for observability lane.
- `docs/architecture.md`, `docs/plan.md`, `docs/use_case.md`: these define intended architecture—use them to justify components/flows.
- `results/*`: experimental outputs; these are not architecture components but help validate flows.

##### Handshake / lifecycle control (Router-centric)
- Planner Adapter → Router: “HELLO/READY” (or initial registration/handshake message)
- Router → Planner Adapter: ACK / transition allowed
- Executor Adapter ↔ Router: same handshake
- Router updates internal state machine and logs events.

- **state transitions enforced by Router**
- **status values** (`ready`, `working`, `error`, etc.) as part of the envelope

##### Router
- validates schema + TTL
- enriches with shared context metadata (conversation store)
- records event

##### Observability lane (should be explicit)
- Router → `logs/bridge.log`: append structured router events
Optionally show:
- Router events store (in-memory list) + file sink

##### Architectural patterns/design principles to highlight

- **Protocol-first design**: `AgentMessage` is the contract; adapters and router revolve around it.
- **Adapter pattern**: `AgentAdapter` abstracts the LLM integration; concrete implementations swap backends without changing routing logic.
- **Decoupled reasoning/execution**: Planner and Executor are independent agents connected via bridge.
- **State machine / handshake enforcement**: Router controls allowed transitions and message lifecycles.
- **Pluggable transport**: `MessageQueue` is currently in-memory but represents a replaceable messaging substrate (future HTTP/WS).

- **Router** (`src/bridge/router.py`)
- “handshake enforcement”
- “shared context store”
- “event recorder”
- **Protocol** (`src/bridge/protocol.py`)
- “AgentMessage schema”
- “MessageStatus + TTL”
- “(In-memory) MessageQueue”
- **AgentAdapter (base)** (`src/bridge/adapter.py`)
- “send_intent / receive_message”
- “prompt_model + parse_response hooks”
- **LocalLLMAdapter** (`src/bridge/local_adapter.py`)
- **LocalLLMClient** (`src/bridge/local_llm.py`)
- “stub runner / Ollama runner”
- **Handshake demo** (`scripts/handshake_demo.py`)
- **Logs** (`logs/bridge.log`)

##### “Don’t overthink it”: split into as many components as possible (for this repo)
Because this is a scaffold, accuracy improves by explicitly drawing even “small” elements:
- separate **Protocol schema** from **Router** from **Transport**
- separate **Adapter base** from **Local adapter** from **LLM client**
- separate **Handshake/lifecycle** from **Intent routing** from **Logging**

That granularity matches the file structure and makes it clear which pieces are stable contracts vs. pluggable integrations.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% Diagram 1: Container / Component (static)
    %% =========================
    subgraph D1["Diagram 1 — Container / Component view (static structure)"]
        direction TB

        subgraph ENV["Runtime environment"]
            direction TB
            EnvCfg["Environment configuration\n(MODEL_PLANNER / MODEL_EXECUTOR / LLM_BACKEND)"]:::config
        end

        subgraph DEMO["Demo / Composition root"]
            direction TB
            Demo["Handshake demo\n(composition root)"]:::demo
        end

        subgraph CORE["bridge package (library boundary)"]
            direction TB

            BridgePkg["bridge/ (package boundary)"]:::pkg

            subgraph PROTO["Protocol + Transport"]
                direction TB
                Protocol["Protocol schema\nAgentMessage / MessageStatus / TTL\nSerialization (JSON envelope)"]:::core
                MsgQueue[/"MessageQueue\n(in-memory transport)\n(pluggable substrate)"/]:::queue
            end

            subgraph ROUTE["Router / Bridge Orchestrator"]
                direction TB
                Router["Router / Bridge orchestrator\n- handshake state machine\n- validation gate (schema/TTL)\n- dispatch (deliver)\n- event recorder\n- shared context store"]:::core
                CtxStore[("Shared context store\n(conversation metadata/journal)")]:::store
                EventBuf[("Router events (in-memory)\n(observability buffer)")]:::store
            end

            subgraph ADAPT["Adapter layer"]
                direction TB
                AgentAdapter["AgentAdapter (base interface)\n- send_intent / receive_message\n- prompt_model() hook\n- parse_response() hook"]:::core
                LocalAdapter["LocalLLMAdapter (concrete)\n- builds structured prompts\n- pulls shared context\n- sends replies via Router"]:::core
            end

            subgraph LLMCLIENT["Local LLM integration"]
                direction TB
                LocalClient["LocalLLMClient wrapper\n(stub runner / Ollama runner boundary)"]:::core
            end
        end

        subgraph AGENTS["Logical Agents (decoupled)"]
            direction TB
            subgraph PLANNER["Planner agent"]
                direction TB
                PlannerA["Planner: LocalLLMAdapter"]:::agent
            end
            subgraph EXECUTOR["Executor agent"]
                direction TB
                ExecutorA["Executor: LocalLLMAdapter"]:::agent
            end
        end

        subgraph EXT["External dependencies"]
            direction TB
            LLMBackend(["LLM Backend\n(Ollama / stub)"]):::external
        end

        subgraph OBS["Observability"]
            direction TB
            LogSink[("Log file sink\nbridge.log")]:::obs
            DocsArch["Architecture doc\n(ground truth for flows)"]:::docs
            DocsPlan["Plan doc"]:::docs
            DocsUse["Use-case doc"]:::docs
        end

        %% --- Wiring / dependencies (static) ---
        EnvCfg -->|"provides config"| Demo

        Demo -->|"instantiates/wires"| Router
        Demo -->|"instantiates/wires"| PlannerA
        Demo -->|"instantiates/wires"| ExecutorA
        Demo -->|"instantiates/wires"| LocalClient

        %% Adapter inheritance/implementation relationships (conceptual)
        PlannerA -->|"implements"| AgentAdapter
        ExecutorA -->|"implements"| AgentAdapter

        %% Adapters use Router and Local client
        PlannerA -->|"send/receive AgentMessage"| Router
        ExecutorA -->|"send/receive AgentMessage"| Router

        PlannerA -->|"prompt_model()"| LocalClient
        ExecutorA -->|"prompt_model()"| LocalClient

        LocalClient -->|"calls"| LLMBackend

        %% Router uses protocol/queue + stores + logging
        Router -->|"validates schema/ttl via"| Protocol
        Router -.->|"publish/consume (conceptual)"| MsgQueue
        Router -->|"reads/writes"| CtxStore
        Router -->|"records"| EventBuf
        Router -->|"appends events"| LogSink

        %% Docs as reference lane
        DocsArch -.->|"specifies intended architecture"| Router
        DocsArch -.->|"specifies protocol contract"| Protocol
        DocsUse -.->|"defines scenarios"| Demo
        DocsPlan -.->|"roadmap / future transport"| MsgQueue
    end

    %% =========================
    %% Diagram 2: Sequence (dynamic)
    %% =========================
    subgraph D2["Diagram 2 — Runtime sequence (one intent end-to-end)"]
        direction TB

        subgraph SEQ["Sequence: handshake → intent → execute → reply + observability"]
            direction TB

            PSeq["PlannerAdapter\n(LocalLLMAdapter)"]:::agent
            RSeq["Router\n(handshake/validate/dispatch/log)"]:::core
            QSeq[/"MessageQueue\n(in-memory)"/]:::queue
            ESeq["ExecutorAdapter\n(LocalLLMAdapter)"]:::agent
            CSeq["LocalLLMClient"]:::core
            BSeq(["LLM Backend\n(Ollama/stub)"]):::external
            LSeq[("logs/bridge.log")]:::obs
        end
    end

    %% --- Sequence flow as vertical message steps ---
    PSeq -->|"HELLO/READY AgentMessage\n{conversation_id,status,ttl}"| RSeq
    RSeq -->|"log handshake event"| LSeq
    RSeq -->|"ACK/allowed transition\n{status=ready}"| PSeq

    ESeq -->|"HELLO/READY AgentMessage\n{conversation_id,status,ttl}"| RSeq
    RSeq -->|"log handshake event"| LSeq
    RSeq -->|"ACK/allowed transition\n{status=ready}"| ESeq

    PSeq -->|"send_intent AgentMessage\n{message_id,intent,payload,ttl,status}"| RSeq
    RSeq -->|"validate schema + TTL\n(enforce lifecycle)"| RSeq
    RSeq -->|"enrich from context store\n{conversation metadata}"| RSeq
    RSeq -->|"log intent received"| LSeq

    RSeq -.->|"publish intent (conceptual)"| QSeq
    QSeq -.->|"deliver/consume"| RSeq

    RSeq -->|"dispatch request AgentMessage\n{intent,payload,status}"| ESeq
    RSeq -->|"log dispatch"| LSeq

    ESeq -->|"prompt_model(structured prompt)"| CSeq
    CSeq -->|"call LLM backend"| BSeq
    BSeq -->|"raw response"| CSeq
    CSeq -->|"raw response"| ESeq

    ESeq -->|"parse_response() → reply AgentMessage\n{status,results}"| ESeq
    ESeq -->|"reply/ack/status update\n{status=working/done/error}"| RSeq
    RSeq -->|"log status update"| LSeq

    RSeq -->|"deliver result AgentMessage\n{payload,status}"| PSeq
    RSeq -->|"log delivery"| LSeq

    %% =========================
    %% Click Events (mapped components)
    %% =========================
    click BridgePkg "https://github.com/codered-dev/ai-agent-bridge/tree/main/src/bridge/"
    click Protocol "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/protocol.py"
    click MsgQueue "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/protocol.py"
    click AgentAdapter "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/adapter.py"
    click Router "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/router.py"
    click LocalClient "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/local_llm.py"
    click LocalAdapter "https://github.com/codered-dev/ai-agent-bridge/blob/main/src/bridge/local_adapter.py"
    click Demo "https://github.com/codered-dev/ai-agent-bridge/blob/main/scripts/handshake_demo.py"
    click LogSink "https://github.com/codered-dev/ai-agent-bridge/blob/main/logs/bridge.log"
    click EnvCfg "https://github.com/codered-dev/ai-agent-bridge/blob/main/.env"
    click DocsArch "https://github.com/codered-dev/ai-agent-bridge/blob/main/docs/architecture.md"
    click DocsPlan "https://github.com/codered-dev/ai-agent-bridge/blob/main/docs/plan.md"
    click DocsUse "https://github.com/codered-dev/ai-agent-bridge/blob/main/docs/use_case.md"

    %% =========================
    %% Styles (color coding)
    %% =========================
    classDef core fill:#cfe8ff,stroke:#1d4ed8,stroke-width:1.5px,color:#0b1f44
    classDef pkg fill:#bfe3ff,stroke:#1e40af,stroke-width:2px,color:#0b1f44
    classDef agent fill:#d1fae5,stroke:#047857,stroke-width:1.5px,color:#052e1a
    classDef external fill:#ffedd5,stroke:#c2410c,stroke-width:1.5px,color:#431407
    classDef obs fill:#e5e7eb,stroke:#374151,stroke-width:1.5px,color:#111827
    classDef docs fill:#f3f4f6,stroke:#6b7280,stroke-width:1.2px,color:#111827
    classDef queue fill:#ede9fe,stroke:#6d28d9,stroke-width:1.5px,color:#2e1065
    classDef store fill:#fff7d6,stroke:#b45309,stroke-width:1.5px,color:#3b2200
    classDef config fill:#e0f2fe,stroke:#0284c7,stroke-width:1.5px,color:#082f49
    classDef demo fill:#dcfce7,stroke:#15803d,stroke-width:1.8px,color:#052e1a
```
