dia-bridge 0.1.2 → 0.2.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/README.md CHANGED
@@ -1,38 +1,48 @@
1
1
  # dia-bridge
2
2
 
3
- > **先说清楚**:这是一套基于 **MCP** 的桥接方案,不是纯网络协议反代。因为目前 Dia 只有 macOS 和 Windows 桌面端(没有 Linux 版),所以跑 Dia 的机器必须是桌面系统——**当前版本已支持 macOS**(Windows 暂未适配),Linux 电脑可以把服务跑在 Mac 上,再通过 SSH 隧道或 Tailscale 远程连过来用。
3
+ > **先说清楚**:这是一套基于 **MCP** 的桥接方案,不是纯网络协议反代。因为目前 Dia 只有 macOS 和 Windows 桌面端(没有 Linux 版),所以跑 Dia 的机器必须是桌面系统——**当前版本已支持 macOS 与 Windows**,Linux 电脑可以把服务跑在 Mac 或 Windows 宿主机上,再通过 SSH 隧道或 Tailscale 远程连过来用。
4
4
 
5
- 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.
5
+ A Magpie (`kind: "tools"`) / OpenCode plugin that exposes the locally running **Dia** browser AI assistant (macOS `company.thebrowser.dia` / Windows `Dia`) to Claude Code, Codex, OpenCode, and other MCP-capable agents via a single `dia_ask(prompt)` tool.
6
6
 
7
7
  > **Terms of Service & Account Risk Warning / 风险提示**
8
8
  >
9
- > 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.
9
+ > This plugin drives the Dia desktop application outside its official interactive workflow via macOS Accessibility or Windows UI 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.
10
10
  >
11
- > 本插件通过 macOS 辅助功能在官方交互界面之外调用 Dia,可能违反 Dia / The Browser Company 的服务条款,存在触发风控或账号被封禁的风险。请仅在个人本地环境谨慎使用,风险自负。
11
+ > 本插件通过 macOS 辅助功能或 Windows UI Automation 在官方交互界面之外调用 Dia,可能违反 Dia / The Browser Company 的服务条款,存在触发风控或账号被封禁的风险。请仅在个人本地环境谨慎使用,风险自负。
12
12
 
13
- ## Why macOS Accessibility (AX)?
13
+ ## Why Native UI Automation (macOS AX / Windows UIA)?
14
14
 
15
15
  - 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.
16
- - 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.
17
- - 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.
18
- - macOS Accessibility (`AXValue` direct write) is therefore the only non-invasive path that works without disabling SIP or re-signing `Dia.app`.
16
+ - Dia's local `agent-server` IPC socket enforces a single-client lock (`409 Already connected`, held by Dia itself) and delegates all BCNY-encrypted LLM requests back to Dia.
17
+ - Dia's AI panel is native desktop UI rather than a standard web page (`chrome://assistant/...` is an empty `Placeholder WebUI`), so CDP / browser extensions cannot access it.
18
+ - Native OS UI Automation — macOS Accessibility (`AXValue` direct write) and Windows UI Automation (`.NET UIAutomationClient` `ValuePattern.SetValue` direct write) — is therefore the only non-invasive path that works without disabling SIP, re-signing `Dia.app`, or simulating keystrokes.
19
19
 
20
20
  ## How It Works
21
21
 
22
22
  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.
