@namzu/computer-use 4.1.0 → 4.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +18 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +28 -2
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y-script.d.ts +47 -0
  7. package/dist/a11y/a11y-script.d.ts.map +1 -0
  8. package/dist/a11y/a11y-script.js +738 -0
  9. package/dist/a11y/a11y-script.js.map +1 -0
  10. package/dist/a11y/a11y.d.ts +60 -0
  11. package/dist/a11y/a11y.d.ts.map +1 -0
  12. package/dist/a11y/a11y.js +400 -0
  13. package/dist/a11y/a11y.js.map +1 -0
  14. package/dist/a11y/index.d.ts +8 -0
  15. package/dist/a11y/index.d.ts.map +1 -0
  16. package/dist/a11y/index.js +5 -0
  17. package/dist/a11y/index.js.map +1 -0
  18. package/dist/a11y/interface.d.ts +198 -0
  19. package/dist/a11y/interface.d.ts.map +1 -0
  20. package/dist/a11y/interface.js +22 -0
  21. package/dist/a11y/interface.js.map +1 -0
  22. package/dist/a11y/windows.d.ts +20 -0
  23. package/dist/a11y/windows.d.ts.map +1 -0
  24. package/dist/a11y/windows.js +40 -0
  25. package/dist/a11y/windows.js.map +1 -0
  26. package/dist/adapters/cua-driver/adapter.d.ts +47 -0
  27. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  28. package/dist/adapters/cua-driver/adapter.js +138 -3
  29. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  30. package/dist/adapters/types.d.ts +11 -0
  31. package/dist/adapters/types.d.ts.map +1 -1
  32. package/dist/adapters/types.js.map +1 -1
  33. package/dist/adapters/win32.d.ts +3 -0
  34. package/dist/adapters/win32.d.ts.map +1 -1
  35. package/dist/adapters/win32.js +1 -0
  36. package/dist/adapters/win32.js.map +1 -1
  37. package/dist/foreground/guard.d.ts.map +1 -1
  38. package/dist/foreground/guard.js +1 -0
  39. package/dist/foreground/guard.js.map +1 -1
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -0
  43. package/dist/index.js.map +1 -1
  44. package/dist/presence/helper-script.d.ts +18 -11
  45. package/dist/presence/helper-script.d.ts.map +1 -1
  46. package/dist/presence/helper-script.js +301 -86
  47. package/dist/presence/helper-script.js.map +1 -1
  48. package/dist/presence/index.d.ts +3 -1
  49. package/dist/presence/index.d.ts.map +1 -1
  50. package/dist/presence/index.js +2 -1
  51. package/dist/presence/index.js.map +1 -1
  52. package/dist/presence/motion.d.ts +84 -0
  53. package/dist/presence/motion.d.ts.map +1 -0
  54. package/dist/presence/motion.js +114 -0
  55. package/dist/presence/motion.js.map +1 -0
  56. package/dist/presence/preview.d.ts +25 -0
  57. package/dist/presence/preview.d.ts.map +1 -0
  58. package/dist/presence/preview.js +32 -0
  59. package/dist/presence/preview.js.map +1 -0
  60. package/package.json +2 -2
  61. package/src/SubprocessComputerUseHost.ts +48 -1
  62. package/src/a11y/a11y-script.ts +740 -0
  63. package/src/a11y/a11y.ts +499 -0
  64. package/src/a11y/index.ts +24 -0
  65. package/src/a11y/interface.ts +226 -0
  66. package/src/a11y/windows.ts +56 -0
  67. package/src/adapters/cua-driver/adapter.ts +151 -6
  68. package/src/adapters/types.ts +8 -0
  69. package/src/adapters/win32.ts +4 -0
  70. package/src/foreground/guard.ts +1 -0
  71. package/src/index.ts +19 -0
  72. package/src/presence/helper-script.ts +327 -87
  73. package/src/presence/index.ts +10 -1
  74. package/src/presence/motion.ts +141 -0
  75. package/src/presence/preview.ts +42 -0
