Agent Bridge
# Agent Bridge
Local MCP message bridge for **Claude Code**, **Kimi CLI** and **OpenClaude**.
Agent Bridge lets coding agents exchange tasks, results and bounded autonomous conversations through one shared SQLite database. It uses MCP stdio transport and local files only — no TCP/UDP server, no external service and no network protocol of its own.
The reference Claude Code setup runs the Claude-side worker against **Strata**, model `qwen3.8-flash-next-unsloth-ud-q4_k_xl`, through the local launcher; the `local` side runs an OpenClaude worker against the same model through its OpenAI-compatible endpoint. The bridge core itself is model-agnostic and can dispatch work to any compatible agent client.
> **Status: experimental.** The main exchange flow is implemented and covered by tests, but the project is still evolving. See [TODO.md](TODO.md) for known gaps.
## Stack
- **Claude Code worker:** local headless Claude Code launcher, configured for **Strata**, model `qwen3.8-flash-next-unsloth-ud-q4_k_xl`.
- **Kimi CLI worker:** official Kimi CLI in prompt mode.
- **OpenClaude worker:** open OpenClaude client run headless against the local model through its OpenAI-compatible endpoint (llama-server / Strata).
- **Agent Bridge core:** Python 3.11+, MCP stdio transport and SQLite.
## Highlights
- **Two-way agent inbox:** send, receive, acknowledge and reply to messages.
- **Safe concurrent workers:** atomic claims with expiring leases prevent two workers from executing the same task.
- **Bounded conversations:** goal-driven `task → result` dialogues with a turn limit, expiry, server-side ordering and reviewer decisions.
- **Automatic headless delivery:** per-agent listeners can dispatch root tasks and conversation turns to one-shot worker processes.
- **Progress indication:** a compact listener status shows the current lifecycle stage and the last dispatch result without exposing task payload.
- **Anti-spam primitives:** response deadlines, idempotency keys and no automatic retries.
- **Payload-safe diagnostics:** logs and status files contain ids, stages and exit codes — not prompts, message text, tokens or worker output.
- **Single-file state:** the shared message database is plain SQLite with WAL mode and busy timeouts.
## How it works
```text
Claude Code session ── MCP stdio ──► server.py (AGENT_ID=claude) ─┐
OpenClaude session ─── MCP stdio ──► server.py (AGENT_ID=local) ──┼──► bridge.db
Kimi CLI session ───── MCP stdio ──► server.py (AGENT_ID=kimi) ───┘
▲
│ scan / dispatch
systemd/listener.py
│
systemd/on_message.py
│
one-shot Claude, Kimi or OpenClaude worker
(cclocal_headless.sh / kimi_headless.sh /
oclocal_headless.sh → OpenClaude on the local model
through the OpenAI-compatible llama-server/Strata endpoint)
```
Each MCP server process derives its sender identity from `AGENT_ID`; tool arguments cannot impersonate another sender. All three sessions point at the same `bridge.db`, each with its own value of `AGENT_ID`. Agent ids are fixed (`claude`, `kimi` and `local`, `AGENTS` in `server.py`); the names `cclocal` and `oclocal` elsewhere in this README are only the local launcher/integration names and the report prefixes for the `claude` and `local` sides — `AGENT_ID=cclocal` and `AGENT_ID=oclocal` are rejected.
Interactive MCP sessions do not receive push notifications: an active agent checks `receive_messages` when it is already running. The optional listener adds the headless path: it scans the database, runs `on_message.py` for one dispatchable message and waits until that supervisor exits before scanning again.
## Requirements
- Linux or another POSIX environment
- Python 3.11+
- [uv](https://docs.astral.sh/uv/)
- Claude Code, Kimi CLI and/or OpenClaude, depending on the side being automated
## Quick start
```bash
git clone <your-repository-url>
cd agent-bridge
uv sync
```
Run the safe dispatcher test suite:
```bash
uv run python systemd/test_dispatcher.py
```
Start a bridge server manually for development:
```bash
AGENT_ID=claude uv run python server.py
# in another terminal:
AGENT_ID=kimi uv run python server.py
```
`server.py` is an MCP stdio process, so normally it is launched by the agent client rather than used directly as an interactive command.
## MCP registration
Use an absolute repository path. Registration is project-scoped; restart the agent session after adding or changing the MCP server.
### Claude Code
```bash
claude mcp add-json agent_bridge -s project '{
"command": "uv",
"args": [
"run",
"--directory",
"/absolute/path/to/agent-bridge",
"python",
"server.py"
],
"env": {
"AGENT_ID": "claude"
}
}'
```
Start a new Claude Code session, approve the project-scoped server and check that eight `agent_bridge` tools are available.
### Kimi CLI
Add the following to the project-scoped Kimi MCP configuration, changing the absolute path as needed:
```json
{
"mcpServers": {
"agent_bridge": {
"command": "uv",
"args": [
"run",
"--directory",
"/absolute/path/to/agent-bridge",
"python",
"server.py"
],
"env": {
"AGENT_ID": "kimi"
},
"enabled": true,
"startupTimeoutMs": 30000,
"toolTimeoutMs": 40000,
"enabledTools": [
"send_message",
"receive_messages",
"claim_message",
"release_message",
"mark_read",
"start_conversation",
"conversation",
"listener"
]
}
}
}
```
Start a new Kimi session from the project and trust the workspace if the MCP command is expected.
### OpenClaude
Register the bridge through the tracked [`systemd/mcp.local.json`](systemd/mcp.local.json), which starts `server.py` with `AGENT_ID=local` and references the repository as `${AGENT_BRIDGE_DIR}`. The variable is **required and has no default**: OpenClaude expands `${VAR}` client-side and fails the connection with a "Missing environment variables" error naming it. `systemd/oclocal_headless.sh` exports `AGENT_BRIDGE_DIR` itself from its own location, so the headless path works from any clone layout; an interactive launch must export it beforehand. Pin the config file when starting the session:
```bash
openclaude --mcp-config /absolute/path/to/agent-bridge/systemd/mcp.local.json --strict-mcp-config
```
An interactive OpenClaude session must never load the project `.mcp.json` used by the Claude Code worker — that file registers the same bridge as `claude`.
### OpenCode
Supported client: **OpenCode 2** (`opencode.ai/v2/install`); the 1.x config format (`mcp.<name>`, `permission`) is not used. The agent id is `opencode`.
Headless workers need no registration: `systemd/opencode_headless.sh` injects the bridge itself (see [Worker launchers](#worker-launchers)). For an interactive OpenCode session, register the bridge globally with its own identity:
```bash
opencode mcp add agent_bridge --global --env AGENT_ID=opencode -- \
uv run --directory /absolute/path/to/agent-bridge python server.py
```
or in `~/.config/opencode/opencode.json`:
```json
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"servers": {
"agent_bridge": {
"type": "local",
"command": ["uv", "run", "--directory", "/absolute/path/to/agent-bridge", "python", "server.py"],
"environment": { "AGENT_ID": "opencode" },
"codemode": false
}
}
}
}
```
OpenCode names MCP tools `<server>_<tool>`, so the bridge tools are `agent_bridge_send_message`, `agent_bridge_receive_messages` and so on; `"codemode": false` keeps them plain tool calls instead of Code Mode.
## Tools
| Tool | Purpose |
|---|---|
| `send_message` | Store a message, optionally linked with `reply_to`, deadline and `dedup_key`. |
| `receive_messages` | Return unread messages for the current `AGENT_ID`; optionally long-poll up to 30 seconds. |
| `claim_message` | Atomically claim or renew a message lease before headless execution. |
| `release_message` | Return an unfinished claim to the shared inbox without acknowledging it. |
| `mark_read` | Acknowledge completed messages; only the recipient can acknowledge. |
| `start_conversation` | Create a bounded dialogue and send its root `task`. |
| `conversation` | Inspect, complete, cancel or escalate a dialogue. |
| `listener` | Enable, disable or inspect the current agent's background listener; `action="progress"` returns the same one-line progress string as the cclocal status line. |
| `manager` | `claude` only: turn [manager mode](#manager-mode) on for a project (`action="on"`, returns the role text) or inspect it (`action="status"`). There is no `off` for the model. |
The server also exposes one MCP prompt, `manager`, which Claude Code shows as the slash command `/mcp__agent_bridge__manager`.
## Basic exchange
```text
1. sender: send_message(recipient, text, dedup_key="task-1")
2. recipient: receive_messages()
3. recipient: claim_message(message_id)
4. recipient: send_message(sender, result, reply_to=message_id,
dedup_key="task-1:result")
5. recipient: mark_read([message_id])
6. sender: receive_messages()
7. sender: mark_read([result_id])
```
If the recipient cannot finish, it sends a `blocked: ...` result and releases the original message instead of acknowledging it. A response deadline is advisory metadata: Agent Bridge never auto-resends and never retries an attempted dispatch, and a passed deadline does not stop a never-attempted message from being delivered.
## Bounded conversations
`start_conversation(recipient, goal, max_turns=6, expires_in_seconds=14400)` creates a dialogue with a fixed goal, a turn budget and an expiry time. Messages inside the conversation use `kind`:
- `task` asks the other side to perform the next step;
- `result` reports completion, blockage or a request for clarification;
- `notice` carries operational information without waking a worker or consuming a turn.
The server enforces pairing and direction: a `result` answers a `task`, a follow-up `task` answers a `result`, and only one message may be in flight. The reviewer side must choose exactly one terminal action after a result: complete the conversation, send one concrete follow-up task or escalate to `needs_human`.
Terminal conversations accept no new tasks or results. Hard dispatch failures freeze the dialogue so a broken chain cannot continue automatically.
## Manager–worker pattern
The bounded-conversation primitives fit a division of labor between the two local sides:
- **`claude` — manager and reviewer.** An interactive Claude Code session owns architecture, research and review: it writes the goal, breaks it into concrete tasks and judges every result against the repository.
- **`local` — executor.** A headless OpenClaude worker performs the approved work. There is no human in its loop: actions outside the project allowlist are denied automatically, and the honest outcome for anything it cannot complete is a `blocked:` report instead of a risky action.
The loop:
```text
manager (claude) worker (local)
start_conversation ── task ──────────► claim, execute
◄──────────────── result ────── report done / blocked
review the result
├─ follow-up task (concrete fixes) ──► next turn
└─ complete / needs_human
```
Only the manager opens conversations and only the manager decides the terminal action after a result. A `blocked` report is a normal review input, not a dispatch failure: the manager either narrows the task to what the allowlist actually permits or does the denied step itself in the interactive session — unless it is in manager mode, where code changes are left to the worker or to the human.
### Manager mode
Manager mode keeps the interactive `claude` session in the manager role for the whole session: it plans, writes task specs, delegates to `local`, waits for the signal and reviews — it does not write code. It is per project (keyed by the git root) and can be switched on **in a running session**.
One-time setup — install the hooks into your Claude Code user settings (`$CLAUDE_CONFIG_DIR` or `~/.claude`, `settings.json`; other keys and hooks are kept, the old file is backed up):
```bash
python3 systemd/manager_mode.py install
```
Claude Code snapshots hooks when a session starts, so they work from the next start — once. After that the mode is switched without any restart, because every hook call reads the per-project flag in `systemd/runtime/manager/`.
Turning it on, in any session:
- `/mcp__agent_bridge__manager` (the MCP prompt), or ask the model to call `manager(action="on", project="<path>")`. The tool returns the role text (`commands/manager-role.md`, with the bridge and project paths filled in), which takes effect at once;
- or from a shell: `python3 systemd/manager_mode.py on --project <path>`.
While the mode is on, the hooks:
- **PreToolUse** — block `Edit`, `Write`, `MultiEdit`, `NotebookEdit` and obvious Bash writes (`>`, `>>`, `tee`, `sed -i`, `perl -i`, `patch`, `git apply/am`) inside the project, with a reason that tells the model to delegate. Allowed inside the project: `.agent-tasks/` (long task specs) and `.git/info/exclude`; outside the project root nothing is blocked;
- **UserPromptSubmit** — add a short role reminder to every user turn, so the role does not fade in a long session;
- **SessionStart** — add the full role text after startup, `/clear` and compaction.
Turning it off is for a human only: `python3 systemd/manager_mode.py off --project <path>` (the MCP tool has no `off`, or the model could lift its own guard). `status`, `list` and `role` are read-only.
Workers are never blocked: the headless launchers export `AGENT_BRIDGE_WORKER=1`, and interactive OpenClaude shifts run with `CLAUDE_CODE_USE_OPENAI=1`. Notes:
- the mode applies to every Claude Code session in that project, not to one session;
- a session started before `install` gets the role text but no enforcement; in it use `/permissions` → Deny `Edit`, `Write`, `NotebookEdit`;
- the new `manager` tool and prompt appear after the MCP server is reconnected (`/mcp` → `agent_bridge` → Reconnect), without restarting Claude Code;
- the guard is a safety net, not a sandbox: a write through, say, `python3 -c` is not recognised, and anything the hook cannot parse is let through. The role does the main work.
## Automatic delivery and progress
The default automation gate is:
```json
{
"auto": {
"claude": true,
"kimi": false,
"local": true
},
"dispatch_max_age_seconds": 86400
}
```
Claude-side and `local`-side headless execution are enabled by default in this configuration. Kimi-side headless execution remains disabled because Kimi CLI prompt mode applies its own automatic permission policy without interactive approvals; enable `auto.kimi` only as a deliberate local decision.
`dispatch_max_age_seconds` (default 24 h) bounds automatic delivery by message **age**. A message that arrived while the listener was stopped, restarting or busy with another worker is still dispatched when it comes back, even if its `response_deadline` has passed — the deadline is metadata for the worker and the human. Only a backlog older than the bound is left alone: `listener.py pending` lists it and a manual `on_message.py <id>` runs one message on purpose.
A malformed `config.json` automates nothing (fail closed).
Useful commands:
```bash
uv run python systemd/listener.py status --agent claude
uv run python systemd/listener.py progress --agent claude --once
uv run python systemd/listener.py watch --agent claude
uv run python systemd/listener.py pending --agent claude
uv run python systemd/listener.py disable --agent claude
uv run python systemd/listener.py enable --agent claude
```
`listener status` keeps the original machine-readable fields and additionally reports:
- `stage`: `stopped`, `starting`, `idle`, `received`, `supervising`, `legacy`, `unknown` or `error`;
- `progress_state`: why a stage is not the ordinary one — `unreadable` (the progress file exists but cannot be parsed), `missing_file` (a live listener past the startup grace never wrote one: old code), `no_format_version` (its document predates the version marker), `stale_pid` (the document was written by a different process); null on the normal stages;
- `progress`: the currently trusted lifecycle record;
- `last`: the previous dispatch outcome, including duration and exit code where available.
### Waiting for a result without polling
An interactive session that delegated work should not call `receive_messages` every 30 seconds: each call is a full model turn. `listener wait` blocks instead, and the session runs it as a **background command** (Claude Code: Bash with `run_in_background`), then does nothing until the command exits — Claude Code delivers a completion notification on exit.
```bash
python3 "$AGENT_BRIDGE_DIR/systemd/listener.py" wait --agent claude --conversation 12 --timeout 3600
python3 "$AGENT_BRIDGE_DIR/systemd/listener.py" wait --agent claude --conversation 12 --conversation 13 # several workers: first event wins
python3 "$AGENT_BRIDGE_DIR/systemd/listener.py" wait --agent claude --message 57 # legacy root task
```
It prints exactly one JSON line and exits:
- `{"event":"message","message":58,"conversation":12,"reply_to":57,"sender":"local","kind":"result","outcome":"done"|"blocked"}` — the worker reported;
- `"kind":"notice","outcome":"failed"|"timeout"|"uncertain"|"interrupted"` — the worker never reported, the supervisor did (the signal does not depend on the worker behaving);
- `{"event":"conversation_closed","state":"needs_human"|...}` — the dialogue left `active` without a message (expired, closed by hand);
- exit 2 `{"event":"timeout"}`; exit 1 `{"event":"error","error":"unknown_conversation"|...}` at once for a mistyped id.
An event is the first **unacknowledged** message to the waiter in the target, so a report that arrived before `wait` started is returned immediately, and after `mark_read` the next `wait` waits again. Read-only, ids and enums only, never message text. Only `python3` is needed (stdlib), so it runs from any project directory.
Reports themselves are compact: the protocol asks every worker for four lines — `done: <one-line outcome>` (or `blocked: <reason>`), `files: …`, `check: <command> -> <result>`, `not done: …` — so the reviewer reads a few lines before verifying the diff and the tests itself.
`listener pending` is a read-only backlog report: never-attempted messages that could wake a worker, split into `dispatchable` (the listener will take them) and `stale` (older than `dispatch_max_age_seconds`). It prints ids and ages only and never writes to the database.
Progress reflects the supervisor lifecycle only: a message moves `received` → `supervising` → `finished`, and the `last` segment carries the outcome of the most recent dispatch. Worker-internal stages (tool calls, intermediate reasoning) are neither transmitted nor planned.
From an MCP session the same human-readable snapshot is one call: `listener(action="progress")` returns `{"line": ...}` — the exact string the cclocal status line renders, e.g. `[claude] idle | last msg#43 sender=kimi result=succeeded in 21.5s rc=0`. It is ids, enums and numbers only, never task payload, and the call never raises.
Progress files live in `systemd/runtime/<agent>.progress.json` and contain ids, enums and numbers only. Every document opens with `"format_version": 2`; a document without that marker comes from a listener written before the marker existed, and `status()` reports it as `legacy` instead of guessing its stage. The runtime directory is private and gitignored.
### Claude Code status line
There is no supported API for injecting an arbitrary external event into a live Claude Code session. A supported read-side option is Claude Code's custom status line: the command runs on a timer and its stdout becomes the status line.
Create the script in the config directory your interactive sessions actually use — for this machine's cclocal setup that is `~/.claude-local` (`CLAUDE_CONFIG_DIR=$HOME/.claude-local`); on a default Claude Code install it is `~/.claude`. Use absolute paths inside, make it executable, and keep it exit 0 unconditionally — a status line command that fails or hangs degrades the whole session UI:
```bash
#!/usr/bin/env bash
# ~/.claude-local/statusline-agent-bridge.sh — one line about the claude listener.
BRIDGE=/absolute/path/to/agent-bridge
PY="$BRIDGE/.venv/bin/python"
[ -x "$PY" ] || PY=python3
"$PY" "$BRIDGE/systemd/listener.py" progress --agent claude --once 2>/dev/null
exit 0
```
```bash
chmod +x ~/.claude-local/statusline-agent-bridge.sh
```
Then add this key to the `settings.json` in that same config directory, leaving every other key untouched:
```json
{
"statusLine": {
"type": "command",
"command": "/home/<user>/.claude-local/statusline-agent-bridge.sh",
"refreshInterval": 2
}
}
```
The line carries only ids, stage words, sender names, durations and exit codes. Right after a listener restart, before the first dispatch, it is just:
```text
[claude] idle
```
Once work flows, the same command grows the current-dispatch and history segments:
```text
[claude] supervising msg#33 sender=kimi supervisor=564040 for 12s
[claude] idle | last msg#33 sender=kimi result=blocked in 938.7s rc=0
```
**Limitation:** the status line is visible only inside interactive Claude Code sessions. Outside a session there is no indication — no desktop notification, sound or dbus integration is provided, by design. A running session may not pick up `settings.json` changes mid-flight; open a new session to see the line.
This is optional local configuration; Agent Bridge does not modify global Claude settings by itself — enabling it is a deliberate per-machine decision.
### OpenClaude status line
OpenClaude supports the same `statusLine` settings key, and the bridge ships a ready-made command: `systemd/statusline.sh` (executable, derives the bridge location from its own path, always exits 0). It prints the `local` worker's dispatch state, e.g. `[local] supervising msg#123 sender=claude supervisor=564040 for 12s` — so an interactive OpenClaude window shows when a delegated task was received and is being executed.
Register it in `~/.openclaude/settings.json`:
```json
{
"statusLine": {
"type": "command",
"command": "/absolute/path/to/agent-bridge/systemd/statusline.sh",
"refreshInterval": 5
}
}
```
**Refresh behavior:** stock OpenClaude re-runs a status line command on TUI events only (assistant message, mode switches), so the line updates between events but does not tick on a timer; it also strips the unknown `refreshInterval` key instead of failing the file, so the snippet above is safe on a stock build. Periodic refresh requires a build with the `statusLine.refreshInterval` patch (proposed upstream; locally applied via `npm link` from a patched clone). The same output contract as everywhere else: ids, enums and numbers only, never task text.
## Interactive bridge-agent mode
An interactive window can consume bridge tasks itself — no manager loop, no headless dispatch. This ships as two **prompt commands** (markdown files, zero client patches: the client expands the command into a user message and the model runs the loop through the eight bridge MCP tools it is already connected with):
- `commands/oc-bridge-agent.md` — OpenClaude, identity `local` (`/oc-bridge-agent [idle-minutes]`);
- `commands/cc-bridge-agent.md` — Claude Code, identity `claude` (`/cc-bridge-agent [idle-minutes]`).
Install by symlink so the repo stays the source of truth:
```bash
ln -s /path/to/agent-bridge/commands/oc-bridge-agent.md ~/.openclaude/commands/
ln -s /path/to/agent-bridge/commands/cc-bridge-agent.md ~/.claude/commands/
```
A **shift** works like this: step 0 verifies the identity via `listener(status)`; the `oc` variant then **disables the `local` listener** (the headless dispatcher must not compete for messages — claim leases are respected by the scan and the supervisor, but winning the sub-second race every time is only guaranteed with the dispatcher off) and **re-enables it on exit**, including after a user interrupt. The `cc` variant never toggles the listener: in the reference setup the `claude` listener is kept disabled, and a shift refuses to start while `listener(status)` reports it running (disable it with `listener.py disable --agent claude` first). The loop is the worker protocol verbatim: `receive_messages(wait_seconds=30)` → `claim_message(lease_seconds=3600)` → do the work → `send_message(kind="result", dedup_key="<prefix>:<id>:result")` → `mark_read`; a blocker answers `blocked: <reason>` and calls `release_message`. The shift exits after the idle limit (default 10 minutes, overridable by the argument) and reports per-message outcomes. An interactively consumed message leaves no `dispatch_attempts` row and is indistinguishable from a headless success in the DB.
Trade-off and rules:
- **No manager review.** The shift rules forbid destructive and external actions (git push, deploys, deletions beyond the task, sending data out) — the answer to those is `blocked` with a reason.
- **One shift at a time** per agent; per-message disputes are settled by `claim_message`.
- If the window dies mid-shift, the `local` listener stays disabled — recover with the `listener` MCP tool (`action="enable"`) or `uv run python systemd/listener.py enable --agent local`.
- The shift calls only bridge MCP tools; allow `mcp__agent_bridge__*` in the client's project settings (or approve interactively) so the loop does not stall on permission prompts.
`systemd/test_dispatcher.py` guards both files against drifting away from the dispatch protocol (`test_64_bridge_agent_command_contract`).
## Worker launchers
The supervisor chooses a launcher by recipient:
- `systemd/cclocal_headless.sh` starts a non-interactive Claude Code worker. It is an example integration for a local Claude-compatible wrapper and expects the local environment variables used by that wrapper.
- `systemd/kimi_headless.sh` starts the official Kimi CLI in prompt mode and passes the task through a private request file so task text does not appear in argv or the process list.
- `systemd/oclocal_headless.sh` starts a non-interactive OpenClaude worker (`openclaude --print`). It strips the inherited `ANTHROPIC_*` variables so the OpenAI-compatible endpoint of the local llama-server is the only provider the child can see, and exports `AGENT_BRIDGE_DIR` from its own location so `systemd/mcp.local.json` resolves from any clone layout. Like the Claude launcher it requires `LOCAL_CLAUDE_BASE_URL` and `LOCAL_CLAUDE_MODEL` (there is no built-in endpoint; a base URL ending in `/v1` is accepted as is), while `LOCAL_CLAUDE_AUTO_COMPACT` and `LOCAL_API_TIMEOUT_MS` stay optional. Permissions: `--permission-mode default` plus the project allowlist — there is no human to approve anything, so every action outside the allowlist is denied automatically.
- `systemd/opencode_headless.sh` starts a non-interactive **OpenCode 2** worker: `opencode run --standalone --archived --format json`, with the task on stdin (OpenCode reads the whole message from stdin when no message argument is given, so it never reaches argv). Everything the worker needs goes in through `OPENCODE_CONFIG_CONTENT`, an extra config source on top of your own OpenCode config: the bridge MCP server (`mcp.servers.agent_bridge`, `AGENT_ID=opencode`, Code Mode off) and the permission rules from [`systemd/opencode-permissions.json`](systemd/opencode-permissions.json). `--standalone` gives the run a private server — OpenCode 2's background service keeps the environment it started with, so the injected config would not reliably apply through it. `run` is started **without `--auto`**: a request the rules leave at `ask` is rejected and the worker is told it cannot ask, so the honest outcome is a `blocked:` report. Settings:
- `OPENCODE_WORKER_MODEL` — `provider/model[#variant]`; empty means OpenCode's own default model;
- `OPENCODE_WORKER_PROVIDER=local` — use the local llama-server: the same `LOCAL_CLAUDE_*` assignments as `oclocal_headless.sh` become an OpenAI-compatible provider `llama` (model `llama/<LOCAL_CLAUDE_MODEL>` unless `OPENCODE_WORKER_MODEL` is set); the key travels in the environment and the config only refers to it as `{env:OPENCODE_LOCAL_API_KEY}`;
- `OPENCODE_WORKER_AGENT` — an OpenCode agent name; `OPENCODE_WORKER_PERMISSIONS` — your own rules file; `OPENCODE_BIN` — the executable.
Run `uv sync` in the bridge directory once before the first dispatch: the worker starts the bridge MCP server with `uv run`, and a first-time environment build can outlast OpenCode's MCP startup window, leaving the worker without the bridge tools. The listener and its supervisors inherit these variables from the MCP server that started the listener, so set them in the environment of that session (or export them before `listener.py enable --agent opencode`). `opencode` is opt-in: `auto.opencode` is `false` until you review the rules. The default rules ask (= reject) for everything, then allow reading, searching, editing inside the workspace, the bridge tools (`agent_bridge_*`) and read-only git/`ls`, and deny `git push`, `git reset --hard`, `rm -rf`, `sudo`, `.env` files, questions, subagents and web access. Rules are ordered and **the last matching rule wins**; add your project's test commands, e.g. `{"action": "shell", "resource": "uv run pytest*", "effect": "allow"}`.
For public or team use, review these launchers and adapt them to your own client wrappers and permission model. Do not weaken static deny rules or hide permission requests.
Workers run in the **workspace** directory — the project both CLIs open, where their project MCP configs live (`.mcp.json` for the Claude worker's `--strict-mcp-config`, `.kimi-code/mcp.json` for Kimi). By default it is the directory that *contains* this repository, which fits a layout like `~/project/agent-bridge`. If the clone lives elsewhere, set `AGENT_BRIDGE_WORKSPACE` in the `env` of both MCP registrations; the listener and its supervisors inherit it.
If a launcher cannot be started at all (missing file, wrong permissions, bad workspace), the attempt is recorded as `failed` with `error_kind=spawn:<Error>`, the sender gets the usual payload-free notice and a conversation is frozen — the message is not left silently in `spawned`.
## Headless worker permissions
Claude-side workers start with `--permission-prompts none`: there is no human to approve anything, so every action that is not already allowed is denied automatically. A worker's effective permission set is rebuilt at process start from three sources:
1. **User settings** from `CLAUDE_CONFIG_DIR` (`cclocal_headless.sh` sets it from the local wrapper env). In this deployment that file carries no `permissions` block at all.
2. **Project settings** for the worker's cwd — `<workspace>/.claude/settings.local.json` (`--workspace` / `AGENT_BRIDGE_WORKSPACE`, see above). This file is the entire allowlist picture: both `permissions.allow` and `additionalDirectories`. MCP configuration is separate (`--mcp-config` + `--strict-mcp-config`) and grants nothing.
3. **Sandbox auto-approval** for simple read-only commands (`ls`, `cat`, `grep`, …) whose paths stay inside the workspace and `additionalDirectories`. Everything else — arbitrary interpreters (`python3 -c`), script execution, writes, or any path outside those boundaries (even `ls -l` of a symlink that resolves into `~/.local/share/uv/…`) — requires approval and is therefore denied headless.
Minimal sets per task type:
- **Ordinary two-way task** (read code, answer over the bridge): the `mcp__agent_bridge__*` tools plus sandboxed read-only commands are enough. The worker must be able to finish either way — `result` or `blocked` — without writing anything.
- **Engineering task** (edits in the repo): add file rules matching the target paths, plus explicit `Bash(...)` entries for every interpreter invocation the task uses (`uv run …`, `.venv/bin/python …`, `bash script.sh`) — the sandbox never auto-approves them. If those rules are absent, the dispatch ends `blocked` after burning the whole worker run; mark such tasks "interactive session" instead of dispatching them.
Denial behavior:
- **Compound commands die whole.** `allowed && denied`, `allowed; denied` or `allowed | denied` are denied as a unit — the allowed parts produce nothing. Probe suspect and safe commands in separate calls or you lose the data they could have given.
- A denial is not fatal. After the first write denial an honest worker stops retrying, files a `blocked:` report and releases the claim (required by the dispatcher prompt); the supervisor classifies a self-filed blocker as an honest stop, not a dispatch error.
Why an extended allowlist can appear to "not reach" the worker (TODO P1-11): the worker does read `<workspace>/.claude/settings.local.json` — proven by `additionalDirectories` taking effect in headless sessions and by `Bash` allow rules matching (`uv run python systemd/listener.py …` runs). What did not match were file rules written with single-slash absolute paths: `Edit(/home/<user>/project/**)`. `Edit`/`Read` rules use gitignore-style paths anchored to the settings file's directory, so a leading `/` anchors the pattern *inside* that directory and the rule matches nothing; absolute paths in these rules require the `//` prefix (`//home/<user>/project/**`), or write them relative to the settings directory (`Edit(agent_bridge/**)`). Workers 35 and 49, both started after the file was extended, were still denied `Edit`/`Write` under `agent_bridge/**` because of this, while `additionalDirectories` (which does accept real absolute paths) worked — the mixed effect is what looked like "the worker saw the old set". Confirmed live on 2026-11-03: a headless `Edit` of `agent_bridge/README.md` was denied with this rule in place; a positive test of the fixed rule form is still pending (one dispatch after the rule is rewritten).
## Reliability model
- **One attempt barrier:** `dispatch_attempts.message_id` is the primary key. A rescan, restart or duplicate listener cannot launch the same message twice.
- **No automatic retry:** crash, timeout or uncertainty remains visible for a human decision; a short operational notice is sent without task payload.
- **Evidence-based success:** exit code 0 alone is not success. The protocol requires an acknowledged original plus the appropriate result, blocked report, follow-up or terminal conversation state.
- **Lease and timeout:** worker claims expire; a worker timeout kills only that worker process group.
- **Delivery window:** never-attempted messages are dispatched regardless of `response_deadline`, within `dispatch_max_age_seconds`; older ones wait for a human.
- **Answered means done:** a message its recipient has already replied to (anything but a `notice`) is never dispatched headless, attempt row or not. This covers interactive bridge-agent shifts, which answer `blocked: …` and release without creating a `dispatch_attempts` row; a second, headless run would repeat the work and its report would be swallowed by the `<prefix>:<id>:result` dedup key. A manual `on_message.py <id>` still runs it on purpose.
- **Supervisor failures back off:** if a dispatch leaves no `dispatch_attempts` row (the supervisor crashed at start or could not be spawned), the listener waits 2, 4, 8 … up to 60 s before trying again instead of re-running the same message in a tight loop; each pause is logged as `no attempt recorded`.
- **Spawn failure means spawn failure:** only an error before the worker process exists is recorded as `spawn:<Error>`. Once the worker runs, its pid is written first and nothing after that (output rotation shared with sibling supervisors, for one) can mark it failed or abandon it.
- **Crash recovery:** stale attempts are reconciled by process evidence and report evidence. A recorded worker pid only counts as alive when `/proc` shows that process started together with its attempt, so a recycled pid cannot pin an attempt in `spawned`. `--recover` examines only messages that have never been attempted and uses the same dispatch set as the listener.
- **Concurrent start:** every process switches the database to WAL through the same retried recipe (`systemd/schema.py`), because on a not-yet-WAL file SQLite rejects the switch immediately while another writer holds a lock.
- **Fresh database bootstrap:** the listener creates the dispatcher schema additively before scanning, so a new bridge database does not require a manual supervisor run.
## Security notes
- The bridge is local: MCP stdio, SQLite and local subprocesses.
- Do not commit `bridge.db`, runtime files, outbox reports or agent MCP configuration.
- Secrets are passed through environment variables or private files and are never written to the database, prompts, logs or progress files.
- Logs are operational metadata only and are created `0600` (`dispatcher.log` by both the listener and the supervisor, `errors.log` by the server). Do not redirect MCP stderr into a file that also stores secret-bearing diagnostics.
- Claude-side workers may run with permission prompts disabled. Keep their allowlist minimal and prefer an explicit `blocked` response over any uncertain action.
- Kimi-side automatic dispatch is deliberately gated off in the default configuration.
- Conversations are not authorization to perform external or irreversible actions. Deployments, pushes, purchases and messages to third parties require a human decision.
## Development
Safe tests use temporary databases and fake launchers/listeners/workers:
```bash
uv run python systemd/test_dispatcher.py
```
`test_bridge.py` is a destructive end-to-end test that deletes and recreates `bridge.db`. Run it only in a disposable copy of the project before live traffic, never against a database containing real messages.
Current safe suite: 76 dispatcher tests, including a deterministic stress test for concurrent supervisors against a non-WAL database held by a writer.
`systemd/schema.py` is the shared core of the dispatcher: DDL, the connection recipe, the `config.json` reader and the single definition of the dispatch set used by both the listener and `--recover`. Change dispatch rules there, not in the callers.
## Known limitations
See [TODO.md](TODO.md). The main open items are operational: minimal permissions for headless workers and visibility of `blocked` outcomes.
## License
[MIT](LICENSE)
TDQS
Scored across 8 tools
Most tools target clearly distinct operations: listener controls the local daemon, send_message emits, receive_messages reads, and claim/release/mark_read handle message ownership and acknowledgement. The main soft spots are send_message versus start_conversation (start implicitly posts a root task) and receive_messages versus claim_message, though the descriptions spell out the difference reasonably well.
Six of eight tools follow a clear verb_noun pattern (send_message, start_conversation, claim_message, release_message, receive_messages, mark_read), which is highly readable. The two outliers, 'listener' and 'conversation', are bare nouns, a minor deviation from the otherwise predictable convention.
Eight tools is a well-scoped surface for an inter-agent messaging bridge, with each tool covering a distinct lifecycle step (dispatch, inbox, claim lease, ack, conversation control). No tool looks redundant or gratuitous.
The message lifecycle is well covered end-to-end: send with dedup/reply linking, receive, atomic claim with lease, release, acknowledge, plus bounded conversation start/inspect/steer and listener enable/disable. Minor gaps remain — there is no direct 'get message by id' or 'list conversations' operation, so agents must go through receive_messages or track ids themselves.