peer-bus

peer-bus: A Shared Message Bus for Coding Agents

Running several coding-agent sessions at the same time turns you into a manual relay. One session finishes a migration, another is blocked on a shared port, and a third is editing the same staging environment on a second machine. Tool-specific features like Claude Code agent teams coordinate instances of the same client on one machine, but they stop at that tool’s boundary.

The idea came from seeing xAI’s Grok Bots message each other rather than relying on a human to copy context between windows. I built a bus for my own omp sessions first, then expanded it over stdio MCP to include Claude Code, Codex, Antigravity (agy), T3 Code, and OpenCode. It is now open-sourced as peer-bus.

peer-bus diagram showing omp, Claude Code, Codex, Antigravity, OpenCode, Hermes, and T3 Code connected to one shared bus backed by SQLite, Markdown, or Postgres

How clients connect

Different coding agents expose incompatible extension APIs, or none at all, but almost all of them support stdio MCP. Because the omp integration came first, peer-bus puts two client layers over one BusStore interface (src/store/types.ts):

  • A native extension for omp (src/index.ts, built on pi’s extension API) that connects over a local unix socket to a per-machine daemon (src/daemon.ts) and injects incoming messages into live sessions.
  • A standalone stdio JSON-RPC 2.0 MCP server (bin/mcp.ts) for Claude Code, Codex, Antigravity, T3 Code, OpenCode, and any other stdio MCP client.

Both paths read and write the same three tables (or files): sessions, messages, and cursors. An Antigravity session over MCP sees omp sessions on the same roster and addresses them by name, session ID, last, all, or host:<host> when that host has a single live session.

bin/mcp.ts implements stdio JSON-RPC 2.0 directly in 351 lines rather than pulling in an MCP SDK. It exposes five tools (peer_sessions, peer_send, peer_ask, peer_receive, peer_label) and heartbeats every 20 seconds. Running peer-bus on a new machine takes Bun and a git clone, with no node_modules install.

Why one daemon per machine

My first pass had every omp session open its own Postgres connection and run its own poll loop. Ten open sessions meant ten pools and ten poll loops keeping serverless Neon compute awake continuously.

src/daemon.ts collapses that to one singleton process per machine behind ~/.peer-bus/daemon.sock (0600), guarded by an exclusive PID lockfile (flag: "wx"). Sessions open a unix socket to the daemon instead of opening their own database connections:

  • One Bun.SQL pool (max: 2, 30-second idle timeout) serves every local omp session regardless of how many are open.
  • Local omp-to-omp sends bypass polling. handleSend writes the row, reads it back, and pushes it down the recipient’s unix socket immediately. Sends from local MCP clients or the CLI write straight to the store, so local omp sessions pick those up - along with messages from other machines - on the daemon’s 2-second poll cycle.
  • When no session has been attached for 15 minutes (IDLE_EXIT_MS), the daemon shuts itself down so Neon compute can suspend.

Serverless Postgres introduces one more failure mode: a connection held across a Neon compute suspend can wedge an awaited query indefinitely. Inside src/store/postgres.ts, every runtime query races an 8-second timer (DB_QUERY_MS), and on timeout the store closes and discards its pool so the next call opens a fresh one. Outside the poll loop in src/daemon.ts, a 60-second watchdog (CYCLE_WATCHDOG_MS) calls process.exit(1) if a poll cycle stays in flight past its deadline, and the next session heartbeat respawns a clean daemon.

How messages enter a session

Every message pushed into an active agent transcript stays in the conversation history and gets replayed on every later LLM turn. Dumping full multi-paragraph broadcasts into every session burns tokens fast and interrupts agents doing unrelated work.

src/daemon.ts and src/index.ts split delivery by message kind (omp uses pi’s pi.sendMessage API):

pi.sendMessage(
	{
		customType: "peer-bus",
		content: [`[peer-bus ${rows.length} message(s)]`, ...lines, hint].join("\n"),
		display: true,
		attribution: "agent",
	},
	requests.length ? { triggerTurn: true } : { deliverAs: "nextTurn" },
);

A note is flattened and clipped to 180 characters (EXCERPT_CHARS) and delivered with deliverAs: "nextTurn". It rides along on the agent’s next turn without waking an idle session, and the full body remains on the bus for peer_receive({ id }) if the agent wants it. An ask or steer travels whole up to 2,000 characters (REQUEST_CHARS) and sets triggerTurn: true, because a clipped question forces a second round trip to the inbox before the peer can answer.

Inbound pushes coalesce over a 600ms window (COALESCE_MS), so a burst of updates lands as one [peer-bus N message(s)] block rather than waking the model once per row. Muting a session with peer_watch({ enabled: false }) or PEER_BUS_QUIET=1 skips that session in both pump() and push(). Leaving its cursor untouched keeps muted messages queued in the log until the session resumes listening.

Single machine: SQLite (or Markdown)

SQLite (src/store/sqlite.ts) is the zero-config default at ~/.peer-bus/peer-bus.sqlite (0600). It stays local to one host. That machine’s daemon, CLI commands, and MCP servers all open the same .sqlite file, so it enables WAL mode and a 5-second busy_timeout to avoid lock errors. To run the SQLite test suite under Node as well as Bun without native addons, openSqlite switches between the two built-in drivers:

function openSqlite(filePath: string): SqliteDbLike {
	if ("Bun" in globalThis) {
		const { Database } = require("bun:sqlite") as {
			Database: new (path: string, opts?: { create?: boolean }) => SqliteDbLike;
		};
		return new Database(filePath, { create: true });
	}
	const { DatabaseSync } = require("node:sqlite") as {
		DatabaseSync: new (path: string) => SqliteDbLike;
	};
	return new DatabaseSync(filePath);
}

