@namzu/computer-use 4.4.0 → 4.6.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 (139) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +8 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +15 -4
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +15 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +12 -5
  9. package/dist/a11y/a11y.js.map +1 -1
  10. package/dist/a11y/index.d.ts +7 -1
  11. package/dist/a11y/index.d.ts.map +1 -1
  12. package/dist/a11y/index.js +4 -1
  13. package/dist/a11y/index.js.map +1 -1
  14. package/dist/a11y/macos-helper.d.ts +80 -0
  15. package/dist/a11y/macos-helper.d.ts.map +1 -0
  16. package/dist/a11y/macos-helper.js +436 -0
  17. package/dist/a11y/macos-helper.js.map +1 -0
  18. package/dist/a11y/macos-signing.d.ts +56 -0
  19. package/dist/a11y/macos-signing.d.ts.map +1 -0
  20. package/dist/a11y/macos-signing.js +228 -0
  21. package/dist/a11y/macos-signing.js.map +1 -0
  22. package/dist/a11y/macos.d.ts +173 -0
  23. package/dist/a11y/macos.d.ts.map +1 -0
  24. package/dist/a11y/macos.js +271 -0
  25. package/dist/a11y/macos.js.map +1 -0
  26. package/dist/a11y/windows.d.ts +14 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +31 -6
  29. package/dist/a11y/windows.js.map +1 -1
  30. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/adapter.js +48 -10
  32. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  33. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  34. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  36. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  37. package/dist/adapters/darwin-ax.d.ts +94 -0
  38. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  39. package/dist/adapters/darwin-ax.js +754 -0
  40. package/dist/adapters/darwin-ax.js.map +1 -0
  41. package/dist/adapters/darwin.d.ts +43 -2
  42. package/dist/adapters/darwin.d.ts.map +1 -1
  43. package/dist/adapters/darwin.js +145 -7
  44. package/dist/adapters/darwin.js.map +1 -1
  45. package/dist/adapters/png.d.ts +6 -0
  46. package/dist/adapters/png.d.ts.map +1 -0
  47. package/dist/adapters/png.js +7 -0
  48. package/dist/adapters/png.js.map +1 -0
  49. package/dist/adapters/win32-native.d.ts +53 -0
  50. package/dist/adapters/win32-native.d.ts.map +1 -0
  51. package/dist/adapters/win32-native.js +279 -0
  52. package/dist/adapters/win32-native.js.map +1 -0
  53. package/dist/adapters/win32.d.ts +19 -1
  54. package/dist/adapters/win32.d.ts.map +1 -1
  55. package/dist/adapters/win32.js +35 -8
  56. package/dist/adapters/win32.js.map +1 -1
  57. package/dist/foreground/ladder.d.ts.map +1 -1
  58. package/dist/foreground/ladder.js +5 -1
  59. package/dist/foreground/ladder.js.map +1 -1
  60. package/dist/foreground/types.d.ts +6 -0
  61. package/dist/foreground/types.d.ts.map +1 -1
  62. package/dist/foreground/types.js.map +1 -1
  63. package/dist/foreground/windows.d.ts +2 -0
  64. package/dist/foreground/windows.d.ts.map +1 -1
  65. package/dist/foreground/windows.js +24 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/index.d.ts +9 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +7 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/native/a11y.d.ts +61 -0
  72. package/dist/native/a11y.d.ts.map +1 -0
  73. package/dist/native/a11y.js +197 -0
  74. package/dist/native/a11y.js.map +1 -0
  75. package/dist/native/env.d.ts +19 -0
  76. package/dist/native/env.d.ts.map +1 -0
  77. package/dist/native/env.js +29 -0
  78. package/dist/native/env.js.map +1 -0
  79. package/dist/native/foreground-monitor.d.ts +51 -0
  80. package/dist/native/foreground-monitor.d.ts.map +1 -0
  81. package/dist/native/foreground-monitor.js +120 -0
  82. package/dist/native/foreground-monitor.js.map +1 -0
  83. package/dist/native/presence.d.ts +24 -0
  84. package/dist/native/presence.d.ts.map +1 -0
  85. package/dist/native/presence.js +47 -0
  86. package/dist/native/presence.js.map +1 -0
  87. package/dist/native/process.d.ts +73 -0
  88. package/dist/native/process.d.ts.map +1 -0
  89. package/dist/native/process.js +302 -0
  90. package/dist/native/process.js.map +1 -0
  91. package/dist/native/protocol.d.ts +476 -0
  92. package/dist/native/protocol.d.ts.map +1 -0
  93. package/dist/native/protocol.js +601 -0
  94. package/dist/native/protocol.js.map +1 -0
  95. package/dist/native/shared.d.ts +16 -0
  96. package/dist/native/shared.d.ts.map +1 -0
  97. package/dist/native/shared.js +62 -0
  98. package/dist/native/shared.js.map +1 -0
  99. package/dist/native/watch.d.ts +35 -0
  100. package/dist/native/watch.d.ts.map +1 -0
  101. package/dist/native/watch.js +45 -0
  102. package/dist/native/watch.js.map +1 -0
  103. package/dist/presence/presence.d.ts +3 -2
  104. package/dist/presence/presence.d.ts.map +1 -1
  105. package/dist/presence/presence.js.map +1 -1
  106. package/dist/presence/windows.d.ts +2 -0
  107. package/dist/presence/windows.d.ts.map +1 -1
  108. package/dist/presence/windows.js +15 -0
  109. package/dist/presence/windows.js.map +1 -1
  110. package/helper-macos/main.swift +1756 -0
  111. package/package.json +3 -2
  112. package/src/SubprocessComputerUseHost.ts +26 -2
  113. package/src/a11y/a11y.ts +25 -11
  114. package/src/a11y/index.ts +28 -1
  115. package/src/a11y/macos-helper.ts +538 -0
  116. package/src/a11y/macos-signing.ts +280 -0
  117. package/src/a11y/macos.ts +496 -0
  118. package/src/a11y/windows.ts +31 -4
  119. package/src/adapters/cua-driver/adapter.ts +55 -15
  120. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  121. package/src/adapters/darwin-ax.ts +920 -0
  122. package/src/adapters/darwin.ts +184 -4
  123. package/src/adapters/png.ts +5 -0
  124. package/src/adapters/win32-native.ts +329 -0
  125. package/src/adapters/win32.ts +53 -5
  126. package/src/foreground/ladder.ts +5 -1
  127. package/src/foreground/types.ts +6 -0
  128. package/src/foreground/windows.ts +25 -11
  129. package/src/index.ts +14 -0
  130. package/src/native/a11y.ts +267 -0
  131. package/src/native/env.ts +33 -0
  132. package/src/native/foreground-monitor.ts +165 -0
  133. package/src/native/presence.ts +58 -0
  134. package/src/native/process.ts +347 -0
  135. package/src/native/protocol.ts +1103 -0
  136. package/src/native/shared.ts +75 -0
  137. package/src/native/watch.ts +78 -0
  138. package/src/presence/presence.ts +3 -2
  139. package/src/presence/windows.ts +15 -0
