@namzu/computer-use 4.3.1 → 4.5.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 (143) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +21 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +67 -15
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +16 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +23 -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/interface.d.ts +5 -0
  15. package/dist/a11y/interface.d.ts.map +1 -1
  16. package/dist/a11y/interface.js.map +1 -1
  17. package/dist/a11y/macos-helper.d.ts +80 -0
  18. package/dist/a11y/macos-helper.d.ts.map +1 -0
  19. package/dist/a11y/macos-helper.js +436 -0
  20. package/dist/a11y/macos-helper.js.map +1 -0
  21. package/dist/a11y/macos-signing.d.ts +56 -0
  22. package/dist/a11y/macos-signing.d.ts.map +1 -0
  23. package/dist/a11y/macos-signing.js +228 -0
  24. package/dist/a11y/macos-signing.js.map +1 -0
  25. package/dist/a11y/macos.d.ts +173 -0
  26. package/dist/a11y/macos.d.ts.map +1 -0
  27. package/dist/a11y/macos.js +271 -0
  28. package/dist/a11y/macos.js.map +1 -0
  29. package/dist/a11y/windows.d.ts +13 -2
  30. package/dist/a11y/windows.d.ts.map +1 -1
  31. package/dist/a11y/windows.js +29 -6
  32. package/dist/a11y/windows.js.map +1 -1
  33. package/dist/adapters/cua-driver/adapter.d.ts +26 -0
  34. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/adapter.js +224 -13
  36. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  37. package/dist/adapters/cua-driver/client.d.ts +5 -0
  38. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  39. package/dist/adapters/cua-driver/client.js +31 -0
  40. package/dist/adapters/cua-driver/client.js.map +1 -1
  41. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  42. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  43. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  44. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  45. package/dist/adapters/darwin-ax.d.ts +94 -0
  46. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  47. package/dist/adapters/darwin-ax.js +754 -0
  48. package/dist/adapters/darwin-ax.js.map +1 -0
  49. package/dist/adapters/darwin.d.ts +43 -2
  50. package/dist/adapters/darwin.d.ts.map +1 -1
  51. package/dist/adapters/darwin.js +145 -7
  52. package/dist/adapters/darwin.js.map +1 -1
  53. package/dist/adapters/png.d.ts +6 -0
  54. package/dist/adapters/png.d.ts.map +1 -0
  55. package/dist/adapters/png.js +7 -0
  56. package/dist/adapters/png.js.map +1 -0
  57. package/dist/adapters/types.d.ts +5 -0
  58. package/dist/adapters/types.d.ts.map +1 -1
  59. package/dist/adapters/types.js.map +1 -1
  60. package/dist/adapters/win32-native.d.ts +53 -0
  61. package/dist/adapters/win32-native.d.ts.map +1 -0
  62. package/dist/adapters/win32-native.js +279 -0
  63. package/dist/adapters/win32-native.js.map +1 -0
  64. package/dist/adapters/win32.d.ts +19 -1
  65. package/dist/adapters/win32.d.ts.map +1 -1
  66. package/dist/adapters/win32.js +34 -8
  67. package/dist/adapters/win32.js.map +1 -1
  68. package/dist/foreground/guard.d.ts.map +1 -1
  69. package/dist/foreground/guard.js +2 -0
  70. package/dist/foreground/guard.js.map +1 -1
  71. package/dist/foreground/ladder.d.ts.map +1 -1
  72. package/dist/foreground/ladder.js +5 -1
  73. package/dist/foreground/ladder.js.map +1 -1
  74. package/dist/foreground/types.d.ts +6 -0
  75. package/dist/foreground/types.d.ts.map +1 -1
  76. package/dist/foreground/types.js.map +1 -1
  77. package/dist/foreground/windows.d.ts +2 -0
  78. package/dist/foreground/windows.d.ts.map +1 -1
  79. package/dist/foreground/windows.js +23 -11
  80. package/dist/foreground/windows.js.map +1 -1
  81. package/dist/native/a11y.d.ts +61 -0
  82. package/dist/native/a11y.d.ts.map +1 -0
  83. package/dist/native/a11y.js +197 -0
  84. package/dist/native/a11y.js.map +1 -0
  85. package/dist/native/foreground-monitor.d.ts +51 -0
  86. package/dist/native/foreground-monitor.d.ts.map +1 -0
  87. package/dist/native/foreground-monitor.js +120 -0
  88. package/dist/native/foreground-monitor.js.map +1 -0
  89. package/dist/native/presence.d.ts +24 -0
  90. package/dist/native/presence.d.ts.map +1 -0
  91. package/dist/native/presence.js +47 -0
  92. package/dist/native/presence.js.map +1 -0
  93. package/dist/native/process.d.ts +73 -0
  94. package/dist/native/process.d.ts.map +1 -0
  95. package/dist/native/process.js +292 -0
  96. package/dist/native/process.js.map +1 -0
  97. package/dist/native/protocol.d.ts +408 -0
  98. package/dist/native/protocol.d.ts.map +1 -0
  99. package/dist/native/protocol.js +527 -0
  100. package/dist/native/protocol.js.map +1 -0
  101. package/dist/native/shared.d.ts +16 -0
  102. package/dist/native/shared.d.ts.map +1 -0
  103. package/dist/native/shared.js +62 -0
  104. package/dist/native/shared.js.map +1 -0
  105. package/dist/presence/presence.d.ts +11 -2
  106. package/dist/presence/presence.d.ts.map +1 -1
  107. package/dist/presence/presence.js +15 -0
  108. package/dist/presence/presence.js.map +1 -1
  109. package/dist/presence/windows.d.ts +2 -0
  110. package/dist/presence/windows.d.ts.map +1 -1
  111. package/dist/presence/windows.js +14 -0
  112. package/dist/presence/windows.js.map +1 -1
  113. package/helper-macos/main.swift +1756 -0
  114. package/package.json +3 -2
  115. package/src/SubprocessComputerUseHost.ts +80 -10
  116. package/src/a11y/a11y.ts +36 -11
  117. package/src/a11y/index.ts +28 -1
  118. package/src/a11y/interface.ts +5 -0
  119. package/src/a11y/macos-helper.ts +538 -0
  120. package/src/a11y/macos-signing.ts +280 -0
  121. package/src/a11y/macos.ts +496 -0
  122. package/src/a11y/windows.ts +29 -4
  123. package/src/adapters/cua-driver/adapter.ts +245 -17
  124. package/src/adapters/cua-driver/client.ts +27 -0
  125. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  126. package/src/adapters/darwin-ax.ts +920 -0
  127. package/src/adapters/darwin.ts +184 -4
  128. package/src/adapters/png.ts +5 -0
  129. package/src/adapters/types.ts +5 -0
  130. package/src/adapters/win32-native.ts +328 -0
  131. package/src/adapters/win32.ts +52 -5
  132. package/src/foreground/guard.ts +1 -0
  133. package/src/foreground/ladder.ts +5 -1
  134. package/src/foreground/types.ts +6 -0
  135. package/src/foreground/windows.ts +24 -11
  136. package/src/native/a11y.ts +267 -0
  137. package/src/native/foreground-monitor.ts +165 -0
  138. package/src/native/presence.ts +58 -0
  139. package/src/native/process.ts +335 -0
  140. package/src/native/protocol.ts +963 -0
  141. package/src/native/shared.ts +75 -0
  142. package/src/presence/presence.ts +23 -2
  143. package/src/presence/windows.ts +14 -0
