Skip to main content
Glama
README.md
# dia-bridge

> **先说清楚**:这是一套基于 **MCP** 的桥接方案,不是纯网络协议反代。因为目前 Dia 只有 macOS 和 Windows 桌面端(没有 Linux 版),所以跑 Dia 的机器必须是桌面系统——**当前版本已支持 macOS**(Windows 暂未适配),Linux 电脑可以把服务跑在 Mac 上,再通过 SSH 隧道或 Tailscale 远程连过来用。

A Magpie (`kind: "tools"`) / OpenCode plugin that exposes the locally running macOS **Dia** browser AI assistant (`company.thebrowser.dia`) to Claude Code, Codex, OpenCode, and other MCP-capable agents via a single `dia_ask(prompt)` tool.

> **Terms of Service & Account Risk Warning / 风险提示**
>
> This plugin drives the Dia desktop application outside its official interactive workflow via macOS Accessibility automation. Automated or programmatic use of Dia may violate The Browser Company's Terms of Service and carries a risk of rate-limiting, feature restriction, or account suspension. Use it solely with your own local Dia installation and at your own risk.
>
> 本插件通过 macOS 辅助功能在官方交互界面之外调用 Dia,可能违反 Dia / The Browser Company 的服务条款,存在触发风控或账号被封禁的风险。请仅在个人本地环境谨慎使用,风险自负。

## Why macOS Accessibility (AX)?

- Dia's AI backend (`https://ai-service.diabrowser.engineering/claude/messages`) requires proprietary **BCNY** application-layer encryption (plaintext Anthropic JSON returns HTTP `400`). BCNY has not been reverse-engineered.
- Dia's local `agent-server` unix socket enforces a single-client lock (`409 Already connected`, held by Dia itself) and delegates all BCNY-encrypted LLM requests back to Dia.
- Dia's AI panel is native macOS UI rather than a web page (`chrome://assistant/...` is an empty `Placeholder WebUI`), so CDP / browser extensions cannot access it.
- macOS Accessibility (`AXValue` direct write) is therefore the only non-invasive path that works without disabling SIP or re-signing `Dia.app`.

## How It Works

1. **Single-request mutex (`src/mutex.mjs`)**: Serializes all calls in-process and across processes via a PID-aware lockfile, honoring `AbortSignal` and timeouts while queued.
2. **Environment verification (`src/ax.mjs`)**: Checks macOS platform, Dia process (`company.thebrowser.dia`), and Accessibility trust (`AXIsProcessTrusted()`).
3. **Pre-submit disk snapshot (`src/store.mjs`)**: Records byte offsets of every existing `logs/feedback.jsonl` and file states under `work/` in `~/Library/Application Support/Dia/User Data/Default/AgentServer/contexts/<uuid>/` so historical answers are never mistaken for new ones.
4. **Direct `AXValue` write (`src/ax.mjs`)**: Locates Dia's writable `AXTextArea` and writes the prompt directly to `AXValue` (no simulated typing keystrokes, preventing Chinese IME corruption), then submits.
5. **Answer polling (`src/store.mjs`)**: Reads only newly appended bytes in `logs/feedback.jsonl` (skipping `thinking` blocks) and falls back to newly written text files in `work/`, returning the full answer once stable.

## Requirements

- **macOS** (Darwin)
- **Dia browser** (`company.thebrowser.dia`) running with at least one open window showing the AI chat input box
- **macOS Accessibility permission** granted to the host process running Magpie:
  1. Open **System Settings -> Privacy & Security -> Accessibility**(系统设置 -> 隐私与安全性 -> 辅助功能)
  2. Add and enable **Magpie** (or the terminal / runtime hosting `magpie`)
  3. Restart Magpie (or toggle `dia-bridge` off and back on)

## Installation in Magpie

```bash
magpie plugin add ./dia-bridge
```

Magpie exposes plugin tools on its built-in MCP server at `/mcp/magpie/tools` (named `dia-bridge_dia_ask`) and in the Library MCP router as `dia-bridge__dia_ask`.

Example for Claude Code:

```bash
claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/tools
```

## Standalone MCP Server (for Linux / Remote Clients or Direct Use)

`dia-bridge` also ships a zero-dependency standalone MCP server (`bin/dia-bridge-mcp.mjs`) that works without Magpie and defaults to a **120s** timeout (avoiding Magpie's 55s tool call cap).

### 1. Streamable HTTP Mode (Mac host → Linux / remote agents)

Start on the Mac running Dia:

```bash
# Localhost only (recommended with SSH tunnel)
node bin/dia-bridge-mcp.mjs --http --host 127.0.0.1 --port 3847

# Or bind to Tailscale/LAN with a Bearer token
DIA_MCP_TOKEN="your-secret-token" node bin/dia-bridge-mcp.mjs --http --host 0.0.0.0 --port 3847
```

From a Linux machine (via SSH port forward):

```bash
ssh -N -L 3847:127.0.0.1:3847 <your-mac>
claude mcp add --transport http dia-bridge http://127.0.0.1:3847/mcp
```

Or with Bearer auth over Tailscale/LAN:

```bash
claude mcp add --transport http dia-bridge http://<mac-ip>:3847/mcp \
  --header "Authorization: Bearer your-secret-token"
```

Health check: `GET http://127.0.0.1:3847/health` returns `{ ok, service, version, busy, queueLength }`.

### 2. Stdio Mode (direct local MCP on Mac)

```bash
claude mcp add dia-bridge -- node /path/to/dia-bridge/bin/dia-bridge-mcp.mjs --stdio
```

## Tool Reference

### `dia_ask`

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `prompt` | `string` | Yes | Prompt sent to Dia's AI assistant. |
| `timeoutMs` | `number` | No | Timeout in ms (default `50000`, range `1000`–`300000`). |

Returns: `string` (the assistant's full reply text).

### Environment Variables

- `DIA_CONTEXTS_DIR`: Override the default Dia `AgentServer/contexts` directory (useful for non-default Dia profiles).

## Known Limitations

- **Latency & Magpie 55s cap**: Simple Dia replies take ~16s+; complex prompts can exceed Magpie's 55-second tool timeout (`ctx.abort`). `dia_ask` aborts cleanly when `ctx.abort` fires.
- **No concurrency**: Requests are strictly serialized via mutex; Dia can only run one chat turn at a time.
- **Dia must remain open**: Requires an active desktop session with Dia running and an open window.
- **No streaming / system prompt / native tool protocol**: Returns the full reply after it lands on disk.
- **No credential access**: This plugin never reads Dia Keychain items, Firebase tokens, refresh tokens, or device signatures.

## Development & Tests

```bash
npm test
```

## License

MIT