@@ -0,0 +1,496 @@
1
+ import { mkdirSync } from 'node:fs'
2
+ import { readFile, unlink } from 'node:fs/promises'
3
+ import { sep } from 'node:path'
4
+ import { WindowsA11yHost, toNode } from './a11y.js'
5
+ import type { A11yProcess, WindowsA11yOptions } from './a11y.js'
6
+ import {
7
+ A11yError,
8
+ type A11yFingerprint,
9
+ type A11yNode,
10
+ type A11yRect,
11
+ type A11ySnapshotRequest,
12
+ } from './interface.js'
13
+ import {
14
+ type EnsureMacHelperOptions,
15
+ type MacHelperPaths,
16
+ connectMacHelper,
17
+ ensureMacHelper,
18
+ socketProcess,
19
+ } from './macos-helper.js'
20
+ import { a11yDisabledByEnv } from './windows.js'
21
+
22
+ /** What the helper says about the two permissions it needs, and what the person must click. */
23
+ export interface MacPermissions {
24
+ readonly accessibility: boolean
25
+ readonly screenCapture: boolean
26
+ /** The name the person looks for in System Settings. */
27
+ readonly app: string
28
+ readonly bundleId: string
29
+ readonly path: string
30
+ /** One plain sentence per switch that is still off. */
31
+ readonly steps: readonly string[]
32
+ }
33
+
34
+ export interface MacNode extends A11yNode {
35
+ /** Names the control well enough to find it again after the window changed. */
36
+ readonly fingerprint: A11yFingerprint
37
+ }
38
+
39
+ export interface MacTree {
40
+ readonly windowId: string
41
+ readonly revision: number
42
+ readonly nodes: readonly MacNode[]
43
+ readonly total: number
44
+ readonly truncated: boolean
45
+ readonly readMs: number
46
+ readonly app: string
47
+ readonly title: string
48
+ readonly pid: number
49
+ readonly selectedText?: string
50
+ }
51
+
52
+ export interface MacTreeRequest extends Omit<A11ySnapshotRequest, 'windowId'> {
53
+ /** A window id as a number, or as a string in decimal or `0x` form. */
54
+ readonly windowId: string | number
55
+ /** Read only the subtree of this control. */
56
+ readonly root?: A11yFingerprint
57
+ }
58
+
59
+ export type MacControlAction =
60
+ | 'invoke'
61
+ | 'show_menu'
62
+ | 'raise'
63
+ | 'increment'
64
+ | 'decrement'
65
+ | 'scroll_into_view'
66
+ | 'focus'
67
+ | 'set_value'
68
+ | 'toggle'
69
+ | 'select'
70
+ | 'expand'
71
+ | 'collapse'
72
+
73
+ export interface MacActResult {
74
+ /** False when the control refused or the call could not be made. */
75
+ readonly done: boolean
76
+ readonly detail?: string
77
+ readonly via?: string
78
+ readonly before?: string
79
+ readonly after?: string
80
+ readonly expected?: string
81
+ /** True when the state read back is the one asked for; absent when nothing was asked. */
82
+ readonly verified?: boolean
83
+ }
84
+
85
+ export interface MacCapture {
86
+ readonly data: Buffer
87
+ readonly width: number
88
+ readonly height: number
89
+ readonly via: string
90
+ }
91
+
92
+ export interface MacSelfCheck {
93
+ readonly checks: readonly {
94
+ readonly name: string
95
+ readonly ok: boolean
96
+ readonly detail: string
97
+ }[]
98
+ readonly pid: number
99
+ readonly build: string
100
+ readonly path: string
101
+ readonly os: string
102
+ }
103
+
104
+ const num = (value: unknown, fallback = 0): number =>
105
+ typeof value === 'number' && Number.isFinite(value) ? value : fallback
106
+ const str = (value: unknown): string => (typeof value === 'string' ? value : '')
107
+
108
+ /** A window id as the helper knows it (a CGWindowID); accepts a number, or a string in decimal or `0x` form. */
109
+ export function cgWindowId(windowId: string | number): number {
110
+ if (typeof windowId === 'number') {
111
+ if (!Number.isSafeInteger(windowId) || windowId <= 0)
112
+ throw new A11yError('bad_window_id', 'not a window id this backend handed out')
113
+ return windowId
114
+ }
115
+ if (typeof windowId !== 'string')
116
+ throw new A11yError('bad_window_id', 'not a window id this backend handed out')
117
+ const text = windowId.trim().toLowerCase()
118
+ const value = /^0x[0-9a-f]+$/.test(text)
119
+ ? Number.parseInt(text.slice(2), 16)
120
+ : /^\d+$/.test(text)
121
+ ? Number.parseInt(text, 10)
122
+ : Number.NaN
123
+ if (!Number.isSafeInteger(value) || value <= 0)
124
+ throw new A11yError('bad_window_id', 'not a window id this backend handed out')
125
+ return value
126
+ }
127
+
128
+ function fingerprintOf(value: unknown): A11yFingerprint {
129
+ const f = (value ?? {}) as Record<string, unknown>
130
+ return {
131
+ runtimeId: str(f.runtimeId),
132
+ automationId: str(f.automationId),
133
+ role: str(f.role),
134
+ nameHash: str(f.nameHash),
135
+ parentPath: str(f.parentPath),
136
+ ordinal: num(f.ordinal),
137
+ processStart: num(f.processStart),
138
+ }
139
+ }
140
+
141
+ export interface MacA11yOptions extends WindowsA11yOptions {
142
+ /** Where window captures are written; the same directory the helper is told. */
143
+ readonly captureDir?: string
144
+ }
145
+
146
+ /**
147
+ * {@link WindowsA11yHost}'s client protocol spoken to the macOS helper, with
148
+ * the questions only macOS has: the permissions, a tree whose controls carry
149
+ * their fingerprint, acting on a control by AX action, window capture and
150
+ * input posted to one process.
151
+ */
152
+ export class MacA11yHost extends WindowsA11yHost {
153
+ constructor(options: MacA11yOptions) {
154
+ super({ ...options, id: options.id ?? 'macos-ax', greeting: false })
155
+ this.captureDir = options.captureDir
156
+ }
157
+
158
+ private captureDir: string | undefined
159
+
160
+ /** Where the helper writes window captures; created owner-only. */
161
+ useCaptureDir(dir: string): void {
162
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
163
+ this.captureDir = dir
164
+ }
165
+
166
+ async permissions(
167
+ options: { readonly prompt?: boolean } = {},
168
+ signal?: AbortSignal,
169
+ ): Promise<MacPermissions> {
170
+ const reply = await this.request(
171
+ 'permissions',
172
+ options.prompt ? { prompt: true } : {},
173
+ options.prompt ? 20_000 : 5_000,
174
+ signal,
175
+ )
176
+ return {
177
+ accessibility: reply.accessibility === true,
178
+ screenCapture: reply.screenCapture === true,
179
+ app: str(reply.app) || 'Namzu Helper',
180
+ bundleId: str(reply.bundleId),
181
+ path: str(reply.path),
182
+ steps: Array.isArray(reply.steps) ? reply.steps.filter((s) => typeof s === 'string') : [],
183
+ }
184
+ }
185
+
186
+ async readTree(request: MacTreeRequest, signal?: AbortSignal): Promise<MacTree> {
187
+ const timeoutMs = request.timeoutMs ?? 8_000
188
+ const reply = await this.request(
189
+ 'snapshot',
190
+ {
191
+ hwnd: cgWindowId(request.windowId),
192
+ timeoutMs,
193
+ ...(request.maxNodes !== undefined ? { maxNodes: request.maxNodes } : {}),
194
+ ...(request.maxDepth !== undefined ? { maxDepth: request.maxDepth } : {}),
195
+ ...(request.skeleton ? { skeleton: true } : {}),
196
+ ...(request.allowChromium ? { allowChromium: true } : {}),
197
+ ...(request.root ? { root: request.root } : {}),
198
+ },
199
+ timeoutMs,
200
+ signal,
201
+ )
202
+ const raw = (Array.isArray(reply.nodes) ? reply.nodes : []) as Record<string, unknown>[]
203
+ return {
204
+ windowId: String(cgWindowId(request.windowId)),
205
+ revision: num(reply.rev),
206
+ nodes: raw.map((n) => ({
207
+ ...toNode(n),
208
+ fingerprint: fingerprintOf(n.fp),
209
+ })),
210
+ total: num(reply.total),
211
+ truncated: reply.truncated === true,
212
+ readMs: num(reply.readMs),
213
+ app: str(reply.app),
214
+ title: str(reply.title),
215
+ pid: num(reply.pid),
216
+ ...(typeof reply.selectedText === 'string' ? { selectedText: reply.selectedText } : {}),
217
+ }
218
+ }
219
+
220
+ async act(
221
+ request: {
222
+ readonly windowId: string | number
223
+ readonly fingerprint: A11yFingerprint
224
+ readonly action: MacControlAction
225
+ readonly value?: string
226
+ },
227
+ signal?: AbortSignal,
228
+ ): Promise<MacActResult> {
229
+ const reply = await this.request(
230
+ 'act',
231
+ {
232
+ hwnd: cgWindowId(request.windowId),
233
+ fingerprint: request.fingerprint,
234
+ action: request.action,
235
+ ...(request.value !== undefined ? { value: request.value } : {}),
236
+ },
237
+ 10_000,
238
+ signal,
239
+ )
240
+ return {
241
+ done: reply.done === true,
242
+ ...(typeof reply.detail === 'string' ? { detail: reply.detail } : {}),
243
+ ...(typeof reply.via === 'string' ? { via: reply.via } : {}),
244
+ ...(typeof reply.before === 'string' ? { before: reply.before } : {}),
245
+ ...(typeof reply.after === 'string' ? { after: reply.after } : {}),
246
+ ...(typeof reply.expected === 'string' ? { expected: reply.expected } : {}),
247
+ ...(typeof reply.verified === 'boolean' ? { verified: reply.verified } : {}),
248
+ }
249
+ }
250
+
251
+ /** Brings a window forward; the window that is in front afterwards, as an id, or null. */
252
+ async focus(
253
+ windowId: string | number,
254
+ signal?: AbortSignal,
255
+ ): Promise<{ ok: boolean; focusedId: string | null }> {
256
+ const reply = await this.request('focus', { hwnd: cgWindowId(windowId) }, 8_000, signal)
257
+ return {
258
+ ok: reply.ok === true,
259
+ focusedId: typeof reply.focusedId === 'number' ? String(reply.focusedId) : null,
260
+ }
261
+ }
262
+
263
+ /** Wheel scroll in lines, posted to the window's process; `at` is a global point in physical pixels. */
264
+ async scroll(
265
+ request: {
266
+ readonly windowId?: string | number
267
+ readonly direction: 'up' | 'down' | 'left' | 'right'
268
+ readonly amount: number
269
+ /** Global screen points (not pixels). */
270
+ readonly at?: { readonly x: number; readonly y: number }
271
+ },
272
+ signal?: AbortSignal,
273
+ ): Promise<void> {
274
+ await this.request(
275
+ 'scroll',
276
+ {
277
+ ...(request.windowId ? { hwnd: cgWindowId(request.windowId) } : {}),
278
+ direction: request.direction,
279
+ amount: request.amount,
280
+ ...(request.at ? { x: request.at.x, y: request.at.y } : {}),
281
+ },
282
+ 5_000,
283
+ signal,
284
+ )
285
+ }
286
+
287
+ /** Clicks, double-clicks or drags at global screen points, posted to the window's process. */
288
+ async click(
289
+ request: {
290
+ readonly windowId?: string | number
291
+ readonly x: number
292
+ readonly y: number
293
+ readonly button?: 'left' | 'right'
294
+ readonly count?: number
295
+ readonly to?: { readonly x: number; readonly y: number }
296
+ },
297
+ signal?: AbortSignal,
298
+ ): Promise<void> {
299
+ await this.request(
300
+ 'click',
301
+ {
302
+ ...(request.windowId ? { hwnd: cgWindowId(request.windowId) } : {}),
303
+ x: request.x,
304
+ y: request.y,
305
+ ...(request.button ? { button: request.button } : {}),
306
+ ...(request.count ? { count: request.count } : {}),
307
+ ...(request.to ? { to: request.to } : {}),
308
+ },
309
+ 8_000,
310
+ signal,
311
+ )
312
+ }
313
+
314
+ async typeText(
315
+ request: { readonly windowId?: string | number; readonly text: string },
316
+ signal?: AbortSignal,
317
+ ): Promise<void> {
318
+ await this.request(
319
+ 'type',
320
+ {
321
+ ...(request.windowId ? { hwnd: cgWindowId(request.windowId) } : {}),
322
+ text: request.text,
323
+ },
324
+ 10_000 + request.text.length * 4,
325
+ signal,
326
+ )
327
+ }
328
+
329
+ async pressKey(
330
+ request: {
331
+ readonly windowId?: string | number
332
+ readonly code: number
333
+ readonly flags: readonly string[]
334
+ },
335
+ signal?: AbortSignal,
336
+ ): Promise<void> {
337
+ await this.request(
338
+ 'key',
339
+ {
340
+ ...(request.windowId ? { hwnd: cgWindowId(request.windowId) } : {}),
341
+ code: request.code,
342
+ flags: request.flags,
343
+ },
344
+ 5_000,
345
+ signal,
346
+ )
347
+ }
348
+
349
+ /** One window as a PNG, whatever is in front of it. Needs Screen Recording. */
350
+ async captureWindow(windowId: string | number, signal?: AbortSignal): Promise<MacCapture> {
351
+ if (!this.captureDir)
352
+ throw new A11yError('unavailable', 'the accessibility host has no capture folder')
353
+ const reply = await this.request(
354
+ 'capture_window',
355
+ { hwnd: cgWindowId(windowId), dir: this.captureDir },
356
+ 15_000,
357
+ signal,
358
+ )
359
+ const path = str(reply.path)
360
+ if (!path.startsWith(this.captureDir.endsWith(sep) ? this.captureDir : this.captureDir + sep))
361
+ throw new A11yError('bad_reply', 'the helper named a capture outside its folder')
362
+ try {
363
+ return {
364
+ data: await readFile(path),
365
+ width: num(reply.width),
366
+ height: num(reply.height),
367
+ via: str(reply.via),
368
+ }
369
+ } finally {
370
+ await unlink(path).catch(() => undefined)
371
+ }
372
+ }
373
+
374
+ async selfCheck(signal?: AbortSignal): Promise<MacSelfCheck> {
375
+ const reply = await this.request('selfcheck', {}, 8_000, signal)
376
+ const checks = (Array.isArray(reply.checks) ? reply.checks : []) as Record<string, unknown>[]
377
+ return {
378
+ checks: checks.map((c) => ({
379
+ name: str(c.name),
380
+ ok: c.ok === true,
381
+ detail: str(c.detail),
382
+ })),
383
+ pid: num(reply.pid),
384
+ build: str(reply.build),
385
+ path: str(reply.path),
386
+ os: str(reply.os),
387
+ }
388
+ }
389
+
390
+ /**
391
+ * The helper reads, acts on and watches a small window of its own and reports each step. Needs no
392
+ * permission (an app may read itself), so it tells a broken helper from a missing grant.
393
+ */
394
+ async selfTest(signal?: AbortSignal): Promise<MacSelfCheck['checks']> {
395
+ const reply = await this.request('selftest', {}, 25_000, signal)
396
+ const checks = (Array.isArray(reply.checks) ? reply.checks : []) as Record<string, unknown>[]
397
+ return checks.map((c) => ({
398
+ name: str(c.name),
399
+ ok: c.ok === true,
400
+ detail: str(c.detail),
401
+ }))
402
+ }
403
+
404
+ /** The rectangle as the helper reports it, for callers that read raw replies. */
405
+ static rect(value: unknown): A11yRect {
406
+ const r = Array.isArray(value) ? value : []
407
+ return { x: num(r[0]), y: num(r[1]), width: num(r[2]), height: num(r[3]) }
408
+ }
409
+ }
410
+
411
+ export interface MacA11yFactoryOptions {
412
+ readonly env?: NodeJS.ProcessEnv
413
+ readonly platform?: NodeJS.Platform
414
+ /** Default true. `false` starts nothing, whatever the environment says. */
415
+ readonly enabled?: boolean
416
+ readonly onNotice?: (notice: string) => void
417
+ /** For tests: a helper that is not the real one. */
418
+ readonly spawnHelper?: () => A11yProcess
419
+ /** For tests. */
420
+ readonly ensure?: (options: EnsureMacHelperOptions) => Promise<MacHelperPaths>
421
+ }
422
+
423
+ /** The macOS accessibility host plus the step that builds its helper. */
424
+ export interface MacA11yHandle {
425
+ readonly host: MacA11yHost
426
+ /**
427
+ * Builds the helper when it is not built yet and starts it. Resolves with
428
+ * why it cannot (no compiler, no desktop session) instead of throwing.
429
+ */
430
+ prepare(): Promise<{ readonly ok: true } | { readonly ok: false; readonly reason: string }>
431
+ }
432
+
433
+ /**
434
+ * The accessibility host for this Mac, or undefined when it is turned off
435
+ * (`NAMZU_COMPUTER_USE_A11Y=off`) or this is not macOS. Nothing is built or
436
+ * started until `prepare()`.
437
+ */
438
+ export function createMacA11yHost(options: MacA11yFactoryOptions = {}): MacA11yHandle | undefined {
439
+ const env = options.env ?? process.env
440
+ const platform = options.platform ?? process.platform
441
+ if (options.enabled === false || a11yDisabledByEnv(env)) return undefined
442
+ if (platform !== 'darwin' && !options.spawnHelper) return undefined
443
+ let paths: MacHelperPaths | undefined
444
+ let building: Promise<MacHelperPaths> | undefined
445
+ const ensure = (): Promise<MacHelperPaths> => {
446
+ building ??= (options.ensure ?? ensureMacHelper)({
447
+ env,
448
+ ...(options.onNotice ? { onNotice: options.onNotice } : {}),
449
+ }).then(
450
+ (p) => {
451
+ paths = p
452
+ return p
453
+ },
454
+ (error: unknown) => {
455
+ building = undefined
456
+ throw error
457
+ },
458
+ )
459
+ return building
460
+ }
461
+ const host = new MacA11yHost({
462
+ // A real helper may need a first compile before it can start; the compile has its own wait.
463
+ startTimeoutMs: 60_000,
464
+ spawnHelper:
465
+ options.spawnHelper ??
466
+ (() =>
467
+ socketProcess(async () => {
468
+ const p = paths ?? (await ensure())
469
+ return connectMacHelper({ paths: p, env })
470
+ })),
471
+ })
472
+ return {
473
+ host,
474
+ async prepare() {
475
+ if (options.spawnHelper)
476
+ return (await host.ready())
477
+ ? { ok: true }
478
+ : { ok: false, reason: 'the helper did not answer' }
479
+ try {
480
+ const p = await ensure()
481
+ host.useCaptureDir(p.captures)
482
+ if (await host.ready()) return { ok: true }
483
+ return {
484
+ ok: false,
485
+ reason:
486
+ 'the macOS helper did not start; it must be launched from a logged-in desktop session',
487
+ }
488
+ } catch (error) {
489
+ return {
490
+ ok: false,
491
+ reason: error instanceof Error ? error.message : String(error),
492
+ }
493
+ }
494
+ },
495
+ }
496
+ }
@@ -5,6 +5,8 @@ import {
5
5
  wslChildEnv,
6
6
  wslPowerShellPath,
7
7
  } from '../adapters/wsl.js'