@@ -0,0 +1,920 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { homedir } from 'node:os'
3
+ import { basename } from 'node:path'
4
+ import type {
5
+ ActionDelivery,
6
+ FocusWindowResult,
7
+ Rect,
8
+ UiActFailureCode,
9
+ UiActResult,
10
+ UiElement,
11
+ UiElementAction,
12
+ UiSnapshot,
13
+ UiSnapshotOptions,
14
+ WindowInfo,
15
+ WindowInputAction,
16
+ WindowInputResult,
17
+ WindowScreenshotResult,
18
+ } from '@namzu/sdk'
19
+ import type { A11ySeq, A11yWindow } from '../a11y/interface.js'
20
+ import { A11yError } from '../a11y/interface.js'
21
+ import { cgWindowId } from '../a11y/macos.js'
22
+ import type { MacA11yHost, MacControlAction, MacNode, MacTree } from '../a11y/macos.js'
23
+ import { decodePngSize } from './png.js'
24
+
25
+ /** A window with more shown controls than this is returned as an outline. */
26
+ const OUTLINE_THRESHOLD = 400
27
+ /** The most controls an outline shows; the rest are counted, not listed. */
28
+ const OUTLINE_BUDGET = 300
29
+ /** The most children of one element an outline lists; a long list is opened as a region. */
30
+ const OUTLINE_PER_PARENT = 20
31
+ /** The children of a region opened by itself that one page lists. */
32
+ const OUTLINE_PAGE = 60
33
+ /** The most nodes one read asks the helper for. */
34
+ const READ_MAX_NODES = 3_000
35
+ const READ_MAX_DEPTH = 24
36
+ const READ_TIMEOUT_MS = 8_000
37
+ /** Refs the model holds; the oldest are forgotten past this. */
38
+ const MAX_REFS = 6_000
39
+
40
+ /** Containers that say nothing: passed through, their children take their place. */
41
+ const TRANSPARENT_ROLES: ReadonlySet<string> = new Set([
42
+ 'AXGroup',
43
+ 'AXUnknown',
44
+ 'AXLayoutArea',
45
+ 'AXLayoutItem',
46
+ ])
47
+ const TEXT_INPUT_ROLES: ReadonlySet<string> = new Set([
48
+ 'AXTextField',
49
+ 'AXTextArea',
50
+ 'AXComboBox',
51
+ 'AXSearchField',
52
+ 'AXSecureTextField',
53
+ ])
54
+
55
+ interface RefEntry {
56
+ readonly windowId: string
57
+ readonly node: MacNode
58
+ /** The ref names a region of hidden children, not a control to act on. */
59
+ readonly region: boolean
60
+ }
61
+
62
+ interface CaptureFrame {
63
+ readonly captureId: string
64
+ readonly window: WindowInfo
65
+ readonly width: number
66
+ readonly height: number
67
+ }
68
+
69
+ export interface MacAxSurfaceOptions {
70
+ readonly host: MacA11yHost
71
+ /** Captured pixels per point of the main display; the adapter binds its own after construction. */
72
+ readonly scale: () => Promise<number>
73
+ /** A key combination as a virtual key code and modifier names; throws on one it cannot press. */
74
+ readonly keyEvent: (combo: string) => { readonly code: number; readonly flags: readonly string[] }
75
+ /** For tests. */
76
+ readonly now?: () => number
77
+ /** Waits between looks at a panel that is still listing a folder; for tests. */
78
+ readonly wait?: (ms: number) => Promise<void>
79
+ }
80
+
81
+ const stripAx = (role: string): string => role.replace(/^AX/i, '').toLowerCase()
82
+
83
+ function windowInfo(w: A11yWindow): WindowInfo {
84
+ return {
85
+ id: String(cgWindowId(w.windowId)),
86
+ title: w.title,
87
+ app: w.processName,
88
+ pid: w.processId,
89
+ bounds: w.bounds,
90
+ focused: w.focused,
91
+ minimized: w.minimized,
92
+ }
93
+ }
94
+
95
+ function failure(code: UiActFailureCode, detail: string): UiActResult {
96
+ return { ok: false, delivery: 'not_delivered', retrySafety: 'safe', code, detail }
97
+ }
98
+
99
+ function statesOf(node: MacNode): string[] {
100
+ const states: string[] = []
101
+ if (!node.enabled) states.push('disabled')
102
+ if (node.focused) states.push('focused')
103
+ if (node.selected) states.push('selected')
104
+ if (node.toggle === 'on') states.push('checked')
105
+ else if (node.toggle === 'mixed') states.push('mixed')
106
+ if (node.expand === 'expanded' || node.expand === 'collapsed') states.push(node.expand)
107
+ return states
108
+ }
109
+
110
+ function actionsOf(node: MacNode): UiElementAction[] {
111
+ const out: UiElementAction[] = []
112
+ for (const a of node.actions) {
113
+ if (a === 'invoke') out.push('invoke')
114
+ else if (a === 'value') out.push('set_value')
115
+ else if (a === 'toggle') out.push('toggle')
116
+ else if (a === 'selectionItem') out.push('select')
117
+ else if (a === 'expandCollapse') out.push('expand', 'collapse')
118
+ }
119
+ if (TEXT_INPUT_ROLES.has(node.role) && !out.includes('focus')) out.push('focus')
120
+ return out
121
+ }
122
+
123
+ function refFor(windowId: string, node: MacNode): string {
124
+ const digest = createHash('sha1')
125
+ .update(`${windowId}|${node.fingerprint.runtimeId}`)
126
+ .digest('hex')
127
+ return `ax${digest.slice(0, 8)}`
128
+ }
129
+
130
+ /**
131
+ * macOS windows and accessibility for the macOS adapter, answered by the
132
+ * helper app. A ref names a control by its fingerprint, not by one reading:
133
+ * it survives snapshots, and when the control is rebuilt the helper finds it
134
+ * again by id, name and place, or says `STALE_REF` / `AMBIGUOUS_TARGET`.
135
+ */
136
+ export class MacAxSurface {
137
+ private readonly refs = new Map<string, RefEntry>()
138
+ private readonly frames = new Map<string, CaptureFrame>()
139
+ private readonly marks = new Map<string, A11ySeq>()
140
+ private captureCounter = 0
141
+
142
+ private scaleOf: () => Promise<number>
143
+
144
+ constructor(private readonly options: MacAxSurfaceOptions) {
145
+ this.scaleOf = options.scale
146
+ }
147
+
148
+ /** Uses the adapter's own pixels-per-point, which a capture keeps exact. */
149
+ bindScale(scale: () => Promise<number>): void {
150
+ this.scaleOf = scale
151
+ }
152
+
153
+ async close(): Promise<void> {
154
+ await this.host.close()
155
+ }
156
+
157
+ release(): void {
158
+ this.host.release()
159
+ }
160
+
161
+ private get host(): MacA11yHost {
162
+ return this.options.host
163
+ }
164
+
165
+ async listWindows(): Promise<readonly WindowInfo[]> {
166
+ return (await this.host.listWindows({ includeOwned: true })).map(windowInfo)
167
+ }
168
+
169
+ async focusWindow(id: string | number): Promise<FocusWindowResult> {
170
+ const result = await this.host.focus(String(cgWindowId(id)))
171
+ return {
172
+ ok: result.ok,
173
+ focusedId: result.focusedId,
174
+ ...(result.ok
175
+ ? {}
176
+ : {
177
+ detail: 'macOS did not put that window in front; another app may be holding the focus',
178
+ }),
179
+ }
180
+ }
181
+
182
+ private async windowById(id: string | number): Promise<WindowInfo> {
183
+ const wanted = String(cgWindowId(id))
184
+ const found = (await this.listWindows()).find((w) => w.id === wanted)
185
+ if (!found)
186
+ throw new Error(`window ${wanted} is not on screen; list the windows again and pick one`)
187
+ return found
188
+ }
189
+
190
+ async captureWindow(id: string): Promise<WindowScreenshotResult> {
191
+ const window = await this.windowById(id)
192
+ const shot = await this.host.captureWindow(window.id)
193
+ const size = decodePngSize(shot.data) ?? { width: shot.width, height: shot.height }
194
+ const captureId = `mac-${window.id}-${++this.captureCounter}`
195
+ this.frames.set(window.id, { captureId, window, width: size.width, height: size.height })
196
+ return {
197
+ data: shot.data,
198
+ mimeType: 'image/png',
199
+ width: size.width,
200
+ height: size.height,
201
+ window,
202
+ captureId,
203
+ captureCoverage:
204
+ shot.via === 'screencapturekit' ? 'window only' : 'window only (screencapture)',
205
+ }
206
+ }
207
+
208
+ /** Global screen points for a pixel of the capture. */
209
+ private async pointOf(
210
+ frame: CaptureFrame,
211
+ x: number,
212
+ y: number,
213
+ ): Promise<{ x: number; y: number }> {
214
+ const scale = await this.scaleOf()
215
+ const b = frame.window.bounds
216
+ const ratioX = frame.width > 0 ? b.width / frame.width : 1
217
+ const ratioY = frame.height > 0 ? b.height / frame.height : 1
218
+ return { x: (b.x + x * ratioX) / scale, y: (b.y + y * ratioY) / scale }
219
+ }
220
+
221
+ async executeWindow(
222
+ captureId: string,
223
+ action: WindowInputAction,
224
+ ): Promise<WindowInputResult | undefined> {
225
+ const frame = [...this.frames.values()].find((f) => f.captureId === captureId)
226
+ if (!frame || this.frames.get(frame.window.id)?.captureId !== captureId)
227
+ throw new Error('that capture is out of date; capture the window again before acting on it')
228
+ const current = await this.windowById(frame.window.id)
229
+ const a = frame.window.bounds
230
+ const b = current.bounds
231
+ if (a.x !== b.x || a.y !== b.y || a.width !== b.width || a.height !== b.height)
232
+ throw new Error('the window moved or changed size since the capture; capture it again')
233
+ const windowId = frame.window.id
234
+ this.marks.set(windowId, await this.host.seq(windowId).catch(() => 0))
235
+ const unverified = (detail?: string): WindowInputResult => ({
236
+ delivery: 'delivered_unverified' as ActionDelivery,
237
+ retrySafety: 'unsafe',
238
+ ...(detail ? { detail } : {}),
239
+ })
240
+ switch (action.type) {
241
+ case 'mouse_click': {
242
+ const at = await this.pointOf(frame, action.at.x, action.at.y)
243
+ await this.host.click({
244
+ windowId,
245
+ ...at,
246
+ ...(action.button === 'right' ? { button: 'right' as const } : {}),
247
+ ...(action.count ? { count: action.count } : {}),
248
+ })
249
+ return unverified()
250
+ }
251
+ case 'mouse_drag': {
252
+ const from = await this.pointOf(frame, action.from.x, action.from.y)
253
+ const to = await this.pointOf(frame, action.to.x, action.to.y)
254
+ await this.host.click({ windowId, ...from, to })
255
+ return unverified()
256
+ }
257
+ case 'scroll': {
258
+ const at = await this.pointOf(frame, action.at.x, action.at.y)
259
+ await this.host.scroll({
260
+ windowId,
261
+ direction: action.direction,
262
+ amount: action.amount,
263
+ at,
264
+ })
265
+ return unverified()
266
+ }
267
+ case 'type_text': {
268
+ if (action.delivery_mode === 'foreground') await this.host.focus(windowId)
269
+ await this.host.typeText({ windowId, text: action.text })
270
+ return unverified()
271
+ }
272
+ case 'key': {
273
+ if (action.delivery_mode === 'foreground') await this.host.focus(windowId)
274
+ const key = this.options.keyEvent(action.keys)
275
+ await this.host.pressKey({ windowId, code: key.code, flags: key.flags })
276
+ return unverified()
277
+ }
278
+ }
279
+ }
280
+
281
+ async settleAfterInput(
282
+ request: { readonly windowId?: string; readonly budgetMs: number },
283
+ signal?: AbortSignal,
284
+ ): Promise<{ readonly waitedMs: number; readonly changed: boolean } | undefined> {
285
+ if (request.windowId === undefined || !this.host.isReady) return undefined
286
+ const windowId = String(cgWindowId(request.windowId))
287
+ const since = this.marks.get(windowId)
288
+ try {
289
+ const waited = await this.host.waitForChange(
290
+ {
291
+ windowId,
292
+ timeoutMs: request.budgetMs,
293
+ quietMs: 120,
294
+ ...(since !== undefined ? { since } : {}),
295
+ },
296
+ signal,
297
+ )
298
+ return waited.changed
299
+ ? { waitedMs: waited.settledMs, changed: true }
300
+ : { waitedMs: waited.settledMs, changed: false }
301
+ } catch {
302
+ return undefined
303
+ }
304
+ }
305
+
306
+ async scrollAt(
307
+ at: { readonly x: number; readonly y: number },
308
+ direction: 'up' | 'down' | 'left' | 'right',
309
+ amount: number,
310
+ ): Promise<void> {
311
+ const scale = await this.scaleOf()
312
+ await this.host.scroll({ direction, amount, at: { x: at.x / scale, y: at.y / scale } })
313
+ }
314
+
315
+ // --- accessibility tree -------------------------------------------------
316
+
317
+ private remember(windowId: string, node: MacNode, region: boolean): string {
318
+ const ref = refFor(windowId, node)
319
+ this.refs.delete(ref)
320
+ this.refs.set(ref, { windowId, node, region })
321
+ if (this.refs.size > MAX_REFS) {
322
+ const oldest = this.refs.keys().next().value
323
+ if (oldest !== undefined) this.refs.delete(oldest)
324
+ }
325
+ return ref
326
+ }
327
+
328
+ private async pickWindow(requested: string | number | undefined): Promise<WindowInfo> {
329
+ if (requested !== undefined) return this.windowById(requested)
330
+ const windows = await this.listWindows()
331
+ const front = windows.find((w) => w.focused) ?? windows[0]
332
+ if (!front) throw new Error('no window is on screen')
333
+ return front
334
+ }
335
+
336
+ async uiSnapshot(
337
+ requested?: string | number,
338
+ options: UiSnapshotOptions = {},
339
+ ): Promise<UiSnapshot> {
340
+ let windowId = requested === undefined ? undefined : String(cgWindowId(requested))
341
+ let rootEntry: RefEntry | undefined
342
+ if (options.root !== undefined) {
343
+ rootEntry = this.refs.get(options.root)
344
+ if (!rootEntry)
345
+ throw new Error(
346
+ `STALE_REF: ${options.root} is not a region or control this session was shown. Take a ui_snapshot of the window and use a ref from it.`,
347
+ )
348
+ if (windowId !== undefined && windowId !== rootEntry.windowId)
349
+ throw new Error(
350
+ `${options.root} belongs to window ${rootEntry.windowId}, not ${windowId}. Pass the window it came from, or leave window_id out.`,
351
+ )
352
+ windowId = rootEntry.windowId
353
+ }
354
+ const window = await this.pickWindow(windowId)
355
+ const tree = await this.host.readTree({
356
+ windowId: window.id,
357
+ maxNodes: READ_MAX_NODES,
358
+ maxDepth: READ_MAX_DEPTH,
359
+ timeoutMs: READ_TIMEOUT_MS,
360
+ allowChromium: true,
361
+ ...(rootEntry ? { root: rootEntry.node.fingerprint } : {}),
362
+ })
363
+ const built = this.buildTree(tree)
364
+ const query = options.query?.trim().toLowerCase()
365
+ const roles = new Set(
366
+ (options.role ?? '')
367
+ .split(',')
368
+ .map((r) => stripAx(r.trim()))
369
+ .filter((r) => r.length > 0),
370
+ )
371
+ let root = built.element
372
+ let regions = false
373
+ let next: number | undefined
374
+ if (query || roles.size > 0) {
375
+ root = prune(root, (el) => {
376
+ const text = `${el.name} ${el.value ?? ''}`.toLowerCase()
377
+ const textOk = !query || text.includes(query)
378
+ const roleOk = roles.size === 0 || roles.has(stripAx(el.role))
379
+ return textOk && roleOk
380
+ })
381
+ } else if (visibleCount(root) > OUTLINE_THRESHOLD) {
382
+ const out = outlineOf(
383
+ root,
384
+ OUTLINE_BUDGET,
385
+ rootEntry ? { offset: options.offset ?? 0 } : undefined,
386
+ )
387
+ root = out.root
388
+ regions = out.regions
389
+ next = out.next
390
+ }
391
+ root = this.bindRefs(window.id, root, built.nodes)
392
+ return {
393
+ windowId: window.id,
394
+ ...(window.title ? { title: tree.title || window.title } : {}),
395
+ app: tree.app || window.app,
396
+ root,
397
+ ...(tree.truncated ? { truncated: true } : {}),
398
+ ...(regions ? { outline: true } : {}),
399
+ total: tree.total,
400
+ ...(rootEntry ? { region: true } : {}),
401
+ ...(next !== undefined ? { next } : {}),
402
+ ...(tree.selectedText ? { selectedText: tree.selectedText } : {}),
403
+ }
404
+ }
405
+
406
+ /** The tree as elements; each element's `ref` is its fingerprint's key until bound. */
407
+ private buildTree(tree: MacTree): { element: UiElement; nodes: Map<UiElement, MacNode> } {
408
+ const byIndex = new Map<number, MacNode[]>()
409
+ for (const node of tree.nodes) {
410
+ const list = byIndex.get(node.parent) ?? []
411
+ list.push(node)
412
+ byIndex.set(node.parent, list)
413
+ }
414
+ const nodes = new Map<UiElement, MacNode>()
415
+ const make = (node: MacNode): UiElement[] => {
416
+ const kids = (byIndex.get(node.index) ?? []).flatMap(make)
417
+ const hidden = kids.length === 0 && (node.childCount ?? 0) > 0 ? (node.childCount ?? 0) : 0
418
+ const actions = actionsOf(node)
419
+ const name = node.name ?? ''
420
+ if (
421
+ TRANSPARENT_ROLES.has(node.role) &&
422
+ name === '' &&
423
+ node.value === undefined &&
424
+ actions.length === 0 &&
425
+ hidden === 0 &&
426
+ node.index !== 0
427
+ )
428
+ return kids
429
+ const states = statesOf(node)
430
+ const r = node.bounds
431
+ const bounds: Rect | undefined =
432
+ r.width > 0 && r.height > 0 && !node.offscreen
433
+ ? { x: r.x, y: r.y, width: r.width, height: r.height }
434
+ : undefined
435
+ const element: UiElement = {
436
+ ref: '',
437
+ role: node.role,
438
+ name,
439
+ ...(node.value !== undefined ? { value: node.value } : {}),
440
+ ...(node.automationId ? { automationId: node.automationId } : {}),
441
+ ...(bounds ? { bounds } : {}),
442
+ ...(states.length > 0 ? { states } : {}),
443
+ ...(actions.length > 0 ? { actions } : {}),
444
+ ...(kids.length > 0 ? { children: kids } : {}),
445
+ ...(hidden > 0 ? { hiddenChildren: hidden } : {}),
446
+ }
447
+ nodes.set(element, node)
448
+ return [element]
449
+ }
450
+ const top = tree.nodes.find((n) => n.parent === -1)
451
+ const made = top ? make(top) : []
452
+ const element = made[0] ?? { ref: '', role: 'AXWindow', name: tree.title }
453
+ return { element, nodes }
454
+ }
455
+
456
+ /** Gives the kept elements their refs: controls that can be acted on, and regions with hidden children. */
457
+ private bindRefs(windowId: string, root: UiElement, nodes: Map<UiElement, MacNode>): UiElement {
458
+ const walk = (el: UiElement): UiElement => {
459
+ const children = (el.children ?? []).map(walk)
460
+ const node = nodes.get(el) ?? nodes.get(original.get(el) as UiElement)
461
+ const actionable = (el.actions?.length ?? 0) > 0
462
+ const isRegion = (el.hiddenChildren ?? 0) > 0
463
+ const ref = node && (actionable || isRegion) ? this.remember(windowId, node, !actionable) : ''
464
+ const { children: _children, ...rest } = el
465
+ return Object.freeze({
466
+ ...rest,
467
+ ref,
468
+ ...(children.length > 0 ? { children: Object.freeze(children) } : {}),
469
+ }) as UiElement
470
+ }
471
+ return walk(root)
472
+ }
473
+
474
+ async uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult> {
475
+ const entry = this.refs.get(ref)
476
+ if (!entry)
477
+ return failure(
478
+ 'STALE_REF',
479
+ `${ref} is not a control this session was shown. Take a ui_snapshot and use a ref from it.`,
480
+ )
481
+ if (entry.region)
482
+ return failure(
483
+ 'STALE_REF',
484
+ `${ref} names a region, not a control. Open it with ui_snapshot root.`,
485
+ )
486
+ const mapped: Record<UiElementAction, MacControlAction> = {
487
+ invoke: 'invoke',
488
+ focus: 'focus',
489
+ set_value: 'set_value',
490
+ toggle: 'toggle',
491
+ select: 'select',
492
+ expand: 'expand',
493
+ collapse: 'collapse',
494
+ scroll_into_view: 'scroll_into_view',
495
+ }
496
+ if (action === 'set_value' && value === undefined)
497
+ return failure('STALE_REF', 'set_value needs a value')
498
+ this.marks.set(entry.windowId, await this.host.seq(entry.windowId).catch(() => 0))
499
+ try {
500
+ const result = await this.host.act({
501
+ windowId: entry.windowId,
502
+ fingerprint: entry.node.fingerprint,
503
+ action: mapped[action],
504
+ ...(value !== undefined ? { value } : {}),
505
+ })
506
+ if (!result.done)
507
+ return {
508
+ ok: false,
509
+ delivery: 'not_delivered',
510
+ retrySafety: 'safe',
511
+ detail: result.detail ?? 'the control did not accept that action',
512
+ }
513
+ const readBack =
514
+ result.expected !== undefined || result.after !== undefined
515
+ ? {
516
+ ...(result.expected !== undefined ? { expected: result.expected } : {}),
517
+ ...(result.after !== undefined ? { observed: result.after } : {}),
518
+ }
519
+ : undefined
520
+ if (result.verified === false)
521
+ return {
522
+ ok: true,
523
+ delivery: 'delivered_unverified',
524
+ retrySafety: 'unsafe',
525
+ detail: 'the control took the action but its state did not read back as asked',
526
+ ...(readBack ? { readBack } : {}),
527
+ }
528
+ return {
529
+ ok: true,
530
+ delivery: result.verified === true ? 'delivered_verified' : 'delivered_unverified',
531
+ retrySafety: 'unsafe',
532
+ ...(readBack ? { readBack } : {}),
533
+ }
534
+ } catch (error) {
535
+ if (error instanceof A11yError) {
536
+ if (error.code === 'STALE_REF' || error.code === 'AMBIGUOUS_TARGET')
537
+ return failure(error.code, error.message)
538
+ return { ok: false, delivery: 'not_delivered', retrySafety: 'safe', detail: error.message }
539
+ }
540
+ throw error
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Picks a file in the open or save panel that is in front, through the
546
+ * panel's accessibility tree: no key shortcut (Cmd+Shift+G does not reach a
547
+ * panel through posted key events). It uses, in this order, a "Go to the
548
+ * folder" sheet that is already open; the panel's own path or name field (a
549
+ * save panel has one); and the panel's "Go to Folder" button when it has
550
+ * one. It then presses the panel's default button (Open, Choose, Select or
551
+ * Save) unless `confirm` is false.
552
+ */
553
+ async pickFile(
554
+ path: string,
555
+ options: {
556
+ readonly windowId?: string | number
557
+ readonly confirm?: boolean
558
+ /** For `~` and for the sidebar's home row; default the current user's home. */
559
+ readonly home?: string
560
+ } = {},
561
+ ): Promise<PickFileResult> {
562
+ const wanted = path.trim()
563
+ if (wanted.length === 0) return { ok: false, detail: 'pickFile needs a path' }
564
+ const read = async (query?: string): Promise<readonly Located[]> => {
565
+ const snap = await this.uiSnapshot(options.windowId, {
566
+ ...(query === undefined ? { role: PANEL_ROLES } : { query }),
567
+ })
568
+ return flatten(snap.root)
569
+ }
570
+ let elements = await read()
571
+ if (!findPanel(elements.map((e) => e.element)))
572
+ return {
573
+ ok: false,
574
+ detail:
575
+ 'no open or save panel is in that window; open it first (its Open, Save or Choose button and Cancel button show it)',
576
+ }
577
+ const confirm = options.confirm !== false
578
+ let sheet = findGoSheet(elements)
579
+ if (!sheet) {
580
+ const field = findPathField(elements)
581
+ if (field) {
582
+ const set = await this.uiAct(field.ref, 'set_value', wanted)
583
+ if (!set.ok)
584
+ return {
585
+ ok: false,
586
+ detail: set.detail ?? 'the path field refused the path',
587
+ via: 'path_field',
588
+ }
589
+ return this.confirmPick(read, confirm, 'path_field')
590
+ }
591
+ const goButton = elements.find(
592
+ (e) =>
593
+ e.element.ref &&
594
+ isRole(e.element, 'button', 'menuitem', 'menubutton') &&
595
+ GO_TO_FOLDER.test(e.element.name),
596
+ )
597
+ if (!goButton) return this.browseTo(wanted, options.home ?? homedir(), read, confirm)
598
+ const opened = await this.uiAct(goButton.element.ref, 'invoke')
599
+ if (!opened.ok)
600
+ return { ok: false, detail: opened.detail ?? 'Go to Folder did not open', via: 'go_sheet' }
601
+ elements = await read()
602
+ sheet = findGoSheet(elements)
603
+ if (!sheet)
604
+ return {
605
+ ok: false,
606
+ detail: 'Go to Folder was pressed but its sheet did not appear',
607
+ via: 'go_sheet',
608
+ }
609
+ }
610
+ const set = await this.uiAct(sheet.field.ref, 'set_value', wanted)
611
+ if (!set.ok)
612
+ return {
613
+ ok: false,
614
+ detail: set.detail ?? 'the Go to Folder field refused the path',
615
+ via: 'go_sheet',
616
+ }
617
+ const go = await this.uiAct(sheet.go.ref, 'invoke')
618
+ if (!go.ok)
619
+ return { ok: false, detail: go.detail ?? 'the Go button did not press', via: 'go_sheet' }
620
+ return this.confirmPick(read, confirm, 'go_sheet')
621
+ }
622
+
623
+ /**
624
+ * An open panel that offers no field for a path (the usual one): start at the sidebar's home (or the
625
+ * startup disk) and select each folder of the path in the browser, then the file.
626
+ */
627
+ private async browseTo(
628
+ wanted: string,
629
+ home: string,
630
+ read: (query?: string) => Promise<readonly Located[]>,
631
+ confirm: boolean,
632
+ ): Promise<PickFileResult> {
633
+ const via = 'browse' as const
634
+ const absolute = wanted === '~' || wanted.startsWith('~/') ? home + wanted.slice(1) : wanted
635
+ if (!absolute.startsWith('/'))
636
+ return { ok: false, detail: `${wanted} is not an absolute path`, via }
637
+ const underHome = absolute === home || absolute.startsWith(`${home}/`)
638
+ const start = underHome ? basename(home) : 'Macintosh HD'
639
+ const parts = (underHome ? absolute.slice(home.length) : absolute).split('/').filter(Boolean)
640
+ const row = (await read(start)).find(
641
+ (e) => e.inSidebar && isRole(e.element, 'statictext') && e.element.name === start,
642
+ )
643
+ const sidebarRow = row && lastOf(row.ancestors, (a) => isRole(a, 'row') && a.ref !== '')
644
+ if (!sidebarRow)
645
+ return { ok: false, detail: `the panel's sidebar has no "${start}" entry to start from`, via }
646
+ const first = await this.uiAct(sidebarRow.ref, 'select')
647
+ if (!first.ok) return { ok: false, detail: first.detail ?? `${start} did not open`, via }
648
+ // Entries already chosen: right after a folder opens its old column can still be the last one listed,
649
+ // and a same-named entry there (a/a) must not be taken for the next step.
650
+ const chosen = new Set<string>()
651
+ for (const [index, part] of parts.entries()) {
652
+ const last = index === parts.length - 1
653
+ const hit = await this.waitForEntry(read, part, chosen)
654
+ if (!hit) return { ok: false, detail: `"${part}" is not in the folder the panel shows`, via }
655
+ chosen.add(hit.element.ref)
656
+ const act = isRole(hit.element, 'group', 'row') ? 'select' : 'invoke'
657
+ const done = await this.uiAct(hit.element.ref, act)
658
+ if (!done.ok) {
659
+ // Opening the file closes the panel under the call, and macOS answers that call with an error.
660
+ if (last && (await this.panelGone(read)))
661
+ return { ok: true, detail: 'the panel opened the file', via }
662
+ return { ok: false, detail: done.detail ?? `${part} did not open`, via }
663
+ }
664
+ if (!last && hit.element.actions?.includes('expand') && act === 'select')
665
+ await this.uiAct(hit.element.ref, 'expand')
666
+ }
667
+ return this.confirmPick(read, confirm, via)
668
+ }
669
+
670
+ private async panelGone(read: (query?: string) => Promise<readonly Located[]>): Promise<boolean> {
671
+ try {
672
+ return !findPanel((await read()).map((e) => e.element))
673
+ } catch {
674
+ return true
675
+ }
676
+ }
677
+
678
+ /** The browser entry named `name`, in the rightmost column, not one in `skip`; the panel needs a moment to list a folder. */
679
+ private async waitForEntry(
680
+ read: (query?: string) => Promise<readonly Located[]>,
681
+ name: string,
682
+ skip: ReadonlySet<string> = new Set(),
683
+ ): Promise<{ readonly element: UiElement } | undefined> {
684
+ for (let attempt = 0; attempt < 8; attempt++) {
685
+ const found = (await read(name)).filter(
686
+ (e) =>
687
+ !e.inSidebar &&
688
+ isRole(e.element, 'textfield', 'statictext') &&
689
+ (e.element.value === name || e.element.name === name),
690
+ )
691
+ const hit = found.at(-1)
692
+ // The entry is the row (a list) or the item (a column) that holds the name; `select` picks it. A name
693
+ // whose holder is not in the tree is pressed itself.
694
+ const entries = found.flatMap((h) => {
695
+ const e =
696
+ lastOf(h.ancestors, (a) => a.ref !== '' && isRole(a, 'group', 'row')) ??
697
+ (h.element.ref !== '' ? h.element : undefined)
698
+ return e && !skip.has(e.ref) ? [e] : []
699
+ })
700
+ const entry = hit && entries.at(-1)
701
+ if (entry) return { element: entry }
702
+ await (
703
+ this.options.wait ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
704
+ )(150)
705
+ }
706
+ return undefined
707
+ }
708
+
709
+ private async confirmPick(
710
+ read: (query?: string) => Promise<readonly Located[]>,
711
+ confirm: boolean,
712
+ via: PickFileResult['via'],
713
+ ): Promise<PickFileResult> {
714
+ if (!confirm) return { ok: true, detail: 'the path is entered; the panel is still open', via }
715
+ const elements = await read().catch(() => undefined)
716
+ if (!elements || !findPanel(elements.map((e) => e.element)))
717
+ return { ok: true, detail: 'the panel closed with the file chosen', via }
718
+ const button = findDefaultButton(elements)
719
+ if (!button)
720
+ return {
721
+ ok: true,
722
+ detail:
723
+ 'the path is entered; the panel has no Open, Choose or Save button in view to press',
724
+ via,
725
+ }
726
+ const pressed = await this.uiAct(button.ref, 'invoke')
727
+ if (!pressed.ok)
728
+ return { ok: false, detail: pressed.detail ?? `${button.name} did not press`, via }
729
+ return { ok: true, detail: `pressed ${button.name}`, via }
730
+ }
731
+
732
+ forgetRefs(): void {
733
+ this.refs.clear()
734
+ }
735
+ }
736
+
737
+ // ---------------------------------------------------------------------------
738
+ // Open and save panels
739
+ // ---------------------------------------------------------------------------
740
+
741
+ export interface PickFileResult {
742
+ readonly ok: boolean
743
+ readonly detail: string
744
+ /** Which part of the panel took the path. */
745
+ readonly via?: 'go_sheet' | 'path_field' | 'browse'
746
+ }
747
+
748
+ const PANEL_ROLES =
749
+ 'AXSheet,AXWindow,AXButton,AXMenuItem,AXMenuButton,AXTextField,AXComboBox,AXSearchField'
750
+ const GO_TO_FOLDER = /^go to( the)? folder/i
751
+ const DEFAULT_BUTTON = /^(open|choose|select|save)$/i
752
+
753
+ function lastOf<T>(items: readonly T[], test: (item: T) => boolean): T | undefined {
754
+ for (let i = items.length - 1; i >= 0; i--) if (test(items[i] as T)) return items[i]
755
+ return undefined
756
+ }
757
+
758
+ /** An element with the elements above it, and whether it sits in the panel's sidebar. */
759
+ interface Located {
760
+ readonly element: UiElement
761
+ readonly ancestors: readonly UiElement[]
762
+ readonly inSidebar: boolean
763
+ }
764
+
765
+ function flatten(root: UiElement): Located[] {
766
+ const out: Located[] = []
767
+ const walk = (element: UiElement, ancestors: readonly UiElement[]): void => {
768
+ out.push({
769
+ element,
770
+ ancestors,
771
+ inSidebar: ancestors.some((a) => a.name === 'sidebar'),
772
+ })
773
+ for (const child of element.children ?? []) walk(child, [...ancestors, element])
774
+ }
775
+ walk(root, [])
776
+ return out
777
+ }
778
+
779
+ const isRole = (element: UiElement, ...roles: string[]): boolean =>
780
+ roles.includes(stripAx(element.role))
781
+
782
+ /** A panel shows as a Cancel button beside an Open, Choose, Select or Save one. */
783
+ function findPanel(elements: readonly UiElement[]): boolean {
784
+ const buttons = elements.filter((e) => isRole(e, 'button'))
785
+ return (
786
+ buttons.some((b) => /^cancel$/i.test(b.name)) &&
787
+ buttons.some((b) => DEFAULT_BUTTON.test(b.name))
788
+ )
789
+ }
790
+
791
+ function findDefaultButton(elements: readonly Located[]): UiElement | undefined {
792
+ return elements.find(
793
+ (e) => e.element.ref && isRole(e.element, 'button') && DEFAULT_BUTTON.test(e.element.name),
794
+ )?.element
795
+ }
796
+
797
+ /** The sheet "Go to the folder:" holds a text field and a Go button. */
798
+ function findGoSheet(
799
+ elements: readonly Located[],
800
+ ): { readonly field: UiElement; readonly go: UiElement } | undefined {
801
+ for (const sheet of elements.filter((e) => isRole(e.element, 'sheet'))) {
802
+ const inside = flatten(sheet.element).map((e) => e.element)
803
+ const field = inside.find((e) => e.ref && isRole(e, 'textfield', 'combobox'))
804
+ const go = inside.find((e) => e.ref && isRole(e, 'button') && /^go$/i.test(e.name))
805
+ if (field && go) return { field, go }
806
+ }
807
+ return undefined
808
+ }
809
+
810
+ /**
811
+ * A save panel's name field takes a full path. Never the search field (it holds a search button), and
812
+ * never a name inside the file browser, where every file's name is a text field.
813
+ */
814
+ function findPathField(elements: readonly Located[]): UiElement | undefined {
815
+ const fields = elements.filter(
816
+ (e) =>
817
+ e.element.ref &&
818
+ isRole(e.element, 'textfield', 'combobox') &&
819
+ !e.ancestors.some((a) => isRole(a, 'browser', 'outline', 'table', 'list', 'row')) &&
820
+ !/search/i.test(e.element.name) &&
821
+ !(e.element.children ?? []).some((c) => /search/i.test(c.name)),
822
+ )
823
+ return (
824
+ fields.find((f) => /save as|name|path|go to|folder|where/i.test(f.element.name)) ??
825
+ (fields.length === 1 ? fields[0] : undefined)
826
+ )?.element
827
+ }
828
+
829
+ // ---------------------------------------------------------------------------
830
+ // Views of a tree
831
+ // ---------------------------------------------------------------------------
832
+
833
+ /** Original element of a rebuilt (frozen) one, so a pruned view still finds its node. */
834
+ const original = new WeakMap<UiElement, UiElement>()
835
+
836
+ function isSilent(element: UiElement): boolean {
837
+ return (
838
+ (element.actions?.length ?? 0) === 0 &&
839
+ (element.hiddenChildren ?? 0) === 0 &&
840
+ element.name.trim().length === 0 &&
841
+ element.value === undefined
842
+ )
843
+ }
844
+
845
+ function visibleCount(element: UiElement): number {
846
+ let count = isSilent(element) ? 0 : 1
847
+ for (const child of element.children ?? []) count += visibleCount(child)
848
+ return count
849
+ }
850
+
851
+ /** The elements that match, with every element above them. */
852
+ function prune(root: UiElement, matches: (element: UiElement) => boolean): UiElement {
853
+ const walk = (element: UiElement): UiElement | undefined => {
854
+ const kept = (element.children ?? []).map(walk).filter((c): c is UiElement => c !== undefined)
855
+ if (!matches(element) && kept.length === 0) return undefined
856
+ const { children: _children, hiddenChildren: _hidden, ...rest } = element
857
+ const copy = Object.freeze({
858
+ ...rest,
859
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
860
+ }) as UiElement
861
+ original.set(copy, element)
862
+ return copy
863
+ }
864
+ const { children: _children, ...bare } = root
865
+ return walk(root) ?? (Object.freeze({ ...bare, hiddenChildren: 0 }) as UiElement)
866
+ }
867
+
868
+ /**
869
+ * The top of a big tree, breadth first, so the window's layout shows before
870
+ * any one region's detail; what is left out is counted on the element that
871
+ * holds it, and that element is a region the model can open.
872
+ */
873
+ function outlineOf(
874
+ root: UiElement,
875
+ budget: number,
876
+ page?: { readonly offset: number },
877
+ ): { root: UiElement; regions: boolean; next: number | undefined } {
878
+ const keep = new Set<UiElement>([root])
879
+ const queue: UiElement[] = [root]
880
+ let used = isSilent(root) ? 0 : 1
881
+ let next: number | undefined
882
+ while (queue.length > 0) {
883
+ const element = queue.shift() as UiElement
884
+ const isRoot = element === root
885
+ const children = element.children ?? []
886
+ const first = isRoot && page ? Math.min(page.offset, children.length) : 0
887
+ const cap = isRoot && page ? OUTLINE_PAGE : OUTLINE_PER_PARENT
888
+ let listed = 0
889
+ let cut = false
890
+ for (let index = first; index < children.length; index++) {
891
+ const child = children[index] as UiElement
892
+ const cost = isSilent(child) ? 0 : 1
893
+ if (cut || used + cost > budget || listed + cost > cap || keep.size > budget * 4) {
894
+ cut = true
895
+ if (isRoot && page && next === undefined) next = index
896
+ continue
897
+ }
898
+ used += cost
899
+ listed += cost
900
+ keep.add(child)
901
+ queue.push(child)
902
+ }
903
+ }
904
+ let regions = false
905
+ const build = (element: UiElement): UiElement => {
906
+ const children = element.children ?? []
907
+ const kept = children.filter((c) => keep.has(c)).map(build)
908
+ const hidden = children.length - kept.length + (element.hiddenChildren ?? 0)
909
+ if (children.length - kept.length > 0) regions = true
910
+ const { children: _children, hiddenChildren: _hidden, ...rest } = element
911
+ const copy = Object.freeze({
912
+ ...rest,
913
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
914
+ ...(hidden > 0 ? { hiddenChildren: hidden } : {}),
915
+ }) as UiElement
916
+ original.set(copy, element)
917
+ return copy
918
+ }
919
+ return { root: build(root), regions, next }
920
+ }