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 +21 -0
- package/README.md +117 -2
- package/bin/dia-bridge-mcp.mjs +120 -0
- package/index.mjs +69 -0
- package/package.json +48 -4
- package/src/ax.mjs +478 -0
- package/src/bridge.mjs +99 -0
- package/src/errors.mjs +83 -0
- package/src/mcp-server.mjs +380 -0
- package/src/mutex.mjs +218 -0
- package/src/store.mjs +396 -0
package/src/ax.mjs
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
import { spawn } from "node:child_process"
|
|
2
|
+
import crypto from "node:crypto"
|
|
3
|
+
import fs from "node:fs/promises"
|
|
4
|
+
import os from "node:os"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import {
|
|
7
|
+
DiaAbortedError,
|
|
8
|
+
DiaAccessibilityError,
|
|
9
|
+
DiaBridgeError,
|
|
10
|
+
DiaInputNotFoundError,
|
|
11
|
+
DiaNotRunningError,
|
|
12
|
+
DiaPlatformError,
|
|
13
|
+
DiaTimeoutError,
|
|
14
|
+
} from "./errors.mjs"
|
|
15
|
+
|
|
16
|
+
export const DIA_BUNDLE_ID = "company.thebrowser.dia"
|
|
17
|
+
|
|
18
|
+
export function isAccessibilityErrorText(text) {
|
|
19
|
+
if (!text) return false
|
|
20
|
+
return /ACCESSIBILITY_DENIED|-1719|-25211|not allowed assistive access|assistive access/i.test(
|
|
21
|
+
text,
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function runOsascript(script, { signal, timeoutMs = 15000, env = {} } = {}) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
if (signal?.aborted) {
|
|
28
|
+
reject(new DiaAbortedError(signal.reason))
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const child = spawn("/usr/bin/osascript", ["-l", "JavaScript", "-"], {
|
|
33
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
34
|
+
env: { ...process.env, ...env },
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
let stdout = ""
|
|
38
|
+
let stderr = ""
|
|
39
|
+
let settled = false
|
|
40
|
+
let killTimer = null
|
|
41
|
+
|
|
42
|
+
const terminate = () => {
|
|
43
|
+
if (child.killed) return
|
|
44
|
+
try {
|
|
45
|
+
child.kill("SIGTERM")
|
|
46
|
+
} catch {
|
|
47
|
+
// ignore
|
|
48
|
+
}
|
|
49
|
+
killTimer = setTimeout(() => {
|
|
50
|
+
try {
|
|
51
|
+
child.kill("SIGKILL")
|
|
52
|
+
} catch {
|
|
53
|
+
// ignore
|
|
54
|
+
}
|
|
55
|
+
}, 500)
|
|
56
|
+
killTimer.unref?.()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const cleanup = () => {
|
|
60
|
+
if (timer) clearTimeout(timer)
|
|
61
|
+
if (killTimer) clearTimeout(killTimer)
|
|
62
|
+
signal?.removeEventListener("abort", onAbort)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const onAbort = () => {
|
|
66
|
+
if (settled) return
|
|
67
|
+
settled = true
|
|
68
|
+
cleanup()
|
|
69
|
+
terminate()
|
|
70
|
+
reject(new DiaAbortedError(signal.reason))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const timer =
|
|
74
|
+
typeof timeoutMs === "number" && timeoutMs > 0
|
|
75
|
+
? setTimeout(() => {
|
|
76
|
+
if (settled) return
|
|
77
|
+
settled = true
|
|
78
|
+
cleanup()
|
|
79
|
+
terminate()
|
|
80
|
+
reject(new DiaTimeoutError(timeoutMs, "communicating with Dia via Accessibility"))
|
|
81
|
+
}, timeoutMs)
|
|
82
|
+
: null
|
|
83
|
+
|
|
84
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
85
|
+
|
|
86
|
+
child.stdout.setEncoding("utf8")
|
|
87
|
+
child.stderr.setEncoding("utf8")
|
|
88
|
+
child.stdout.on("data", (chunk) => {
|
|
89
|
+
stdout += chunk
|
|
90
|
+
})
|
|
91
|
+
child.stderr.on("data", (chunk) => {
|
|
92
|
+
stderr += chunk
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
child.on("error", (err) => {
|
|
96
|
+
if (settled) return
|
|
97
|
+
settled = true
|
|
98
|
+
cleanup()
|
|
99
|
+
reject(new DiaBridgeError("OSASCRIPT_SPAWN_FAILED", `Failed to run osascript: ${err.message}`, { cause: err }))
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
child.on("close", (code) => {
|
|
103
|
+
if (settled) return
|
|
104
|
+
settled = true
|
|
105
|
+
cleanup()
|
|
106
|
+
resolve({ code, stdout: stdout.trim(), stderr: stderr.trim() })
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
child.stdin.end(script, "utf8")
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const CHECK_ENV_JXA = `
|
|
114
|
+
ObjC.import("Cocoa");
|
|
115
|
+
ObjC.import("ApplicationServices");
|
|
116
|
+
ObjC.import("Foundation");
|
|
117
|
+
|
|
118
|
+
function run() {
|
|
119
|
+
var env = $.NSProcessInfo.processInfo.environment;
|
|
120
|
+
var bundleId = ObjC.unwrap(env.objectForKey("DIA_BRIDGE_BUNDLE_ID")) || "company.thebrowser.dia";
|
|
121
|
+
var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(bundleId);
|
|
122
|
+
var running = apps && apps.count > 0;
|
|
123
|
+
var trusted = Boolean($.AXIsProcessTrusted());
|
|
124
|
+
return JSON.stringify({ running: running, trusted: trusted, bundleId: bundleId });
|
|
125
|
+
}
|
|
126
|
+
run();
|
|
127
|
+
`
|
|
128
|
+
|
|
129
|
+
const SUBMIT_PROMPT_JXA = `
|
|
130
|
+
ObjC.import("Cocoa");
|
|
131
|
+
ObjC.import("CoreGraphics");
|
|
132
|
+
ObjC.import("ApplicationServices");
|
|
133
|
+
ObjC.import("Foundation");
|
|
134
|
+
|
|
135
|
+
function unwrapStr(v) {
|
|
136
|
+
if (v === null || v === undefined) return "";
|
|
137
|
+
try { return String(v); } catch (e) { return ""; }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function getAttr(el, name) {
|
|
141
|
+
try {
|
|
142
|
+
return el.attributes.byName(name);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function isWritableTextArea(el) {
|
|
149
|
+
try {
|
|
150
|
+
if (el.role() !== "AXTextArea") return false;
|
|
151
|
+
var valAttr = getAttr(el, "AXValue");
|
|
152
|
+
if (!valAttr || !valAttr.settable()) return false;
|
|
153
|
+
try {
|
|
154
|
+
if (el.enabled() === false) return false;
|
|
155
|
+
} catch (e) {}
|
|
156
|
+
return true;
|
|
157
|
+
} catch (e) {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function findWritableTextArea(win) {
|
|
163
|
+
var queue = [{ el: win, depth: 0 }];
|
|
164
|
+
var visited = 0;
|
|
165
|
+
var maxNodes = 1500;
|
|
166
|
+
var maxDepth = 18;
|
|
167
|
+
|
|
168
|
+
while (queue.length > 0 && visited < maxNodes) {
|
|
169
|
+
var item = queue.shift();
|
|
170
|
+
visited += 1;
|
|
171
|
+
var el = item.el;
|
|
172
|
+
if (isWritableTextArea(el)) {
|
|
173
|
+
return el;
|
|
174
|
+
}
|
|
175
|
+
if (item.depth >= maxDepth) continue;
|
|
176
|
+
var children = [];
|
|
177
|
+
try {
|
|
178
|
+
children = el.uiElements();
|
|
179
|
+
} catch (e) {
|
|
180
|
+
children = [];
|
|
181
|
+
}
|
|
182
|
+
for (var i = 0; i < children.length; i++) {
|
|
183
|
+
queue.push({ el: children[i], depth: item.depth + 1 });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function findSendButton(textArea, win) {
|
|
190
|
+
var roots = [];
|
|
191
|
+
try {
|
|
192
|
+
var p1 = textArea.attributes.byName("AXParent").value();
|
|
193
|
+
if (p1) {
|
|
194
|
+
roots.push(p1);
|
|
195
|
+
try {
|
|
196
|
+
var p2 = p1.attributes.byName("AXParent").value();
|
|
197
|
+
if (p2) roots.push(p2);
|
|
198
|
+
} catch (e) {}
|
|
199
|
+
}
|
|
200
|
+
} catch (e) {}
|
|
201
|
+
roots.push(win);
|
|
202
|
+
|
|
203
|
+
var pattern = /(send|submit|ask|arrow\\.up|发送|提交)/i;
|
|
204
|
+
for (var r = 0; r < roots.length; r++) {
|
|
205
|
+
var queue = [{ el: roots[r], depth: 0 }];
|
|
206
|
+
var visited = 0;
|
|
207
|
+
while (queue.length > 0 && visited < 400) {
|
|
208
|
+
var item = queue.shift();
|
|
209
|
+
visited += 1;
|
|
210
|
+
var el = item.el;
|
|
211
|
+
try {
|
|
212
|
+
if (el.role() === "AXButton" && el.enabled() !== false) {
|
|
213
|
+
var label = [
|
|
214
|
+
unwrapStr(el.title ? el.title() : ""),
|
|
215
|
+
unwrapStr(el.description ? el.description() : ""),
|
|
216
|
+
unwrapStr(el.help ? el.help() : ""),
|
|
217
|
+
].join(" ");
|
|
218
|
+
if (pattern.test(label)) {
|
|
219
|
+
return el;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
} catch (e) {}
|
|
223
|
+
if (item.depth >= 6) continue;
|
|
224
|
+
var children = [];
|
|
225
|
+
try {
|
|
226
|
+
children = el.uiElements();
|
|
227
|
+
} catch (e) {
|
|
228
|
+
children = [];
|
|
229
|
+
}
|
|
230
|
+
for (var i = 0; i < children.length; i++) {
|
|
231
|
+
queue.push({ el: children[i], depth: item.depth + 1 });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function postReturnKeyToPid(pid) {
|
|
239
|
+
try {
|
|
240
|
+
var keyDown = $.CGEventCreateKeyboardEvent($(), 36, true);
|
|
241
|
+
var keyUp = $.CGEventCreateKeyboardEvent($(), 36, false);
|
|
242
|
+
if (!keyDown || !keyUp) return false;
|
|
243
|
+
$.CGEventPostToPid(pid, keyDown);
|
|
244
|
+
delay(0.05);
|
|
245
|
+
$.CGEventPostToPid(pid, keyUp);
|
|
246
|
+
return true;
|
|
247
|
+
} catch (e) {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function run() {
|
|
253
|
+
var env = $.NSProcessInfo.processInfo.environment;
|
|
254
|
+
var bundleId = ObjC.unwrap(env.objectForKey("DIA_BRIDGE_BUNDLE_ID")) || "company.thebrowser.dia";
|
|
255
|
+
var promptPath = ObjC.unwrap(env.objectForKey("DIA_BRIDGE_PROMPT_FILE"));
|
|
256
|
+
|
|
257
|
+
if (!$.AXIsProcessTrusted()) {
|
|
258
|
+
return JSON.stringify({ ok: false, error: "ACCESSIBILITY_DENIED" });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(bundleId);
|
|
262
|
+
if (!apps || apps.count === 0) {
|
|
263
|
+
return JSON.stringify({ ok: false, error: "DIA_NOT_RUNNING" });
|
|
264
|
+
}
|
|
265
|
+
var pid = apps.objectAtIndex(0).processIdentifier;
|
|
266
|
+
|
|
267
|
+
var nsPrompt = $.NSString.stringWithContentsOfFileEncodingError(
|
|
268
|
+
promptPath,
|
|
269
|
+
$.NSUTF8StringEncoding,
|
|
270
|
+
null
|
|
271
|
+
);
|
|
272
|
+
if (!nsPrompt) {
|
|
273
|
+
return JSON.stringify({ ok: false, error: "PROMPT_READ_FAILED" });
|
|
274
|
+
}
|
|
275
|
+
var promptText = ObjC.unwrap(nsPrompt);
|
|
276
|
+
|
|
277
|
+
var se = Application("System Events");
|
|
278
|
+
var procs = se.applicationProcesses.whose({ bundleIdentifier: bundleId });
|
|
279
|
+
if (!procs || procs.length === 0) {
|
|
280
|
+
return JSON.stringify({ ok: false, error: "DIA_NOT_RUNNING" });
|
|
281
|
+
}
|
|
282
|
+
var proc = procs[0];
|
|
283
|
+
var windows = [];
|
|
284
|
+
try {
|
|
285
|
+
windows = proc.windows();
|
|
286
|
+
} catch (e) {
|
|
287
|
+
return JSON.stringify({ ok: false, error: "WINDOW_ACCESS_FAILED", detail: String(e) });
|
|
288
|
+
}
|
|
289
|
+
if (!windows || windows.length === 0) {
|
|
290
|
+
return JSON.stringify({ ok: false, error: "INPUT_NOT_FOUND", detail: "Dia has no open windows" });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
var textArea = null;
|
|
294
|
+
var targetWindow = null;
|
|
295
|
+
for (var w = 0; w < windows.length; w++) {
|
|
296
|
+
textArea = findWritableTextArea(windows[w]);
|
|
297
|
+
if (textArea) {
|
|
298
|
+
targetWindow = windows[w];
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!textArea) {
|
|
303
|
+
return JSON.stringify({ ok: false, error: "INPUT_NOT_FOUND", detail: "No writable AXTextArea found in Dia windows" });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Write directly via AXValue (never simulate typing keystrokes) to preserve Chinese/Unicode/JSON verbatim.
|
|
307
|
+
var valAttr = getAttr(textArea, "AXValue");
|
|
308
|
+
valAttr.value = promptText;
|
|
309
|
+
delay(0.05);
|
|
310
|
+
|
|
311
|
+
var readback = "";
|
|
312
|
+
try { readback = unwrapStr(textArea.value()); } catch (e) {}
|
|
313
|
+
if (readback !== promptText) {
|
|
314
|
+
try { textArea.focused = true; } catch (e) {}
|
|
315
|
+
delay(0.05);
|
|
316
|
+
valAttr.value = promptText;
|
|
317
|
+
delay(0.05);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
try { textArea.focused = true; } catch (e) {}
|
|
321
|
+
delay(0.05);
|
|
322
|
+
|
|
323
|
+
var submitMethod = "cg_return";
|
|
324
|
+
var sendBtn = findSendButton(textArea, targetWindow);
|
|
325
|
+
if (sendBtn) {
|
|
326
|
+
try {
|
|
327
|
+
sendBtn.actions.byName("AXPress").perform();
|
|
328
|
+
submitMethod = "ax_send_button";
|
|
329
|
+
} catch (e) {
|
|
330
|
+
postReturnKeyToPid(pid);
|
|
331
|
+
submitMethod = "cg_return";
|
|
332
|
+
}
|
|
333
|
+
} else {
|
|
334
|
+
postReturnKeyToPid(pid);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
delay(0.18);
|
|
338
|
+
var remaining = "";
|
|
339
|
+
try { remaining = unwrapStr(textArea.value()); } catch (e) {}
|
|
340
|
+
if (remaining === promptText) {
|
|
341
|
+
// Fallback: if AXPress didn't submit, try Return key; if Return didn't submit, try Send button.
|
|
342
|
+
if (submitMethod === "ax_send_button") {
|
|
343
|
+
postReturnKeyToPid(pid);
|
|
344
|
+
submitMethod = "ax_send_button+cg_return";
|
|
345
|
+
} else if (sendBtn) {
|
|
346
|
+
try {
|
|
347
|
+
sendBtn.actions.byName("AXPress").perform();
|
|
348
|
+
submitMethod = "cg_return+ax_send_button";
|
|
349
|
+
} catch (e) {}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return JSON.stringify({
|
|
354
|
+
ok: true,
|
|
355
|
+
method: submitMethod,
|
|
356
|
+
pid: pid,
|
|
357
|
+
length: promptText.length,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
run();
|
|
361
|
+
`
|
|
362
|
+
|
|
363
|
+
export async function checkDiaEnvironment({
|
|
364
|
+
signal,
|
|
365
|
+
timeoutMs = 10000,
|
|
366
|
+
bundleId = DIA_BUNDLE_ID,
|
|
367
|
+
platform = process.platform,
|
|
368
|
+
execOsascript = runOsascript,
|
|
369
|
+
} = {}) {
|
|
370
|
+
if (platform !== "darwin") {
|
|
371
|
+
throw new DiaPlatformError(platform)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const res = await execOsascript(CHECK_ENV_JXA, {
|
|
375
|
+
signal,
|
|
376
|
+
timeoutMs,
|
|
377
|
+
env: { DIA_BRIDGE_BUNDLE_ID: bundleId },
|
|
378
|
+
})
|
|
379
|
+
|
|
380
|
+
if (res.code !== 0) {
|
|
381
|
+
if (isAccessibilityErrorText(res.stderr)) {
|
|
382
|
+
throw new DiaAccessibilityError(res.stderr)
|
|
383
|
+
}
|
|
384
|
+
throw new DiaBridgeError(
|
|
385
|
+
"ENV_CHECK_FAILED",
|
|
386
|
+
`Failed to inspect Dia process state: ${res.stderr || `osascript exited with code ${res.code}`}`,
|
|
387
|
+
)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let parsed
|
|
391
|
+
try {
|
|
392
|
+
parsed = JSON.parse(res.stdout)
|
|
393
|
+
} catch (err) {
|
|
394
|
+
throw new DiaBridgeError(
|
|
395
|
+
"ENV_CHECK_PARSE_FAILED",
|
|
396
|
+
`Unexpected response from Dia environment check: ${res.stdout}`,
|
|
397
|
+
{ cause: err },
|
|
398
|
+
)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (!parsed.running) {
|
|
402
|
+
throw new DiaNotRunningError(bundleId)
|
|
403
|
+
}
|
|
404
|
+
if (!parsed.trusted) {
|
|
405
|
+
throw new DiaAccessibilityError()
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return parsed
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export async function submitPromptViaAX(
|
|
412
|
+
prompt,
|
|
413
|
+
{
|
|
414
|
+
signal,
|
|
415
|
+
timeoutMs = 15000,
|
|
416
|
+
bundleId = DIA_BUNDLE_ID,
|
|
417
|
+
execOsascript = runOsascript,
|
|
418
|
+
} = {},
|
|
419
|
+
) {
|
|
420
|
+
const promptFile = path.join(
|
|
421
|
+
os.tmpdir(),
|
|
422
|
+
`dia-bridge-prompt-${process.pid}-${crypto.randomBytes(8).toString("hex")}.txt`,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
await fs.writeFile(promptFile, prompt, { encoding: "utf8", mode: 0o600 })
|
|
426
|
+
|
|
427
|
+
try {
|
|
428
|
+
const res = await execOsascript(SUBMIT_PROMPT_JXA, {
|
|
429
|
+
signal,
|
|
430
|
+
timeoutMs,
|
|
431
|
+
env: {
|
|
432
|
+
DIA_BRIDGE_BUNDLE_ID: bundleId,
|
|
433
|
+
DIA_BRIDGE_PROMPT_FILE: promptFile,
|
|
434
|
+
},
|
|
435
|
+
})
|
|
436
|
+
|
|
437
|
+
if (res.code !== 0) {
|
|
438
|
+
if (isAccessibilityErrorText(res.stderr)) {
|
|
439
|
+
throw new DiaAccessibilityError(res.stderr)
|
|
440
|
+
}
|
|
441
|
+
throw new DiaBridgeError(
|
|
442
|
+
"AX_SUBMIT_FAILED",
|
|
443
|
+
`Failed to submit prompt to Dia via Accessibility: ${res.stderr || `osascript exited with code ${res.code}`}`,
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let parsed
|
|
448
|
+
try {
|
|
449
|
+
parsed = JSON.parse(res.stdout)
|
|
450
|
+
} catch (err) {
|
|
451
|
+
throw new DiaBridgeError(
|
|
452
|
+
"AX_SUBMIT_PARSE_FAILED",
|
|
453
|
+
`Unexpected response from AX submit script: ${res.stdout}`,
|
|
454
|
+
{ cause: err },
|
|
455
|
+
)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
if (!parsed.ok) {
|
|
459
|
+
if (parsed.error === "ACCESSIBILITY_DENIED") {
|
|
460
|
+
throw new DiaAccessibilityError(parsed.detail)
|
|
461
|
+
}
|
|
462
|
+
if (parsed.error === "DIA_NOT_RUNNING") {
|
|
463
|
+
throw new DiaNotRunningError(bundleId)
|
|
464
|
+
}
|
|
465
|
+
if (parsed.error === "INPUT_NOT_FOUND") {
|
|
466
|
+
throw new DiaInputNotFoundError(parsed.detail)
|
|
467
|
+
}
|
|
468
|
+
throw new DiaBridgeError(
|
|
469
|
+
parsed.error || "AX_SUBMIT_FAILED",
|
|
470
|
+
`Dia AX submission failed (${parsed.error || "unknown"})${parsed.detail ? `: ${parsed.detail}` : ""}`,
|
|
471
|
+
)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
return parsed
|
|
475
|
+
} finally {
|
|
476
|
+
await fs.unlink(promptFile).catch(() => {})
|
|
477
|
+
}
|
|
478
|
+
}
|
package/src/bridge.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { checkDiaEnvironment, DIA_BUNDLE_ID, submitPromptViaAX } from "./ax.mjs"
|
|
2
|
+
import { DiaAbortedError, DiaTimeoutError, DiaValidationError } from "./errors.mjs"
|
|
3
|
+
import { DiaMutex } from "./mutex.mjs"
|
|
4
|
+
import { captureSnapshot, getDefaultContextsDir, pollForNewAnswer } from "./store.mjs"
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_TIMEOUT_MS = 50000
|
|
7
|
+
export const MIN_TIMEOUT_MS = 1000
|
|
8
|
+
export const MAX_TIMEOUT_MS = 300000
|
|
9
|
+
|
|
10
|
+
export function normalizeTimeoutMs(value, fallback = DEFAULT_TIMEOUT_MS) {
|
|
11
|
+
if (value === undefined || value === null) return fallback
|
|
12
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
13
|
+
throw new DiaValidationError(`timeoutMs must be a finite number; got ${typeof value}.`)
|
|
14
|
+
}
|
|
15
|
+
const rounded = Math.floor(value)
|
|
16
|
+
if (rounded < MIN_TIMEOUT_MS) {
|
|
17
|
+
throw new DiaValidationError(`timeoutMs must be at least ${MIN_TIMEOUT_MS}ms.`)
|
|
18
|
+
}
|
|
19
|
+
return Math.min(rounded, MAX_TIMEOUT_MS)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createDiaBridge(config = {}) {
|
|
23
|
+
const mutex = config.mutex ?? new DiaMutex({ lockFilePath: config.lockFilePath })
|
|
24
|
+
const bundleId = config.bundleId ?? DIA_BUNDLE_ID
|
|
25
|
+
const defaultTimeoutMs = normalizeTimeoutMs(config.defaultTimeoutMs, DEFAULT_TIMEOUT_MS)
|
|
26
|
+
const pollIntervalMs = config.pollIntervalMs ?? 350
|
|
27
|
+
const settleMs = config.settleMs ?? 400
|
|
28
|
+
const workFallbackSettleMs = config.workFallbackSettleMs ?? 2000
|
|
29
|
+
|
|
30
|
+
const deps = {
|
|
31
|
+
checkEnv: config.deps?.checkEnv ?? checkDiaEnvironment,
|
|
32
|
+
captureSnapshot: config.deps?.captureSnapshot ?? captureSnapshot,
|
|
33
|
+
submitPrompt: config.deps?.submitPrompt ?? submitPromptViaAX,
|
|
34
|
+
pollForNewAnswer: config.deps?.pollForNewAnswer ?? pollForNewAnswer,
|
|
35
|
+
getContextsDir: config.deps?.getContextsDir ?? (() => config.contextsDir ?? getDefaultContextsDir()),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function ask(prompt, options = {}) {
|
|
39
|
+
if (typeof prompt !== "string" || prompt.trim().length === 0) {
|
|
40
|
+
throw new DiaValidationError("prompt must be a non-empty string.")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const signal = options.signal
|
|
44
|
+
if (signal?.aborted) {
|
|
45
|
+
throw new DiaAbortedError(signal.reason)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const timeoutMs = normalizeTimeoutMs(options.timeoutMs, defaultTimeoutMs)
|
|
49
|
+
const deadlineMs = Date.now() + timeoutMs
|
|
50
|
+
|
|
51
|
+
const remainingMs = (stage) => {
|
|
52
|
+
if (signal?.aborted) {
|
|
53
|
+
throw new DiaAbortedError(signal.reason)
|
|
54
|
+
}
|
|
55
|
+
const rem = deadlineMs - Date.now()
|
|
56
|
+
if (rem <= 0) {
|
|
57
|
+
throw new DiaTimeoutError(timeoutMs, stage)
|
|
58
|
+
}
|
|
59
|
+
return rem
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const release = await mutex.acquire({ signal, deadlineMs })
|
|
63
|
+
try {
|
|
64
|
+
await deps.checkEnv({
|
|
65
|
+
signal,
|
|
66
|
+
timeoutMs: Math.min(10000, remainingMs("checking Dia environment")),
|
|
67
|
+
bundleId,
|
|
68
|
+
platform: config.platform ?? process.platform,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const contextsDir = deps.getContextsDir()
|
|
72
|
+
const snapshot = await deps.captureSnapshot(contextsDir)
|
|
73
|
+
|
|
74
|
+
await deps.submitPrompt(prompt, {
|
|
75
|
+
signal,
|
|
76
|
+
timeoutMs: Math.min(15000, remainingMs("submitting prompt via Accessibility")),
|
|
77
|
+
bundleId,
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const result = await deps.pollForNewAnswer(contextsDir, snapshot, {
|
|
81
|
+
signal,
|
|
82
|
+
deadlineMs,
|
|
83
|
+
timeoutMs,
|
|
84
|
+
pollIntervalMs,
|
|
85
|
+
settleMs,
|
|
86
|
+
workFallbackSettleMs,
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
return result.answer
|
|
90
|
+
} finally {
|
|
91
|
+
await release()
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
ask,
|
|
97
|
+
mutex,
|
|
98
|
+
}
|
|
99
|
+
}
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export class DiaBridgeError extends Error {
|
|
2
|
+
constructor(code, message, options = {}) {
|
|
3
|
+
super(message, options.cause ? { cause: options.cause } : undefined)
|
|
4
|
+
this.name = this.constructor.name
|
|
5
|
+
this.code = code
|
|
6
|
+
if (options.hint) this.hint = options.hint
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class DiaPlatformError extends DiaBridgeError {
|
|
11
|
+
constructor(platform = process.platform) {
|
|
12
|
+
super(
|
|
13
|
+
"UNSUPPORTED_PLATFORM",
|
|
14
|
+
`dia-bridge requires macOS (darwin) with Accessibility support; current platform is "${platform}".`,
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class DiaNotRunningError extends DiaBridgeError {
|
|
20
|
+
constructor(bundleId = "company.thebrowser.dia") {
|
|
21
|
+
const hint =
|
|
22
|
+
"Launch Dia.app and ensure at least one window with the AI chat panel is open, then retry."
|
|
23
|
+
super(
|
|
24
|
+
"DIA_NOT_RUNNING",
|
|
25
|
+
`Dia browser (${bundleId}) is not running. ${hint}`,
|
|
26
|
+
{ hint },
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class DiaAccessibilityError extends DiaBridgeError {
|
|
32
|
+
constructor(detail = "") {
|
|
33
|
+
const guidance = [
|
|
34
|
+
"macOS Accessibility permission is not granted for the process hosting dia-bridge.",
|
|
35
|
+
"To enable it:",
|
|
36
|
+
"1. Open System Settings -> Privacy & Security -> Accessibility (系统设置 -> 隐私与安全性 -> 辅助功能).",
|
|
37
|
+
"2. Add and toggle ON the host app running Magpie/plugin (e.g., Magpie, Terminal, iTerm2, or bun/node).",
|
|
38
|
+
"3. Restart Magpie (or toggle the dia-bridge plugin off and back on) and retry.",
|
|
39
|
+
].join("\n")
|
|
40
|
+
const message = detail ? `${guidance}\nDetails: ${detail}` : guidance
|
|
41
|
+
super("ACCESSIBILITY_DENIED", message, { hint: guidance })
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class DiaInputNotFoundError extends DiaBridgeError {
|
|
46
|
+
constructor(detail = "") {
|
|
47
|
+
const hint =
|
|
48
|
+
"Make sure a Dia browser window is open (not minimized) and its AI chat input box is visible."
|
|
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}`
|
|
52
|
+
super("INPUT_NOT_FOUND", message, { hint })
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class DiaTimeoutError extends DiaBridgeError {
|
|
57
|
+
constructor(timeoutMs, stage = "waiting for Dia response") {
|
|
58
|
+
super(
|
|
59
|
+
"TIMEOUT",
|
|
60
|
+
`dia_ask timed out after ${timeoutMs}ms while ${stage}. Note: Dia responses typically take 15-50s and Magpie enforces a 55s tool call limit.`,
|
|
61
|
+
)
|
|
62
|
+
this.timeoutMs = timeoutMs
|
|
63
|
+
this.stage = stage
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class DiaAbortedError extends DiaBridgeError {
|
|
68
|
+
constructor(reason) {
|
|
69
|
+
const detail =
|
|
70
|
+
reason instanceof Error
|
|
71
|
+
? reason.message
|
|
72
|
+
: typeof reason === "string" && reason
|
|
73
|
+
? reason
|
|
74
|
+
: "request cancelled"
|
|
75
|
+
super("ABORTED", `dia_ask was cancelled: ${detail}`)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class DiaValidationError extends DiaBridgeError {
|
|
80
|
+
constructor(message) {
|
|
81
|
+
super("INVALID_ARGUMENT", message)
|
|
82
|
+
}
|
|
83
|
+
}
|