8
+ import { NativeA11yBackend } from '../native/a11y.js'
9
+ import { LEGACY_NATIVE_HELPER_ENV, nativeHelperFromEnv } from '../native/env.js'
8
10
  import { WindowsA11yHost } from './a11y.js'
9
11
  import type { AccessibilityBackend } from './interface.js'
10
12
 
@@ -22,6 +24,20 @@ export interface WindowsA11yFactoryOptions {
22
24
  readonly enabled?: boolean
23
25
  }
24
26
 
27
+ /**
28
+ * The path of the native helper (`namzu-native.exe`). While the helper is not
29
+ * delivered with the product, naming it here is how it is chosen over the
30
+ * PowerShell host; unset, nothing changes.
31
+ */
32
+ /** @deprecated Prefer the variable `NAMZU_NATIVE_HELPER`. Still holds the old name, `NAMZU_WIN_HELPER`, until the next major release, so code that reads `env[WIN_HELPER_ENV]` keeps working. */
33
+ export const WIN_HELPER_ENV = LEGACY_NATIVE_HELPER_ENV
34
+
35
+ function withoutSecrets(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
36
+ const clean: NodeJS.ProcessEnv = {}
37
+ for (const [name, value] of Object.entries(env)) if (!SECRET_NAME.test(name)) clean[name] = value
38
+ return clean
39
+ }
40
+
25
41
  /** Whether the environment asks for the accessibility host to be off. */