@@ -0,0 +1,226 @@
1
+ /**
2
+ * What the computer-use host needs to know about a desktop's windows and
3
+ * their contents, written without any one platform's terms so a macOS or a
4
+ * Linux backend only adds a file that implements {@link AccessibilityBackend}.
5
+ *
6
+ * - A window is named by an opaque `windowId` string; the backend defines its
7
+ * format and accepts the ones it handed out.
8
+ * - Rectangles are virtual-desktop physical pixels.
9
+ * - Nothing here is a promise about speed except {@link AccessibilityBackend.listWindows},
10
+ * which a backend serves from the platform's window list without reading
11
+ * any window's contents.
12
+ */
13
+
14
+ export interface A11yRect {
15
+ readonly x: number
16
+ readonly y: number
17
+ readonly width: number
18
+ readonly height: number
19
+ }
20
+
21
+ /** A top-level window a person would call a window. */
22
+ export interface A11yWindow {
23
+ readonly windowId: string
24
+ readonly processId: number
25
+ /** The program's file name (`app.exe` on Windows); empty when it cannot be read. */
26
+ readonly processName: string
27
+ readonly title: string
28
+ readonly bounds: A11yRect
29
+ readonly minimized: boolean
30
+ /** The window the user is typing into. */
31
+ readonly focused: boolean
32
+ /** Position front to back among the listed windows; 0 is in front. */
33
+ readonly z: number
34
+ }
35
+
36
+ export interface A11yDisplay {
37
+ readonly id: string
38
+ readonly bounds: A11yRect
39
+ /** The part of the display not taken by the shell's own bars. */
40
+ readonly workArea: A11yRect
41
+ /** 1 is 96 dpi, 1.5 is 144 dpi. */
42
+ readonly scale: number
43
+ readonly primary: boolean
44
+ }
45
+
46
+ /** What a control can be asked to do, by the pattern it offers. */
47
+ export type A11yAction =
48
+ | 'invoke'
49
+ | 'value'
50
+ | 'toggle'
51
+ | 'expandCollapse'
52
+ | 'selectionItem'
53
+ | 'scroll'
54
+
55
+ export interface A11yNode {
56
+ /** Position in {@link A11ySnapshot.nodes}; the handle `identity` takes. */
57
+ readonly index: number
58
+ /** Index of the parent, -1 for the window itself. */
59
+ readonly parent: number
60
+ readonly depth: number
61
+ /** The control's kind (`Button`, `Edit`, `Text`, …), as the platform names it. */
62
+ readonly role: string
63
+ readonly name?: string
64
+ readonly automationId?: string
65
+ readonly className?: string
66
+ readonly bounds: A11yRect
67
+ readonly enabled: boolean
68
+ readonly offscreen: boolean
69
+ readonly focused: boolean
70
+ readonly actions: readonly A11yAction[]
71
+ readonly value?: string
72
+ readonly toggle?: 'on' | 'off' | 'mixed'
73
+ readonly expand?: 'expanded' | 'collapsed' | 'partial' | 'leaf'
74
+ readonly selected?: boolean
75
+ /** Present when the children of this control were not all listed. */
76
+ readonly childCount?: number
77
+ }
78
+
79
+ export interface A11ySnapshotRequest {
80
+ readonly windowId: string
81
+ /** Default 400. */
82
+ readonly maxNodes?: number
83
+ /** Default 12. */
84
+ readonly maxDepth?: number
85
+ /** Only the window, its children and theirs, with `childCount` on the containers. */
86
+ readonly skeleton?: boolean
87
+ /**
88
+ * Read a Chromium or Electron window anyway. Reading one switches its
89
+ * accessibility on for the rest of the session, so it is refused
90
+ * (`chromium_not_activated`) unless the caller asks.
91
+ */
92
+ readonly allowChromium?: boolean
93
+ /** Longest the read may take, ms. Default 8 000. */
94
+ readonly timeoutMs?: number
95
+ }
96
+
97
+ export interface A11ySnapshot {
98
+ readonly windowId: string
99
+ /** Names this read; `identity` refuses an index from an older one when given it. */
100
+ readonly revision: number
101
+ readonly nodes: readonly A11yNode[]
102
+ /** Controls in the window, listed or not. */
103
+ readonly total: number
104
+ readonly truncated: boolean
105
+ readonly skeleton: boolean
106
+ /** How long the platform call took, ms. */
107
+ readonly readMs: number
108
+ }
109
+
110
+ /** Which kind of change to wait for. Default: all. */
111
+ export type A11yChangeKind = 'structure' | 'property' | 'location'
112
+
113
+ /** A marker in the stream of changes; see {@link AccessibilityBackend.seq}. Opaque. */
114
+ export type A11ySeq = number
115
+
116
+ export interface A11yWaitRequest {
117
+ readonly windowId: string
118
+ /** A token from {@link AccessibilityBackend.seq}: count changes since then. Default: since this call. */
119
+ readonly since?: A11ySeq
120
+ /** How long the window must stay quiet after its last change, ms. Default 120. */
121
+ readonly quietMs?: number
122
+ /** Longest to wait, ms. Default 2 000, at most 10 000. */
123
+ readonly timeoutMs?: number
124
+ readonly kinds?: readonly A11yChangeKind[]
125
+ }
126
+
127
+ export type A11yWaitResult =
128
+ | {
129
+ readonly changed: true
130
+ /** False when changes were still arriving at the timeout. */
131
+ readonly settled: boolean
132
+ /** From the start of the wait to the first change; negative when it came earlier (see `since`). */
133
+ readonly firstEventMs: number
134
+ readonly settledMs: number
135
+ readonly events: number
136
+ /** Windows of the same program that appeared. */
137
+ readonly newWindows: readonly string[]
138
+ }
139
+ | { readonly changed: false; readonly timedOut: true; readonly settledMs: number }
140
+
141
+ /**
142
+ * Names a control well enough to find it again after the window changed:
143
+ * the platform's own runtime id first, else its automation id and kind, else
144
+ * its kind, a hash of its name and the path of its ancestors. Holds no text.
145
+ */
146
+ export interface A11yFingerprint {
147
+ readonly runtimeId: string
148
+ readonly automationId: string
149
+ readonly role: string
150
+ readonly nameHash: string
151
+ readonly parentPath: string
152
+ /** Among siblings with the same kind and name. */
153
+ readonly ordinal: number
154
+ /** When the owning process started (ms); a different value means a different program run. */
155
+ readonly processStart: number
156
+ }
157
+
158
+ export interface A11yIdentityRequest {
159
+ readonly windowId: string
160
+ readonly index: number
161
+ /** Refuse (`stale_snapshot`) when the window was read again since this revision. */
162
+ readonly revision?: number
163
+ }
164
+
165
+ export interface A11yResolveRequest {
166
+ readonly windowId: string
167
+ readonly fingerprint: A11yFingerprint
168
+ }
169
+
170
+ export type A11yResolution =
171
+ | {
172
+ readonly found: true
173
+ /** Index in the read this call made (it is the window's latest snapshot now). */
174
+ readonly index: number
175
+ readonly via: 'runtimeId' | 'automationId' | 'name'
176
+ readonly revision: number
177
+ }
178
+ | {
179
+ readonly found: false
180
+ readonly code: 'not_found' | 'ambiguous'
181
+ readonly candidates?: number
182
+ }
183
+
184
+ export interface AccessibilityBackend {
185
+ /** Which implementation this is, for diagnosis. */
186
+ readonly id: string
187
+ /** True once the backend answered its first greeting and has not ended since. */
188
+ readonly isReady: boolean
189
+ /** Starts the backend ahead of the first question. Does not wait; safe to repeat. */
190
+ warm(): void
191
+ /** Resolves true when the backend is up; false (never throws) when it cannot be. */
192
+ ready(): Promise<boolean>
193
+ /** The visible, un-cloaked, non-tool top-level windows, front to back. */
194
+ listWindows(
195
+ options?: { readonly includeOwned?: boolean },
196
+ signal?: AbortSignal,
197
+ ): Promise<readonly A11yWindow[]>
198
+ listDisplays(signal?: AbortSignal): Promise<readonly A11yDisplay[]>
199
+ snapshot(request: A11ySnapshotRequest, signal?: AbortSignal): Promise<A11ySnapshot>
200
+ /**
201
+ * A marker in the stream of changes. With a window it also starts
202
+ * watching that window (the first time costs about 100 ms), so that
203
+ * `const since = await seq(w); act(); await waitForChange({ windowId: w, since })`
204
+ * misses nothing the action did.
205
+ */
206
+ seq(windowId?: string, signal?: AbortSignal): Promise<A11ySeq>
207
+ /**
208
+ * Resolves from events, not from sleeping: after at least one change and
209
+ * then `quietMs` without another, or `{ changed: false }` after `timeoutMs`.
210
+ */
211
+ waitForChange(request: A11yWaitRequest, signal?: AbortSignal): Promise<A11yWaitResult>
212
+ identity(request: A11yIdentityRequest, signal?: AbortSignal): Promise<A11yFingerprint>
213
+ resolve(request: A11yResolveRequest, signal?: AbortSignal): Promise<A11yResolution>
214
+ close(): Promise<void>
215
+ }
216
+
217
+ /** A failure the backend reports, or the client's own (`timeout`, `helper_exited`, `unavailable`, …). */
218
+ export class A11yError extends Error {
219
+ constructor(
220
+ readonly code: string,
221
+ message: string,
222
+ ) {
223
+ super(message)
224
+ this.name = 'A11yError'
225
+ }
226
+ }
@@ -0,0 +1,56 @@
1
+ import {
2
+ type WslProbes,
3
+ isWsl,
4
+ realWslProbes,
5
+ wslChildEnv,
6
+ wslPowerShellPath,
7
+ } from '../adapters/wsl.js'
8
+ import { WindowsA11yHost } from './a11y.js'
9
+ import type { AccessibilityBackend } from './interface.js'
10
+
11
+ /** Variable names never handed to a helper process. */
12
+ const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i
13
+
14
+ /** The environment variable that turns the accessibility host off (`off`, `0`, `false`, `no`). */
15
+ export const A11Y_ENV = 'NAMZU_COMPUTER_USE_A11Y'
16
+
17
+ export interface WindowsA11yFactoryOptions {
18
+ readonly env?: NodeJS.ProcessEnv
19
+ readonly platform?: NodeJS.Platform
20
+ readonly wslProbes?: WslProbes
21
+ /** Default true. `false` starts nothing, whatever the environment says. */
22
+ readonly enabled?: boolean
23
+ }
24
+
25
+ /** Whether the environment asks for the accessibility host to be off. */
26
+ export function a11yDisabledByEnv(env: NodeJS.ProcessEnv): boolean {
27
+ const value = env[A11Y_ENV]
28
+ return value !== undefined && /^(off|0|false|no|none)$/i.test(value.trim())
29
+ }
30
+
31
+ /**
32
+ * The accessibility host for this machine's Windows desktop (WSL included),
33
+ * or undefined when it is turned off or there is no Windows PowerShell to run
34
+ * it in. Nothing is started until it is first used or warmed.
35
+ */
36
+ export function createWindowsA11yHost(
37
+ options: WindowsA11yFactoryOptions = {},
38
+ ): AccessibilityBackend | undefined {
39
+ const env = options.env ?? process.env
40
+ if (options.enabled === false || a11yDisabledByEnv(env)) return undefined
41
+ const platform = options.platform ?? process.platform
42
+ const probes = options.wslProbes ?? realWslProbes
43
+ const wsl = isWsl(env, platform, probes)
44
+ const powershell = wsl
45
+ ? wslPowerShellPath(probes)
46
+ : platform === 'win32'
47
+ ? 'powershell.exe'
48
+ : undefined
49
+ if (!powershell) return undefined
50
+ const clean: NodeJS.ProcessEnv = {}
51
+ for (const [name, value] of Object.entries(env)) if (!SECRET_NAME.test(name)) clean[name] = value
52
+ return new WindowsA11yHost({
53
+ powershell,
54
+ env: wsl ? wslChildEnv(clean, [], probes) : clean,
55
+ })
56
+ }
@@ -20,6 +20,7 @@ import type {
20
20
  WindowInputResult,
21
21
  WindowScreenshotResult,
22
22
  } from '@namzu/sdk'