23
- 2. **Environment verification (`src/ax.mjs`)**: Checks macOS platform, Dia process (`company.thebrowser.dia`), and Accessibility trust (`AXIsProcessTrusted()`).
24
- 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.
25
- 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.
23
+ 2. **Environment verification (`src/ax.mjs` / `src/win-uia.mjs`)**:
24
+ - **macOS (`darwin`)**: Checks Dia process (`company.thebrowser.dia`) and Accessibility trust (`AXIsProcessTrusted()`).
25
+ - **Windows (`win32`)**: Checks that the `Dia` process is running via PowerShell (`powershell.exe -NoProfile -NonInteractive -STA`).
26
+ 3. **Pre-submit disk snapshot (`src/store.mjs`)**: Records byte offsets of every existing `logs/feedback.jsonl` and file states under `work/` so historical answers are never mistaken for new ones:
27
+ - **macOS**: `~/Library/Application Support/Dia/User Data/Default/AgentServer/contexts/<uuid>/`
28
+ - **Windows**: `%LOCALAPPDATA%\Packages\TheBrowserCompany.Dia_*\LocalCache\Local\Dia\User Data\Default\AgentServer\contexts\<uuid>\` (falls back to `%LOCALAPPDATA%\Dia\User Data\Default\AgentServer\contexts\<uuid>\`)
29
+ 4. **Direct value write (`src/ax.mjs` / `src/win-uia.mjs`)**:
30
+ - **macOS**: Locates Dia's writable `AXTextArea` and writes the prompt directly to `AXValue`.
31
+ - **Windows**: Locates Dia's writable `ControlType.Edit` or `ControlType.Document` supporting `ValuePattern` (`IsReadOnly == false`) via `.NET UIAutomationClient`, writes the prompt directly via `ValuePattern.SetValue` (never simulating typing keystrokes, preserving Chinese/Unicode/JSON verbatim), verifies readback, focuses, and submits via `InvokePattern` on a Send/Submit button (with Enter fallback).
26
32
  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.
27
33
 
28
34
  ## Requirements
29
35
 
30
- - **macOS** (Darwin)
31
- - **Dia browser** (`company.thebrowser.dia`) running with at least one open window showing the AI chat input box
32
- - **macOS Accessibility permission** granted to the host process running Magpie:
33
- 1. Open **System Settings -> Privacy & Security -> Accessibility**(系统设置 -> 隐私与安全性 -> 辅助功能)
34
- 2. Add and enable **Magpie** (or the terminal / runtime hosting `magpie`)
35
- 3. Restart Magpie (or toggle `dia-bridge` off and back on)
36
+ - **Node.js >= 18** (or Bun), zero runtime npm dependencies
37
+ - **Dia browser** running with at least one open window showing the AI chat input box
38
+ - **macOS (`darwin`)**:
39
+ - **macOS Accessibility permission** granted to the host process running Magpie:
40
+ 1. Open **System Settings -> Privacy & Security -> Accessibility**(系统设置 -> 隐私与安全性 -> 辅助功能)
41
+ 2. Add and enable **Magpie** (or the terminal / runtime hosting `magpie`)
42
+ 3. Restart Magpie (or toggle `dia-bridge` off and back on)
43
+ - **Windows (`win32`)**:
44
+ - Windows PowerShell (`powershell.exe`, built into Windows 10/11 and Windows Server) with `.NET UIAutomationClient` / `UIAutomationTypes` (built into Windows `.NET Framework`)
45
+ - No extra Accessibility permission toggle is required, provided `dia-bridge` runs at the same integrity level (non-elevated) as Dia
36
46
 
37
47
  ## Installation in Magpie
38
48
 
@@ -52,35 +62,42 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
52
62
 
53
63
  `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).
54
64
 
55
- ### 1. Streamable HTTP Mode (Mac host → Linux / remote agents)
65
+ ### 1. Streamable HTTP Mode (macOS / Windows host → Linux / remote agents)
56
66
 
57
- Start on the Mac running Dia:
67
+ Start on the Mac or Windows machine running Dia:
58
68
 
59
69
  ```bash
60
70
  # Localhost only (recommended with SSH tunnel)
61
71
  node bin/dia-bridge-mcp.mjs --http --host 127.0.0.1 --port 3847
62
72
 
63
- # Or bind to Tailscale/LAN with a Bearer token
73
+ # Or bind to Tailscale/LAN with a Bearer token (macOS / bash)
64
74
  DIA_MCP_TOKEN="your-secret-token" node bin/dia-bridge-mcp.mjs --http --host 0.0.0.0 --port 3847
65
75
  ```
66
76
 
77
+ On Windows PowerShell:
78
+
79
+ ```powershell
80
+ $env:DIA_MCP_TOKEN="your-secret-token"
81
+ node bin/dia-bridge-mcp.mjs --http --host 0.0.0.0 --port 3847
82
+ ```
83
+
67
84
  From a Linux machine (via SSH port forward):
68
85
 
69
86
  ```bash
70
- ssh -N -L 3847:127.0.0.1:3847 <your-mac>
87
+ ssh -N -L 3847:127.0.0.1:3847 <your-mac-or-windows-host>
71
88
  claude mcp add --transport http dia-bridge http://127.0.0.1:3847/mcp
72
89
  ```
73
90
 
74
91
  Or with Bearer auth over Tailscale/LAN:
75
92
 