26
42
  export function a11yDisabledByEnv(env: NodeJS.ProcessEnv): boolean {
27
43
  const value = env[A11Y_ENV]
@@ -30,8 +46,13 @@ export function a11yDisabledByEnv(env: NodeJS.ProcessEnv): boolean {
30
46
 
31
47
  /**
32
48
  * 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.
49
+ * or undefined when it is turned off or there is neither a native helper nor
50
+ * a Windows PowerShell to run it in. Nothing is started until it is first
51
+ * used or warmed.
52
+ *
53
+ * With `NAMZU_NATIVE_HELPER` naming an executable, the host is the native helper
54
+ * and no PowerShell is involved. The variable is the only way to choose it
55
+ * for now.
35
56
  */
36
57
  export function createWindowsA11yHost(
37
58
  options: WindowsA11yFactoryOptions = {},
@@ -41,14 +62,20 @@ export function createWindowsA11yHost(
41
62
  const platform = options.platform ?? process.platform
42
63
  const probes = options.wslProbes ?? realWslProbes
43
64
  const wsl = isWsl(env, platform, probes)
65
+ const clean = withoutSecrets(env)
66
+ const helper = nativeHelperFromEnv(env)
67
+ if (helper && (wsl || platform === 'win32')) {
68
+ return new NativeA11yBackend({
69
+ executable: helper,
70
+ env: wsl ? wslChildEnv(clean, [], probes) : clean,
71
+ })
72
+ }
44
73
  const powershell = wsl
45
74
  ? wslPowerShellPath(probes)
46
75
  : platform === 'win32'
47
76
  ? 'powershell.exe'
48
77
  : undefined
49
78
  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
79
  return new WindowsA11yHost({
53
80
  powershell,
54
81
  env: wsl ? wslChildEnv(clean, [], probes) : clean,
@@ -142,11 +142,11 @@ const UI_MAX_ELEMENTS = 5_000
142
142
  */
143
143
  const UI_WALK_CUT_AT = Math.floor(UI_MAX_ELEMENTS * 0.95)
144
144
  /** A window with more shown controls than this is returned as an outline. */
145
- const OUTLINE_THRESHOLD = 220
145
+ const OUTLINE_THRESHOLD = 400
146
146
  /** The most controls an outline shows; the rest are counted, not listed. */
147
- const OUTLINE_BUDGET = 150
147
+ const OUTLINE_BUDGET = 300
148
148
  /** The most children of one element an outline lists; a long list is opened as a region. */
149
- const OUTLINE_PER_PARENT = 12
149
+ const OUTLINE_PER_PARENT = 20
150
150
  /** The children of a region opened by itself that one page lists. */
151
151
  const OUTLINE_PAGE = 60
152
152
  /** A browser tree this small is the window frame alone: the page has not been built yet. */
@@ -379,6 +379,32 @@ function outlineOf(
379
379
  return { root: build(root, basePath), regions, next }
380
380
  }
381
381
 
382
+ /**
383
+ * The controls whose role is one of `roles`, with every element above them.
384
+ * Kept children carry their index in the full tree, as an outline's do, so
385
+ * refs bind to the right places.
386
+ */
387
+ function pruneByRole(root: UiElement, roles: ReadonlySet<string>): UiElement {
388
+ const walk = (element: UiElement): UiElement | undefined => {
389
+ const kept: UiElement[] = []
390
+ ;(element.children ?? []).forEach((child, index) => {
391
+ const built = walk(child)
392
+ if (!built) return
393
+ ORIGINAL_INDEX.set(built, index)
394
+ kept.push(built)
395
+ })
396
+ const matches = roles.has(element.role.toLowerCase())
397
+ if (!matches && kept.length === 0) return undefined
398
+ const { children: _children, ...rest } = element
399
+ return Object.freeze({
400
+ ...rest,
401
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
402
+ }) as UiElement
403
+ }
404
+ const { children: _children, ...bare } = root
405
+ return walk(root) ?? (Object.freeze(bare) as UiElement)
406
+ }
407
+
382
408
  /** The paths of the elements a view contains. */
383
409
  function collectShown(element: UiElement, path: readonly number[], into: Set<string>): void {
384
410
  into.add(pathKey(path))
@@ -1426,15 +1452,27 @@ export class CuaDriverAdapter implements Adapter {
1426
1452
  }
1427
1453
  const viewRoot = located?.element ?? tree.root
1428
1454
  const basePath = located?.path ?? []
1455
+ const roles = new Set(
1456
+ (options.role ?? '')
1457
+ .split(',')
1458
+ .map((role) => role.trim().toLowerCase())
1459
+ .filter((role) => role.length > 0),
1460
+ )
1429
1461
  const view =
1430
- !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
1431
- ? outlineOf(
1432
- viewRoot,
1433
- basePath,
1434
- OUTLINE_BUDGET,
1435
- located ? { offset: options.offset ?? 0 } : undefined,
1436
- )
1437
- : { root: viewRoot, regions: new Set<string>(), next: undefined }
1462
+ roles.size > 0
1463
+ ? {
1464
+ root: pruneByRole(viewRoot, roles),
1465
+ regions: new Set<string>(),
1466
+ next: undefined,
1467
+ }
1468
+ : !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
1469
+ ? outlineOf(
1470
+ viewRoot,
1471
+ basePath,
1472
+ OUTLINE_BUDGET,
1473
+ located ? { offset: options.offset ?? 0 } : undefined,
1474
+ )
1475
+ : { root: viewRoot, regions: new Set<string>(), next: undefined }
1438
1476
  const shownKeys = new Set<string>()
1439
1477
  collectShown(view.root, basePath, shownKeys)
1440
1478
  const refs = this.bindRead(target, read, {
@@ -1448,8 +1486,13 @@ export class CuaDriverAdapter implements Adapter {
1448
1486
  const title = typeof state.window_title === 'string' ? state.window_title : undefined
1449
1487
  const app =
1450
1488
  typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
1489
+ const selectedText =
1490
+ typeof state.selected_text === 'string' && state.selected_text.trim().length > 0
1491
+ ? state.selected_text.slice(0, 2_000)
1492
+ : undefined
1451
1493
  return {
1452
1494
  windowId: windowIdOf(target.hwnd),
1495
+ ...(selectedText !== undefined ? { selectedText } : {}),
1453
1496
  ...(title !== undefined ? { title } : {}),
1454
1497
  ...(app !== undefined ? { app } : {}),
1455
1498
  root,
@@ -2027,10 +2070,7 @@ export class CuaDriverAdapter implements Adapter {
2027
2070
  const windows = await this.windowIdsOf(target.pid)
2028
2071
  // Each read of the window replaces the driver's handles: click through the refreshed one.
2029
2072
  const current = this.uiRefs.get(uiRef.ref) ?? facts
2030
- const sent = await this.clickRef(current, {
2031
- ref: uiRef.ref,
2032
- facts: current,
2033
- })
2073
+ const sent = await this.clickRef(current, { ref: uiRef.ref, facts: current })
2034
2074
  if (!sent.ok || sent.delivery !== 'delivered_unverified' || !before) return sent
2035
2075
  const seen = await this.verifyByReading(target, {
2036
2076
  typed: undefined,
@@ -26,6 +26,7 @@ export interface CuaUiElement {
26
26
  readonly value?: unknown
27
27
  readonly enabled?: unknown
28
28
  readonly selected?: unknown
29
+ readonly focused?: unknown
29
30
  readonly actions?: unknown
30
31
  readonly frame?: unknown
31
32
  readonly parent_index?: unknown
@@ -152,6 +153,7 @@ function fromRecord(record: CuaUiElement, automationId: string | undefined): Mut
152
153
  const states: string[] = []
153
154
  if (record.enabled === false) states.push('disabled')
154
155
  if (record.selected === true) states.push('selected')
156
+ if (record.focused === true) states.push('focused')
155
157
  const value = text(record.value)
156
158
  const bounds = boundsOf(record.frame)
157
159
  return {