23
+ import type { A11ySeq, A11yWindow, AccessibilityBackend } from '../../a11y/interface.js'
23
24
  import { droppedInputNote, foregroundNote, interferenceNote } from '../../foreground/guard.js'
24
25
  import type { ForegroundLadder, LadderRequest } from '../../foreground/ladder.js'
25
26
  import { BurstInterrupted, type ForegroundSubject } from '../../foreground/types.js'
@@ -105,6 +106,14 @@ export interface CuaDriverAdapterOptions {
105
106
  * Absent, nothing is drawn.
106
107
  */
107
108
  readonly presence?: Presence
109
+ /**
110
+ * A resident accessibility host. While it is up, the window list is served
111
+ * from it (a fraction of a millisecond, with no driver call), and a window
112
+ * input is followed by waiting for the window to stop changing instead of
113
+ * a fixed pause. Absent, or on any failure of it, the driver answers as it
114
+ * always did.
115
+ */
116
+ readonly a11y?: AccessibilityBackend
108
117
  /** For tests: the clock the freshness of a read is judged by. */
109
118
  readonly now?: () => number
110
119
  /** For tests: how the adapter waits for a window to show an input's effect. */
@@ -147,6 +156,12 @@ const OBSERVE_WAITS_MS = [0, 80, 200, 450] as const
147
156
  * moves the check by that much later, not closer to the send.
148
157
  */
149
158
  const WINDOW_LIST_FRESH_MS = 1_000
159
+ /** After the accessibility host failed once, the driver answers alone for this long (ms), doubled for each further failure. */
160
+ const A11Y_BACKOFF_MS = 30_000
161
+ /** The accessibility host is given up on for the session after this many failures. */
162
+ const A11Y_MAX_FAILURES = 3
163
+ /** How long (ms) a window must stay quiet after its last change before an action counts as settled. */
164
+ const SETTLE_QUIET_MS = 120
150
165
 
151
166
  /** The window list as the driver gave it, and when it was read. */
152
167
  interface WindowListing {
@@ -399,6 +414,13 @@ export class CuaDriverAdapter implements Adapter {
399
414
  private readonly windowApps = new Map<string, string>()
400
415
  private readonly foreground: ForegroundLadder | undefined
401
416
  private readonly presence: Presence | undefined
417
+ private readonly a11y: AccessibilityBackend | undefined
418
+ private a11yFailures = 0
419
+ private a11yRetryAt = 0
420
+ /** Whether the latest window list came from the accessibility host (its bounds are then its own, not the driver's). */
421
+ private listedByHost = false
422
+ /** Per window: the change marker taken before the first input since its last capture. */
423
+ private readonly settleMarks = new Map<number, A11ySeq>()
402
424
  /** False once the driver would not switch its own cursor off: Namzu's is then not shown, so there is never a second one. */
403
425
  private driverCursorOff: boolean | undefined
404
426
  /** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
@@ -423,6 +445,9 @@ export class CuaDriverAdapter implements Adapter {
423
445
  this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`
424
446
  this.foreground = options.foreground
425
447
  this.presence = options.presence
448
+ this.a11y = options.a11y
449
+ // Compiling the helper takes a moment; start it now so the first window list can already use it.
450
+ options.a11y?.warm()
426
451
  this.now = options.now ?? Date.now
427
452
  this.settle = options.settle ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
428
453
  this.client = new McpStdioClient({
@@ -569,11 +594,14 @@ export class CuaDriverAdapter implements Adapter {
569
594
  async listWindows(): Promise<readonly WindowInfo[]> {
570
595
  // The model is about to work in a window: have the overlay ready for its first action.
571
596
  this.tryPresence((presence) => presence.warm())
572
- const listed = structured(
573
- await this.callTool('list_windows', {}, LIST_TIMEOUT_MS),
574
- 'list_windows',
575
- )
576
- const windows = toWindowInfos(listed.windows)
597
+ const fromHost = await this.windowsFromHost()
598
+ this.listedByHost = fromHost !== undefined
599
+ const windows =
600
+ fromHost ??
601
+ toWindowInfos(
602
+ structured(await this.callTool('list_windows', {}, LIST_TIMEOUT_MS), 'list_windows')
603
+ .windows,
604
+ )
577
605
  this.windowPids.clear()
578
606
  this.windowApps.clear()
579
607
  for (const window of windows) {
@@ -583,6 +611,77 @@ export class CuaDriverAdapter implements Adapter {
583
611
  return windows
584
612
  }
585
613
 
614
+ /**
615
+ * The window list from the accessibility host, or undefined when it is not
616
+ * up yet (it is started now and used from the next call), was given up
617
+ * on, or failed this time. A failure is never retried within the call:
618
+ * the driver answers it, and the host is left alone for a while.
619
+ */
620
+ private async windowsFromHost(): Promise<WindowInfo[] | undefined> {
621
+ const a11y = this.a11y
622
+ if (!a11y || this.a11yFailures >= A11Y_MAX_FAILURES) return undefined
623
+ if (!a11y.isReady) {
624
+ a11y.warm()
625
+ return undefined
626
+ }
627
+ if (this.now() < this.a11yRetryAt) return undefined
628
+ try {
629
+ const windows = windowInfosFromHost(
630
+ await a11y.listWindows({ includeOwned: true }, currentCallSignal()),
631
+ )
632
+ this.a11yFailures = 0
633
+ return windows
634
+ } catch {
635
+ this.a11yFailures++
636
+ this.a11yRetryAt = this.now() + A11Y_BACKOFF_MS * 2 ** (this.a11yFailures - 1)
637
+ return undefined
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Called by the tool instead of its fixed pause after a batch: waits for
643
+ * the window the batch acted in to stop changing, as the window reports it.
644
+ * Undefined when there is nothing to wait on (the host is not up, the
645
+ * batch did not act in a window through this adapter, the host failed):
646
+ * the tool then pauses as it always did.
647
+ */
648
+ async settleAfterInput(
649
+ request: { readonly windowId?: string; readonly budgetMs: number },
650
+ signal?: AbortSignal,
651
+ ): Promise<{ readonly waitedMs: number; readonly changed: boolean } | undefined> {
652
+ const a11y = this.a11y
653
+ if (!a11y || !a11y.isReady || request.windowId === undefined) return undefined
654
+ const hwnd = parseWindowId(request.windowId)
655
+ const since = hwnd === undefined ? undefined : this.settleMarks.get(hwnd)
656
+ if (hwnd === undefined || since === undefined) return undefined
657
+ this.settleMarks.delete(hwnd)
658
+ try {
659
+ const waited = await a11y.waitForChange(
660
+ {
661
+ windowId: windowIdOf(hwnd),
662
+ since,
663
+ quietMs: Math.min(SETTLE_QUIET_MS, request.budgetMs),
664
+ timeoutMs: request.budgetMs,
665
+ },
666
+ signal,
667
+ )
668
+ return { waitedMs: waited.settledMs, changed: waited.changed }
669
+ } catch {
670
+ return undefined
671
+ }
672
+ }
673
+
674
+ /** Takes (and, for a window not watched yet, starts) the change marker an input's settle counts from. Never fails the input. */
675
+ private async markForSettle(hwnd: number): Promise<void> {
676
+ const a11y = this.a11y
677
+ if (!a11y?.isReady || this.settleMarks.has(hwnd)) return
678
+ try {
679
+ this.settleMarks.set(hwnd, await a11y.seq(windowIdOf(hwnd)))
680
+ } catch {
681
+ this.settleMarks.delete(hwnd)
682
+ }
683
+ }
684
+
586
685
  async focusWindow(id: string): Promise<FocusWindowResult> {
587
686
  const hwnd = parseWindowId(id)
588
687
  if (hwnd === undefined)
@@ -615,6 +714,17 @@ export class CuaDriverAdapter implements Adapter {
615
714
  // A failed or overlapping capture invalidates the old resize ratio even
616
715
  // if the driver returned no image. Never let it address a later action.
617
716
  this.windowFrame = undefined
717
+ // What an earlier input changed was seen by the screenshot being taken now; and the window
718
+ // starts being watched while it is captured, so the first input after it loses no event.
719
+ this.settleMarks.delete(target.hwnd)
720
+ const armed = this.a11y?.isReady
721
+ ? this.a11y.seq(windowIdOf(target.hwnd)).catch(() => undefined)
722
+ : undefined
723
+ // The window where the host says it is before the capture: the host's rectangle is its own,
724
+ // so "did not move during the capture" is judged against it, not against the driver's.
725
+ const hostBefore = this.listedByHost
726
+ ? (await this.windowsFromHost())?.find((window) => window.id === windowIdOf(target.hwnd))
727
+ : undefined
618
728
  let captureStarts = 0
619
729
  let captureGeneration = this.sessionGeneration
620
730
  const result = await this.callTool(
@@ -665,12 +775,13 @@ export class CuaDriverAdapter implements Adapter {
665
775
  throw new Error(
666
776
  'cua-driver: the driver session changed after the window capture; take a new screenshot.',
667
777
  )
778
+ await armed
668
779
  const listed = windows.find((window) => window.id === windowIdOf(target.hwnd))
669
780
  if (
670
781
  !listed ||
671
782
  listed.pid !== target.pid ||
672
783
  listed.minimized ||
673
- !sameBounds(listed.bounds, bounds)
784
+ !sameBounds(listed.bounds, this.listedByHost && hostBefore ? hostBefore.bounds : bounds)
674
785
  )
675
786
  throw new Error(
676
787
  `cua-driver: window ${id} moved, closed or was minimized during capture; take a new screenshot.`,
@@ -1033,6 +1144,7 @@ export class CuaDriverAdapter implements Adapter {
1033
1144
  'computer-use: the captured window changed or its driver restarted; take a new window screenshot.',
1034
1145
  )
1035
1146
  this.showPresence(frame, current.bounds, name, args)
1147
+ await this.markForSettle(target.window_id as number)
1036
1148
  return this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
1037
1149
  }
1038
1150
  // The driver's hotkey finds a shortcut only through an accelerator the window names, and refuses (sending
@@ -2597,6 +2709,39 @@ export function toWindowInfos(raw: unknown): WindowInfo[] {
2597
2709
  return ordered.map((entry) => ({ ...entry.info, focused: entry === front }))
2598
2710
  }
2599
2711
 
2712
+ /**
2713
+ * The accessibility host's window list → the host's `WindowInfo`, front to
2714
+ * back, with the same drops as {@link toWindowInfos} (untitled windows, the
2715
+ * driver's own, the shell's `Program Manager`, windows a pixel wide or tall).
2716
+ * `focused` is the window the system reports as the foreground one when it
2717
+ * is among those kept, else the front-most one that is not minimized.
2718
+ */
2719
+ export function windowInfosFromHost(raw: readonly A11yWindow[]): WindowInfo[] {
2720
+ const kept: A11yWindow[] = []
2721
+ for (const entry of raw) {
2722
+ const hwnd = parseWindowId(entry.windowId)
2723
+ if (hwnd === undefined || entry.title.trim().length === 0) continue
2724
+ const app = entry.processName.toLowerCase()
2725
+ if (app === 'cua-driver.exe') continue
2726
+ if (app === 'explorer.exe' && entry.title === 'Program Manager') continue
2727
+ if (entry.bounds.width <= 1 || entry.bounds.height <= 1) continue
2728
+ kept.push(entry)
2729
+ }
2730
+ kept.sort((a, b) => a.z - b.z)
2731
+ const front =
2732
+ kept.find((entry) => entry.focused && !entry.minimized) ??
2733
+ kept.find((entry) => !entry.minimized)
2734
+ return kept.map((entry) => ({
2735
+ id: windowIdOf(parseWindowId(entry.windowId) as number),
2736
+ title: entry.title,
2737
+ app: entry.processName.replace(/\.exe$/i, ''),
2738
+ pid: entry.processId,
2739
+ bounds: { ...entry.bounds },
2740
+ minimized: entry.minimized,
2741
+ focused: entry === front,
2742
+ }))
2743
+ }
2744
+
2600
2745
  function structured(result: McpToolResult, tool: string): Record<string, unknown> {
2601
2746
  if (!result.structuredContent)
2602
2747
  throw new Error(`cua-driver: ${tool} returned no structured result.`)
@@ -47,6 +47,14 @@ export interface Adapter {
47
47
  captureId: string,
48
48
  action: WindowInputAction,
49
49
  ): Promise<WindowInputResult | undefined>
50
+ /**
51
+ * Waits for the window the last input went to to stop changing, as the
52
+ * window reports it, within `budgetMs`. Undefined when it cannot say.
53
+ */
54
+ settleAfterInput?(
55
+ request: { readonly windowId?: string; readonly budgetMs: number },
56
+ signal?: AbortSignal,
57
+ ): Promise<{ readonly waitedMs: number; readonly changed: boolean } | undefined>
50
58
  /** With `capabilities.regionCapture`. */
51
59
  captureRegion?(rect: Rect): Promise<ScreenshotResult>
52
60
  /** With `capabilities.uiTree`. */
@@ -1,3 +1,4 @@
1
+ import type { AccessibilityBackend } from '../a11y/interface.js'
1
2
  import { guardForeground } from '../foreground/guard.js'
2
3
  import type { ForegroundLadder } from '../foreground/ladder.js'
3
4
  import type { Presence } from '../presence/presence.js'
@@ -40,6 +41,8 @@ export interface Win32AdapterOptions {
40
41
  readonly foreground?: ForegroundLadder
41
42
  /** The agent cursor and window border shown while a window is operated. Absent, none. */
42
43
  readonly presence?: Presence
44
+ /** The resident accessibility host the driver backend serves its window list from. Absent, the driver does. */
45
+ readonly a11y?: AccessibilityBackend
43
46
  /** For tests. */
44
47
  readonly wslProbes?: WslProbes
45
48
  /** For tests. */
@@ -129,6 +132,7 @@ export class Win32Adapter {
129
132
  ...(resolved.source === 'configured' ? {} : { version: CUA_DRIVER_RELEASE.version }),
130
133
  ...(ladder ? { foreground: ladder } : {}),
131
134
  ...(options.presence ? { presence: options.presence } : {}),
135
+ ...(options.a11y ? { a11y: options.a11y } : {}),
132
136
  }
133
137
  adapter = options.createCuaDriverAdapter
134
138
  ? options.createCuaDriverAdapter(adapterOptions)
@@ -162,6 +162,7 @@ export function guardForeground(adapter: Adapter, ladder: ForegroundLadder): Ada
162
162
  'captureRegion',
163
163
  'uiSnapshot',
164
164
  'uiAct',
165
+ 'settleAfterInput',
165
166
  ] as const) {
166
167
  const method = adapter[name]
167
168
  if (method) (guarded as unknown as Record<string, unknown>)[name] = method.bind(adapter)
package/src/index.ts CHANGED
@@ -39,3 +39,22 @@ export { SpawnError } from './util/spawn.js'
39
39
  export type { SpawnOptions, SpawnResult } from './util/spawn.js'
40
40
  export { PRESENCE_ENV } from './presence/index.js'
41
41
  export type { Presence, PresenceKind, PresenceMark } from './presence/index.js'
42
+ export { A11Y_ENV, A11yError } from './a11y/index.js'
43
+ export type {
44
+ A11yAction,
45
+ A11yChangeKind,
46
+ A11yDisplay,
47
+ A11yFingerprint,
48
+ A11yIdentityRequest,
49
+ A11yNode,
50
+ A11yRect,
51
+ A11yResolution,
52
+ A11yResolveRequest,
53
+ A11ySeq,
54
+ A11ySnapshot,
55
+ A11ySnapshotRequest,
56
+ A11yWaitRequest,
57
+ A11yWaitResult,
58
+ A11yWindow,
59
+ AccessibilityBackend,
60
+ } from './a11y/index.js'