dia-bridge 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 binbin ye
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # dia-bridge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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.
4
+
5
+ > **Terms of Service & Account Risk Warning / 风险提示**
6
+ >
7
+ > 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.
8
+ >
9
+ > 本插件通过 macOS 辅助功能在官方交互界面之外调用 Dia,可能违反 Dia / The Browser Company 的服务条款,存在触发风控或账号被封禁的风险。请仅在个人本地环境谨慎使用,风险自负。
10
+
11
+ ## Why macOS Accessibility (AX)?
12
+
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+ - macOS Accessibility (`AXValue` direct write) is therefore the only non-invasive path that works without disabling SIP or re-signing `Dia.app`.
17
+
18
+ ## How It Works
19
+
20
+ 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.
21
+ 2. **Environment verification (`src/ax.mjs`)**: Checks macOS platform, Dia process (`company.thebrowser.dia`), and Accessibility trust (`AXIsProcessTrusted()`).
22
+ 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.
23
+ 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.
24
+ 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.
25
+
26
+ ## Requirements
27
+
28
+ - **macOS** (Darwin)
29
+ - **Dia browser** (`company.thebrowser.dia`) running with at least one open window showing the AI chat input box
30
+ - **macOS Accessibility permission** granted to the host process running Magpie:
31
+ 1. Open **System Settings -> Privacy & Security -> Accessibility**(系统设置 -> 隐私与安全性 -> 辅助功能)
32
+ 2. Add and enable **Magpie** (or the terminal / runtime hosting `magpie`)
33
+ 3. Restart Magpie (or toggle `dia-bridge` off and back on)
34
+
35
+ ## Installation in Magpie
36
+
37
+ ```bash
38
+ magpie plugin add ./dia-bridge
39
+ ```
40
+
41
+ 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`.
42
+
43
+ Example for Claude Code:
44
+
45
+ ```bash
46
+ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/tools
47
+ ```
48
+
49
+ ## Standalone MCP Server (for Linux / Remote Clients or Direct Use)
50
+
51
+ `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).
52
+
53
+ ### 1. Streamable HTTP Mode (Mac host → Linux / remote agents)
54
+
55
+ Start on the Mac running Dia:
56
+
57
+ ```bash
58
+ # Localhost only (recommended with SSH tunnel)
59
+ node bin/dia-bridge-mcp.mjs --http --host 127.0.0.1 --port 3847
60
+
61
+ # Or bind to Tailscale/LAN with a Bearer token
62
+ DIA_MCP_TOKEN="your-secret-token" node bin/dia-bridge-mcp.mjs --http --host 0.0.0.0 --port 3847
63
+ ```
64
+
65
+ From a Linux machine (via SSH port forward):
66
+
67
+ ```bash
68
+ ssh -N -L 3847:127.0.0.1:3847 <your-mac>
69
+ claude mcp add --transport http dia-bridge http://127.0.0.1:3847/mcp
70
+ ```
71
+
72
+ Or with Bearer auth over Tailscale/LAN:
73
+
74
+ ```bash
75
+ claude mcp add --transport http dia-bridge http://<mac-ip>:3847/mcp \
76
+ --header "Authorization: Bearer your-secret-token"
77
+ ```
78
+
79
+ Health check: `GET http://127.0.0.1:3847/health` returns `{ ok, service, version, busy, queueLength }`.
80
+
81
+ ### 2. Stdio Mode (direct local MCP on Mac)
82
+
83
+ ```bash
84
+ claude mcp add dia-bridge -- node /path/to/dia-bridge/bin/dia-bridge-mcp.mjs --stdio
85
+ ```
86
+
87
+ ## Tool Reference
88
+
89
+ ### `dia_ask`
90
+
91
+ | Parameter | Type | Required | Description |
92
+ | --- | --- | --- | --- |
93
+ | `prompt` | `string` | Yes | Prompt sent to Dia's AI assistant. |
94
+ | `timeoutMs` | `number` | No | Timeout in ms (default `50000`, range `1000`–`300000`). |
95
+
96
+ Returns: `string` (the assistant's full reply text).
97
+
98
+ ### Environment Variables
99
+
100
+ - `DIA_CONTEXTS_DIR`: Override the default Dia `AgentServer/contexts` directory (useful for non-default Dia profiles).
101
+
102
+ ## Known Limitations
103
+
104
+ - **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.
105
+ - **No concurrency**: Requests are strictly serialized via mutex; Dia can only run one chat turn at a time.
106
+ - **Dia must remain open**: Requires an active desktop session with Dia running and an open window.
107
+ - **No streaming / system prompt / native tool protocol**: Returns the full reply after it lands on disk.
108
+ - **No credential access**: This plugin never reads Dia Keychain items, Firebase tokens, refresh tokens, or device signatures.
109
+
110
+ ## Development & Tests
111
+
112
+ ```bash
113
+ npm test
114
+ ```
115
+
116
+ ## License
117
+
118
+ MIT
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ STANDALONE_DEFAULT_TIMEOUT_MS,
4
+ startHttpMcpServer,
5
+ startStdioMcpServer,
6
+ } from "../src/mcp-server.mjs"
7
+
8
+ function parseArgs(argv) {
9
+ const opts = {
10
+ mode: "http",
11
+ host: process.env.DIA_MCP_HOST || "127.0.0.1",
12
+ port: Number(process.env.DIA_MCP_PORT || 3847),
13
+ token: process.env.DIA_MCP_TOKEN || "",
14
+ timeoutMs: Number(process.env.DIA_TIMEOUT_MS || STANDALONE_DEFAULT_TIMEOUT_MS),
15
+ contextsDir: process.env.DIA_CONTEXTS_DIR || undefined,
16
+ help: false,
17
+ }
18
+
19
+ for (let i = 0; i < argv.length; i++) {
20
+ const arg = argv[i]
21
+ if (arg === "--stdio") {
22
+ opts.mode = "stdio"
23
+ } else if (arg === "--http") {
24
+ opts.mode = "http"
25
+ } else if (arg === "--host" && argv[i + 1]) {
26
+ opts.host = argv[++i]
27
+ } else if (arg === "--port" && argv[i + 1]) {
28
+ opts.port = Number(argv[++i])
29
+ } else if (arg === "--token" && argv[i + 1]) {
30
+ opts.token = argv[++i]
31
+ } else if (arg === "--timeout-ms" && argv[i + 1]) {
32
+ opts.timeoutMs = Number(argv[++i])
33
+ } else if (arg === "--contexts-dir" && argv[i + 1]) {
34
+ opts.contextsDir = argv[++i]
35
+ } else if (arg === "-h" || arg === "--help") {
36
+ opts.help = true
37
+ } else {
38
+ throw new Error(`Unknown argument: ${arg}`)
39
+ }
40
+ }
41
+
42
+ if (!Number.isInteger(opts.port) || opts.port < 0 || opts.port > 65535) {
43
+ throw new Error(`Invalid port: ${opts.port}`)
44
+ }
45
+ return opts
46
+ }
47
+
48
+ function printHelp() {
49
+ console.error(
50
+ [
51
+ "Usage: dia-bridge-mcp [options]",
52
+ "",
53
+ "Options:",
54
+ " --http Run Streamable HTTP MCP server (default)",
55
+ " --stdio Run stdio MCP server (for local MCP clients)",
56
+ " --host <addr> Bind address for HTTP mode (default: 127.0.0.1, env: DIA_MCP_HOST)",
57
+ " --port <port> Port for HTTP mode (default: 3847, env: DIA_MCP_PORT)",
58
+ " --token <secret> Optional Bearer token for HTTP auth (env: DIA_MCP_TOKEN)",
59
+ " --timeout-ms <ms> Default Dia request timeout (default: 120000, env: DIA_TIMEOUT_MS)",
60
+ " --contexts-dir <path> Override Dia AgentServer/contexts dir (env: DIA_CONTEXTS_DIR)",
61
+ " -h, --help Show this help",
62
+ ].join("\n"),
63
+ )
64
+ }
65
+
66
+ async function main() {
67
+ let opts
68
+ try {
69
+ opts = parseArgs(process.argv.slice(2))
70
+ } catch (err) {
71
+ console.error(`[dia-bridge-mcp] ${err.message}`)
72
+ printHelp()
73
+ process.exit(1)
74
+ }
75
+
76
+ if (opts.help) {
77
+ printHelp()
78
+ process.exit(0)
79
+ }
80
+
81
+ if (opts.mode === "stdio") {
82
+ startStdioMcpServer({
83
+ defaultTimeoutMs: opts.timeoutMs,
84
+ contextsDir: opts.contextsDir,
85
+ })
86
+ console.error("[dia-bridge-mcp] stdio MCP server ready")
87
+ return
88
+ }
89
+
90
+ const isLoopback =
91
+ opts.host === "127.0.0.1" || opts.host === "localhost" || opts.host === "::1"
92
+ if (!isLoopback && !opts.token) {
93
+ console.error(
94
+ `[dia-bridge-mcp] WARNING: binding to non-loopback host (${opts.host}) without --token / DIA_MCP_TOKEN.`,
95
+ )
96
+ }
97
+
98
+ const instance = await startHttpMcpServer({
99
+ host: opts.host,
100
+ port: opts.port,
101
+ token: opts.token,
102
+ defaultTimeoutMs: opts.timeoutMs,
103
+ contextsDir: opts.contextsDir,
104
+ })
105
+
106
+ console.error(`[dia-bridge-mcp] Streamable HTTP MCP listening on ${instance.url}`)
107
+ console.error(`[dia-bridge-mcp] Health check: ${instance.healthUrl}`)
108
+
109
+ const shutdown = async () => {
110
+ await instance.close().catch(() => {})
111
+ process.exit(0)
112
+ }
113
+ process.once("SIGINT", shutdown)
114
+ process.once("SIGTERM", shutdown)
115
+ }
116
+
117
+ main().catch((err) => {
118
+ console.error(`[dia-bridge-mcp] fatal: ${err.message}`)
119
+ process.exit(1)
120
+ })
package/index.mjs ADDED
@@ -0,0 +1,69 @@
1
+ import { createDiaBridge, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, MIN_TIMEOUT_MS } from "./src/bridge.mjs"
2
+ import * as ax from "./src/ax.mjs"
3
+ import * as errors from "./src/errors.mjs"
4
+ import * as mcp from "./src/mcp-server.mjs"
5
+ import { DiaMutex } from "./src/mutex.mjs"
6
+ import * as store from "./src/store.mjs"
7
+
8
+ export const DIA_ASK_SCHEMA = {
9
+ type: "object",
10
+ properties: {
11
+ prompt: {
12
+ type: "string",
13
+ description: "The prompt to send to the locally running Dia browser AI assistant.",
14
+ minLength: 1,
15
+ },
16
+ timeoutMs: {
17
+ type: "number",
18
+ description: `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}; Magpie enforces a 55s tool call limit).`,
19
+ minimum: MIN_TIMEOUT_MS,
20
+ maximum: MAX_TIMEOUT_MS,
21
+ },
22
+ },
23
+ required: ["prompt"],
24
+ additionalProperties: false,
25
+ }
26
+
27
+ /**
28
+ * Magpie / OpenCode tools plugin entrypoint.
29
+ * Note: Magpie invokes every exported function in the entry module as a plugin,
30
+ * so helper internals live on `_internal` rather than top-level exported functions.
31
+ */
32
+ export const DiaBridgePlugin = async (_input, options = {}) => {
33
+ const bridge = createDiaBridge({
34
+ contextsDir: options?.contextsDir,
35
+ defaultTimeoutMs: options?.timeoutMs,
36
+ pollIntervalMs: options?.pollIntervalMs,
37
+ settleMs: options?.settleMs,
38
+ workFallbackSettleMs: options?.workFallbackSettleMs,
39
+ lockFilePath: options?.lockFilePath,
40
+ })
41
+
42
+ return {
43
+ tool: {
44
+ dia_ask: {
45
+ description:
46
+ "Send a prompt to the locally running macOS Dia browser AI assistant via Accessibility (AXValue) and return its full reply from disk. Serial execution (one request at a time), macOS-only, typical latency 15-50s.",
47
+ args: DIA_ASK_SCHEMA,
48
+ async execute(args, ctx) {
49
+ const prompt = args?.prompt
50
+ const timeoutMs = args?.timeoutMs
51
+ return await bridge.ask(prompt, {
52
+ timeoutMs,
53
+ signal: ctx?.abort,
54
+ })
55
+ },
56
+ },
57
+ },
58
+ }
59
+ }
60
+
61
+ export const _internal = {
62
+ createDiaBridge,
63
+ DiaMutex,
64
+ ax,
65
+ store,
66
+ errors,
67
+ mcp,
68
+ DIA_ASK_SCHEMA,
69
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "dia-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Magpie tools plugin that bridges Dia browser AI via macOS Accessibility (AX)",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "bin": {
8
+ "dia-bridge-mcp": "./bin/dia-bridge-mcp.mjs"
9
+ },
10
+ "files": [
11
+ "index.mjs",
12
+ "bin/",
13
+ "src/",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "keywords": [
18
+ "magpie",
19
+ "magpie-plugin",
20
+ "opencode",
21
+ "opencode-plugin",
22
+ "mcp",
23
+ "dia",
24
+ "macos",
25
+ "accessibility"
26
+ ],
27
+ "author": "binbin ye",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/DaBinBinah/dia-bridge.git"
32
+ },
33
+ "homepage": "https://github.com/DaBinBinah/dia-bridge#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/DaBinBinah/dia-bridge/issues"
36
+ },
37
+ "engines": {
38
+ "node": ">=18.0.0"
39
+ },
40
+ "scripts": {
41
+ "mcp:http": "node bin/dia-bridge-mcp.mjs --http",
42
+ "mcp:stdio": "node bin/dia-bridge-mcp.mjs --stdio",
43
+ "test": "node --test test/*.test.mjs"
44
+ },
45
+ "magpie": {
46
+ "name": "dia-bridge",
47
+ "kind": "tools",
48
+ "maxConcurrency": 1
49
+ }
50
+ }