# Understanding the Proxy Bridge Mechanism for Agent Communication in Munder Difflin

> Explore the proxy bridge mechanism in Munder Difflin enabling LLM CLI agents to join the Hive protocol. Discover how it intercepts API traffic and synthesizes lifecycle events for seamless communication.

- Repository: [Chaitanya Giri/munder-difflin](https://github.com/chaitanyagiri/munder-difflin)
- Tags: deep-dive
- Published: 2026-08-22

---

**The proxy bridge mechanism enables hook-less LLM CLI agents to fully participate in Munder Difflin’s Hive protocol by spawning a reverse-proxy sidecar that intercepts API traffic and synthesizes lifecycle events over a Unix-domain socket.**

Munder Difflin orchestrates diverse LLM providers through a unified Hive protocol that tracks status updates, tool calls, and cost metrics in real time. While most providers ship with a native **hook-shim** that writes directly to the `HIVE_SOCK` Unix socket, agents like Qwen and other "hook-less" CLIs lack this capability. The **proxy bridge mechanism** solves this integration gap by creating a lightweight Node.js sidecar that transparently proxies HTTP requests while parsing responses to emit the same socket-based telemetry that native hooks provide.

## Bridge Configuration and Runtime Detection

The core first determines whether an agent requires a proxy bridge by inspecting its provider descriptor. In [`src/shared/agentProvider.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/shared/agentProvider.ts), providers that lack native hook support declare a `bridge` object of kind `'proxy'`.

```typescript
// src/shared/agentProvider.ts – lines 44-50
{
  id: 'qwen',
  label: 'Qwen',
  hiveAware: false,
  bridge: {
    kind: 'proxy',
    api: 'openai',
    baseUrlEnv: 'OPENAI_BASE_URL',
    inboxDelivery: 'terminal'
  }
}

```

The `bridgeOf()` helper (lines 82-86) returns this descriptor at runtime. When `bridge.kind` equals `'proxy'`, the core switches from direct socket wiring to sidecar initialization.

## Sidecar Initialization and Environment Wiring

When `Hive.ensureAgent()` detects a proxy-tier provider, it invokes `startProxyBridge()` located in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) (lines 49-57). This method performs three critical setup operations:

1. **Shim Generation**: It writes the embedded `PROXY_BRIDGE_SHIM` source code to `<hive>/bin/hive-proxy.cjs` as a dependency-free Node.js script.
2. **Port Allocation**: It binds an ephemeral loopback port (e.g., `127.0.0.1:34567`) to intercept the CLI’s upstream traffic.
3. **Environment Injection**: It spawns the sidecar as a child process with a specific environment block (lines 68-78):

```typescript
const env = {
  HIVE_SOCK: this.sockPath(),           // Unix domain socket for Hive events
  AGENT_ID: agentId,                    // Unique agent identifier
  UPSTREAM_BASE_URL: upstreamUrl,       // Real API endpoint (e.g., OpenAI)
  HIVE_PROXY_SESSION: sessionId,        // Session correlation ID
  HIVE_PROXY_API: desc.api              // 'openai' | 'anthropic'
};

```

The sidecar immediately overrides the CLI’s base URL environment variable (e.g., `OPENAI_BASE_URL`) to point to its own loopback listener, ensuring all LLM traffic routes through the proxy.

## Traffic Interception and Event Synthesis

Once active, the proxy bridge operates as a transparent reverse-proxy. Every HTTP request from the CLI forwards unchanged to the real upstream URL. However, the shim parses both the request payload and the streaming SSE or JSON response to extract:

- Token usage statistics
- Tool-call invocations
- Model metadata
- Finish reasons

While streaming or upon completion, the sidecar emits synthetic Hive protocol events back to the main process via `HIVE_SOCK`. These include `Status` updates, `ToolUse` records, `CostSample` metrics, and lifecycle `Stop` signals. This behavior mirrors the native hook-shim implementation, ensuring the core receives consistent telemetry regardless of the agent type.

## Idle Detection and Stop Signals

To maintain protocol parity with hook-based agents, the proxy bridge implements an idle detection mechanism. If no new HTTP request arrives within approximately **800 milliseconds**, the shim fires a synthetic `Stop` event via the socket. This logic, implemented in the `armStop()` function within `PROXY_BRIDGE_SHIM`, prevents hung sessions and ensures accurate billing and session accounting when the CLI enters an idle state.

## Lifecycle Management and Cleanup

Each active sidecar is tracked in the `proxyChildren` Map (`Map<agentId, ChildProcess>`) within the Hive core. This registry enables precise resource management through two key methods:

- **`stopProxyBridge(agentId)`**: Terminates the specific child process for a given agent.
- **`stopAllProxyBridges()`**: Iterates the Map to kill every active sidecar during application shutdown.

These methods guarantee that no orphan proxy processes remain after agent removal or when the Munder Difflin application exits, preventing resource leaks and port exhaustion.

## Practical Configuration and Usage

### Defining a Proxy-Tier Provider

To add a new hook-less CLI, declare the bridge descriptor in [`src/shared/agentProvider.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/shared/agentProvider.ts):

```typescript
{
  id: 'qwen',
  label: 'Qwen',
  defaultCommand: 'qwen',
  autoModeFlag: '--no-permission',
  hiveAware: false,
  canReceiveInbox: true,
  bridge: {
    kind: 'proxy',
    api: 'openai',
    baseUrlEnv: 'OPENAI_BASE_URL',
    inboxDelivery: 'terminal'
  }
}

```

### Debugging the Sidecar Manually

For troubleshooting, you can launch the proxy bridge outside of Munder Difflin:

```bash
export HIVE_SOCK=/tmp/munder-difflin/hooks.sock
export AGENT_ID=debug-qwen
export UPSTREAM_BASE_URL=https://api.openai.com/v1
export HIVE_PROXY_SESSION=proxy-debug-123
export HIVE_PROXY_API=openai

node ~/.munder-difflin/bin/hive-proxy.cjs

```

The process outputs a JSON line like `{"port":34567}` and remains active, forwarding requests and printing emitted Hive events to stdout.

### Programmatic Cleanup

When tearing down agents programmatically, ensure the sidecar terminates cleanly:

```typescript
// Terminate a specific agent's bridge
hive.stopProxyBridge('my-qwen-agent');

// Or shutdown all proxy bridges during app exit
hive.stopAllProxyBridges();

```

## Summary

- The **proxy bridge** integrates hook-less LLM CLIs by acting as a reverse-proxy sidecar that parses HTTP traffic.
- Configuration occurs in [`src/shared/agentProvider.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/shared/agentProvider.ts) using a `bridge` descriptor with `kind: 'proxy'`.
- The core spawns the sidecar via `startProxyBridge()` in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts), which writes and executes `hive-proxy.cjs`.
- Environment variables (`HIVE_SOCK`, `UPSTREAM_BASE_URL`, etc.) wire the CLI traffic through the local proxy.
- The sidecar synthesizes Hive events (`Status`, `ToolUse`, `CostSample`, `Stop`) by parsing streaming responses.
- An **800ms idle timer** triggers automatic `Stop` events to maintain protocol consistency.
- The `proxyChildren` Map tracks all sidecars, ensuring clean termination via `stopProxyBridge()` or `stopAllProxyBridges()`.

## Frequently Asked Questions

### What is the difference between a hook-shim and a proxy bridge?

A **hook-shim** is native code embedded within the CLI agent that writes Hive protocol messages directly to the `HIVE_SOCK` Unix socket. A **proxy bridge** is an external Node.js sidecar used when the CLI lacks hook capabilities; it intercepts HTTP traffic, parses responses, and synthesizes the same socket events on the agent’s behalf.

### How does the proxy bridge handle different API formats like OpenAI versus Anthropic?

The bridge descriptor specifies the expected API shape via the `api` field (either `'openai'` or `'anthropic'`). The `PROXY_BRIDGE_SHIM` source embedded in [`src/main/hive.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/hive.ts) adapts its parsing logic based on `HIVE_PROXY_API`, ensuring correct extraction of token usage and tool-call data regardless of whether the upstream follows OpenAI’s or Anthropic’s JSON schema.

### What triggers the idle Stop event in the proxy bridge?

The sidecar implements an `armStop()` function that starts an approximately **800 millisecond** timer after each request completes. If no subsequent HTTP request arrives before the timer expires, the shim automatically emits a `Stop` event to the Hive socket. This mechanism ensures that idle sessions are properly closed even when the underlying CLI does not explicitly signal completion.

### How do I verify that a proxy bridge is running correctly for an agent?

Check that the `hive-proxy.cjs` process appears in your system process list with the correct `AGENT_ID` environment variable. You can also manually launch the sidecar using the debugging environment variables described above and monitor the JSON events it prints to stdout. If the CLI’s requests return errors, verify that `UPSTREAM_BASE_URL` points to the correct external API endpoint and that the loopback port printed by the shim is accessible.