If you want readable files in a git repo, an Obsidian vault, or a Syncthing folder, the Markdown backend (src/store/md.ts) implements the same BusStore interface over three files (messages.md, sessions.md, cursors.md). Running bun bin/bus.ts send all "migration finished on branch feat/auth" --name "api@Hades#a1b2" --backend md --path /tmp/peer-bus writes a block like this to messages.md:

## #1 | 2026-12-01T19:12:37.620Z | note | api@Hades#a1b2 -> all
<!-- bus:{"id":1,"ts":"2026-12-01T19:12:37.620Z","from_id":"cli:Hades:72161","from_name":"api@Hades#a1b2","to_id":null,"kind":"note","reply_to":null,"meta":{}} -->

migration finished on branch feat/auth

<!-- /bus -->

Structured metadata sits in the HTML comment and the body runs until <!-- /bus --> (escaped if a message body contains that literal line). Multiple local processes share the files via a cooperative .lock file (flag: "wx", dead-PID or 10-second stale reclamation) and atomic temp-file renames.

Multiple machines: Postgres

Postgres (src/store/postgres.ts and schema.sql) connects daemons and MCP servers across machines over Bun.SQL. Neon’s free tier is a good fit because its compute suspends after inactivity, though any Postgres URL works. Putting the shared state in a hosted database rather than exposing the daemon over TCP keeps every workstation client-only with no listening network port, and none of them has to stay awake. peer-bus selects Postgres automatically when ~/.config/peer-bus/postgres.env contains a connection URL, unless a CLI flag or backend env var overrides it.

Once multiple hosts share one roster, liveness cannot rely on local PIDs alone. Across all three backends, src/store/types.ts uses the same five-line rule:

export function alive(row: LivenessFields): boolean {
	if (row.status === "offline") return false;
	if (row.host === localHost() && row.pid !== null) return pidAlive(row.pid);
	return row.age_seconds < LIVE_WINDOW_S;
}

If a row belongs to the local host and carries a PID, process.kill(pid, 0) decides immediately whether the process still exists (EPERM counts as alive). Remote hosts cannot be probed by PID, so they fall back to a 300-second heartbeat window (LIVE_WINDOW_S).

What broke in early versions

1. The process.execPath fork bomb. omp ships as a compiled Bun binary, so inside an extension process.execPath is omp, not bun. Spawning [DAEMON_PATH, "serve"] with process.execPath handed the script path to a new omp process as a positional user prompt, and that child session loaded peer-bus and tried to start the daemon again. bunBinary() in src/index.ts now resolves OMP_BUN or Bun.which("bun") on PATH instead of process.execPath, and bunRuntime() probes --version once per process before allowing a spawn:

function bunRuntime(): string | null {
	if (bunVerdict === true) return bunBinary();
	if (bunVerdict === false) return null;
	const candidate = bunBinary();
	try {
		const probe = spawnSync(candidate, ["--version"], { encoding: "utf8", timeout: 5000 });
		bunVerdict = probe.status === 0 && /^\d+\.\d+/.test(probe.stdout ?? "");
	} catch {
		bunVerdict = false;
	}
	if (!bunVerdict) debug(`refusing to spawn the daemon: ${candidate} is not a bun runtime`);
	return bunVerdict ? candidate : null;
}

2. Session name collisions from raw ID prefixes. Early session names appended the first four characters of the session ID (code@Hades#01a1). Two sessions created in the same run share a time-ordered prefix (01a11885... and 01a1187d...), so both got #01a1 and every send by name failed as ambiguous. idTag() in src/index.ts hashes the full ID with 32-bit FNV-1a and encodes four base-36 characters:

function idTag(sessionId: string): string {
	let hash = 0x811c9dc5;
	for (let index = 0; index < sessionId.length; index++) {
		hash = Math.imul(hash ^ sessionId.charCodeAt(index), 0x01000193) >>> 0;
	}
	return hash.toString(36).padStart(4, "0").slice(-4);
}

Sessions created in the same run no longer collide on their timestamp prefix, and a resumed session keeps its previous name because its session ID is unchanged.

3. Disposed context timers on resumed sessions. Arming the heartbeat interval and push flush timer on the extension host’s context worked on fresh sessions and silently broke on resumed ones. When a resumed session disposed its startup context after session_start, the host tore down those timers, leaving the session stale on the roster and dropping pending flushes. Moving both timers to process-owned setInterval/setTimeout calls and refreshing a module-level lastCtx reference on every lifecycle event (session_start, agent_start, agent_end) resolved both failures.

4. Accidental broadcasts from a defaulted recipient. An early CLI revision defaulted send to broadcast when the recipient was omitted. A mistyped shell command delivered the message to every live session across every machine. Both bin/bus.ts and the store layer now reject sends without an explicit recipient; broadcasting requires passing an explicit target such as all.

Limits and security

MCP tool calls are pull-based. An MCP server speaking over stdin and stdout cannot inject an unsolicited turn into an idle MCP client session. Those clients discover peers with peer_sessions, pull messages with peer_receive, or block on peer_ask for a reply. Live push delivery into an idle turn exists only in the native omp extension, where omp exposes pi.sendMessage(..., { triggerTurn: true }) to extensions.

peer-bus assumes a single trusted user on personal machines. There is no per-session authentication, no signing of messages (unlike Buzz’s keypair event chain), and local SQLite and Markdown files sit in plaintext on disk with 0600 permissions. The MCP server runs over local stdio with no listening TCP port, and the Postgres path is intended for your own machines sharing a private database, never for untrusted peers or credentials.

Source and client setup snippets are at github.com/danieljohnmorris/peer-bus.