dia-bridge 0.1.2 → 0.2.1

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.
@@ -0,0 +1,544 @@
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
+ DiaBridgeError,
9
+ DiaInputNotFoundError,
10
+ DiaNotRunningError,
11
+ DiaPlatformError,
12
+ DiaTimeoutError,
13
+ } from "./errors.mjs"
14
+
15
+ export const DIA_PROCESS_NAME = "Dia"
16
+
17
+ export function runPowerShell(script, { signal, timeoutMs = 15000, env = {} } = {}) {
18
+ return new Promise((resolve, reject) => {
19
+ if (signal?.aborted) {
20
+ reject(new DiaAbortedError(signal.reason))
21
+ return
22
+ }
23
+
24
+ const child = spawn(
25
+ "powershell.exe",
26
+ ["-NoProfile", "-NonInteractive", "-STA", "-Command", "-"],
27
+ {
28
+ stdio: ["pipe", "pipe", "pipe"],
29
+ windowsHide: true,
30
+ env: { ...process.env, ...env },
31
+ },
32
+ )
33
+
34
+ let stdout = ""
35
+ let stderr = ""
36
+ let settled = false
37
+ let killTimer = null
38
+
39
+ const terminate = () => {
40
+ if (child.killed || child.exitCode !== null) return
41
+ try {
42
+ child.kill("SIGTERM")
43
+ } catch {
44
+ // ignore
45
+ }
46
+ killTimer = setTimeout(() => {
47
+ if (child.exitCode !== null) return
48
+ try {
49
+ child.kill("SIGKILL")
50
+ } catch {
51
+ // ignore
52
+ }
53
+ }, 500)
54
+ killTimer.unref?.()
55
+ }
56
+
57
+ const cleanup = () => {
58
+ if (timer) clearTimeout(timer)
59
+ if (killTimer) clearTimeout(killTimer)
60
+ signal?.removeEventListener("abort", onAbort)
61
+ }
62
+
63
+ const onAbort = () => {
64
+ if (settled) return
65
+ settled = true
66
+ cleanup()
67
+ terminate()
68
+ reject(new DiaAbortedError(signal.reason))
69
+ }
70
+
71
+ const timer =
72
+ typeof timeoutMs === "number" && timeoutMs > 0
73
+ ? setTimeout(() => {
74
+ if (settled) return
75
+ settled = true
76
+ cleanup()
77
+ terminate()
78
+ reject(
79
+ new DiaTimeoutError(timeoutMs, "communicating with Dia via Windows UI Automation"),
80
+ )
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(
100
+ new DiaBridgeError(
101
+ "POWERSHELL_SPAWN_FAILED",
102
+ `Failed to run powershell.exe: ${err.message}`,
103
+ { cause: err },
104
+ ),
105
+ )
106
+ })
107
+
108
+ child.on("close", (code) => {
109
+ if (settled) return
110
+ settled = true
111
+ cleanup()
112
+ resolve({ code, stdout: stdout.trim(), stderr: stderr.trim() })
113
+ })
114
+
115
+ child.stdin.end(`${script}\n`, "utf8")
116
+ })
117
+ }
118
+
119
+ function parseJsonOutput(stdout) {
120
+ if (!stdout) throw new Error("Empty output")
121
+ try {
122
+ return JSON.parse(stdout)
123
+ } catch {
124
+ const lines = stdout
125
+ .split(/\r?\n/)
126
+ .map((line) => line.trim())
127
+ .filter(Boolean)
128
+ for (let i = lines.length - 1; i >= 0; i--) {
129
+ try {
130
+ return JSON.parse(lines[i])
131
+ } catch {
132
+ // try previous line
133
+ }
134
+ }
135
+ throw new Error("No valid JSON found in output")
136
+ }
137
+ }
138
+
139
+ const CHECK_ENV_PS = `
140
+ $ErrorActionPreference = 'Stop'
141
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
142
+ $processName = if ($env:DIA_BRIDGE_PROCESS_NAME) { $env:DIA_BRIDGE_PROCESS_NAME } else { 'Dia' }
143
+ $procs = @(Get-Process -Name $processName -ErrorAction SilentlyContinue)
144
+ $pids = @($procs | ForEach-Object { $_.Id })
145
+ $result = @{
146
+ running = ($procs.Count -gt 0)
147
+ processName = $processName
148
+ pids = $pids
149
+ }
150
+ Write-Output ($result | ConvertTo-Json -Compress)
151
+ `
152
+
153
+ const SUBMIT_PROMPT_PS = `
154
+ $ErrorActionPreference = 'Stop'
155
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
156
+
157
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
158
+ Add-Type -AssemblyName System.Windows.Forms
159
+
160
+ function Emit-Json($obj) {
161
+ Write-Output ($obj | ConvertTo-Json -Compress)
162
+ }
163
+
164
+ function Get-WritableInput($win) {
165
+ $editCond = [System.Windows.Automation.PropertyCondition]::new(
166
+ [System.Windows.Automation.AutomationElement]::ControlTypeProperty,
167
+ [System.Windows.Automation.ControlType]::Edit
168
+ )
169
+ $docCond = [System.Windows.Automation.PropertyCondition]::new(
170
+ [System.Windows.Automation.AutomationElement]::ControlTypeProperty,
171
+ [System.Windows.Automation.ControlType]::Document
172
+ )
173
+ $typeCond = [System.Windows.Automation.OrCondition]::new(
174
+ [System.Windows.Automation.Condition[]]@($editCond, $docCond)
175
+ )
176
+ $enabledCond = [System.Windows.Automation.PropertyCondition]::new(
177
+ [System.Windows.Automation.AutomationElement]::IsEnabledProperty,
178
+ $true
179
+ )
180
+ $cond = [System.Windows.Automation.AndCondition]::new(
181
+ [System.Windows.Automation.Condition[]]@($typeCond, $enabledCond)
182
+ )
183
+
184
+ $found = $win.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)
185
+ if (-not $found -or $found.Count -eq 0) {
186
+ return $null
187
+ }
188
+
189
+ $candidates = @()
190
+ for ($i = 0; $i -lt $found.Count; $i++) {
191
+ $el = $found.Item($i)
192
+ try {
193
+ $patternObj = $null
194
+ if (-not $el.TryGetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern, [ref]$patternObj)) {
195
+ continue
196
+ }
197
+ $vp = [System.Windows.Automation.ValuePattern]$patternObj
198
+ if ($vp.Current.IsReadOnly) {
199
+ continue
200
+ }
201
+ $name = ""
202
+ $autoId = ""
203
+ $isOffscreen = $false
204
+ $ctrlType = $el.Current.ControlType
205
+ try { $name = [string]$el.Current.Name } catch {}
206
+ try { $autoId = [string]$el.Current.AutomationId } catch {}
207
+ try { $isOffscreen = [bool]$el.Current.IsOffscreen } catch {}
208
+
209
+ $label = "$name $autoId"
210
+ $score = 0
211
+ if (-not $isOffscreen) { $score += 100 }
212
+ if ($ctrlType -eq [System.Windows.Automation.ControlType]::Document) { $score += 10 }
213
+ if ($label -match '(chat|ask|prompt|message|assistant|dia)') { $score += 30 }
214
+ if ($label -match '(address|url|omnibox|location bar)') { $score -= 50 }
215
+
216
+ $candidates += [PSCustomObject]@{
217
+ Element = $el
218
+ Pattern = $vp
219
+ Score = $score
220
+ Index = $i
221
+ }
222
+ } catch {}
223
+ }
224
+
225
+ if ($candidates.Count -eq 0) {
226
+ return $null
227
+ }
228
+
229
+ $best = $candidates | Sort-Object -Property @{ Expression = 'Score'; Descending = $true }, @{ Expression = 'Index'; Ascending = $true } | Select-Object -First 1
230
+ return $best
231
+ }
232
+
233
+ function Find-SendButton($inputEl, $win) {
234
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
235
+ $rootEl = [System.Windows.Automation.AutomationElement]::RootElement
236
+ $roots = @()
237
+ try {
238
+ $p1 = $walker.GetParent($inputEl)
239
+ if ($p1 -and -not [System.Windows.Automation.Automation]::Compare($p1, $win) -and -not [System.Windows.Automation.Automation]::Compare($p1, $rootEl)) {
240
+ $roots += $p1
241
+ try {
242
+ $p2 = $walker.GetParent($p1)
243
+ if ($p2 -and -not [System.Windows.Automation.Automation]::Compare($p2, $win) -and -not [System.Windows.Automation.Automation]::Compare($p2, $rootEl)) {
244
+ $roots += $p2
245
+ }
246
+ } catch {}
247
+ }
248
+ } catch {}
249
+ $roots += $win
250
+
251
+ $btnTypeCond = [System.Windows.Automation.PropertyCondition]::new(
252
+ [System.Windows.Automation.AutomationElement]::ControlTypeProperty,
253
+ [System.Windows.Automation.ControlType]::Button
254
+ )
255
+ $btnEnabledCond = [System.Windows.Automation.PropertyCondition]::new(
256
+ [System.Windows.Automation.AutomationElement]::IsEnabledProperty,
257
+ $true
258
+ )
259
+ $btnCond = [System.Windows.Automation.AndCondition]::new(
260
+ [System.Windows.Automation.Condition[]]@($btnTypeCond, $btnEnabledCond)
261
+ )
262
+
263
+ $labelPattern = '(send|submit|ask|arrow\.up|\\u53d1\\u9001|\\u63d0\\u4ea4)'
264
+ foreach ($root in $roots) {
265
+ try {
266
+ $buttons = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $btnCond)
267
+ if (-not $buttons) { continue }
268
+ for ($i = 0; $i -lt $buttons.Count; $i++) {
269
+ $btn = $buttons.Item($i)
270
+ try {
271
+ $label = "$([string]$btn.Current.Name) $([string]$btn.Current.HelpText) $([string]$btn.Current.AutomationId)"
272
+ if ($label -match $labelPattern) {
273
+ $invObj = $null
274
+ if ($btn.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern, [ref]$invObj)) {
275
+ return [PSCustomObject]@{
276
+ Element = $btn
277
+ Pattern = [System.Windows.Automation.InvokePattern]$invObj
278
+ }
279
+ }
280
+ }
281
+ } catch {}
282
+ }
283
+ } catch {}
284
+ }
285
+ return $null
286
+ }
287
+
288
+ function Send-EnterKey($inputEl) {
289
+ try {
290
+ $inputEl.SetFocus()
291
+ Start-Sleep -Milliseconds 50
292
+ [System.Windows.Forms.SendKeys]::SendWait('{ENTER}')
293
+ return $true
294
+ } catch {
295
+ return $false
296
+ }
297
+ }
298
+
299
+ $processName = if ($env:DIA_BRIDGE_PROCESS_NAME) { $env:DIA_BRIDGE_PROCESS_NAME } else { 'Dia' }
300
+ $promptPath = $env:DIA_BRIDGE_PROMPT_FILE
301
+ $targetPidRaw = $env:DIA_BRIDGE_TARGET_PID
302
+
303
+ if (-not $promptPath -or -not (Test-Path -LiteralPath $promptPath)) {
304
+ Emit-Json @{ ok = $false; error = 'PROMPT_READ_FAILED'; detail = 'Prompt file missing' }
305
+ exit 0
306
+ }
307
+
308
+ $promptText = [System.IO.File]::ReadAllText($promptPath, [System.Text.UTF8Encoding]::new($false))
309
+
310
+ $procs = @()
311
+ if ($targetPidRaw) {
312
+ $parsedPid = [int]$targetPidRaw
313
+ $procs = @(Get-Process -Id $parsedPid -ErrorAction SilentlyContinue)
314
+ } else {
315
+ $procs = @(Get-Process -Name $processName -ErrorAction SilentlyContinue)
316
+ }
317
+
318
+ if ($procs.Count -eq 0) {
319
+ Emit-Json @{ ok = $false; error = 'DIA_NOT_RUNNING' }
320
+ exit 0
321
+ }
322
+
323
+ # Prioritize processes that own a main window handle
324
+ $orderedProcs = @($procs | Sort-Object -Property @{ Expression = { $_.MainWindowHandle -ne [IntPtr]::Zero }; Descending = $true })
325
+ $root = [System.Windows.Automation.AutomationElement]::RootElement
326
+ $windows = @()
327
+ $seenHandles = @{}
328
+
329
+ foreach ($p in $orderedProcs) {
330
+ try {
331
+ $pidCond = [System.Windows.Automation.PropertyCondition]::new(
332
+ [System.Windows.Automation.AutomationElement]::ProcessIdProperty,
333
+ [int]$p.Id
334
+ )
335
+ $foundWins = $root.FindAll([System.Windows.Automation.TreeScope]::Children, $pidCond)
336
+ if ($foundWins) {
337
+ for ($i = 0; $i -lt $foundWins.Count; $i++) {
338
+ $w = $foundWins.Item($i)
339
+ $hwnd = 0
340
+ try { $hwnd = [int]$w.Current.NativeWindowHandle } catch {}
341
+ if ($hwnd -ne 0 -and $seenHandles.ContainsKey($hwnd)) { continue }
342
+ if ($hwnd -ne 0) { $seenHandles[$hwnd] = $true }
343
+ $windows += [PSCustomObject]@{ Window = $w; Pid = $p.Id }
344
+ }
345
+ }
346
+ } catch {}
347
+ }
348
+
349
+ if ($windows.Count -eq 0) {
350
+ Emit-Json @{ ok = $false; error = 'INPUT_NOT_FOUND'; detail = 'Dia has no open windows' }
351
+ exit 0
352
+ }
353
+
354
+ $target = $null
355
+ $targetWin = $null
356
+ $targetPid = $orderedProcs[0].Id
357
+ foreach ($entry in $windows) {
358
+ $foundInput = Get-WritableInput $entry.Window
359
+ if ($foundInput) {
360
+ $target = $foundInput
361
+ $targetWin = $entry.Window
362
+ $targetPid = $entry.Pid
363
+ break
364
+ }
365
+ }
366
+
367
+ if (-not $target) {
368
+ Emit-Json @{ ok = $false; error = 'INPUT_NOT_FOUND'; detail = 'No writable Edit/Document control supporting ValuePattern found in Dia windows' }
369
+ exit 0
370
+ }
371
+
372
+ $inputEl = $target.Element
373
+ $valPattern = $target.Pattern
374
+
375
+ # Write directly via ValuePattern.SetValue (never simulate typing keystrokes) to preserve Unicode/Chinese/JSON verbatim.
376
+ $valPattern.SetValue($promptText)
377
+ Start-Sleep -Milliseconds 50
378
+
379
+ $readback = ''
380
+ try { $readback = [string]$valPattern.Current.Value } catch {}
381
+ $normPrompt = $promptText -replace "\`r\`n", "\`n"
382
+ $normReadback = $readback -replace "\`r\`n", "\`n"
383
+
384
+ if ($normReadback -ne $normPrompt) {
385
+ try { $inputEl.SetFocus() } catch {}
386
+ Start-Sleep -Milliseconds 50
387
+ $valPattern.SetValue($promptText)
388
+ Start-Sleep -Milliseconds 50
389
+ try { $readback = [string]$valPattern.Current.Value } catch {}
390
+ $normReadback = $readback -replace "\`r\`n", "\`n"
391
+ }
392
+
393
+ try { $inputEl.SetFocus() } catch {}
394
+ Start-Sleep -Milliseconds 50
395
+
396
+ $submitMethod = 'sendkeys_enter'
397
+ $sendBtn = Find-SendButton $inputEl $targetWin
398
+ if ($sendBtn) {
399
+ try {
400
+ $sendBtn.Pattern.Invoke()
401
+ $submitMethod = 'uia_invoke_button'
402
+ } catch {
403
+ [void](Send-EnterKey $inputEl)
404
+ $submitMethod = 'sendkeys_enter'
405
+ }
406
+ } else {
407
+ [void](Send-EnterKey $inputEl)
408
+ }
409
+
410
+ Start-Sleep -Milliseconds 180
411
+ $remaining = ''
412
+ try { $remaining = [string]$valPattern.Current.Value } catch {}
413
+ $normRemaining = $remaining -replace "\`r\`n", "\`n"
414
+ if ($normRemaining -eq $normPrompt) {
415
+ if ($submitMethod -eq 'uia_invoke_button') {
416
+ [void](Send-EnterKey $inputEl)
417
+ $submitMethod = 'uia_invoke_button+sendkeys_enter'
418
+ } elseif ($sendBtn) {
419
+ try {
420
+ $sendBtn.Pattern.Invoke()
421
+ $submitMethod = 'sendkeys_enter+uia_invoke_button'
422
+ } catch {}
423
+ }
424
+ }
425
+
426
+ Emit-Json @{
427
+ ok = $true
428
+ method = $submitMethod
429
+ pid = $targetPid
430
+ length = $promptText.Length
431
+ readbackMatched = ($normReadback -eq $normPrompt)
432
+ }
433
+ `
434
+
435
+ export async function checkDiaEnvironmentWindows({
436
+ signal,
437
+ timeoutMs = 10000,
438
+ processName = DIA_PROCESS_NAME,
439
+ platform = process.platform,
440
+ execPowerShell = runPowerShell,
441
+ } = {}) {
442
+ if (platform !== "win32") {
443
+ throw new DiaPlatformError(platform)
444
+ }
445
+
446
+ const res = await execPowerShell(CHECK_ENV_PS, {
447
+ signal,
448
+ timeoutMs,
449
+ env: { DIA_BRIDGE_PROCESS_NAME: processName },
450
+ })
451
+
452
+ if (res.code !== 0) {
453
+ throw new DiaBridgeError(
454
+ "ENV_CHECK_FAILED",
455
+ `Failed to inspect Dia process state on Windows: ${res.stderr || `powershell.exe exited with code ${res.code}`}`,
456
+ )
457
+ }
458
+
459
+ let parsed
460
+ try {
461
+ parsed = parseJsonOutput(res.stdout)
462
+ } catch (err) {
463
+ throw new DiaBridgeError(
464
+ "ENV_CHECK_PARSE_FAILED",
465
+ `Unexpected response from Windows Dia environment check: ${res.stdout}`,
466
+ { cause: err },
467
+ )
468
+ }
469
+
470
+ if (!parsed.running) {
471
+ throw new DiaNotRunningError(processName)
472
+ }
473
+
474
+ return parsed
475
+ }
476
+
477
+ export async function submitPromptViaUIA(
478
+ prompt,
479
+ {
480
+ signal,
481
+ timeoutMs = 15000,
482
+ processName = DIA_PROCESS_NAME,
483
+ targetPid = null,
484
+ execPowerShell = runPowerShell,
485
+ } = {},
486
+ ) {
487
+ const promptFile = path.join(
488
+ os.tmpdir(),
489
+ `dia-bridge-prompt-${process.pid}-${crypto.randomBytes(8).toString("hex")}.txt`,
490
+ )
491
+
492
+ await fs.writeFile(promptFile, prompt, { encoding: "utf8", mode: 0o600 })
493
+
494
+ try {
495
+ const env = {
496
+ DIA_BRIDGE_PROCESS_NAME: processName,
497
+ DIA_BRIDGE_PROMPT_FILE: promptFile,
498
+ }
499
+ if (targetPid !== null && targetPid !== undefined) {
500
+ env.DIA_BRIDGE_TARGET_PID = String(targetPid)
501
+ }
502
+
503
+ const res = await execPowerShell(SUBMIT_PROMPT_PS, {
504
+ signal,
505
+ timeoutMs,
506
+ env,
507
+ })
508
+
509
+ if (res.code !== 0) {
510
+ throw new DiaBridgeError(
511
+ "UIA_SUBMIT_FAILED",
512
+ `Failed to submit prompt to Dia via Windows UI Automation: ${res.stderr || `powershell.exe exited with code ${res.code}`}`,
513
+ )
514
+ }
515
+
516
+ let parsed
517
+ try {
518
+ parsed = parseJsonOutput(res.stdout)
519
+ } catch (err) {
520
+ throw new DiaBridgeError(
521
+ "UIA_SUBMIT_PARSE_FAILED",
522
+ `Unexpected response from Windows UIA submit script: ${res.stdout}`,
523
+ { cause: err },
524
+ )
525
+ }
526
+
527
+ if (!parsed.ok) {
528
+ if (parsed.error === "DIA_NOT_RUNNING") {
529
+ throw new DiaNotRunningError(processName)
530
+ }
531
+ if (parsed.error === "INPUT_NOT_FOUND") {
532
+ throw new DiaInputNotFoundError(parsed.detail)
533
+ }
534
+ throw new DiaBridgeError(
535
+ parsed.error || "UIA_SUBMIT_FAILED",
536
+ `Dia Windows UIA submission failed (${parsed.error || "unknown"})${parsed.detail ? `: ${parsed.detail}` : ""}`,
537
+ )
538
+ }
539
+
540
+ return parsed
541
+ } finally {
542
+ await fs.unlink(promptFile).catch(() => {})
543
+ }
544
+ }