76
93
  ```bash
77
- claude mcp add --transport http dia-bridge http://<mac-ip>:3847/mcp \
94
+ claude mcp add --transport http dia-bridge http://<host-ip>:3847/mcp \
78
95
  --header "Authorization: Bearer your-secret-token"
79
96
  ```
80
97
 
81
98
  Health check: `GET http://127.0.0.1:3847/health` returns `{ ok, service, version, busy, queueLength }`.
82
99
 
83
- ### 2. Stdio Mode (direct local MCP on Mac)
100
+ ### 2. Stdio Mode (direct local MCP on macOS / Windows)
84
101
 
85
102
  ```bash
86
103
  claude mcp add dia-bridge -- node /path/to/dia-bridge/bin/dia-bridge-mcp.mjs --stdio
@@ -93,21 +110,35 @@ claude mcp add dia-bridge -- node /path/to/dia-bridge/bin/dia-bridge-mcp.mjs --s
93
110
  | Parameter | Type | Required | Description |
94
111
  | --- | --- | --- | --- |
95
112
  | `prompt` | `string` | Yes | Prompt sent to Dia's AI assistant. |
96
- | `timeoutMs` | `number` | No | Timeout in ms (default `50000`, range `1000`–`300000`). |
113
+ | `timeoutMs` | `number` | No | Timeout in ms (default `50000` in Magpie / `120000` standalone, range `1000`–`300000`). |
97
114
 
98
115
  Returns: `string` (the assistant's full reply text).
99
116
 
117
+ ### `dia_status` (read-only)
118
+
119
+ No parameters. Returns JSON diagnostics: platform, Dia process/permission status, mutex `busy`/`queueLength`, and whether `AgentServer/contexts` exists on disk.
120
+
121
+ ### `dia_get_chat_history` (read-only)
122
+
123
+ | Parameter | Type | Required | Description |
124
+ | --- | --- | --- | --- |
125
+ | `limit` | `number` | No | Number of recent replies to read from local `feedback.jsonl` (default `5`, max `50`). |
126
+
127
+ Returns: JSON list of recent `{ contextId, updatedAt, answer }` entries without invoking UI automation.
128
+
100
129
  ### Environment Variables
101
130
 
102
- - `DIA_CONTEXTS_DIR`: Override the default Dia `AgentServer/contexts` directory (useful for non-default Dia profiles).
131
+ - `DIA_CONTEXTS_DIR`: Override the default Dia `AgentServer/contexts` directory (useful for non-default Dia profiles or custom Windows install locations).
132
+ - `DIA_LOG_LEVEL`: Structured diagnostic log level written to `stderr` (`debug` | `info` | `warn` | `error` | `silent`, default `warn`).
103
133
 
104
134
  ## Known Limitations
105
135
 
136
+ - **Windows verification status**: Windows UI Automation (`ValuePattern.SetValue` with Chinese/Unicode/JSON, readback verification, focus, and button `InvokePattern` / Enter submission) and contexts directory discovery have been verified end-to-end on Windows against live desktop UI controls, but **real Dia on Windows with a logged-in account has not yet been tested directly**. If your Windows Dia installation stores `AgentServer/contexts` at a different path, set `DIA_CONTEXTS_DIR`.
106
137
  - **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.
107
138
  - **No concurrency**: Requests are strictly serialized via mutex; Dia can only run one chat turn at a time.
108
139
  - **Dia must remain open**: Requires an active desktop session with Dia running and an open window.
109
140
  - **No streaming / system prompt / native tool protocol**: Returns the full reply after it lands on disk.
110
- - **No credential access**: This plugin never reads Dia Keychain items, Firebase tokens, refresh tokens, or device signatures.
141
+ - **No credential access**: This plugin never reads Dia Keychain/DPAPI items, Firebase tokens, refresh tokens, or device signatures.
111
142
 
112
143
  ## Development & Tests
113
144
 
package/index.mjs CHANGED
@@ -4,6 +4,7 @@ import * as errors from "./src/errors.mjs"
4
4
  import * as mcp from "./src/mcp-server.mjs"
5
5
  import { DiaMutex } from "./src/mutex.mjs"
6
6
  import * as store from "./src/store.mjs"
7
+ import * as winUia from "./src/win-uia.mjs"
7
8
 
8
9
  export const DIA_ASK_SCHEMA = {
9
10
  type: "object",
@@ -24,6 +25,25 @@ export const DIA_ASK_SCHEMA = {
24
25
  additionalProperties: false,
25
26
  }
26
27
 
28
+ export const DIA_STATUS_SCHEMA = {
29
+ type: "object",
30
+ properties: {},
31
+ additionalProperties: false,
32
+ }
33
+
34
+ export const DIA_HISTORY_SCHEMA = {
35
+ type: "object",
36
+ properties: {
37
+ limit: {
38
+ type: "number",
39
+ description: "Maximum number of recent Dia answers to return (default 5, max 50).",
40
+ minimum: 1,
41
+ maximum: 50,
42
+ },
43
+ },
44
+ additionalProperties: false,
45
+ }
46
+
27
47
  /**
28
48
  * Magpie / OpenCode tools plugin entrypoint.
29
49
  * Note: Magpie invokes every exported function in the entry module as a plugin,
@@ -43,7 +63,7 @@ export const DiaBridgePlugin = async (_input, options = {}) => {
43
63
  tool: {
44
64
  dia_ask: {
45
65
  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.",
66
+ "Send a prompt to the locally running Dia browser AI assistant (macOS Accessibility AXValue or Windows UI Automation ValuePattern) and return its full reply from disk. Serial execution (one request at a time), macOS & Windows desktop, typical latency 15-50s.",
47
67
  args: DIA_ASK_SCHEMA,
48
68
  async execute(args, ctx) {
49
69
  const prompt = args?.prompt
@@ -54,6 +74,22 @@ export const DiaBridgePlugin = async (_input, options = {}) => {
54
74
  })
55
75
  },
56
76
  },
77
+ dia_status: {
78
+ description:
79
+ "Read-only diagnostic check for Dia browser running state, macOS Accessibility / Windows UIA readiness, mutex busy state, and AgentServer contexts directory.",
80
+ args: DIA_STATUS_SCHEMA,
81
+ async execute(_args, ctx) {
82
+ return await bridge.getStatus({ signal: ctx?.abort })
83
+ },
84
+ },
85
+ dia_get_chat_history: {
86
+ description:
87
+ "Read recent Dia AI assistant replies directly from local AgentServer/contexts/*/logs/feedback.jsonl on disk (read-only, instant, no UI automation).",
88
+ args: DIA_HISTORY_SCHEMA,
89
+ async execute(args) {
90
+ return await bridge.getHistory({ limit: args?.limit })
91
+ },
92
+ },
57
93
  },
58
94
  }
59
95
  }
@@ -62,8 +98,11 @@ export const _internal = {
62
98
  createDiaBridge,
63
99
  DiaMutex,
64
100
  ax,
101
+ winUia,
65
102
  store,
66
103
  errors,
67
104
  mcp,
68
105
  DIA_ASK_SCHEMA,
106
+ DIA_STATUS_SCHEMA,
107
+ DIA_HISTORY_SCHEMA,
69
108
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dia-bridge",
3
- "version": "0.1.2",
4
- "description": "Magpie tools plugin & standalone MCP server bridging Dia browser AI via macOS Accessibility (AX)",
3
+ "version": "0.2.0",
4
+ "description": "Magpie tools plugin & standalone MCP server bridging Dia browser AI via macOS Accessibility (AX) and Windows UI Automation (UIA)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "bin": {
@@ -25,7 +25,9 @@
25
25
  "magpie-plugin",
26
26
  "mcp",
27
27
  "macos",
28
- "accessibility"
28
+ "windows",
29
+ "accessibility",
30
+ "uia"
29
31
  ],
30
32
  "author": "binbin ye",
31
33
  "license": "MIT",
package/src/ax.mjs CHANGED
@@ -159,19 +159,30 @@ function isWritableTextArea(el) {
159
159
  }
160
160
  }
161
161
 
162
- function findWritableTextArea(win) {
162
+ function inspectWindowTextAreas(win) {
163
163
  var queue = [{ el: win, depth: 0 }];
164
164
  var visited = 0;
165
165
  var maxNodes = 1500;
166
166
  var maxDepth = 18;
167
+ var writable = null;
168
+ var readOnlyBubbles = 0;
167
169
 
168
170
  while (queue.length > 0 && visited < maxNodes) {
169
171
  var item = queue.shift();
170
172
  visited += 1;
171
173
  var el = item.el;
172
- if (isWritableTextArea(el)) {
173
- return el;
174
- }
174
+ try {
175
+ if (el.role() === "AXTextArea") {
176
+ if (!writable && isWritableTextArea(el)) {
177
+ writable = el;
178
+ } else {
179
+ var val = unwrapStr(el.value ? el.value() : "");
180
+ if (val.trim().length > 0) {
181
+ readOnlyBubbles += 1;
182
+ }
183
+ }
184
+ }
185
+ } catch (e) {}
175
186
  if (item.depth >= maxDepth) continue;
176
187
  var children = [];
177
188
  try {
@@ -183,7 +194,7 @@ function findWritableTextArea(win) {
183
194
  queue.push({ el: children[i], depth: item.depth + 1 });
184
195
  }
185
196
  }
186
- return null;
197
+ return { textArea: writable, bubbles: readOnlyBubbles };
187
198
  }
188
199
 
189
200
  function findSendButton(textArea, win) {
@@ -235,10 +246,10 @@ function findSendButton(textArea, win) {
235
246
  return null;
236
247
  }
237
248
 
238
- function postReturnKeyToPid(pid) {
249
+ function postKeyCodeToPid(pid, keyCode) {
239
250
  try {
240
- var keyDown = $.CGEventCreateKeyboardEvent($(), 36, true);
241
- var keyUp = $.CGEventCreateKeyboardEvent($(), 36, false);
251
+ var keyDown = $.CGEventCreateKeyboardEvent($(), keyCode, true);
252
+ var keyUp = $.CGEventCreateKeyboardEvent($(), keyCode, false);
242
253
  if (!keyDown || !keyUp) return false;
243
254
  $.CGEventPostToPid(pid, keyDown);
244
255
  delay(0.05);
@@ -249,6 +260,29 @@ function postReturnKeyToPid(pid) {
249
260
  }
250
261
  }
251
262
 
263
+ function postReturnKeyToPid(pid) {
264
+ return postKeyCodeToPid(pid, 36);
265
+ }
266
+
267
+ function focusTextArea(textArea) {
268
+ try {
269
+ textArea.focused = true;
270
+ delay(0.08);
271
+ if (textArea.focused && textArea.focused() === true) {
272
+ return true;
273
+ }
274
+ } catch (e) {}
275
+ try {
276
+ textArea.actions.byName("AXPress").perform();
277
+ delay(0.12);
278
+ textArea.focused = true;
279
+ delay(0.05);
280
+ return true;
281
+ } catch (e) {
282
+ return false;
283
+ }
284
+ }
285
+
252
286
  function run() {
253
287
  var env = $.NSProcessInfo.processInfo.environment;
254
288
  var bundleId = ObjC.unwrap(env.objectForKey("DIA_BRIDGE_BUNDLE_ID")) || "company.thebrowser.dia";
@@ -280,6 +314,12 @@ function run() {
280
314
  return JSON.stringify({ ok: false, error: "DIA_NOT_RUNNING" });
281
315
  }
282
316
  var proc = procs[0];
317
+ // Enable AXManualAccessibility for Chromium-based Dia so lazy AX trees materialize.
318
+ try {
319
+ proc.attributes.byName("AXManualAccessibility").value = true;
320
+ delay(0.15);
321
+ } catch (e) {}
322
+
283
323
  var windows = [];
284
324
  try {
285
325
  windows = proc.windows();
@@ -292,9 +332,12 @@ function run() {
292
332
 
293
333
  var textArea = null;
294
334
  var targetWindow = null;
335
+ var bubbles = 0;
295
336
  for (var w = 0; w < windows.length; w++) {
296
- textArea = findWritableTextArea(windows[w]);
297
- if (textArea) {
337
+ var inspected = inspectWindowTextAreas(windows[w]);
338
+ if (inspected.textArea) {
339
+ textArea = inspected.textArea;
340
+ bubbles = inspected.bubbles;
298
341
  targetWindow = windows[w];
299
342
  break;
300
343
  }
@@ -311,14 +354,12 @@ function run() {
311
354
  var readback = "";
312
355
  try { readback = unwrapStr(textArea.value()); } catch (e) {}
313
356
  if (readback !== promptText) {
314
- try { textArea.focused = true; } catch (e) {}
315
- delay(0.05);
357
+ focusTextArea(textArea);
316
358
  valAttr.value = promptText;
317
359
  delay(0.05);
318
360
  }
319
361
 
320
- try { textArea.focused = true; } catch (e) {}
321
- delay(0.05);
362
+ focusTextArea(textArea);
322
363
 
323
364
  var submitMethod = "cg_return";
324
365
  var sendBtn = findSendButton(textArea, targetWindow);
@@ -327,9 +368,22 @@ function run() {
327
368
  sendBtn.actions.byName("AXPress").perform();
328
369
  submitMethod = "ax_send_button";
329
370
  } catch (e) {
330
- postReturnKeyToPid(pid);
331
- submitMethod = "cg_return";
371
+ if (bubbles < 2) {
372
+ postKeyCodeToPid(pid, 125); // Down -> select Chat row in unified bar
373
+ delay(0.2);
374
+ postReturnKeyToPid(pid);
375
+ submitMethod = "cg_down_return";
376
+ } else {
377
+ postReturnKeyToPid(pid);
378
+ submitMethod = "cg_return";
379
+ }
332
380
  }
381
+ } else if (bubbles < 2) {
382
+ // Fresh unified bar: Down selects the Chat row, then Return submits to chat.
383
+ postKeyCodeToPid(pid, 125);
384
+ delay(0.2);
385
+ postReturnKeyToPid(pid);
386
+ submitMethod = "cg_down_return";
333
387
  } else {
334
388
  postReturnKeyToPid(pid);
335
389
  }
@@ -345,7 +399,7 @@ function run() {
345
399
  } else if (sendBtn) {
346
400
  try {
347
401
  sendBtn.actions.byName("AXPress").perform();
348
- submitMethod = "cg_return+ax_send_button";
402
+ submitMethod = submitMethod + "+ax_send_button";
349
403
  } catch (e) {}
350
404
  }
351
405
  }
@@ -353,6 +407,7 @@ function run() {
353
407
  return JSON.stringify({
354
408
  ok: true,
355
409
  method: submitMethod,
410
+ bubbles: bubbles,
356
411
  pid: pid,
357
412
  length: promptText.length,
358
413
  });
package/src/bridge.mjs CHANGED
@@ -1,7 +1,24 @@
1
+ import fs from "node:fs/promises"
1
2
  import { checkDiaEnvironment, DIA_BUNDLE_ID, submitPromptViaAX } from "./ax.mjs"
2
- import { DiaAbortedError, DiaTimeoutError, DiaValidationError } from "./errors.mjs"
3
+ import {
4
+ DiaAbortedError,
5
+ DiaPlatformError,
6
+ DiaTimeoutError,
7
+ DiaValidationError,
8
+ } from "./errors.mjs"
9
+ import { createLogger } from "./logger.mjs"
3
10
  import { DiaMutex } from "./mutex.mjs"
4
- import { captureSnapshot, getDefaultContextsDir, pollForNewAnswer } from "./store.mjs"
11
+ import {
12
+ captureSnapshot,
13
+ getDefaultContextsDir,
14
+ pollForNewAnswer,
15
+ readRecentChatHistory,
16
+ } from "./store.mjs"
17
+ import {
18
+ checkDiaEnvironmentWindows,
19
+ DIA_PROCESS_NAME,
20
+ submitPromptViaUIA,
21
+ } from "./win-uia.mjs"
5
22
 
6
23
  export const DEFAULT_TIMEOUT_MS = 50000
7
24
  export const MIN_TIMEOUT_MS = 1000
@@ -19,21 +36,54 @@ export function normalizeTimeoutMs(value, fallback = DEFAULT_TIMEOUT_MS) {
19
36
  return Math.min(rounded, MAX_TIMEOUT_MS)
20
37
  }
21
38
 
39
+ function getPlatformBackend(platform) {
40
+ if (platform === "darwin") {
41
+ return {
42
+ checkEnv: checkDiaEnvironment,
43
+ submitPrompt: submitPromptViaAX,
44
+ submitStage: "submitting prompt via Accessibility",
45
+ }
46
+ }
47
+ if (platform === "win32") {
48
+ return {
49
+ checkEnv: checkDiaEnvironmentWindows,
50
+ submitPrompt: submitPromptViaUIA,
51
+ submitStage: "submitting prompt via Windows UI Automation",
52
+ }
53
+ }
54
+ return {
55
+ checkEnv: async ({ platform: p = platform } = {}) => {
56
+ throw new DiaPlatformError(p)
57
+ },
58
+ submitPrompt: async () => {
59
+ throw new DiaPlatformError(platform)
60
+ },
61
+ submitStage: "submitting prompt",
62
+ }
63
+ }
64
+
22
65
  export function createDiaBridge(config = {}) {
66
+ const platform = config.platform ?? process.platform
67
+ const backend = getPlatformBackend(platform)
23
68
  const mutex = config.mutex ?? new DiaMutex({ lockFilePath: config.lockFilePath })
24
69
  const bundleId = config.bundleId ?? DIA_BUNDLE_ID
70
+ const processName = config.processName ?? DIA_PROCESS_NAME
25
71
  const defaultTimeoutMs = normalizeTimeoutMs(config.defaultTimeoutMs, DEFAULT_TIMEOUT_MS)
26
72
  const pollIntervalMs = config.pollIntervalMs ?? 350
27
73
  const settleMs = config.settleMs ?? 400
28
74
  const workFallbackSettleMs = config.workFallbackSettleMs ?? 2000
29
75
 
30
76
  const deps = {
31
- checkEnv: config.deps?.checkEnv ?? checkDiaEnvironment,
77
+ checkEnv: config.deps?.checkEnv ?? backend.checkEnv,
32
78
  captureSnapshot: config.deps?.captureSnapshot ?? captureSnapshot,
33
- submitPrompt: config.deps?.submitPrompt ?? submitPromptViaAX,
79
+ submitPrompt: config.deps?.submitPrompt ?? backend.submitPrompt,
34
80
  pollForNewAnswer: config.deps?.pollForNewAnswer ?? pollForNewAnswer,
35
- getContextsDir: config.deps?.getContextsDir ?? (() => config.contextsDir ?? getDefaultContextsDir()),
81
+ readRecentChatHistory: config.deps?.readRecentChatHistory ?? readRecentChatHistory,
82
+ getContextsDir:
83
+ config.deps?.getContextsDir ??
84
+ (() => config.contextsDir ?? getDefaultContextsDir({ platform })),
36
85
  }
86
+ const log = createLogger("dia-bridge")
37
87
 
38
88
  async function ask(prompt, options = {}) {
39
89
  if (typeof prompt !== "string" || prompt.trim().length === 0) {
@@ -59,23 +109,28 @@ export function createDiaBridge(config = {}) {
59
109
  return rem
60
110
  }
61
111
 
112
+ log.debug("acquiring mutex", { platform, timeoutMs })
62
113
  const release = await mutex.acquire({ signal, deadlineMs })
63
114
  try {
64
115
  await deps.checkEnv({
65
116
  signal,
66
117
  timeoutMs: Math.min(10000, remainingMs("checking Dia environment")),
67
118
  bundleId,
68
- platform: config.platform ?? process.platform,
119
+ processName,
120
+ platform,
69
121
  })
70
122
 
71
123
  const contextsDir = deps.getContextsDir()
72
124
  const snapshot = await deps.captureSnapshot(contextsDir)
125
+ log.debug("captured snapshot", { contexts: snapshot.contexts.size })
73
126
 
74
- await deps.submitPrompt(prompt, {
127
+ const submitRes = await deps.submitPrompt(prompt, {
75
128
  signal,
76
- timeoutMs: Math.min(15000, remainingMs("submitting prompt via Accessibility")),
129
+ timeoutMs: Math.min(15000, remainingMs(backend.submitStage)),
77
130
  bundleId,
131
+ processName,
78
132
  })
133
+ log.debug("submitted prompt", { method: submitRes?.method, length: prompt.length })
79
134
 
80
135
  const result = await deps.pollForNewAnswer(contextsDir, snapshot, {
81
136
  signal,
@@ -86,14 +141,69 @@ export function createDiaBridge(config = {}) {
86
141
  workFallbackSettleMs,
87
142
  })
88
143
 
144
+ log.debug("received answer", { contextId: result.contextId, source: result.source })
89
145
  return result.answer
90
146
  } finally {
91
147
  await release()
92
148
  }
93
149
  }
94
150
 
151
+ async function getStatus({ signal, timeoutMs = 10000 } = {}) {
152
+ const contextsDir = deps.getContextsDir()
153
+ let contextsDirExists = false
154
+ try {
155
+ const stat = await fs.stat(contextsDir)
156
+ contextsDirExists = stat.isDirectory()
157
+ } catch {
158
+ contextsDirExists = false
159
+ }
160
+
161
+ let envOk = false
162
+ let envDetail = null
163
+ let envError = null
164
+ try {
165
+ envDetail = await deps.checkEnv({
166
+ signal,
167
+ timeoutMs,
168
+ bundleId,
169
+ processName,
170
+ platform,
171
+ })
172
+ envOk = true
173
+ } catch (err) {
174
+ envError = {
175
+ code: err?.code || "ENV_CHECK_FAILED",
176
+ message: err instanceof Error ? err.message : String(err),
177
+ }
178
+ }
179
+
180
+ return {
181
+ ok: envOk,
182
+ platform,
183
+ supported: platform === "darwin" || platform === "win32",
184
+ busy: mutex.isLocked,
185
+ queueLength: mutex.queueLength,
186
+ contextsDir,
187
+ contextsDirExists,
188
+ environment: envDetail,
189
+ error: envError,
190
+ }
191
+ }
192
+
193
+ async function getHistory({ limit = 5 } = {}) {
194
+ const contextsDir = deps.getContextsDir()
195
+ const items = await deps.readRecentChatHistory(contextsDir, { limit })
196
+ return {
197
+ contextsDir,
198
+ count: items.length,
199
+ items,
200
+ }
201
+ }
202
+
95
203
  return {
96
204
  ask,
205
+ getStatus,
206
+ getHistory,
97
207
  mutex,
98
208
  }
99
209
  }
package/src/errors.mjs CHANGED
@@ -11,7 +11,7 @@ export class DiaPlatformError extends DiaBridgeError {
11
11
  constructor(platform = process.platform) {
12
12
  super(
13
13
  "UNSUPPORTED_PLATFORM",
14
- `dia-bridge requires macOS (darwin) with Accessibility support; current platform is "${platform}".`,
14
+ `dia-bridge requires macOS (darwin) with Accessibility or Windows (win32) with UI Automation; current platform is "${platform}".`,
15
15
  )
16
16
  }
17
17
  }
@@ -19,7 +19,7 @@ export class DiaPlatformError extends DiaBridgeError {
19
19
  export class DiaNotRunningError extends DiaBridgeError {
20
20
  constructor(bundleId = "company.thebrowser.dia") {
21
21
  const hint =
22
- "Launch Dia.app and ensure at least one window with the AI chat panel is open, then retry."
22
+ "Launch Dia and ensure at least one window with the AI chat panel is open, then retry."
23
23
  super(
24
24
  "DIA_NOT_RUNNING",
25
25
  `Dia browser (${bundleId}) is not running. ${hint}`,
@@ -47,8 +47,8 @@ export class DiaInputNotFoundError extends DiaBridgeError {
47
47
  const hint =
48
48
  "Make sure a Dia browser window is open (not minimized) and its AI chat input box is visible."
49
49
  const message = detail
50
- ? `Could not locate Dia's writable AXTextArea chat input: ${detail}. ${hint}`
51
- : `Could not locate Dia's writable AXTextArea chat input. ${hint}`
50
+ ? `Could not locate Dia's writable chat input: ${detail}. ${hint}`
51
+ : `Could not locate Dia's writable chat input. ${hint}`
52
52
  super("INPUT_NOT_FOUND", message, { hint })
53
53
  }
54
54
  }
package/src/logger.mjs ADDED
@@ -0,0 +1,27 @@
1
+ const LEVELS = {
2
+ debug: 10,
3
+ info: 20,
4
+ warn: 30,
5
+ error: 40,
6
+ silent: 100,
7
+ }
8
+
9
+ export function getLogLevel(envLevel = process.env.DIA_LOG_LEVEL) {
10
+ const key = String(envLevel || "warn").toLowerCase().trim()
11
+ return LEVELS[key] ?? LEVELS.warn
12
+ }
13
+
14
+ export function createLogger(scope = "dia-bridge") {
15
+ function emit(levelName, message, extra) {
16
+ if (LEVELS[levelName] < getLogLevel()) return
17
+ const suffix = extra !== undefined ? ` ${JSON.stringify(extra)}` : ""
18
+ process.stderr.write(`[${scope}] [${levelName}] ${message}${suffix}\n`)
19
+ }
20
+
21
+ return {
22
+ debug: (msg, extra) => emit("debug", msg, extra),
23
+ info: (msg, extra) => emit("info", msg, extra),
24
+ warn: (msg, extra) => emit("warn", msg, extra),
25
+ error: (msg, extra) => emit("error", msg, extra),
26
+ }
27
+ }