@roam-agent/roam-computer-use 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -2
  3. package/assets/reference/img.jpg +0 -0
  4. package/docs/README.md +45 -0
  5. package/docs/content/docs/explanation/action-pipeline.mdx +36 -0
  6. package/docs/content/docs/explanation/architecture.mdx +161 -0
  7. package/docs/content/docs/explanation/index.mdx +19 -0
  8. package/docs/content/docs/explanation/meta.json +5 -0
  9. package/docs/content/docs/explanation/observation-pipeline.mdx +37 -0
  10. package/docs/content/docs/explanation/platform-boundary.mdx +37 -0
  11. package/docs/content/docs/explanation/state-and-scheduling.mdx +35 -0
  12. package/docs/content/docs/how-to-guides/develop-and-validate.mdx +112 -0
  13. package/docs/content/docs/how-to-guides/index.mdx +12 -0
  14. package/docs/content/docs/how-to-guides/linux.mdx +68 -0
  15. package/docs/content/docs/how-to-guides/meta.json +1 -0
  16. package/docs/content/docs/how-to-guides/troubleshooting.mdx +126 -0
  17. package/docs/content/docs/index.mdx +67 -0
  18. package/docs/content/docs/meta.json +5 -0
  19. package/docs/content/docs/reference/agent/contract.mdx +162 -0
  20. package/docs/content/docs/reference/agent/index.mdx +8 -0
  21. package/docs/content/docs/reference/agent/meta.json +8 -0
  22. package/docs/content/docs/reference/agent/tools.mdx +221 -0
  23. package/docs/content/docs/reference/codebase.mdx +139 -0
  24. package/docs/content/docs/reference/configuration.mdx +113 -0
  25. package/docs/content/docs/reference/index.mdx +28 -0
  26. package/docs/content/docs/reference/meta.json +10 -0
  27. package/docs/content/docs/reference/platforms/index.mdx +18 -0
  28. package/docs/content/docs/reference/platforms/macos/accessibility.mdx +61 -0
  29. package/docs/content/docs/reference/platforms/macos/actions.mdx +63 -0
  30. package/docs/content/docs/reference/platforms/macos/capture.mdx +58 -0
  31. package/docs/content/docs/reference/platforms/macos/implementation.mdx +98 -0
  32. package/docs/content/docs/reference/platforms/macos/index.mdx +16 -0
  33. package/docs/content/docs/reference/platforms/macos/meta.json +10 -0
  34. package/docs/content/docs/reference/platforms/macos/root-targeting.mdx +47 -0
  35. package/docs/content/docs/reference/platforms/meta.json +8 -0
  36. package/docs/content/docs/reference/platforms/windows.mdx +75 -0
  37. package/docs/content/docs/tutorials/getting-started.mdx +46 -0
  38. package/docs/content/docs/tutorials/index.mdx +10 -0
  39. package/docs/content/docs/tutorials/meta.json +1 -0
  40. package/extensions/computer-use.ts +235 -0
  41. package/native/linux/bridge-rs/Cargo.lock +1204 -0
  42. package/native/linux/bridge-rs/Cargo.toml +21 -0
  43. package/native/linux/bridge-rs/src/atspi.rs +670 -0
  44. package/native/linux/bridge-rs/src/error.rs +65 -0
  45. package/native/linux/bridge-rs/src/lib.rs +11 -0
  46. package/native/linux/bridge-rs/src/main.rs +1110 -0
  47. package/native/linux/bridge-rs/src/protocol.rs +49 -0
  48. package/native/linux/bridge-rs/src/state.rs +293 -0
  49. package/native/linux/bridge-rs/src/wayland.rs +89 -0
  50. package/native/linux/bridge-rs/src/x11.rs +909 -0
  51. package/native/linux/bridge-rs/tests/protocol_tests.rs +73 -0
  52. package/native/macos/activity_glow.swift +169 -0
  53. package/native/macos/bridge.swift +3968 -0
  54. package/native/windows/bridge-rs/Cargo.lock +396 -0
  55. package/native/windows/bridge-rs/Cargo.toml +30 -0
  56. package/native/windows/bridge-rs/src/capture.rs +561 -0
  57. package/native/windows/bridge-rs/src/error.rs +81 -0
  58. package/native/windows/bridge-rs/src/input.rs +501 -0
  59. package/native/windows/bridge-rs/src/lib.rs +85 -0
  60. package/native/windows/bridge-rs/src/main.rs +1683 -0
  61. package/native/windows/bridge-rs/src/protocol.rs +53 -0
  62. package/native/windows/bridge-rs/src/refs.rs +237 -0
  63. package/native/windows/bridge-rs/src/state.rs +55 -0
  64. package/native/windows/bridge-rs/src/uia.rs +1252 -0
  65. package/native/windows/bridge-rs/src/window.rs +718 -0
  66. package/native/windows/bridge-rs/tests/protocol_tests.rs +252 -0
  67. package/native/windows/bridge-rs/tests/refs_tests.rs +86 -0
  68. package/native/windows/bridge-rs/tests/state_tests.rs +33 -0
  69. package/package.json +104 -5
  70. package/prebuilt/macos/arm64/bridge +0 -0
  71. package/prebuilt/macos/x64/bridge +0 -0
  72. package/roam/README.md +52 -0
  73. package/roam/bridge/macos/arm64/bridge +0 -0
  74. package/roam/bridge/macos/x64/bridge +0 -0
  75. package/roam/bridge/manifest.json +20 -0
  76. package/roam/helper-path.d.mts +9 -0
  77. package/roam/helper-path.mjs +36 -0
  78. package/roam/identity.d.mts +16 -0
  79. package/roam/identity.mjs +64 -0
  80. package/roam/index.ts +51 -0
  81. package/roam/redirect.ts +51 -0
  82. package/roam/repair.ts +120 -0
  83. package/scripts/build-native.mjs +286 -0
  84. package/scripts/setup-helper.mjs +635 -0
  85. package/src/actions.ts +130 -0
  86. package/src/bridge.ts +2594 -0
  87. package/src/cdp.ts +658 -0
  88. package/src/config.ts +226 -0
  89. package/src/contract.ts +107 -0
  90. package/src/extension/index.ts +9 -0
  91. package/src/find-params.ts +21 -0
  92. package/src/note.ts +195 -0
  93. package/src/outline.ts +702 -0
  94. package/src/output.ts +134 -0
  95. package/src/permissions.ts +111 -0
  96. package/src/platform/architecture.ts +23 -0
  97. package/src/platform/coerce.ts +16 -0
  98. package/src/platform/index.ts +61 -0
  99. package/src/platform/linux/backend.ts +186 -0
  100. package/src/platform/linux/helper.ts +238 -0
  101. package/src/platform/macos/backend.ts +147 -0
  102. package/src/platform/macos/browser.ts +110 -0
  103. package/src/platform/macos/helper.ts +369 -0
  104. package/src/platform/macos/permissions.ts +146 -0
  105. package/src/platform/types.ts +229 -0
  106. package/src/platform/windows/backend.ts +142 -0
  107. package/src/platform/windows/helper.ts +140 -0
  108. package/src/root-selection.ts +25 -0
  109. package/src/runtime.ts +129 -0
  110. package/src/state.ts +146 -0
  111. package/src/view.ts +147 -0
@@ -0,0 +1,3968 @@
1
+ import Foundation
2
+ import AppKit
3
+ import ApplicationServices
4
+ import Darwin
5
+ import Vision
6
+ import ImageIO
7
+ import ScreenCaptureKit
8
+
9
+ struct BridgeFailure: Error {
10
+ let message: String
11
+ let code: String
12
+ }
13
+
14
+ final class AXRefStore {
15
+ struct Snapshot {
16
+ let role: String
17
+ let identifier: String
18
+ let label: String
19
+ let rect: CGRect
20
+ }
21
+
22
+ private var nextId: UInt64 = 0
23
+ private var windows: [String: AXUIElement] = [:]
24
+ private var elements: [String: AXUIElement] = [:]
25
+ private var snapshots: [String: Snapshot] = [:]
26
+ private let lock = NSLock()
27
+
28
+ func storeWindow(_ window: AXUIElement) -> String {
29
+ lock.lock()
30
+ defer { lock.unlock() }
31
+ for (ref, existing) in windows {
32
+ if CFEqual(existing, window) {
33
+ return ref
34
+ }
35
+ }
36
+ nextId += 1
37
+ let ref = "w\(nextId)"
38
+ windows[ref] = window
39
+ return ref
40
+ }
41
+
42
+ func storeElement(_ element: AXUIElement, snapshot: Snapshot? = nil) -> String {
43
+ lock.lock()
44
+ defer { lock.unlock() }
45
+ nextId += 1
46
+ let ref = "e\(nextId)"
47
+ elements[ref] = element
48
+ snapshots[ref] = snapshot
49
+ return ref
50
+ }
51
+
52
+ func window(for ref: String) -> AXUIElement? {
53
+ lock.lock()
54
+ defer { lock.unlock() }
55
+ return windows[ref]
56
+ }
57
+
58
+ func element(for ref: String) -> AXUIElement? {
59
+ lock.lock()
60
+ defer { lock.unlock() }
61
+ return elements[ref]
62
+ }
63
+
64
+ func snapshot(for ref: String) -> Snapshot? {
65
+ lock.lock()
66
+ defer { lock.unlock() }
67
+ return snapshots[ref]
68
+ }
69
+ }
70
+
71
+ private struct CGWindowCandidate {
72
+ let windowId: UInt32
73
+ let title: String
74
+ let bounds: CGRect
75
+ let isOnscreen: Bool
76
+ let layer: Int
77
+ let zOrder: Int
78
+ }
79
+
80
+ private struct CGWindowOwnerSummary {
81
+ let pid: Int32
82
+ let name: String
83
+ }
84
+
85
+ private struct AXDescendant {
86
+ let element: AXUIElement
87
+ let depth: Int
88
+ let insideWebArea: Bool
89
+ let axVisible: Bool
90
+ }
91
+
92
+ private struct WindowPairing {
93
+ let candidate: CGWindowCandidate?
94
+ let score: Double
95
+ let confidence: String
96
+ }
97
+
98
+ private struct CapturedWindowImage {
99
+ let image: CGImage
100
+ let windowId: UInt32
101
+ let frame: CGRect
102
+ }
103
+
104
+ // BEGIN PURE (compiled standalone by scripts/check-macos-native-pure.mjs; Foundation only)
105
+ func classifyModal(axModal: Bool?, sheetCount: Int, role: String, subrole: String) -> Bool {
106
+ if sheetCount > 0 || role == "AXSheet" { return true }
107
+ if let axModal { return axModal }
108
+ let text = "\(role) \(subrole)"
109
+ return text.range(of: "dialog", options: [.caseInsensitive]) != nil
110
+ || text.range(of: "modal", options: [.caseInsensitive]) != nil
111
+ }
112
+
113
+ enum CaptureTarget: Equatable {
114
+ case capture(windowId: UInt32)
115
+ case semanticOnly
116
+ case notCapturable
117
+ }
118
+
119
+ func resolveCaptureTarget(windowId: UInt32?, wantsImage: Bool) -> CaptureTarget {
120
+ if let windowId, windowId > 0 { return wantsImage ? .capture(windowId: windowId) : .semanticOnly }
121
+ return wantsImage ? .notCapturable : .semanticOnly
122
+ }
123
+ // END PURE
124
+
125
+ private struct LookRecord {
126
+ let lookId: String
127
+ let windowId: UInt32
128
+ var windowRef: String? = nil
129
+ let windowFrame: CGRect
130
+ let imageWidth: Int
131
+ let imageHeight: Int
132
+ let hasImage: Bool
133
+ }
134
+
135
+ private struct RootAXEvent {
136
+ let sequence: UInt64
137
+ let timestamp: TimeInterval
138
+ let notification: String
139
+ let element: AXUIElement?
140
+ }
141
+
142
+ private final class RootAXObserverState {
143
+ let pid: Int32
144
+ let observer: AXObserver
145
+ let change = NSCondition()
146
+ var changeGeneration: UInt64 = 0
147
+ var events: [RootAXEvent] = []
148
+ var nextSequence: UInt64 = 1
149
+ var lastUsed: TimeInterval = Date().timeIntervalSince1970
150
+
151
+ init(pid: Int32, observer: AXObserver) {
152
+ self.pid = pid
153
+ self.observer = observer
154
+ }
155
+ }
156
+
157
+ private struct OCRBox {
158
+ let string: String
159
+ let confidence: Double
160
+ let rect: CGRect
161
+ }
162
+
163
+ final class LookNode {
164
+ let element: AXUIElement?
165
+ let ref: String
166
+ let role: String
167
+ let subrole: String
168
+ let identifier: String
169
+ let title: String
170
+ let description: String
171
+ let value: String
172
+ let actions: [String]
173
+ let canPress: Bool
174
+ let canFocus: Bool
175
+ let canSetValue: Bool
176
+ let canScroll: Bool
177
+ let canIncrement: Bool
178
+ let canDecrement: Bool
179
+ let isTextInput: Bool
180
+ let rect: CGRect
181
+ let focused: Bool
182
+ var offscreen: Bool
183
+ var pictureOnly: Bool
184
+ var truncated: Bool
185
+ var scrollExtent: [String: Int]?
186
+ var text: [[String: Any]]
187
+ var children: [LookNode]
188
+
189
+ init(element: AXUIElement?, ref: String, role: String, subrole: String, identifier: String, title: String, description: String, value: String, actions: [String], canPress: Bool, canFocus: Bool, canSetValue: Bool, canScroll: Bool, canIncrement: Bool, canDecrement: Bool, isTextInput: Bool, rect: CGRect, focused: Bool = false, offscreen: Bool = false, pictureOnly: Bool = false) {
190
+ self.element = element
191
+ self.ref = ref
192
+ self.role = role
193
+ self.subrole = subrole
194
+ self.identifier = identifier
195
+ self.title = title
196
+ self.description = description
197
+ self.value = value
198
+ self.actions = actions
199
+ self.canPress = canPress
200
+ self.canFocus = canFocus
201
+ self.canSetValue = canSetValue
202
+ self.canScroll = canScroll
203
+ self.canIncrement = canIncrement
204
+ self.canDecrement = canDecrement
205
+ self.isTextInput = isTextInput
206
+ self.rect = rect
207
+ self.focused = focused
208
+ self.offscreen = offscreen
209
+ self.pictureOnly = pictureOnly
210
+ self.truncated = false
211
+ self.text = []
212
+ self.children = []
213
+ }
214
+
215
+ func payload() -> [String: Any] {
216
+ var output: [String: Any] = [
217
+ "ref": ref,
218
+ "role": role,
219
+ "subrole": subrole,
220
+ "identifier": identifier,
221
+ "title": title,
222
+ "description": description,
223
+ "value": value,
224
+ "actions": actions,
225
+ "canPress": canPress,
226
+ "canFocus": canFocus,
227
+ "canSetValue": canSetValue,
228
+ "canScroll": canScroll,
229
+ "canIncrement": canIncrement,
230
+ "canDecrement": canDecrement,
231
+ "isTextInput": isTextInput,
232
+ "rect": ["x": rect.origin.x, "y": rect.origin.y, "w": rect.width, "h": rect.height],
233
+ "children": children.map { $0.payload() },
234
+ ]
235
+ if focused { output["focused"] = true }
236
+ if offscreen { output["offscreen"] = true }
237
+ if pictureOnly { output["pictureOnly"] = true }
238
+ if truncated { output["truncated"] = true }
239
+ if let scrollExtent { output["scrollExtent"] = scrollExtent }
240
+ if !text.isEmpty { output["text"] = text }
241
+ return output
242
+ }
243
+
244
+ }
245
+
246
+ final class Box<T> {
247
+ var value: T
248
+ init(_ value: T) {
249
+ self.value = value
250
+ }
251
+ }
252
+
253
+ final class InputSuppressionGuard {
254
+ static let maxSuppressionSeconds: TimeInterval = 30
255
+
256
+ private let lock = NSLock()
257
+ private var eventTap: CFMachPort?
258
+ private var eventTapSource: CFRunLoopSource?
259
+ private var tapRunLoop: CFRunLoop?
260
+ private var tapThread: Thread?
261
+
262
+ func begin() throws {
263
+ lock.lock()
264
+ if eventTap != nil {
265
+ lock.unlock()
266
+ return
267
+ }
268
+ lock.unlock()
269
+
270
+ let eventTypes: [CGEventType] = [
271
+ .keyDown,
272
+ .keyUp,
273
+ .flagsChanged,
274
+ .leftMouseDown,
275
+ .leftMouseUp,
276
+ .rightMouseDown,
277
+ .rightMouseUp,
278
+ .otherMouseDown,
279
+ .otherMouseUp,
280
+ .mouseMoved,
281
+ .leftMouseDragged,
282
+ .rightMouseDragged,
283
+ .otherMouseDragged,
284
+ .scrollWheel,
285
+ .tabletPointer,
286
+ .tabletProximity,
287
+ ]
288
+ let mask = eventTypes.reduce(CGEventMask(0)) { partial, type in
289
+ partial | (CGEventMask(1) << CGEventMask(type.rawValue))
290
+ }
291
+
292
+ let callback: CGEventTapCallBack = { _proxy, type, event, userInfo in
293
+ guard let userInfo else { return Unmanaged.passUnretained(event) }
294
+ let inputGuard = Unmanaged<InputSuppressionGuard>.fromOpaque(userInfo).takeUnretainedValue()
295
+ if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
296
+ inputGuard.reenableTap()
297
+ return Unmanaged.passUnretained(event)
298
+ }
299
+ return nil
300
+ }
301
+
302
+ guard let tap = CGEvent.tapCreate(
303
+ tap: .cgSessionEventTap,
304
+ place: .headInsertEventTap,
305
+ options: .defaultTap,
306
+ eventsOfInterest: mask,
307
+ callback: callback,
308
+ // passUnretained is only safe because Bridge owns this guard for the
309
+ // whole process lifetime; do not give it a shorter-lived owner.
310
+ userInfo: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
311
+ ) else {
312
+ throw BridgeFailure(message: "Failed to create input suppression event tap", code: "input_suppression_unavailable")
313
+ }
314
+
315
+ lock.lock()
316
+ eventTap = tap
317
+ lock.unlock()
318
+ let thread = Thread { [weak self] in
319
+ guard let self else { return }
320
+ let runLoop = CFRunLoopGetCurrent()
321
+ self.lock.lock()
322
+ self.tapRunLoop = runLoop
323
+ self.eventTapSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)
324
+ if let source = self.eventTapSource {
325
+ CFRunLoopAddSource(runLoop, source, .commonModes)
326
+ }
327
+ // Watchdog: if end() never arrives (e.g. the parent process hangs
328
+ // mid-action), release the tap so the user is not locked out of
329
+ // keyboard and mouse input indefinitely.
330
+ let watchdog = CFRunLoopTimerCreateWithHandler(
331
+ kCFAllocatorDefault,
332
+ CFAbsoluteTimeGetCurrent() + InputSuppressionGuard.maxSuppressionSeconds,
333
+ 0,
334
+ 0,
335
+ 0
336
+ ) { [weak self] _ in
337
+ self?.end()
338
+ }
339
+ if let watchdog {
340
+ CFRunLoopAddTimer(runLoop, watchdog, .commonModes)
341
+ }
342
+ CGEvent.tapEnable(tap: tap, enable: true)
343
+ self.lock.unlock()
344
+ CFRunLoopRun()
345
+ }
346
+ thread.name = "pi-computer-use-input-suppression"
347
+ lock.lock()
348
+ tapThread = thread
349
+ lock.unlock()
350
+ thread.start()
351
+
352
+ let deadline = Date().addingTimeInterval(1.0)
353
+ while tapRunLoop == nil && Date() < deadline {
354
+ Thread.sleep(forTimeInterval: 0.01)
355
+ }
356
+ if tapRunLoop == nil {
357
+ end()
358
+ throw BridgeFailure(message: "Timed out starting input suppression", code: "input_suppression_timeout")
359
+ }
360
+ }
361
+
362
+ func end() {
363
+ lock.lock()
364
+ let tap = eventTap
365
+ let source = eventTapSource
366
+ let runLoop = tapRunLoop
367
+ eventTap = nil
368
+ eventTapSource = nil
369
+ tapRunLoop = nil
370
+ tapThread = nil
371
+ lock.unlock()
372
+
373
+ if let tap {
374
+ CGEvent.tapEnable(tap: tap, enable: false)
375
+ }
376
+ if let source, let runLoop {
377
+ CFRunLoopRemoveSource(runLoop, source, .commonModes)
378
+ CFRunLoopStop(runLoop)
379
+ }
380
+ }
381
+
382
+ func reenableTap() {
383
+ lock.lock()
384
+ let tap = eventTap
385
+ lock.unlock()
386
+ if let tap {
387
+ CGEvent.tapEnable(tap: tap, enable: true)
388
+ }
389
+ }
390
+
391
+ }
392
+
393
+ final class Bridge {
394
+ private let protocolVersion = 7
395
+ private let refStore = AXRefStore()
396
+ private let activityGlow = ActivityGlowController()
397
+ private let inputSuppressionGuard = InputSuppressionGuard()
398
+ private let physicalInputLock = NSRecursiveLock()
399
+ private let supportsAgentCursor = CommandLine.arguments.contains("serve")
400
+ private let browserBundleIds: Set<String> = [
401
+ "com.apple.Safari", "com.google.Chrome", "org.chromium.Chromium", "company.thebrowser.Browser", "com.brave.Browser", "com.microsoft.edgemac", "com.vivaldi.Vivaldi", "net.imput.helium", "org.mozilla.firefox",
402
+ ]
403
+ private var enhancedAccessibilityPids = Set<Int32>()
404
+ private let enhancedAccessibilityLock = NSLock()
405
+ private var stdinBuffer = Data()
406
+ private var output = FileHandle.standardOutput
407
+ private var nextLookId: UInt64 = 0
408
+ private var lookRecords: [String: LookRecord] = [:]
409
+ private var lookRecordOrder: [String] = []
410
+ private let lookRecordLock = NSLock()
411
+ private let rootObserverLock = NSLock()
412
+ private var rootObservers: [Int32: RootAXObserverState] = [:]
413
+ private let maxRootObservers = 4
414
+ private let permissionCacheLock = NSLock()
415
+ private var grantedPermissionStatus: [String: Any]?
416
+ private let completedRequestLock = NSLock()
417
+ private var recentCompletedRequestIds: [String] = []
418
+
419
+ func run() {
420
+ if CommandLine.arguments.contains("serve") {
421
+ let socketPath = argumentValue("--socket") ?? defaultSocketPath()
422
+ Thread.detachNewThread { [self] in runServer(socketPath: socketPath) }
423
+ NSApp.run()
424
+ return
425
+ }
426
+ while true {
427
+ autoreleasepool {
428
+ let data = FileHandle.standardInput.availableData
429
+ if data.isEmpty {
430
+ exit(0)
431
+ }
432
+ stdinBuffer.append(data)
433
+ processBufferedInput()
434
+ }
435
+ }
436
+ }
437
+
438
+ private func argumentValue(_ name: String) -> String? {
439
+ guard let index = CommandLine.arguments.firstIndex(of: name), CommandLine.arguments.indices.contains(index + 1) else { return nil }
440
+ return CommandLine.arguments[index + 1]
441
+ }
442
+
443
+ private func defaultSocketPath() -> String {
444
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
445
+ return "\(home)/Library/Caches/pi-computer-use/bridge.sock"
446
+ }
447
+
448
+ private func runServer(socketPath: String) {
449
+ _ = signal(SIGPIPE, SIG_IGN)
450
+ try? FileManager.default.createDirectory(atPath: (socketPath as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
451
+ // LaunchServices may race multiple `open -n` requests while the first
452
+ // daemon is still binding. Keep process ownership separate from socket
453
+ // cleanup so a late launcher can never unlink the live daemon's socket.
454
+ let lockPath = "\(socketPath).lock"
455
+ let lockFile = open(lockPath, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
456
+ if lockFile < 0 || flock(lockFile, LOCK_EX | LOCK_NB) != 0 {
457
+ if lockFile >= 0 { close(lockFile) }
458
+ exit(0)
459
+ }
460
+ unlink(socketPath)
461
+ let server = socket(AF_UNIX, SOCK_STREAM, 0)
462
+ if server < 0 { close(lockFile); exit(1) }
463
+ var address = sockaddr_un()
464
+ address.sun_family = sa_family_t(AF_UNIX)
465
+ let sunPathCapacity = MemoryLayout.size(ofValue: address.sun_path)
466
+ let bytes = Array(socketPath.utf8.prefix(sunPathCapacity - 1))
467
+ withUnsafeMutablePointer(to: &address.sun_path) { pointer in
468
+ pointer.withMemoryRebound(to: CChar.self, capacity: sunPathCapacity) { dest in
469
+ for (index, byte) in bytes.enumerated() { dest[index] = CChar(bitPattern: byte) }
470
+ }
471
+ }
472
+ let bindStatus = withUnsafePointer(to: &address) { pointer in
473
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(server, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
474
+ }
475
+ if bindStatus != 0 || listen(server, 8) != 0 { close(server); close(lockFile); exit(1) }
476
+ while true {
477
+ let client = accept(server, nil, nil)
478
+ if client < 0 { continue }
479
+ var noSigPipe: Int32 = 1
480
+ _ = setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout.size(ofValue: noSigPipe)))
481
+ Thread.detachNewThread { [weak self] in self?.processClient(client) }
482
+ }
483
+ }
484
+
485
+ private func processClient(_ client: Int32) {
486
+ let clientID = UUID()
487
+ defer { activityGlow.disconnect(clientID) }
488
+ let clientInput = FileHandle(fileDescriptor: client, closeOnDealloc: true)
489
+ var buffer = Data()
490
+ let newline = Data([0x0A])
491
+ while true {
492
+ let data = clientInput.availableData
493
+ if data.isEmpty { break }
494
+ buffer.append(data)
495
+ while let range = buffer.range(of: newline) {
496
+ let lineData = buffer.subdata(in: 0..<range.lowerBound)
497
+ buffer.removeSubrange(0..<range.upperBound)
498
+ if let line = String(data: lineData, encoding: .utf8), !line.isEmpty { handleLine(line, to: client, clientID: clientID) }
499
+ }
500
+ }
501
+ clientInput.closeFile()
502
+ }
503
+
504
+ private func processBufferedInput() {
505
+ let newline = Data([0x0A])
506
+ while let range = stdinBuffer.range(of: newline) {
507
+ let lineData = stdinBuffer.subdata(in: 0..<range.lowerBound)
508
+ stdinBuffer.removeSubrange(0..<range.upperBound)
509
+
510
+ guard !lineData.isEmpty else { continue }
511
+ guard let line = String(data: lineData, encoding: .utf8) else { continue }
512
+ handleLine(line)
513
+ }
514
+ }
515
+
516
+ private func handleLine(_ line: String, to responseSocket: Int32? = nil, clientID: UUID? = nil) {
517
+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
518
+ guard !trimmed.isEmpty else { return }
519
+
520
+ let fallbackId = "invalid"
521
+ var completionId: String?
522
+ defer {
523
+ if responseSocket != nil, let completionId { recordCompletedRequest(completionId) }
524
+ }
525
+ do {
526
+ guard let jsonData = trimmed.data(using: .utf8) else {
527
+ throw BridgeFailure(message: "Input was not valid UTF-8", code: "invalid_request")
528
+ }
529
+ guard let object = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else {
530
+ throw BridgeFailure(message: "Request must be a JSON object", code: "invalid_request")
531
+ }
532
+ let id = (object["id"] as? String) ?? fallbackId
533
+ completionId = id
534
+
535
+ do {
536
+ let result = try handleRequest(object, clientID: clientID)
537
+ send([
538
+ "id": id,
539
+ "ok": true,
540
+ "result": result,
541
+ ], to: responseSocket)
542
+ } catch let failure as BridgeFailure {
543
+ send([
544
+ "id": id,
545
+ "ok": false,
546
+ "error": [
547
+ "message": failure.message,
548
+ "code": failure.code,
549
+ ],
550
+ ], to: responseSocket)
551
+ } catch {
552
+ send([
553
+ "id": id,
554
+ "ok": false,
555
+ "error": [
556
+ "message": error.localizedDescription,
557
+ "code": "internal_error",
558
+ ],
559
+ ], to: responseSocket)
560
+ }
561
+ } catch let failure as BridgeFailure {
562
+ send([
563
+ "id": fallbackId,
564
+ "ok": false,
565
+ "error": [
566
+ "message": failure.message,
567
+ "code": failure.code,
568
+ ],
569
+ ], to: responseSocket)
570
+ } catch {
571
+ send([
572
+ "id": fallbackId,
573
+ "ok": false,
574
+ "error": [
575
+ "message": error.localizedDescription,
576
+ "code": "internal_error",
577
+ ],
578
+ ], to: responseSocket)
579
+ }
580
+ }
581
+
582
+ private func send(_ payload: [String: Any], to responseSocket: Int32? = nil) {
583
+ guard JSONSerialization.isValidJSONObject(payload),
584
+ let data = try? JSONSerialization.data(withJSONObject: payload),
585
+ let line = String(data: data, encoding: .utf8),
586
+ let out = (line + "\n").data(using: .utf8)
587
+ else {
588
+ return
589
+ }
590
+
591
+ guard let responseSocket else {
592
+ try? output.write(contentsOf: out)
593
+ return
594
+ }
595
+ out.withUnsafeBytes { raw in
596
+ guard let base = raw.baseAddress else { return }
597
+ var offset = 0
598
+ while offset < raw.count {
599
+ let sent = Darwin.send(responseSocket, base.advanced(by: offset), raw.count - offset, 0)
600
+ if sent <= 0 { return }
601
+ offset += sent
602
+ }
603
+ }
604
+ }
605
+
606
+ private func recordCompletedRequest(_ id: String) {
607
+ completedRequestLock.lock()
608
+ recentCompletedRequestIds.removeAll { $0 == id }
609
+ recentCompletedRequestIds.append(id)
610
+ if recentCompletedRequestIds.count > 32 {
611
+ recentCompletedRequestIds.removeFirst(recentCompletedRequestIds.count - 32)
612
+ }
613
+ completedRequestLock.unlock()
614
+ }
615
+
616
+ private func completedRequestIds() -> [String] {
617
+ completedRequestLock.lock()
618
+ defer { completedRequestLock.unlock() }
619
+ return recentCompletedRequestIds
620
+ }
621
+
622
+ private func handleRequest(_ request: [String: Any], clientID: UUID?) throws -> Any {
623
+ let cmd = try stringArg(request, "cmd")
624
+
625
+ switch cmd {
626
+ case "diagnostics":
627
+ return diagnostics()
628
+ case "checkPermissions":
629
+ return checkPermissions()
630
+ case "registerPermissions":
631
+ return try registerPermissions()
632
+ case "openPermissionPane":
633
+ return try openPermissionPane(request)
634
+ case "setActivityGlow":
635
+ guard let clientID, let active = boolArg(request, "active") else {
636
+ throw BridgeFailure(message: "Activity glow requires a connected client and boolean 'active' value", code: "invalid_args")
637
+ }
638
+ activityGlow.setActive(active, for: clientID)
639
+ return ["active": active]
640
+ case "shutdown":
641
+ // Reply first, then exit: the caller relaunches the helper to get a
642
+ // process with a fresh TCC client (grant answers are cached per
643
+ // process, so a helper that saw "denied" keeps answering "denied"
644
+ // after the user grants — only a new process re-queries tccd).
645
+ // Background queue: the serve loop occupies the main thread, so a
646
+ // main-queue timer would never fire.
647
+ DispatchQueue.global().asyncAfter(deadline: .now() + 0.2) { exit(0) }
648
+ return ["shuttingDown": true]
649
+ case "listApps":
650
+ return listApps()
651
+ case "listWindows":
652
+ return try listWindows(pid: Int32(try intArg(request, "pid")))
653
+ case "listRoots":
654
+ return try listRoots(pid: optionalIntArg(request, "pid").map { Int32($0) }, title: optionalStringArg(request, "title"))
655
+ case "getFrontmost":
656
+ return try getFrontmost()
657
+ case "getUserContext":
658
+ return try getUserContext()
659
+ case "beginInputSuppression":
660
+ return try beginInputSuppression()
661
+ case "endInputSuppression":
662
+ return endInputSuppression()
663
+ case "restoreUserFocus":
664
+ return try restoreUserFocus(request)
665
+ case "focusWindow":
666
+ return try focusWindow(request)
667
+ case "setWindowFrame":
668
+ return try setWindowFrame(request)
669
+ case "look":
670
+ return try look(request)
671
+ case "act":
672
+ return try act(request)
673
+ case "actBatch":
674
+ return try actBatch(request)
675
+ case "hitTest":
676
+ return try hitTest(request)
677
+ case "axWaitFor":
678
+ return try axWaitFor(request)
679
+ case "focusedElement":
680
+ return try focusedElement(request)
681
+ case "axReadText":
682
+ return try axReadText(request)
683
+ case "getMousePosition":
684
+ return getMousePosition()
685
+ default:
686
+ throw BridgeFailure(message: "Unknown command '\(cmd)'", code: "unknown_command")
687
+ }
688
+ }
689
+
690
+ private func stringArg(_ request: [String: Any], _ key: String) throws -> String {
691
+ if let value = request[key] as? String {
692
+ return value
693
+ }
694
+ throw BridgeFailure(message: "Missing string argument '\(key)'", code: "invalid_args")
695
+ }
696
+
697
+ private func optionalStringArg(_ request: [String: Any], _ key: String) -> String? {
698
+ if let value = request[key] as? String {
699
+ return value
700
+ }
701
+ return nil
702
+ }
703
+
704
+ private func intArg(_ request: [String: Any], _ key: String) throws -> Int {
705
+ if let value = request[key] as? Int {
706
+ return value
707
+ }
708
+ if let value = request[key] as? NSNumber {
709
+ return value.intValue
710
+ }
711
+ if let value = request[key] as? Double {
712
+ return Int(value)
713
+ }
714
+ throw BridgeFailure(message: "Missing integer argument '\(key)'", code: "invalid_args")
715
+ }
716
+
717
+ private func positiveWindowId(_ request: [String: Any]) -> UInt32? {
718
+ guard let value = optionalIntArg(request, "windowId"), value > 0 else { return nil }
719
+ return UInt32(value)
720
+ }
721
+
722
+ private func optionalIntArg(_ request: [String: Any], _ key: String) -> Int? {
723
+ if let value = request[key] as? Int {
724
+ return value
725
+ }
726
+ if let value = request[key] as? NSNumber {
727
+ return value.intValue
728
+ }
729
+ if let value = request[key] as? Double {
730
+ return Int(value)
731
+ }
732
+ return nil
733
+ }
734
+
735
+ private func boolArg(_ request: [String: Any], _ key: String) -> Bool? {
736
+ if let value = request[key] as? Bool { return value }
737
+ if let value = request[key] as? NSNumber { return value.boolValue }
738
+ return nil
739
+ }
740
+
741
+ private func doubleArg(_ request: [String: Any], _ key: String) throws -> Double {
742
+ if let value = request[key] as? Double {
743
+ return value
744
+ }
745
+ if let value = request[key] as? NSNumber {
746
+ return value.doubleValue
747
+ }
748
+ if let value = request[key] as? Int {
749
+ return Double(value)
750
+ }
751
+ throw BridgeFailure(message: "Missing numeric argument '\(key)'", code: "invalid_args")
752
+ }
753
+
754
+ private func processPath(pid: pid_t) -> String? {
755
+ var buffer = [CChar](repeating: 0, count: 4096)
756
+ let length = proc_pidpath(pid, &buffer, UInt32(buffer.count))
757
+ return length > 0 ? String(cString: buffer) : nil
758
+ }
759
+
760
+ private func processName(pid: pid_t) -> String? {
761
+ processPath(pid: pid).map { URL(fileURLWithPath: $0).deletingPathExtension().lastPathComponent }
762
+ }
763
+
764
+ private func diagnostics() -> [String: Any] {
765
+ // Cheap booleans only — diagnostics doubles as the daemon liveness
766
+ // probe (1s client timeout), so it must not run the ScreenCaptureKit
767
+ // capturable check (up to 3s when ungranted). Permission truth comes
768
+ // from checkPermissions.
769
+ let permissions: [String: Any] = [
770
+ "accessibility": AXIsProcessTrusted(),
771
+ "screenRecording": {
772
+ if #available(macOS 10.15, *) { return CGPreflightScreenCaptureAccess() }
773
+ return true
774
+ }(),
775
+ ]
776
+ #if arch(arm64)
777
+ let arch = "arm64"
778
+ #elseif arch(x86_64)
779
+ let arch = "x86_64"
780
+ #else
781
+ let arch = "unknown"
782
+ #endif
783
+ let parentPid = Int32(getppid())
784
+ let parentApp = NSRunningApplication(processIdentifier: parentPid)
785
+ let parentPath = processPath(pid: parentPid)
786
+ var output: [String: Any] = [
787
+ "protocolVersion": protocolVersion,
788
+ "architectureVersion": 1,
789
+ "invariants": ["state-scoped-observations", "bounded-observation-history", "multi-root-forest", "progressive-disclosure", "atomic-physical-input", "concurrent-requests", "transactional-batching"],
790
+ "pid": Int32(getpid()),
791
+ "parentPid": parentPid,
792
+ "executablePath": CommandLine.arguments.first ?? "",
793
+ "macOS": ProcessInfo.processInfo.operatingSystemVersionString,
794
+ "arch": arch,
795
+ "accessibility": permissions["accessibility"] ?? false,
796
+ "screenRecording": permissions["screenRecording"] ?? false,
797
+ "activityGlowActive": activityGlow.isActive,
798
+ "recentCompletedRequestIds": completedRequestIds(),
799
+ ]
800
+ if let parentPath {
801
+ output["parentPath"] = parentPath
802
+ }
803
+ if let parentAppName = parentApp?.localizedName ?? parentPath.map({ URL(fileURLWithPath: $0).lastPathComponent }) {
804
+ output["parentAppName"] = parentAppName
805
+ }
806
+ if let parentBundleId = parentApp?.bundleIdentifier {
807
+ output["parentBundleId"] = parentBundleId
808
+ }
809
+ return output
810
+ }
811
+
812
+ /// Live Screen Recording probe. `CGPreflightScreenCaptureAccess()`
813
+ /// answers from a per-process cache that goes stale after `tccutil
814
+ /// reset` or a Settings toggle; a ScreenCaptureKit content fetch only
815
+ /// succeeds when THIS process can genuinely capture right now. When the
816
+ /// two disagree, the preflight boolean is the one lying.
817
+ private func screenRecordingCapturable() -> Bool {
818
+ if #available(macOS 14.0, *) {
819
+ let sema = DispatchSemaphore(value: 0)
820
+ let capturable = Box<Bool>(false)
821
+ SCShareableContent.getExcludingDesktopWindows(false, onScreenWindowsOnly: false) { shareable, error in
822
+ if let shareable = shareable {
823
+ capturable.value = !shareable.displays.isEmpty
824
+ }
825
+ sema.signal()
826
+ }
827
+ guard sema.wait(timeout: .now() + .seconds(5)) == .success else { return false }
828
+ return capturable.value
829
+ }
830
+ if #available(macOS 10.15, *) {
831
+ return CGPreflightScreenCaptureAccess()
832
+ }
833
+ return true
834
+ }
835
+
836
+ /// Which TCC identity the permission booleans reflect. macOS attributes
837
+ /// grants to the *responsible process* (the LaunchServices launching
838
+ /// app), so:
839
+ /// - "helper-app": running from the installed bundle, launched via
840
+ /// LaunchServices — grants belong to the canonical helper identity.
841
+ /// - "caller": anything else (dev binary under a terminal, etc.) —
842
+ /// the booleans reflect whatever app spawned us, NOT the canonical
843
+ /// helper. The extension surfaces this instead of guessing.
844
+ private func permissionSource() -> [String: Any] {
845
+ let parentPid = Int32(getppid())
846
+ let executable = CommandLine.arguments.first ?? ""
847
+ var source: [String: Any] = [
848
+ "pid": Int(getpid()),
849
+ "parentPid": Int(parentPid),
850
+ "executablePath": executable,
851
+ "macOS": ProcessInfo.processInfo.operatingSystemVersionString,
852
+ ]
853
+ if let parentPath = processPath(pid: parentPid) {
854
+ source["parentPath"] = parentPath
855
+ }
856
+ if let parentBundleId = NSRunningApplication(processIdentifier: parentPid)?.bundleIdentifier {
857
+ source["parentBundleId"] = parentBundleId
858
+ }
859
+ let attribution: String
860
+ if executable.contains("/pi-computer-use.app/Contents/MacOS/"), parentPid == 1 {
861
+ // Non-spoofable signals only: installed-bundle executable path +
862
+ // launchd parent (`open` handed us to LaunchServices). A dev
863
+ // binary or a directly-spawned copy fails closed to "caller".
864
+ attribution = "helper-app"
865
+ } else {
866
+ attribution = "caller"
867
+ }
868
+ source["attribution"] = attribution
869
+ return source
870
+ }
871
+
872
+ private func checkPermissions() -> [String: Any] {
873
+ permissionCacheLock.lock()
874
+ if let cached = grantedPermissionStatus {
875
+ permissionCacheLock.unlock()
876
+ return cached
877
+ }
878
+ permissionCacheLock.unlock()
879
+ let accessibility = AXIsProcessTrusted()
880
+ let screenRecordingPreflight: Bool
881
+ if #available(macOS 10.15, *) {
882
+ screenRecordingPreflight = CGPreflightScreenCaptureAccess()
883
+ } else {
884
+ screenRecordingPreflight = true
885
+ }
886
+ let capturable = screenRecordingCapturable()
887
+ let result: [String: Any] = [
888
+ "accessibility": accessibility,
889
+ // The live probe is authoritative; the preflight boolean is kept
890
+ // for diagnostics (a true/false split identifies a stale cache or
891
+ // a grant belonging to a different responsible process).
892
+ "screenRecording": capturable,
893
+ "screenRecordingPreflight": screenRecordingPreflight,
894
+ "screenRecordingCapturable": capturable,
895
+ "source": permissionSource(),
896
+ ]
897
+ // A successful TCC grant is process-stable in practice. Cache only the
898
+ // positive result so missing grants are always rechecked after the user
899
+ // enables them, while fresh agent processes avoid repeating a multi-second
900
+ // ScreenCaptureKit probe against the same long-lived helper daemon.
901
+ if accessibility && capturable {
902
+ permissionCacheLock.lock()
903
+ grantedPermissionStatus = result
904
+ permissionCacheLock.unlock()
905
+ }
906
+ return result
907
+ }
908
+
909
+ /// Register this process's identity with TCC for both grants so the app
910
+ /// appears in the Settings panes BEFORE the user is sent there. The AX
911
+ /// request registers (and prompts for) Accessibility; on recent macOS an
912
+ /// app only appears under Screen Recording after a real ScreenCaptureKit
913
+ /// attempt, which the capturable probe performs.
914
+ private func registerPermissions() throws -> [String: Any] {
915
+ let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
916
+ let accessibility = AXIsProcessTrustedWithOptions(options)
917
+ if #available(macOS 10.15, *) {
918
+ _ = CGRequestScreenCaptureAccess()
919
+ }
920
+ let capturable = screenRecordingCapturable()
921
+ return [
922
+ "accessibility": accessibility,
923
+ "screenRecording": capturable,
924
+ "screenRecordingCapturable": capturable,
925
+ ]
926
+ }
927
+
928
+ private func openPermissionPane(_ request: [String: Any]) throws -> [String: Any] {
929
+ let kind = try stringArg(request, "kind")
930
+ let urlString: String
931
+ switch kind {
932
+ case "accessibility":
933
+ urlString = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
934
+ case "screenRecording", "screenrecording":
935
+ urlString = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
936
+ default:
937
+ throw BridgeFailure(message: "Unknown permission pane '\(kind)'", code: "invalid_args")
938
+ }
939
+
940
+ guard let url = URL(string: urlString) else {
941
+ throw BridgeFailure(message: "Invalid permission pane URL", code: "internal_error")
942
+ }
943
+ let opened = NSWorkspace.shared.open(url)
944
+ return ["opened": opened]
945
+ }
946
+
947
+ private func pidIsAlive(_ pid: pid_t) -> Bool {
948
+ pid > 0 && kill(pid, 0) == 0
949
+ }
950
+
951
+ private func listApps(cgEntries: [[String: Any]]? = nil) -> [[String: Any]] {
952
+ let frontmostPid = NSWorkspace.shared.frontmostApplication?.processIdentifier
953
+ let apps = NSWorkspace.shared.runningApplications.filter { app in
954
+ // Computer-use targets are windows, not Dock-visible applications. Some
955
+ // benchmark/test apps and utility-style apps expose perfectly valid AX
956
+ // windows while using an accessory/prohibited activation policy, so do not
957
+ // gate discovery on `.regular` here. `listWindows` and the higher-level
958
+ // window collector filter to actual controllable windows.
959
+ app.processIdentifier != getpid() && pidIsAlive(app.processIdentifier)
960
+ }
961
+ var seen = Set<Int32>()
962
+ var output = apps.map { app in
963
+ seen.insert(app.processIdentifier)
964
+ var data: [String: Any] = [
965
+ "appName": app.localizedName ?? processName(pid: app.processIdentifier) ?? "Unknown App",
966
+ "pid": Int(app.processIdentifier),
967
+ "isFrontmost": app.processIdentifier == frontmostPid,
968
+ ]
969
+ if let bundleId = app.bundleIdentifier {
970
+ data["bundleId"] = bundleId
971
+ }
972
+ return data
973
+ }
974
+
975
+ // NSWorkspace can miss apps launched from ad-hoc bundles or test harnesses
976
+ // even when their windows are visible and AX-controllable. Add CGWindow
977
+ // owners as acquisition candidates so callers can still resolve by pid/title
978
+ // and then build the normal AX scene through listWindows(pid:).
979
+ for owner in cgWindowOwners(entries: cgEntries) where owner.pid != getpid() && !seen.contains(owner.pid) && pidIsAlive(owner.pid) {
980
+ seen.insert(owner.pid)
981
+ output.append([
982
+ "appName": owner.name,
983
+ "pid": Int(owner.pid),
984
+ "isFrontmost": owner.pid == frontmostPid,
985
+ ])
986
+ }
987
+ return output
988
+ }
989
+
990
+ private func getFrontmost() throws -> [String: Any] {
991
+ guard let app = NSWorkspace.shared.frontmostApplication else {
992
+ throw BridgeFailure(message: "No frontmost app available", code: "frontmost_unavailable")
993
+ }
994
+ let pid = app.processIdentifier
995
+ let windows = try listWindows(pid: pid)
996
+
997
+ var result: [String: Any] = [
998
+ "appName": app.localizedName ?? "Unknown App",
999
+ "pid": Int(pid),
1000
+ ]
1001
+ if let bundleId = app.bundleIdentifier {
1002
+ result["bundleId"] = bundleId
1003
+ }
1004
+
1005
+ if let chosen = windows.sorted(by: { scoreWindow($0) > scoreWindow($1) }).first {
1006
+ result["windowTitle"] = (chosen["title"] as? String) ?? ""
1007
+ if let windowId = chosen["windowId"] {
1008
+ result["windowId"] = windowId
1009
+ }
1010
+ if let windowRef = chosen["windowRef"] as? String {
1011
+ result["windowRef"] = windowRef
1012
+ }
1013
+ }
1014
+ return result
1015
+ }
1016
+
1017
+ private func getUserContext() throws -> [String: Any] {
1018
+ guard let app = NSWorkspace.shared.frontmostApplication else {
1019
+ throw BridgeFailure(message: "No frontmost app available", code: "frontmost_unavailable")
1020
+ }
1021
+ let pid = app.processIdentifier
1022
+ ensureEnhancedAccessibility(pid: pid)
1023
+ let appElement = AXUIElementCreateApplication(pid)
1024
+ let focusedWindow = copyAttribute(appElement, attribute: kAXFocusedWindowAttribute as CFString).flatMap(asAXElement)
1025
+ let focusedElement = copyAttribute(appElement, attribute: kAXFocusedUIElementAttribute as CFString).flatMap(asAXElement)
1026
+ var result: [String: Any] = [
1027
+ "appName": app.localizedName ?? "Unknown App",
1028
+ "pid": Int(pid),
1029
+ ]
1030
+ if let bundleId = app.bundleIdentifier {
1031
+ result["bundleId"] = bundleId
1032
+ }
1033
+ if let window = focusedWindow {
1034
+ result["window"] = [
1035
+ "title": stringAttribute(window, attribute: kAXTitleAttribute as CFString) ?? "",
1036
+ "role": stringAttribute(window, attribute: kAXRoleAttribute as CFString) ?? "",
1037
+ "subrole": stringAttribute(window, attribute: kAXSubroleAttribute as CFString) ?? "",
1038
+ ]
1039
+ }
1040
+ if let element = focusedElement {
1041
+ let focusedRole = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
1042
+ let focusedSubrole = stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
1043
+ result["focusedElement"] = [
1044
+ "role": focusedRole,
1045
+ "subrole": focusedSubrole,
1046
+ "title": stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? "",
1047
+ "description": stringAttribute(element, attribute: kAXDescriptionAttribute as CFString) ?? "",
1048
+ "value": displayValue(element, role: focusedRole, subrole: focusedSubrole),
1049
+ ]
1050
+ }
1051
+ return result
1052
+ }
1053
+
1054
+ private func beginInputSuppression() throws -> [String: Any] {
1055
+ try inputSuppressionGuard.begin()
1056
+ return ["active": true]
1057
+ }
1058
+
1059
+ private func endInputSuppression() -> [String: Any] {
1060
+ inputSuppressionGuard.end()
1061
+ return ["active": false]
1062
+ }
1063
+
1064
+ private func restoreUserFocus(_ request: [String: Any]) throws -> [String: Any] {
1065
+ let pid = Int32(try intArg(request, "pid"))
1066
+ let targetTitle = optionalStringArg(request, "windowTitle")?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
1067
+ guard let app = NSRunningApplication(processIdentifier: pid) else {
1068
+ throw BridgeFailure(message: "App with pid \(pid) is no longer running", code: "app_not_found")
1069
+ }
1070
+
1071
+ let appRestored = app.activate()
1072
+ var restoredWindowTitle = ""
1073
+ var windowRestored = false
1074
+
1075
+ if !targetTitle.isEmpty {
1076
+ let appElement = AXUIElementCreateApplication(pid)
1077
+ let windows = axElementArray(appElement, attribute: kAXWindowsAttribute as CFString)
1078
+ let normalizedTarget = targetTitle.lowercased()
1079
+ if let match = windows.first(where: {
1080
+ (stringAttribute($0, attribute: kAXTitleAttribute as CFString) ?? "")
1081
+ .trimmingCharacters(in: .whitespacesAndNewlines)
1082
+ .lowercased() == normalizedTarget
1083
+ }) {
1084
+ restoredWindowTitle = stringAttribute(match, attribute: kAXTitleAttribute as CFString) ?? ""
1085
+ let setMainStatus = AXUIElementSetAttributeValue(match, kAXMainAttribute as CFString, kCFBooleanTrue)
1086
+ let setFocusedStatus = AXUIElementSetAttributeValue(match, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1087
+ let raiseStatus = AXUIElementPerformAction(match, kAXRaiseAction as CFString)
1088
+ windowRestored = setMainStatus == .success || setFocusedStatus == .success || raiseStatus == .success
1089
+ }
1090
+ }
1091
+
1092
+ return [
1093
+ "restored": appRestored || windowRestored,
1094
+ "appRestored": appRestored,
1095
+ "windowRestored": windowRestored,
1096
+ "appName": app.localizedName ?? "Unknown App",
1097
+ "windowTitle": restoredWindowTitle,
1098
+ ]
1099
+ }
1100
+
1101
+ private func setWindowFrame(_ request: [String: Any]) throws -> [String: Any] {
1102
+ let pid = Int32(try intArg(request, "pid"))
1103
+ let windowId = optionalIntArg(request, "windowId").map { UInt32($0) }
1104
+ let windowRef = optionalStringArg(request, "windowRef")
1105
+ guard let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef) else {
1106
+ return ["ok": false, "reason": "window_not_found"]
1107
+ }
1108
+ let x = try doubleArg(request, "x")
1109
+ let y = try doubleArg(request, "y")
1110
+ let width = max(100.0, try doubleArg(request, "width"))
1111
+ let height = max(80.0, try doubleArg(request, "height"))
1112
+ var origin = CGPoint(x: x, y: y)
1113
+ var size = CGSize(width: width, height: height)
1114
+ guard let originValue = AXValueCreate(.cgPoint, &origin), let sizeValue = AXValueCreate(.cgSize, &size) else {
1115
+ throw BridgeFailure(message: "Failed to create AX frame values", code: "frame_value_failed")
1116
+ }
1117
+ let positionStatus = AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, originValue)
1118
+ let sizeStatus = AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, sizeValue)
1119
+ let frame = frameForWindow(window)
1120
+ return [
1121
+ "ok": positionStatus == .success || sizeStatus == .success,
1122
+ "positionStatus": Int(positionStatus.rawValue),
1123
+ "sizeStatus": Int(sizeStatus.rawValue),
1124
+ "framePoints": ["x": frame.origin.x, "y": frame.origin.y, "w": frame.width, "h": frame.height],
1125
+ ]
1126
+ }
1127
+
1128
+ private func focusWindow(_ request: [String: Any]) throws -> [String: Any] {
1129
+ let pid = Int32(try intArg(request, "pid"))
1130
+ let windowId = positiveWindowId(request)
1131
+ let windowRef = optionalStringArg(request, "windowRef")
1132
+ guard let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef) else {
1133
+ return ["focused": false, "reason": "window_not_found"]
1134
+ }
1135
+
1136
+ let appElement = AXUIElementCreateApplication(pid)
1137
+ if let focusedWindow = copyAttribute(appElement, attribute: kAXFocusedWindowAttribute as CFString).flatMap(asAXElement),
1138
+ sameElement(focusedWindow, window)
1139
+ {
1140
+ return ["focused": true, "alreadyFocused": true]
1141
+ }
1142
+
1143
+ let setMainStatus = AXUIElementSetAttributeValue(window, kAXMainAttribute as CFString, kCFBooleanTrue)
1144
+ let setFocusedStatus = AXUIElementSetAttributeValue(window, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1145
+ let raiseStatus = AXUIElementPerformAction(window, kAXRaiseAction as CFString)
1146
+ let focused = setMainStatus == .success || setFocusedStatus == .success || raiseStatus == .success
1147
+ var result: [String: Any] = [
1148
+ "focused": focused,
1149
+ "setMain": setMainStatus == .success,
1150
+ "setFocused": setFocusedStatus == .success,
1151
+ "raised": raiseStatus == .success,
1152
+ ]
1153
+ if !focused {
1154
+ result["reason"] = "focus_failed"
1155
+ }
1156
+ return result
1157
+ }
1158
+
1159
+ private func scoreWindow(_ window: [String: Any]) -> Int {
1160
+ var score = 0
1161
+ if (window["isFocused"] as? Bool) == true { score += 100 }
1162
+ if (window["isMain"] as? Bool) == true { score += 80 }
1163
+ if (window["isMinimized"] as? Bool) == false { score += 40 }
1164
+ if (window["isOnscreen"] as? Bool) == true { score += 20 }
1165
+ if window["windowId"] != nil { score += 10 }
1166
+ return score
1167
+ }
1168
+
1169
+ private func rootKind(role: String, subrole: String) -> String {
1170
+ if role == "AXSheet" { return "sheet" }
1171
+ if subrole.localizedCaseInsensitiveContains("popover") { return "popover" }
1172
+ if subrole.localizedCaseInsensitiveContains("dialog") || role == "AXDialog" { return "dialog" }
1173
+ return "window"
1174
+ }
1175
+
1176
+ private func isModalRoot(_ window: AXUIElement, role: String, subrole: String, sheetCount: Int) -> Bool {
1177
+ classifyModal(axModal: boolAttribute(window, attribute: "AXModal" as CFString), sheetCount: sheetCount, role: role, subrole: subrole)
1178
+ }
1179
+
1180
+ private func rootMetadata(pairing: WindowPairing, sheetCount: Int) -> [String: Any] {
1181
+ ["pairing": ["confidence": pairing.confidence, "score": pairing.score], "sheetCount": sheetCount]
1182
+ }
1183
+
1184
+ private func broadRootCandidateApps(entries: [[String: Any]]) -> [[String: Any]] {
1185
+ cgBroadRootOwners(entries: entries).compactMap { owner in
1186
+ guard owner.pid != getpid(), pidIsAlive(owner.pid) else { return nil }
1187
+ var app: [String: Any] = ["appName": owner.name, "pid": Int(owner.pid)]
1188
+ if let bundleId = NSRunningApplication(processIdentifier: owner.pid)?.bundleIdentifier {
1189
+ app["bundleId"] = bundleId
1190
+ }
1191
+ return app
1192
+ }
1193
+ }
1194
+
1195
+ private func listRoots(pid: Int32?, title: String? = nil) throws -> [String: Any] {
1196
+ let requestedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""
1197
+ let entries = allCGWindowEntries()
1198
+ let isBroadDiscovery = pid == nil && requestedTitle.isEmpty
1199
+ let apps: [[String: Any]]
1200
+ if let pid {
1201
+ apps = [["pid": Int(pid)]]
1202
+ } else if !requestedTitle.isEmpty {
1203
+ let matchingPids = Set(entries.compactMap { entry -> Int32? in
1204
+ let candidate = ((entry[kCGWindowName as String] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
1205
+ guard candidate == requestedTitle || candidate.contains(requestedTitle) else { return nil }
1206
+ return (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value
1207
+ })
1208
+ apps = listApps(cgEntries: entries).filter { app in
1209
+ guard let rawPid = app["pid"] as? Int else { return false }
1210
+ return matchingPids.contains(Int32(rawPid))
1211
+ }
1212
+ } else {
1213
+ apps = broadRootCandidateApps(entries: entries)
1214
+ }
1215
+ var roots: [[String: Any]] = []
1216
+ for app in apps {
1217
+ guard let rawPid = app["pid"] as? Int else { continue }
1218
+ let appPid = Int32(rawPid)
1219
+ let appName = app["appName"] as? String ?? processName(pid: appPid) ?? "Unknown App"
1220
+ let bundleId = app["bundleId"] as? String
1221
+ for var root in (try? listWindows(pid: appPid, cgEntries: entries, messagingTimeout: isBroadDiscovery ? 0.25 : 1.0)) ?? [] {
1222
+ root["pid"] = rawPid
1223
+ root["appName"] = appName
1224
+ if let bundleId { root["bundleId"] = bundleId }
1225
+ roots.append(root)
1226
+ }
1227
+ let popupCandidates = cgPopupMenuCandidates(pid: appPid, entries: entries)
1228
+ let menuElements = popupCandidates.isEmpty ? [] : openMenuElements(pid: appPid, messagingTimeout: isBroadDiscovery ? 0.25 : 1.0)
1229
+ for (index, candidate) in popupCandidates.enumerated() {
1230
+ let menuElement = index < menuElements.count ? menuElements[index] : nil
1231
+ let menuRef = menuElement.map { refStore.storeWindow($0) } ?? "cgmenu:\(candidate.windowId)"
1232
+ var menu: [String: Any] = [
1233
+ "kind": "menu",
1234
+ "rootRef": menuRef,
1235
+ "windowRef": menuRef,
1236
+ "windowId": Int(candidate.windowId),
1237
+ "zOrder": candidate.zOrder,
1238
+ "title": menuElement.flatMap { stringAttribute($0, attribute: kAXTitleAttribute as CFString) } ?? candidate.title,
1239
+ "role": "AXMenu",
1240
+ "subrole": "",
1241
+ "isModal": false,
1242
+ "framePoints": ["x": candidate.bounds.origin.x, "y": candidate.bounds.origin.y, "w": candidate.bounds.width, "h": candidate.bounds.height],
1243
+ "scaleFactor": displayScaleFactor(for: candidate.bounds),
1244
+ "isMinimized": false,
1245
+ "isOnscreen": candidate.isOnscreen,
1246
+ "isMain": false,
1247
+ "isFocused": true,
1248
+ "metadata": ["pairing": ["confidence": menuElement == nil ? "low" : "high", "score": menuElement == nil ? 0 : 100], "sheetCount": 0],
1249
+ "pid": rawPid,
1250
+ "appName": appName,
1251
+ ]
1252
+ if let bundleId { menu["bundleId"] = bundleId }
1253
+ roots.append(menu)
1254
+ }
1255
+ }
1256
+ roots.sort { (($0["zOrder"] as? Int) ?? Int.max) < (($1["zOrder"] as? Int) ?? Int.max) }
1257
+ return ["roots": roots]
1258
+ }
1259
+
1260
+ private func listWindows(pid: Int32, cgEntries: [[String: Any]]? = nil, messagingTimeout: Float = 1.0) throws -> [[String: Any]] {
1261
+ ensureEnhancedAccessibility(pid: pid)
1262
+ let appElement = AXUIElementCreateApplication(pid)
1263
+ AXUIElementSetMessagingTimeout(appElement, messagingTimeout)
1264
+ var windows = Array(axElementArray(appElement, attribute: kAXWindowsAttribute as CFString).prefix(128))
1265
+ if windows.isEmpty {
1266
+ for attribute in [kAXMainWindowAttribute, kAXFocusedWindowAttribute] {
1267
+ guard let window = copyAttribute(appElement, attribute: attribute as CFString).flatMap(asAXElement), !windows.contains(where: { sameElement($0, window) }) else { continue }
1268
+ windows.append(window)
1269
+ }
1270
+ }
1271
+ let candidates = cgWindowCandidates(pid: pid, entries: cgEntries)
1272
+ let pairings = windowPairings(windows: windows, candidates: candidates)
1273
+
1274
+ var output: [[String: Any]] = []
1275
+ for (zIndex, window) in windows.enumerated() {
1276
+ let axTitle = stringAttribute(window, attribute: kAXTitleAttribute as CFString) ?? ""
1277
+ let axRole = stringAttribute(window, attribute: kAXRoleAttribute as CFString) ?? ""
1278
+ let axSubrole = stringAttribute(window, attribute: kAXSubroleAttribute as CFString) ?? ""
1279
+ let axFrame = frameForWindow(window)
1280
+ let pairing = pairings[ObjectIdentifier(window)] ?? WindowPairing(candidate: nil, score: -Double.greatestFiniteMagnitude, confidence: "low")
1281
+ let candidate = pairing.candidate
1282
+
1283
+ let effectiveFrame = axFrame.width > 1 && axFrame.height > 1 ? axFrame : (candidate?.bounds ?? axFrame)
1284
+ if effectiveFrame.width < 100 || effectiveFrame.height < 80 { continue }
1285
+ let hasUsableAXFrame = axFrame.width > 1 && axFrame.height > 1
1286
+ let title = hasUsableAXFrame && !axTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? axTitle : (candidate?.title.isEmpty == false ? candidate!.title : axTitle)
1287
+ let windowRef = refStore.storeWindow(window)
1288
+ let isMinimized = boolAttribute(window, attribute: kAXMinimizedAttribute as CFString) ?? false
1289
+ let isMain = boolAttribute(window, attribute: kAXMainAttribute as CFString) ?? false
1290
+ let isFocused = boolAttribute(window, attribute: kAXFocusedAttribute as CFString) ?? false
1291
+ let sheetCount = sheetElements(of: window).count
1292
+ let isModal = isModalRoot(window, role: axRole, subrole: axSubrole, sheetCount: sheetCount)
1293
+ let scale = displayScaleFactor(for: effectiveFrame)
1294
+
1295
+ var item: [String: Any] = [
1296
+ "kind": rootKind(role: axRole, subrole: axSubrole),
1297
+ "rootRef": windowRef,
1298
+ "windowRef": windowRef,
1299
+ "zOrder": candidate?.zOrder ?? zIndex,
1300
+ "title": title,
1301
+ "role": axRole,
1302
+ "subrole": axSubrole,
1303
+ "isModal": isModal,
1304
+ "framePoints": [
1305
+ "x": effectiveFrame.origin.x,
1306
+ "y": effectiveFrame.origin.y,
1307
+ "w": effectiveFrame.size.width,
1308
+ "h": effectiveFrame.size.height,
1309
+ ],
1310
+ "scaleFactor": scale,
1311
+ "isMinimized": isMinimized,
1312
+ "isOnscreen": candidate?.isOnscreen ?? !isMinimized,
1313
+ "isMain": isMain,
1314
+ "isFocused": isFocused,
1315
+ "metadata": rootMetadata(pairing: pairing, sheetCount: sheetCount),
1316
+ ]
1317
+ if let candidate {
1318
+ item["windowId"] = Int(candidate.windowId)
1319
+ }
1320
+ output.append(item)
1321
+
1322
+ for sheet in sheetElements(of: window) {
1323
+ let sheetRef = refStore.storeWindow(sheet)
1324
+ let sheetFrame = frameForWindow(sheet)
1325
+ let sheetCandidate = bestCandidate(for: sheet, candidates: candidates)
1326
+ var sheetItem: [String: Any] = [
1327
+ "kind": "sheet",
1328
+ "rootRef": sheetRef,
1329
+ "windowRef": sheetRef,
1330
+ "zOrder": sheetCandidate?.zOrder ?? candidate?.zOrder ?? zIndex,
1331
+ "title": stringAttribute(sheet, attribute: kAXTitleAttribute as CFString) ?? title,
1332
+ "role": stringAttribute(sheet, attribute: kAXRoleAttribute as CFString) ?? "AXSheet",
1333
+ "subrole": stringAttribute(sheet, attribute: kAXSubroleAttribute as CFString) ?? "",
1334
+ "isModal": true,
1335
+ "framePoints": ["x": sheetFrame.origin.x, "y": sheetFrame.origin.y, "w": sheetFrame.width, "h": sheetFrame.height],
1336
+ "scaleFactor": displayScaleFactor(for: sheetFrame),
1337
+ "isMinimized": false,
1338
+ "isOnscreen": sheetCandidate?.isOnscreen ?? candidate?.isOnscreen ?? !isMinimized,
1339
+ "isMain": false,
1340
+ "isFocused": isFocused,
1341
+ "metadata": ["pairing": ["confidence": sheetCandidate == nil ? pairing.confidence : "high", "score": sheetCandidate == nil ? pairing.score : 100], "sheetCount": 0],
1342
+ ]
1343
+ if let sheetCandidate { sheetItem["windowId"] = Int(sheetCandidate.windowId) }
1344
+ output.append(sheetItem)
1345
+ }
1346
+ }
1347
+ return output
1348
+ }
1349
+
1350
+ private func look(_ request: [String: Any]) throws -> [String: Any] {
1351
+ let windowId = positiveWindowId(request)
1352
+ let windowRef = optionalStringArg(request, "windowRef")
1353
+ let maxDimension = optionalIntArg(request, "maxDimension").map { max(1, $0) }
1354
+ let readText = optionalStringArg(request, "readText") ?? "auto"
1355
+ let baseLookId = optionalStringArg(request, "baseLookId")
1356
+ let includeImage = boolArg(request, "includeImage") ?? true
1357
+ guard readText == "auto" || readText == "always" || readText == "never" else {
1358
+ throw BridgeFailure(message: "readText must be auto, always, or never", code: "invalid_args")
1359
+ }
1360
+
1361
+ let requestedRoot = windowRef.flatMap { refStore.window(for: $0) }
1362
+ let requestedRole = requestedRoot.flatMap { stringAttribute($0, attribute: kAXRoleAttribute as CFString) } ?? ""
1363
+ let isMenuRoot = requestedRole == "AXMenu" || (windowRef?.hasPrefix("cgmenu:") == true)
1364
+ let captureStart = Date()
1365
+ let shouldCapture = !isMenuRoot && (includeImage || readText == "always")
1366
+ if resolveCaptureTarget(windowId: windowId, wantsImage: shouldCapture) == .notCapturable {
1367
+ throw BridgeFailure(message: "Root has no capturable window (unpaired with any on-screen window); use semantic observation (image: never)", code: "root_not_capturable")
1368
+ }
1369
+ let capture = try shouldCapture ? windowId.map { try captureWindow(windowId: $0) } : nil
1370
+ let captureMs = capture.map { _ in elapsedMs(captureStart) } ?? 0
1371
+
1372
+ let pid: Int32
1373
+ if let windowId, let ownerPid = pidForWindowId(windowId) {
1374
+ pid = ownerPid
1375
+ } else if let requestedRoot, let owner = pidForElement(requestedRoot) {
1376
+ pid = owner
1377
+ } else {
1378
+ throw BridgeFailure(message: "Root is not owned by a running app", code: "root_not_found")
1379
+ }
1380
+ ensureEnhancedAccessibility(pid: pid)
1381
+ if let windowRef, windowRef.hasPrefix("cgmenu:"), refStore.window(for: windowRef) == nil {
1382
+ let frame = windowId.flatMap { windowInfo(windowId: $0)?.bounds } ?? CGRect(x: 0, y: 0, width: 1, height: 1)
1383
+ let lookId = freshLookId()
1384
+ storeLookRecord(LookRecord(lookId: lookId, windowId: windowId ?? 0, windowFrame: frame, imageWidth: max(1, Int(frame.width)), imageHeight: max(1, Int(frame.height)), hasImage: false))
1385
+ let outline = LookNode(element: nil, ref: windowRef, role: "AXMenu", subrole: "", identifier: "", title: "Menu", description: "", value: "", actions: [], canPress: false, canFocus: false, canSetValue: false, canScroll: false, canIncrement: false, canDecrement: false, isTextInput: false, rect: CGRect(x: 0, y: 0, width: max(1, frame.width), height: max(1, frame.height)), pictureOnly: true)
1386
+ return [
1387
+ "lookId": lookId,
1388
+ "capturedAt": captureStart.timeIntervalSince1970,
1389
+ "window": ["windowId": Int(windowId ?? 0), "rootRef": windowRef, "kind": "menu", "framePoints": ["x": frame.origin.x, "y": frame.origin.y, "w": frame.width, "h": frame.height], "scaleFactor": displayScaleFactor(for: frame), "isModal": false, "metadata": ["pairing": ["confidence": "low", "score": 0], "sheetCount": 0], "role": "AXMenu", "subrole": ""],
1390
+ "outline": outline.payload(),
1391
+ "timings": ["captureMs": 0, "describeMs": 0, "readTextMs": 0],
1392
+ ]
1393
+ }
1394
+ guard let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef) else {
1395
+ throw BridgeFailure(message: "Root is not available through Accessibility", code: "root_not_found")
1396
+ }
1397
+ let rootElement: AXUIElement
1398
+ if let scopeRef = optionalStringArg(request, "scopeRef") {
1399
+ guard let scoped = refStore.element(for: scopeRef), isElement(scoped, descendantOf: window) else {
1400
+ throw BridgeFailure(message: "Scope ref is stale or outside the target root", code: "element_ref_invalid")
1401
+ }
1402
+ rootElement = scoped
1403
+ } else {
1404
+ rootElement = window
1405
+ }
1406
+
1407
+ let rootFrame = frameForWindow(window)
1408
+ let imageWidth: Int
1409
+ let imageHeight: Int
1410
+ let imagePayload: [String: Any]?
1411
+ let transform: (CGRect) -> CGRect
1412
+ if let capture {
1413
+ let outputImage = downscaledImage(capture.image, maxDimension: maxDimension) ?? capture.image
1414
+ imageWidth = outputImage.width
1415
+ imageHeight = outputImage.height
1416
+ transform = rectTransform(windowFrame: capture.frame, imageWidth: outputImage.width, imageHeight: outputImage.height)
1417
+ if includeImage {
1418
+ guard let jpeg = jpegData(image: outputImage, quality: 0.8) else {
1419
+ throw BridgeFailure(message: "Failed to encode look image as JPEG", code: "encoding_failed")
1420
+ }
1421
+ imagePayload = ["jpegBase64": jpeg.base64EncodedString(), "width": outputImage.width, "height": outputImage.height]
1422
+ } else {
1423
+ imagePayload = nil
1424
+ }
1425
+ } else {
1426
+ imageWidth = max(1, Int(rootFrame.width))
1427
+ imageHeight = max(1, Int(rootFrame.height))
1428
+ imagePayload = nil
1429
+ transform = rectTransform(windowFrame: rootFrame, imageWidth: imageWidth, imageHeight: imageHeight)
1430
+ }
1431
+ let describeStart = Date()
1432
+ let outline = buildLookOutline(root: rootElement, transform: transform)
1433
+ let describeMs = elapsedMs(describeStart)
1434
+
1435
+ var readTextMs = 0
1436
+ var readTextExecuted = false
1437
+ if let capture, readText == "always" {
1438
+ readTextExecuted = true
1439
+ let textStart = Date()
1440
+ let boxes = try recognizeText(in: capture.image, outputWidth: imageWidth, outputHeight: imageHeight)
1441
+ attachOCR(boxes, to: outline)
1442
+ readTextMs = elapsedMs(textStart)
1443
+ }
1444
+
1445
+ let lookId = freshLookId()
1446
+ let baseRecord = baseLookId.flatMap { lookRecord(for: $0) }
1447
+ storeLookRecord(LookRecord(
1448
+ lookId: lookId,
1449
+ windowId: windowId ?? baseRecord?.windowId ?? 0,
1450
+ windowRef: windowRef ?? baseRecord?.windowRef,
1451
+ windowFrame: baseRecord?.windowFrame ?? capture?.frame ?? rootFrame,
1452
+ imageWidth: baseRecord?.imageWidth ?? imageWidth,
1453
+ imageHeight: baseRecord?.imageHeight ?? imageHeight,
1454
+ hasImage: baseRecord?.hasImage ?? (capture != nil)
1455
+ ))
1456
+ let scale = (capture?.frame.width ?? rootFrame.width) > 0 ? Double(imageWidth) / (capture?.frame.width ?? rootFrame.width) : displayScaleFactor(for: rootFrame)
1457
+ let pairing = pairingForWindow(window, pid: pid)
1458
+ let role = stringAttribute(window, attribute: kAXRoleAttribute as CFString) ?? ""
1459
+ let subrole = stringAttribute(window, attribute: kAXSubroleAttribute as CFString) ?? ""
1460
+ let sheetCount = sheetElements(of: window).count
1461
+ var response: [String: Any] = [
1462
+ "lookId": lookId,
1463
+ "capturedAt": captureStart.timeIntervalSince1970,
1464
+ "window": [
1465
+ "windowId": Int(windowId ?? 0),
1466
+ "rootRef": windowRef ?? refStore.storeWindow(window),
1467
+ "kind": rootKind(role: role, subrole: subrole),
1468
+ "framePoints": ["x": (capture?.frame ?? rootFrame).origin.x, "y": (capture?.frame ?? rootFrame).origin.y, "w": (capture?.frame ?? rootFrame).width, "h": (capture?.frame ?? rootFrame).height],
1469
+ "scaleFactor": scale,
1470
+ "isModal": isModalRoot(window, role: role, subrole: subrole, sheetCount: sheetCount),
1471
+ "metadata": rootMetadata(pairing: pairing, sheetCount: sheetCount),
1472
+ "role": role,
1473
+ "subrole": subrole,
1474
+ ],
1475
+ "outline": outline.payload(),
1476
+ "timings": ["captureMs": captureMs, "describeMs": describeMs, "readTextMs": readTextMs],
1477
+ "readText": ["requested": readText, "executed": readTextExecuted],
1478
+ ]
1479
+ if let imagePayload { response["image"] = imagePayload }
1480
+ return response
1481
+ }
1482
+
1483
+ private func elapsedMs(_ start: Date) -> Int {
1484
+ max(0, Int(Date().timeIntervalSince(start) * 1000.0))
1485
+ }
1486
+
1487
+ private func storeLookRecord(_ record: LookRecord) {
1488
+ lookRecordLock.lock()
1489
+ defer { lookRecordLock.unlock() }
1490
+ lookRecords[record.lookId] = record
1491
+ lookRecordOrder.append(record.lookId)
1492
+ while lookRecordOrder.count > 8 {
1493
+ let oldest = lookRecordOrder.removeFirst()
1494
+ lookRecords.removeValue(forKey: oldest)
1495
+ }
1496
+ }
1497
+
1498
+ private func freshLookId() -> String {
1499
+ lookRecordLock.lock()
1500
+ defer { lookRecordLock.unlock() }
1501
+ nextLookId += 1
1502
+ return "look_\(nextLookId)"
1503
+ }
1504
+
1505
+ private func lookRecord(for lookId: String) -> LookRecord? {
1506
+ lookRecordLock.lock()
1507
+ defer { lookRecordLock.unlock() }
1508
+ return lookRecords[lookId]
1509
+ }
1510
+
1511
+ private func rectTransform(windowFrame: CGRect, imageWidth: Int, imageHeight: Int) -> (CGRect) -> CGRect {
1512
+ let sx = windowFrame.width > 0 ? Double(imageWidth) / windowFrame.width : 1.0
1513
+ let sy = windowFrame.height > 0 ? Double(imageHeight) / windowFrame.height : 1.0
1514
+ return { frame in
1515
+ let x = (frame.origin.x - windowFrame.origin.x) * sx
1516
+ let y = (frame.origin.y - windowFrame.origin.y) * sy
1517
+ let w = frame.width * sx
1518
+ let h = frame.height * sy
1519
+ return self.clampRect(CGRect(x: x, y: y, width: w, height: h), width: imageWidth, height: imageHeight)
1520
+ }
1521
+ }
1522
+
1523
+ private func clampRect(_ rect: CGRect, width: Int, height: Int) -> CGRect {
1524
+ let maxX = Double(width)
1525
+ let maxY = Double(height)
1526
+ let x1 = min(max(rect.minX, 0), maxX)
1527
+ let y1 = min(max(rect.minY, 0), maxY)
1528
+ let x2 = min(max(rect.maxX, 0), maxX)
1529
+ let y2 = min(max(rect.maxY, 0), maxY)
1530
+ return CGRect(x: x1, y: y1, width: max(0, x2 - x1), height: max(0, y2 - y1))
1531
+ }
1532
+
1533
+ private func buildLookOutline(root: AXUIElement, transform: @escaping (CGRect) -> CGRect) -> LookNode {
1534
+ let rootNode = lookNode(element: root, transform: transform, offscreen: false)
1535
+ let nodeLimit = 2000
1536
+ // Apps with slow AX servers (e.g. Outlook) can take >30s to describe; the
1537
+ // client aborts at 33s, so stop walking well before that and return a
1538
+ // truncated outline instead.
1539
+ let deadline = Date().addingTimeInterval(20.0)
1540
+ var walked = 1
1541
+ var seen = Set<ObjectIdentifier>([ObjectIdentifier(root)])
1542
+ var queue: [(AXUIElement, LookNode)] = [(root, rootNode)]
1543
+ var index = 0
1544
+ while index < queue.count {
1545
+ let (element, node) = queue[index]
1546
+ index += 1
1547
+ let children = axElementArray(element, attribute: kAXChildrenAttribute as CFString)
1548
+ if children.isEmpty { continue }
1549
+ if walked >= nodeLimit || Date() >= deadline {
1550
+ node.truncated = true
1551
+ continue
1552
+ }
1553
+ let visibleByKind = visibleChildrenByKind(element)
1554
+ for child in children {
1555
+ if walked >= nodeLimit || Date() >= deadline {
1556
+ node.truncated = true
1557
+ break
1558
+ }
1559
+ let identity = ObjectIdentifier(child)
1560
+ if seen.contains(identity) { continue }
1561
+ seen.insert(identity)
1562
+ let role = stringAttribute(child, attribute: kAXRoleAttribute as CFString) ?? ""
1563
+ let offscreen = childOffscreen(child, role: role, visibleByKind: visibleByKind)
1564
+ let childNode = lookNode(element: child, transform: transform, offscreen: offscreen)
1565
+ node.children.append(childNode)
1566
+ queue.append((child, childNode))
1567
+ walked += 1
1568
+ }
1569
+ }
1570
+ return rootNode
1571
+ }
1572
+
1573
+ private func lookNode(element: AXUIElement, transform: (CGRect) -> CGRect, offscreen: Bool) -> LookNode {
1574
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
1575
+ let subrole = stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
1576
+ let actions = actionNames(element)
1577
+ var valueSettable = DarwinBoolean(false)
1578
+ let valueStatus = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &valueSettable)
1579
+ var focusedSettable = DarwinBoolean(false)
1580
+ let focusedStatus = AXUIElementIsAttributeSettable(element, kAXFocusedAttribute as CFString, &focusedSettable)
1581
+ let textRoles: Set<String> = ["AXTextField", "AXTextArea", "AXTextView", "AXSearchField", "AXComboBox", "AXEditableText", "AXSecureTextField"]
1582
+ let title = stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? ""
1583
+ let description = stringAttribute(element, attribute: kAXDescriptionAttribute as CFString) ?? ""
1584
+ let value = displayValue(element, role: role, subrole: subrole)
1585
+ let screenRect = frameForElement(element) ?? .zero
1586
+ let node = LookNode(
1587
+ element: element,
1588
+ ref: refStore.storeElement(element, snapshot: AXRefStore.Snapshot(
1589
+ role: role,
1590
+ identifier: stringAttribute(element, attribute: "AXIdentifier" as CFString) ?? "",
1591
+ label: normalizedLabel([title, description, value].joined(separator: " ")),
1592
+ rect: screenRect
1593
+ )),
1594
+ role: role,
1595
+ subrole: subrole,
1596
+ identifier: stringAttribute(element, attribute: "AXIdentifier" as CFString) ?? "",
1597
+ title: title,
1598
+ description: description,
1599
+ value: value,
1600
+ actions: actions,
1601
+ canPress: actions.contains(kAXPressAction as String),
1602
+ canFocus: focusedStatus == .success && focusedSettable.boolValue,
1603
+ canSetValue: valueStatus == .success && valueSettable.boolValue,
1604
+ canScroll: supportsAnyScrollAction(element),
1605
+ canIncrement: actions.contains(kAXIncrementAction as String),
1606
+ canDecrement: actions.contains(kAXDecrementAction as String),
1607
+ isTextInput: textRoles.contains(role),
1608
+ rect: transform(screenRect),
1609
+ focused: boolAttribute(element, attribute: kAXFocusedAttribute as CFString) == true,
1610
+ offscreen: offscreen
1611
+ )
1612
+ if node.canScroll {
1613
+ let rows = axElementArray(element, attribute: kAXRowsAttribute as CFString)
1614
+ let visibleRows = axElementArrayIfPresent(element, attribute: kAXVisibleRowsAttribute as CFString)
1615
+ if !rows.isEmpty, let visibleRows {
1616
+ node.scrollExtent = ["seen": visibleRows.count, "total": rows.count]
1617
+ }
1618
+ }
1619
+ return node
1620
+ }
1621
+
1622
+ private func visibleChildrenByKind(_ element: AXUIElement) -> [String: [AXUIElement]?] {
1623
+ [
1624
+ "AXRow": axElementArrayIfPresent(element, attribute: kAXVisibleRowsAttribute as CFString),
1625
+ "AXColumn": axElementArrayIfPresent(element, attribute: kAXVisibleColumnsAttribute as CFString),
1626
+ "AXCell": axElementArrayIfPresent(element, attribute: kAXVisibleCellsAttribute as CFString),
1627
+ "*": axElementArrayIfPresent(element, attribute: kAXVisibleChildrenAttribute as CFString),
1628
+ ]
1629
+ }
1630
+
1631
+ private func childOffscreen(_ child: AXUIElement, role: String, visibleByKind: [String: [AXUIElement]?]) -> Bool {
1632
+ let key = role == "AXRow" || role == "AXColumn" || role == "AXCell" ? role : "*"
1633
+ guard let visible = visibleByKind[key] ?? nil else { return false }
1634
+ return !visible.contains { sameElement($0, child) }
1635
+ }
1636
+
1637
+ private func recognizeText(in image: CGImage, outputWidth: Int, outputHeight: Int) throws -> [OCRBox] {
1638
+ let semaphore = DispatchSemaphore(value: 0)
1639
+ let recognized = Box<[OCRBox]>([])
1640
+ let recognizedError = Box<Error?>(nil)
1641
+ let request = VNRecognizeTextRequest { request, error in
1642
+ defer { semaphore.signal() }
1643
+ if let error {
1644
+ recognizedError.value = error
1645
+ return
1646
+ }
1647
+ let observations = (request.results as? [VNRecognizedTextObservation]) ?? []
1648
+ recognized.value = observations.compactMap { observation in
1649
+ guard let candidate = observation.topCandidates(1).first else { return nil }
1650
+ let box = observation.boundingBox
1651
+ let x = box.origin.x * Double(outputWidth)
1652
+ let y = (1.0 - box.origin.y - box.height) * Double(outputHeight)
1653
+ let w = box.width * Double(outputWidth)
1654
+ let h = box.height * Double(outputHeight)
1655
+ return OCRBox(string: candidate.string, confidence: Double(candidate.confidence), rect: CGRect(x: x, y: y, width: w, height: h))
1656
+ }
1657
+ }
1658
+ request.recognitionLevel = .accurate
1659
+ request.usesLanguageCorrection = false
1660
+ try VNImageRequestHandler(cgImage: image, options: [:]).perform([request])
1661
+ if semaphore.wait(timeout: .now() + .seconds(8)) == .timedOut {
1662
+ throw BridgeFailure(message: "Text recognition timed out", code: "text_recognition_timeout")
1663
+ }
1664
+ if let error = recognizedError.value {
1665
+ throw BridgeFailure(message: "Text recognition failed: \(error.localizedDescription)", code: "text_recognition_failed")
1666
+ }
1667
+ return recognized.value
1668
+ }
1669
+
1670
+ private func attachOCR(_ boxes: [OCRBox], to root: LookNode) {
1671
+ var pictureOnlyIndex = 0
1672
+ for box in boxes {
1673
+ if ocrBoxDuplicatesAXLabel(box, in: root) { continue }
1674
+ let center = CGPoint(x: box.rect.midX, y: box.rect.midY)
1675
+ if let node = deepestNode(containing: center, in: root) {
1676
+ node.text.append(["string": box.string, "confidence": box.confidence, "rect": ["x": box.rect.origin.x, "y": box.rect.origin.y, "w": box.rect.width, "h": box.rect.height]])
1677
+ } else {
1678
+ pictureOnlyIndex += 1
1679
+ let parent = deepestContainer(containing: center, in: root) ?? root
1680
+ parent.children.append(LookNode(element: nil, ref: "pic_\(pictureOnlyIndex)", role: "AXImage", subrole: "", identifier: "", title: box.string, description: "", value: "", actions: [], canPress: false, canFocus: false, canSetValue: false, canScroll: false, canIncrement: false, canDecrement: false, isTextInput: false, rect: box.rect, pictureOnly: true))
1681
+ }
1682
+ }
1683
+ }
1684
+
1685
+ private func ocrBoxDuplicatesAXLabel(_ box: OCRBox, in root: LookNode) -> Bool {
1686
+ let boxLabel = normalizedLabel(box.string)
1687
+ if boxLabel.isEmpty { return true }
1688
+ var queue = [root]
1689
+ var index = 0
1690
+ while index < queue.count {
1691
+ let node = queue[index]
1692
+ index += 1
1693
+ if !node.pictureOnly, node.rect.intersects(box.rect) {
1694
+ let fields = [node.title, node.value, node.description]
1695
+ if fields.contains(where: { normalizedLabel($0) == boxLabel }) { return true }
1696
+ }
1697
+ queue.append(contentsOf: node.children)
1698
+ }
1699
+ return false
1700
+ }
1701
+
1702
+ private func deepestNode(containing point: CGPoint, in root: LookNode) -> LookNode? {
1703
+ guard root.rect.contains(point), !root.pictureOnly else { return nil }
1704
+ for child in root.children.reversed() {
1705
+ if let match = deepestNode(containing: point, in: child) { return match }
1706
+ }
1707
+ return root
1708
+ }
1709
+
1710
+ private func deepestContainer(containing point: CGPoint, in root: LookNode) -> LookNode? {
1711
+ guard root.rect.contains(point) else { return nil }
1712
+ for child in root.children.reversed() {
1713
+ if let match = deepestContainer(containing: point, in: child) { return match }
1714
+ }
1715
+ return root
1716
+ }
1717
+
1718
+ private func lookPoint(record: LookRecord, x: Double, y: Double) -> CGPoint {
1719
+ let relX = min(max(x / max(1.0, Double(record.imageWidth)), 0), 1)
1720
+ let relY = min(max(y / max(1.0, Double(record.imageHeight)), 0), 1)
1721
+ return CGPoint(x: record.windowFrame.origin.x + record.windowFrame.width * relX, y: record.windowFrame.origin.y + record.windowFrame.height * relY)
1722
+ }
1723
+
1724
+ private func payloadNode(element: AXUIElement) -> [String: Any] {
1725
+ let node = lookNode(element: element, transform: { $0 }, offscreen: false)
1726
+ var payload = node.payload()
1727
+ payload["children"] = []
1728
+ return payload
1729
+ }
1730
+
1731
+ private func normalizedLabel(_ value: String) -> String {
1732
+ value.lowercased().components(separatedBy: CharacterSet.whitespacesAndNewlines).filter { !$0.isEmpty }.joined(separator: " ")
1733
+ }
1734
+
1735
+ private func ensureRootObserver(pid: Int32) -> Bool {
1736
+ rootObserverLock.lock()
1737
+ if let existing = rootObservers[pid] {
1738
+ existing.lastUsed = Date().timeIntervalSince1970
1739
+ rootObserverLock.unlock()
1740
+ return true
1741
+ }
1742
+ rootObserverLock.unlock()
1743
+
1744
+ let appElement = AXUIElementCreateApplication(pid)
1745
+ AXUIElementSetMessagingTimeout(appElement, 0.25)
1746
+ var observer: AXObserver?
1747
+ let createStatus = AXObserverCreate(pid, { observer, element, notification, refcon in
1748
+ guard let refcon else { return }
1749
+ let bridge = Unmanaged<Bridge>.fromOpaque(refcon).takeUnretainedValue()
1750
+ bridge.recordRootAXEvent(observer: observer, notification: notification as String, element: element)
1751
+ }, &observer)
1752
+ guard createStatus == .success, let observer else { return false }
1753
+
1754
+ let state = RootAXObserverState(pid: pid, observer: observer)
1755
+ let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
1756
+ let notifications: [CFString] = [
1757
+ "AXWindowCreated" as CFString,
1758
+ "AXSheetCreated" as CFString,
1759
+ "AXMenuOpened" as CFString,
1760
+ "AXMenuClosed" as CFString,
1761
+ "AXUIElementDestroyed" as CFString,
1762
+ "AXFocusedWindowChanged" as CFString,
1763
+ kAXValueChangedNotification as CFString,
1764
+ kAXTitleChangedNotification as CFString,
1765
+ kAXSelectedChildrenChangedNotification as CFString,
1766
+ kAXLayoutChangedNotification as CFString,
1767
+ ]
1768
+ var registered = false
1769
+ let observedElements = [appElement] + axElementArray(appElement, attribute: kAXWindowsAttribute as CFString)
1770
+ for observed in observedElements {
1771
+ for notification in notifications {
1772
+ let status = AXObserverAddNotification(observer, observed, notification, context)
1773
+ if status == .success || status == .notificationAlreadyRegistered { registered = true }
1774
+ }
1775
+ }
1776
+ guard registered else { return false }
1777
+
1778
+ rootObserverLock.lock()
1779
+ if rootObservers.count >= maxRootObservers,
1780
+ let evict = rootObservers.values.min(by: { $0.lastUsed < $1.lastUsed })?.pid
1781
+ {
1782
+ rootObservers.removeValue(forKey: evict)
1783
+ }
1784
+ rootObservers[pid] = state
1785
+ rootObserverLock.unlock()
1786
+
1787
+ let source = AXObserverGetRunLoopSource(observer)
1788
+ Thread.detachNewThread {
1789
+ // Keep each AXObserver on its own run loop so its callbacks never compete
1790
+ // with AppKit rendering on the helper's main thread.
1791
+ CFRunLoopAddSource(CFRunLoopGetCurrent(), source, .commonModes)
1792
+ CFRunLoopRun()
1793
+ }
1794
+ return true
1795
+ }
1796
+
1797
+ private func recordRootAXEvent(observer: AXObserver, notification: String, element: AXUIElement) {
1798
+ rootObserverLock.lock()
1799
+ let state = rootObservers.values.first { CFEqual($0.observer, observer) }
1800
+ if let state {
1801
+ state.events.append(RootAXEvent(sequence: state.nextSequence, timestamp: Date().timeIntervalSince1970, notification: notification, element: element))
1802
+ state.nextSequence += 1
1803
+ if state.events.count > 64 { state.events.removeFirst(state.events.count - 64) }
1804
+ }
1805
+ rootObserverLock.unlock()
1806
+ if let state {
1807
+ state.change.lock()
1808
+ state.changeGeneration += 1
1809
+ state.change.broadcast()
1810
+ state.change.unlock()
1811
+ }
1812
+ }
1813
+
1814
+ private func rootChangeGeneration(pid: Int32) -> UInt64 {
1815
+ rootObserverLock.lock()
1816
+ let state = rootObservers[pid]
1817
+ rootObserverLock.unlock()
1818
+ guard let state else { return 0 }
1819
+ state.change.lock()
1820
+ defer { state.change.unlock() }
1821
+ return state.changeGeneration
1822
+ }
1823
+
1824
+ private func waitForRootChange(pid: Int32, since generation: UInt64, until deadline: Date) {
1825
+ rootObserverLock.lock()
1826
+ let state = rootObservers[pid]
1827
+ rootObserverLock.unlock()
1828
+ guard let state else {
1829
+ Thread.sleep(forTimeInterval: min(0.2, max(0, deadline.timeIntervalSinceNow)))
1830
+ return
1831
+ }
1832
+ state.change.lock()
1833
+ if state.changeGeneration == generation {
1834
+ _ = state.change.wait(until: min(deadline, Date().addingTimeInterval(0.2)))
1835
+ }
1836
+ state.change.unlock()
1837
+ }
1838
+
1839
+ private func rootEventCursor(pid: Int32) -> UInt64 {
1840
+ rootObserverLock.lock()
1841
+ defer { rootObserverLock.unlock() }
1842
+ return rootObservers[pid]?.nextSequence ?? 1
1843
+ }
1844
+
1845
+ private func rootEvents(pid: Int32, since cursor: UInt64) -> [RootAXEvent] {
1846
+ rootObserverLock.lock()
1847
+ defer { rootObserverLock.unlock() }
1848
+ guard let events = rootObservers[pid]?.events else { return [] }
1849
+ return events.filter { $0.sequence >= cursor }
1850
+ }
1851
+
1852
+ // Onscreen CGWindowList id set for one pid: ~1-2ms per call, so it can be
1853
+ // polled tightly where a full AX enumeration cannot.
1854
+ private func cgRootSignature(pid: Int32) -> Set<UInt32> {
1855
+ guard let entries = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else { return [] }
1856
+ var ids = Set<UInt32>()
1857
+ for entry in entries {
1858
+ guard let owner = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value, owner == pid else { continue }
1859
+ guard let windowId = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value else { continue }
1860
+ ids.insert(windowId)
1861
+ }
1862
+ return ids
1863
+ }
1864
+
1865
+ private func refindElement(ref: String, pid: Int32, windowId: UInt32?, windowRef: String? = nil) -> AXUIElement? {
1866
+ guard let snapshot = refStore.snapshot(for: ref),
1867
+ let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef)
1868
+ else { return nil }
1869
+ let targetCenter = CGPoint(x: snapshot.rect.midX, y: snapshot.rect.midY)
1870
+ let candidates = collectDescendants(startingAt: window, maxDepth: 8).filter { candidate in
1871
+ let role = stringAttribute(candidate, attribute: kAXRoleAttribute as CFString) ?? ""
1872
+ guard role == snapshot.role else { return false }
1873
+ let identifier = stringAttribute(candidate, attribute: "AXIdentifier" as CFString) ?? ""
1874
+ if !snapshot.identifier.isEmpty { return identifier == snapshot.identifier }
1875
+ let subrole = stringAttribute(candidate, attribute: kAXSubroleAttribute as CFString) ?? ""
1876
+ let title = stringAttribute(candidate, attribute: kAXTitleAttribute as CFString) ?? ""
1877
+ let description = stringAttribute(candidate, attribute: kAXDescriptionAttribute as CFString) ?? ""
1878
+ let value = displayValue(candidate, role: role, subrole: subrole)
1879
+ return normalizedLabel([title, description, value].joined(separator: " ")) == snapshot.label
1880
+ }
1881
+ return candidates.min { left, right in
1882
+ let leftFrame = frameForElement(left) ?? .zero
1883
+ let rightFrame = frameForElement(right) ?? .zero
1884
+ let leftDistance = hypot(leftFrame.midX - targetCenter.x, leftFrame.midY - targetCenter.y)
1885
+ let rightDistance = hypot(rightFrame.midX - targetCenter.x, rightFrame.midY - targetCenter.y)
1886
+ return leftDistance < rightDistance
1887
+ }
1888
+ }
1889
+
1890
+ private func hitTest(_ request: [String: Any]) throws -> [String: Any] {
1891
+ let lookId = try stringArg(request, "lookId")
1892
+ guard let record = lookRecord(for: lookId) else {
1893
+ throw BridgeFailure(message: "Look id '\(lookId)' is no longer available", code: "stale_look")
1894
+ }
1895
+ let point = lookPoint(record: record, x: try doubleArg(request, "x"), y: try doubleArg(request, "y"))
1896
+ guard let element = hitTestElement(at: point) else {
1897
+ throw BridgeFailure(message: "No element at point", code: "hit_test_failed")
1898
+ }
1899
+ return payloadNode(element: element)
1900
+ }
1901
+
1902
+ private func act(_ request: [String: Any]) throws -> [String: Any] {
1903
+ let lookId = try stringArg(request, "lookId")
1904
+ guard let record = lookRecord(for: lookId) else {
1905
+ throw BridgeFailure(message: "Look id '\(lookId)' is no longer available", code: "stale_look")
1906
+ }
1907
+ let pid = Int32(try intArg(request, "pid"))
1908
+ let action = try stringArg(request, "action")
1909
+ let target = request["target"] as? [String: Any] ?? [:]
1910
+ let params = request["params"] as? [String: Any] ?? [:]
1911
+ let policy = optionalStringArg(request, "policy") ?? "default"
1912
+ let deferRootDelta = boolArg(request, "deferRootDelta") ?? false
1913
+ let delivery = policy == "background" ? "pid" : ((params["delivery"] as? String) == "pid" ? "pid" : "hid")
1914
+ var holdsPhysicalInput = false
1915
+ func acquirePhysicalInputIfNeeded() {
1916
+ if delivery == "hid" && !holdsPhysicalInput {
1917
+ physicalInputLock.lock()
1918
+ holdsPhysicalInput = true
1919
+ }
1920
+ }
1921
+ defer { if holdsPhysicalInput { physicalInputLock.unlock() } }
1922
+ func rejectInStrictHeadless(_ message: String) throws {
1923
+ if policy == "ax_only" { throw BridgeFailure(message: message, code: "foreground_required") }
1924
+ }
1925
+ var performed: [String: Any] = ["delivery": delivery]
1926
+ var element: AXUIElement?
1927
+ var rawPoint: CGPoint?
1928
+ var preflightCapsUnknown = false
1929
+ let eventsLive = !deferRootDelta && ensureRootObserver(pid: pid)
1930
+ let eventCursor = eventsLive ? rootEventCursor(pid: pid) : 0
1931
+ let beforeRootSnapshot = deferRootDelta ? [:] : rootMetadataSnapshot(pid: pid)
1932
+ let beforeCgSignature = deferRootDelta ? [] : cgRootSignature(pid: pid)
1933
+ let beforeFrontmostPid = deferRootDelta ? nil : NSWorkspace.shared.frontmostApplication?.processIdentifier
1934
+ let beforeSheetCount = windowElement(pid: pid, windowId: record.windowId > 0 ? record.windowId : nil, windowRef: record.windowRef).map { sheetElements(of: $0).count } ?? 0
1935
+ let beforeFocusedWindow = focusedWindowSummary(pid: pid)
1936
+ let beforeValue: String?
1937
+ let beforeSelected: String?
1938
+ func finish(_ response: [String: Any]) -> [String: Any] {
1939
+ if deferRootDelta { return response }
1940
+ return attachRootDelta(to: response, before: beforeRootSnapshot, beforeFrontmostPid: beforeFrontmostPid, pid: pid, eventsLive: eventsLive, eventCursor: eventCursor, beforeCgSignature: beforeCgSignature)
1941
+ }
1942
+
1943
+ if let ref = target["ref"] as? String {
1944
+ var refound = false
1945
+ let cached = refStore.element(for: ref)
1946
+ let cachedIsLive = cached.map {
1947
+ stringAttribute($0, attribute: kAXRoleAttribute as CFString) != nil && frameForElement($0) != nil
1948
+ } ?? false
1949
+ let resolved: AXUIElement?
1950
+ if cachedIsLive {
1951
+ resolved = cached
1952
+ } else {
1953
+ refound = true
1954
+ resolved = refindElement(ref: ref, pid: pid, windowId: record.windowId > 0 ? record.windowId : nil, windowRef: record.windowRef)
1955
+ }
1956
+ guard let stored = resolved else {
1957
+ throw BridgeFailure(message: "Element reference is stale", code: "stale_ref")
1958
+ }
1959
+ if refound { performed["refound"] = true }
1960
+ element = stored
1961
+ beforeValue = stringAttribute(stored, attribute: kAXValueAttribute as CFString)
1962
+ beforeSelected = stringAttribute(stored, attribute: kAXSelectedTextAttribute as CFString)
1963
+ } else if let xNumber = target["x"] as? NSNumber, let yNumber = target["y"] as? NSNumber {
1964
+ guard record.hasImage else {
1965
+ throw BridgeFailure(message: "Coordinate targeting is unavailable for this outline-only root", code: "coordinate_unavailable_for_root")
1966
+ }
1967
+ rawPoint = lookPoint(record: record, x: xNumber.doubleValue, y: yNumber.doubleValue)
1968
+ beforeValue = nil
1969
+ beforeSelected = nil
1970
+ } else {
1971
+ throw BridgeFailure(message: "act target must include ref or x/y", code: "invalid_args")
1972
+ }
1973
+
1974
+ func coordinatePoint() throws -> CGPoint {
1975
+ if let element, let frame = frameForElement(element) {
1976
+ return CGPoint(x: frame.midX, y: frame.midY)
1977
+ }
1978
+ if let rawPoint { return rawPoint }
1979
+ throw BridgeFailure(message: "No coordinate grounding is available", code: "coordinate_unavailable")
1980
+ }
1981
+
1982
+ func animateCursor(at point: CGPoint) {
1983
+ guard supportsAgentCursor,
1984
+ (request["cursorOverlay"] as? Bool ?? true),
1985
+ delivery == "pid",
1986
+ policy != "ax_only",
1987
+ ["press", "click", "moveMouse", "scroll", "drag"].contains(action)
1988
+ else { return }
1989
+ Task { @MainActor in AgentCursor.shared.animate(to: point, above: record.windowId) }
1990
+ }
1991
+
1992
+ func focusTargetForPhysicalInput() {
1993
+ guard delivery == "hid" else { return }
1994
+ if let app = NSRunningApplication(processIdentifier: pid), !app.isActive {
1995
+ performed["activated"] = app.activate()
1996
+ }
1997
+ if let window = windowElement(pid: pid, windowId: record.windowId > 0 ? record.windowId : nil, windowRef: record.windowRef) {
1998
+ _ = AXUIElementSetAttributeValue(window, kAXMainAttribute as CFString, kCFBooleanTrue)
1999
+ _ = AXUIElementSetAttributeValue(window, kAXFocusedAttribute as CFString, kCFBooleanTrue)
2000
+ performed["raised"] = AXUIElementPerformAction(window, kAXRaiseAction as CFString) == .success
2001
+ }
2002
+ usleep(20_000)
2003
+ }
2004
+
2005
+ func preflight(_ point: CGPoint) throws {
2006
+ guard let element else { preflightCapsUnknown = true; return }
2007
+ for attempt in 0..<4 {
2008
+ guard let hit = hitTestElement(at: point) else { preflightCapsUnknown = true; return }
2009
+ if sameElement(hit, element) || isElement(hit, descendantOf: element) || isElement(element, descendantOf: hit) { return }
2010
+ let role = stringAttribute(hit, attribute: kAXRoleAttribute as CFString) ?? ""
2011
+ if role == "AXWindow" || role == "AXApplication" { preflightCapsUnknown = true; return }
2012
+ if delivery == "hid" && attempt < 3 {
2013
+ focusTargetForPhysicalInput()
2014
+ usleep(20_000)
2015
+ continue
2016
+ }
2017
+ throw BridgeFailure(message: "Target is occluded by \(payloadNode(element: hit))", code: "occluded_target")
2018
+ }
2019
+ }
2020
+
2021
+ func executeCoordinates(_ point: CGPoint) throws {
2022
+ try rejectInStrictHeadless("Action requires synthesized pointer input, which strict headless mode prohibits")
2023
+ guard element != nil || record.hasImage else {
2024
+ throw BridgeFailure(message: "Coordinate grounding is unavailable for this outline-only root", code: "coordinate_unavailable_for_root")
2025
+ }
2026
+ performed["grounding"] = "coordinates"
2027
+ if delivery == "pid" { performed["verification"] = "caller_required" }
2028
+ acquirePhysicalInputIfNeeded()
2029
+ focusTargetForPhysicalInput()
2030
+ if delivery == "hid" { try preflight(point) }
2031
+ switch action {
2032
+ case "press", "click":
2033
+ animateCursor(at: point)
2034
+ try postMouseClick(at: point, pid: pid, button: mouseButton(params["button"] as? String ?? "left"), clickCount: max(1, min(3, (params["clickCount"] as? NSNumber)?.intValue ?? 1)), delivery: delivery)
2035
+ case "moveMouse":
2036
+ animateCursor(at: point)
2037
+ try postMouseMove(to: point, pid: pid, delivery: delivery)
2038
+ case "scroll":
2039
+ animateCursor(at: point)
2040
+ try postScrollWheel(at: point, deltaX: (params["scrollX"] as? NSNumber)?.intValue ?? 0, deltaY: (params["scrollY"] as? NSNumber)?.intValue ?? 0, pid: pid, delivery: delivery)
2041
+ case "drag":
2042
+ guard let rawPath = params["path"] as? [[String: Any]], rawPath.count >= 2 else {
2043
+ throw BridgeFailure(message: "drag requires path", code: "invalid_args")
2044
+ }
2045
+ let points = try rawPath.map { raw -> CGPoint in
2046
+ guard let x = (raw["x"] as? NSNumber)?.doubleValue, let y = (raw["y"] as? NSNumber)?.doubleValue else {
2047
+ throw BridgeFailure(message: "drag path entries require x and y", code: "invalid_args")
2048
+ }
2049
+ return lookPoint(record: record, x: x, y: y)
2050
+ }
2051
+ animateCursor(at: point)
2052
+ try postMouseDrag(points: points, pid: pid, delivery: delivery)
2053
+ default:
2054
+ throw BridgeFailure(message: "Action \(action) cannot use coordinate grounding", code: "invalid_args")
2055
+ }
2056
+ }
2057
+
2058
+ func refreshElement() -> AXUIElement? {
2059
+ guard let ref = target["ref"] as? String,
2060
+ let refreshed = refindElement(ref: ref, pid: pid, windowId: record.windowId > 0 ? record.windowId : nil, windowRef: record.windowRef)
2061
+ else { return nil }
2062
+ element = refreshed
2063
+ performed["refound"] = true
2064
+ return refreshed
2065
+ }
2066
+
2067
+ if let element, action == "press" || action == "click" {
2068
+ let elementRole = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2069
+ let textRoles: Set<String> = ["AXTextField", "AXTextArea", "AXTextView", "AXSearchField", "AXComboBox", "AXEditableText", "AXSecureTextField"]
2070
+ let requiresPointerFocus = hasAncestorRole(element, role: "AXWebArea") || textRoles.contains(elementRole)
2071
+ if requiresPointerFocus && policy != "ax_only" {
2072
+ if policy == "foreground" {
2073
+ try executeCoordinates(coordinatePoint())
2074
+ } else {
2075
+ throw BridgeFailure(message: "Web content requires pointer input", code: "foreground_required")
2076
+ }
2077
+ } else if supportsAction(element, action: kAXPressAction as CFString) {
2078
+ let cursorPoint = try? coordinatePoint()
2079
+ var status = AXUIElementPerformAction(element, kAXPressAction as CFString)
2080
+ if status != .success, let refreshed = refreshElement(), supportsAction(refreshed, action: kAXPressAction as CFString) {
2081
+ status = AXUIElementPerformAction(refreshed, kAXPressAction as CFString)
2082
+ }
2083
+ if status == .success {
2084
+ performed["grounding"] = "description"
2085
+ performed["delivery"] = "ax"
2086
+ if let cursorPoint { animateCursor(at: cursorPoint) }
2087
+ } else {
2088
+ try executeCoordinates(coordinatePoint())
2089
+ }
2090
+ } else {
2091
+ try executeCoordinates(coordinatePoint())
2092
+ }
2093
+ } else if let element, action == "setText" {
2094
+ let text = params["text"] as? String ?? ""
2095
+ if hasAncestorRole(element, role: "AXWebArea") {
2096
+ try rejectInStrictHeadless("Web text replacement requires synthesized keyboard input, which strict headless mode prohibits")
2097
+ acquirePhysicalInputIfNeeded()
2098
+ focusTargetForPhysicalInput()
2099
+ _ = AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue)
2100
+ let currentValue = stringAttribute(element, attribute: kAXValueAttribute as CFString) ?? ""
2101
+ var range = CFRange(location: 0, length: (currentValue as NSString).length)
2102
+ let selected = AXValueCreate(.cfRange, &range).map {
2103
+ AXUIElementSetAttributeValue(element, kAXSelectedTextRangeAttribute as CFString, $0) == .success
2104
+ } ?? false
2105
+ if !selected {
2106
+ try postKeyPress(keys: ["cmd", "a"], pid: pid, delivery: delivery)
2107
+ usleep(20_000)
2108
+ }
2109
+ try postAtomicUnicodeText(text, pid: pid, delivery: delivery)
2110
+ usleep(40_000)
2111
+ let verificationElement = refreshElement() ?? element
2112
+ let value = stringAttribute(verificationElement, attribute: kAXValueAttribute as CFString) ?? ""
2113
+ performed["grounding"] = "keyboard-events"
2114
+ performed["delivery"] = delivery
2115
+ performed["selectionGrounding"] = selected ? "ax" : "keyboard"
2116
+ return finish(["outcome": value == text ? "worked" : "didnt", "performed": performed, "evidence": ["value": value]])
2117
+ }
2118
+ var targetElement = element
2119
+ var status = AXUIElementSetAttributeValue(targetElement, kAXValueAttribute as CFString, text as CFTypeRef)
2120
+ if status != .success, let refreshed = refreshElement() {
2121
+ targetElement = refreshed
2122
+ status = AXUIElementSetAttributeValue(targetElement, kAXValueAttribute as CFString, text as CFTypeRef)
2123
+ }
2124
+ if status == .success {
2125
+ performed["grounding"] = "description"
2126
+ performed["delivery"] = "ax"
2127
+ let value = stringAttribute(targetElement, attribute: kAXValueAttribute as CFString) ?? ""
2128
+ if value != text && policy != "foreground" {
2129
+ throw BridgeFailure(message: "The background accessibility value write was accepted but did not take effect", code: "foreground_required")
2130
+ }
2131
+ return finish(["outcome": value == text ? "worked" : "didnt", "performed": performed, "evidence": ["value": value]])
2132
+ }
2133
+ try executeCoordinates(coordinatePoint())
2134
+ } else if action == "typeText" {
2135
+ try rejectInStrictHeadless("Typing requires synthesized keyboard input, which strict headless mode prohibits")
2136
+ let preserveFocus = params["preserveFocus"] as? Bool ?? false
2137
+ if let element {
2138
+ let focused = AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue)
2139
+ if focused == .success { performed["focused"] = true }
2140
+ }
2141
+ acquirePhysicalInputIfNeeded()
2142
+ if delivery == "hid" && !preserveFocus { focusTargetForPhysicalInput() }
2143
+ let text = params["text"] as? String ?? ""
2144
+ try postUnicodeText(text, pid: pid, delivery: delivery)
2145
+ performed["grounding"] = "coordinates"
2146
+ if let element, !text.isEmpty {
2147
+ usleep(30_000)
2148
+ let afterValue = stringAttribute(element, attribute: kAXValueAttribute as CFString) ?? ""
2149
+ let changed = afterValue != (beforeValue ?? "")
2150
+ return finish(["outcome": changed ? "worked" : "didnt", "performed": performed, "evidence": ["value": afterValue, "valueChanged": changed]])
2151
+ }
2152
+ } else if action == "keypress" {
2153
+ try rejectInStrictHeadless("Keypress requires synthesized keyboard input, which strict headless mode prohibits")
2154
+ let preserveFocus = params["preserveFocus"] as? Bool ?? false
2155
+ guard let keys = params["keys"] as? [String], !keys.isEmpty else {
2156
+ throw BridgeFailure(message: "keypress requires keys", code: "invalid_args")
2157
+ }
2158
+ if let element {
2159
+ let focused = AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue)
2160
+ if focused == .success { performed["focused"] = true }
2161
+ let normalizedKeys = keys.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
2162
+ if normalizedKeys.count == 2,
2163
+ normalizedKeys.last == "a",
2164
+ ["cmd", "command", "meta"].contains(normalizedKeys.first ?? ""),
2165
+ let value = stringAttribute(element, attribute: kAXValueAttribute as CFString)
2166
+ {
2167
+ var range = CFRange(location: 0, length: (value as NSString).length)
2168
+ if let selection = AXValueCreate(.cfRange, &range),
2169
+ AXUIElementSetAttributeValue(element, kAXSelectedTextRangeAttribute as CFString, selection) == .success
2170
+ {
2171
+ performed["selectionGrounding"] = "ax"
2172
+ }
2173
+ }
2174
+ }
2175
+ acquirePhysicalInputIfNeeded()
2176
+ if delivery == "hid" && !preserveFocus { focusTargetForPhysicalInput() }
2177
+ try postKeyPress(keys: keys, pid: pid, delivery: delivery)
2178
+ performed["grounding"] = "coordinates"
2179
+ } else if let element, action == "scroll" {
2180
+ let cursorPoint = try? coordinatePoint()
2181
+ let before = scrollPositionSignature(element)
2182
+ let result = performScrollActionOrAncestor(startingAt: element, targetPid: pid, scrollX: (params["scrollX"] as? NSNumber)?.intValue ?? 0, scrollY: (params["scrollY"] as? NSNumber)?.intValue ?? 0, steps: 1)
2183
+ if (result["scrolled"] as? Bool) == true {
2184
+ performed["grounding"] = "description"
2185
+ performed["delivery"] = "ax"
2186
+ if let cursorPoint { animateCursor(at: cursorPoint) }
2187
+ let after = scrollPositionSignature(element)
2188
+ return finish(["outcome": before != after ? "worked" : "unknown", "performed": performed])
2189
+ }
2190
+ try executeCoordinates(coordinatePoint())
2191
+ } else {
2192
+ try executeCoordinates(coordinatePoint())
2193
+ }
2194
+
2195
+ let afterSheetCount = windowElement(pid: pid, windowId: record.windowId > 0 ? record.windowId : nil, windowRef: record.windowRef).map { sheetElements(of: $0).count } ?? beforeSheetCount
2196
+ let windowChanged = beforeFocusedWindow != focusedWindowSummary(pid: pid) || beforeSheetCount != afterSheetCount
2197
+ var outcome = preflightCapsUnknown ? "unknown" : "unknown"
2198
+ var evidence: [String: Any] = [:]
2199
+ if let element, action == "press" || action == "click" {
2200
+ let afterValue = stringAttribute(element, attribute: kAXValueAttribute as CFString)
2201
+ let afterSelected = stringAttribute(element, attribute: kAXSelectedTextAttribute as CFString)
2202
+ if beforeValue != afterValue || beforeSelected != afterSelected || windowChanged {
2203
+ outcome = "worked"
2204
+ }
2205
+ } else if windowChanged {
2206
+ outcome = "worked"
2207
+ }
2208
+ if windowChanged { evidence["windowChanged"] = true }
2209
+ var response: [String: Any] = ["outcome": outcome, "performed": performed]
2210
+ if !evidence.isEmpty { response["evidence"] = evidence }
2211
+ return finish(response)
2212
+ }
2213
+
2214
+ private func actBatch(_ request: [String: Any]) throws -> [String: Any] {
2215
+ guard let actions = request["actions"] as? [[String: Any]], !actions.isEmpty, actions.count <= 20 else {
2216
+ throw BridgeFailure(message: "actBatch requires 1...20 actions", code: "invalid_args")
2217
+ }
2218
+ let pid = Int32(try intArg(actions[0], "pid"))
2219
+ let lookId = try stringArg(actions[0], "lookId")
2220
+ guard actions.allSatisfy({ ($0["pid"] as? NSNumber)?.int32Value == pid }) else {
2221
+ throw BridgeFailure(message: "actBatch actions must target one pid", code: "invalid_args")
2222
+ }
2223
+ guard actions.allSatisfy({ ($0["lookId"] as? String) == lookId }) else {
2224
+ throw BridgeFailure(message: "actBatch actions must belong to one look", code: "invalid_args")
2225
+ }
2226
+ let eventsLive = ensureRootObserver(pid: pid)
2227
+ let eventCursor = eventsLive ? rootEventCursor(pid: pid) : 0
2228
+ let beforeRootSnapshot = rootMetadataSnapshot(pid: pid)
2229
+ let beforeCgSignature = cgRootSignature(pid: pid)
2230
+ let beforeFrontmostPid = NSWorkspace.shared.frontmostApplication?.processIdentifier
2231
+ let mayUsePhysicalInput = actions.contains { action in
2232
+ (optionalStringArg(action, "policy") ?? "default") != "ax_only"
2233
+ }
2234
+ if mayUsePhysicalInput { physicalInputLock.lock() }
2235
+ defer { if mayUsePhysicalInput { physicalInputLock.unlock() } }
2236
+
2237
+ var steps: [[String: Any]] = []
2238
+ var stoppedAt: Int?
2239
+ for (index, action) in actions.enumerated() {
2240
+ var deferred = action
2241
+ deferred["deferRootDelta"] = true
2242
+ do {
2243
+ let step = try act(deferred)
2244
+ steps.append(step)
2245
+ if (step["outcome"] as? String) == "didnt" { stoppedAt = index; break }
2246
+ } catch let failure as BridgeFailure {
2247
+ steps.append(["outcome": "didnt", "error": ["code": failure.code, "message": failure.message]])
2248
+ stoppedAt = index
2249
+ break
2250
+ }
2251
+ }
2252
+ let outcomes = steps.compactMap { $0["outcome"] as? String }
2253
+ let outcome = outcomes.contains("didnt") ? "didnt" : (outcomes.contains("unknown") ? "unknown" : "worked")
2254
+ var response: [String: Any] = ["outcome": outcome, "performed": ["transaction": true, "actionCount": steps.count], "steps": steps]
2255
+ if let stoppedAt { response["stoppedAt"] = stoppedAt }
2256
+ return attachRootDelta(to: response, before: beforeRootSnapshot, beforeFrontmostPid: beforeFrontmostPid, pid: pid, eventsLive: eventsLive, eventCursor: eventCursor, beforeCgSignature: beforeCgSignature)
2257
+ }
2258
+
2259
+ private func rootIdentity(_ root: [String: Any]) -> String {
2260
+ if let windowId = root["windowId"] as? Int, windowId > 0 { return "window:\(windowId)" }
2261
+ // AXUIElement CFEqual/CFHash are not stable after re-enumeration for all
2262
+ // transient roots; use the metadata tuple that comes from the cheap pass.
2263
+ let kind = root["kind"] as? String ?? "window"
2264
+ let title = root["title"] as? String ?? ""
2265
+ let role = root["role"] as? String ?? ""
2266
+ let frame = root["framePoints"] as? [String: Any] ?? [:]
2267
+ let x = Int((frame["x"] as? NSNumber)?.doubleValue ?? 0)
2268
+ let y = Int((frame["y"] as? NSNumber)?.doubleValue ?? 0)
2269
+ let w = Int((frame["w"] as? NSNumber)?.doubleValue ?? 0)
2270
+ let h = Int((frame["h"] as? NSNumber)?.doubleValue ?? 0)
2271
+ return "meta:\(kind):\(role):\(title):\(x),\(y),\(w),\(h)"
2272
+ }
2273
+
2274
+ private func rootMetadataSnapshot(pid: Int32) -> [String: [String: Any]] {
2275
+ let roots = ((try? listRoots(pid: pid)["roots"] as? [[String: Any]]) ?? [])
2276
+ return Dictionary(uniqueKeysWithValues: roots.map { (rootIdentity($0), $0) })
2277
+ }
2278
+
2279
+ private func rootDelta(before: [String: [String: Any]], beforeFrontmostPid: pid_t?, pid: Int32) -> [[String: Any]] {
2280
+ let after = rootMetadataSnapshot(pid: pid)
2281
+ var delta: [[String: Any]] = []
2282
+ for (key, root) in after where before[key] == nil {
2283
+ delta.append(rootDeltaItem(change: "appeared", root: root, pid: pid))
2284
+ }
2285
+ for (key, root) in before where after[key] == nil {
2286
+ delta.append(rootDeltaItem(change: "closed", root: root, pid: pid))
2287
+ }
2288
+ for (key, root) in after {
2289
+ if (root["isFocused"] as? Bool) == true && (before[key]?["isFocused"] as? Bool) != true {
2290
+ delta.append(rootDeltaItem(change: "focused", root: root, pid: pid))
2291
+ }
2292
+ }
2293
+ if let beforeFrontmostPid, beforeFrontmostPid != NSWorkspace.shared.frontmostApplication?.processIdentifier {
2294
+ if let frontmost = NSWorkspace.shared.frontmostApplication {
2295
+ delta.append(["change": "focused", "kind": "app", "title": frontmost.localizedName ?? processName(pid: frontmost.processIdentifier) ?? "Unknown App", "pid": Int(frontmost.processIdentifier)])
2296
+ }
2297
+ }
2298
+ return delta
2299
+ }
2300
+
2301
+ private func rootDeltaItem(change: String, root: [String: Any], pid: Int32) -> [String: Any] {
2302
+ var item: [String: Any] = ["change": change, "kind": root["kind"] as? String ?? "window", "title": root["title"] as? String ?? "", "pid": root["pid"] as? Int ?? Int(pid)]
2303
+ if let isModal = root["isModal"] as? Bool { item["isModal"] = isModal }
2304
+ if let metadata = root["metadata"] as? [String: Any] { item["metadata"] = metadata }
2305
+ if let ref = root["rootRef"] as? String ?? root["windowRef"] as? String { item["ref"] = ref }
2306
+ return item
2307
+ }
2308
+
2309
+ // The AX snapshot diff is authoritative: macOS emits no AXObserver
2310
+ // notification at all when a sheet appears (verified on macOS 26), so
2311
+ // events can only accelerate the decision, never make it. A cheap
2312
+ // CGWindowList id-set poll detects real-window appearance/closure early;
2313
+ // the AX diff runs once at the first signal or at timeout.
2314
+ private func attachRootDelta(to response: [String: Any], before: [String: [String: Any]], beforeFrontmostPid: pid_t?, pid: Int32, eventsLive: Bool, eventCursor: UInt64, beforeCgSignature: Set<UInt32>) -> [String: Any] {
2315
+ var output = response
2316
+ var performed = output["performed"] as? [String: Any] ?? [:]
2317
+
2318
+ // AXUIElementDestroyed is deliberately not a signal: it fires for every
2319
+ // rebuilt list row; a genuinely closed root also leaves the CG set.
2320
+ let signalNotifications: Set<String> = ["AXWindowCreated", "AXSheetCreated", "AXMenuOpened", "AXMenuClosed", "AXFocusedWindowChanged"]
2321
+ var source = "snapshot"
2322
+ let deadline = Date().addingTimeInterval(0.40)
2323
+ while Date() < deadline {
2324
+ if cgRootSignature(pid: pid) != beforeCgSignature { source = "cg-poll"; break }
2325
+ if let beforeFrontmostPid, NSWorkspace.shared.frontmostApplication?.processIdentifier != beforeFrontmostPid { source = "cg-poll"; break }
2326
+ if eventsLive && rootEvents(pid: pid, since: eventCursor).contains(where: { signalNotifications.contains($0.notification) }) { source = "events"; break }
2327
+ usleep(30_000)
2328
+ }
2329
+
2330
+ var delta = rootDelta(before: before, beforeFrontmostPid: beforeFrontmostPid, pid: pid)
2331
+ if delta.isEmpty && source != "snapshot" {
2332
+ // A signal fired but the AX tree can lag the CG window; give it a
2333
+ // bounded moment to catch up.
2334
+ for _ in 0..<3 where delta.isEmpty {
2335
+ usleep(80_000)
2336
+ delta = rootDelta(before: before, beforeFrontmostPid: beforeFrontmostPid, pid: pid)
2337
+ }
2338
+ }
2339
+ performed["deltaSource"] = source
2340
+ output["performed"] = performed
2341
+ if !delta.isEmpty { output["rootDelta"] = delta }
2342
+ return output
2343
+ }
2344
+
2345
+ private func focusedWindowSummary(pid: Int32) -> String {
2346
+ let app = AXUIElementCreateApplication(pid)
2347
+ guard let element = copyAttribute(app, attribute: kAXFocusedWindowAttribute as CFString).flatMap(asAXElement) else { return "none" }
2348
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2349
+ let title = stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? ""
2350
+ return "\(role):\(title)"
2351
+ }
2352
+
2353
+ private func scrollPositionSignature(_ element: AXUIElement) -> String {
2354
+ let names: [CFString] = ["AXVerticalScrollBar" as CFString, "AXHorizontalScrollBar" as CFString, kAXValueAttribute as CFString]
2355
+ return names.map { String(describing: copyAttribute(element, attribute: $0) ?? "" as CFTypeRef) }.joined(separator: "|")
2356
+ }
2357
+
2358
+ private func axWaitFor(_ request: [String: Any]) throws -> [String: Any] {
2359
+ let pid = Int32(try intArg(request, "pid"))
2360
+ ensureEnhancedAccessibility(pid: pid)
2361
+ let windowId = positiveWindowId(request)
2362
+ let windowRef = optionalStringArg(request, "windowRef")
2363
+ let role = optionalStringArg(request, "role")?.trimmingCharacters(in: .whitespacesAndNewlines)
2364
+ let text = optionalStringArg(request, "text")?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
2365
+ let expectedValue = optionalStringArg(request, "value")?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
2366
+ let waitForGone = boolArg(request, "gone") ?? false
2367
+ let scopeExact = boolArg(request, "scopeExact") ?? false
2368
+ let timeoutMs = max(100, min(60_000, optionalIntArg(request, "timeoutMs") ?? 10_000))
2369
+ let deadline = Date().addingTimeInterval(Double(timeoutMs) / 1000.0)
2370
+ guard role?.isEmpty == false || text?.isEmpty == false || expectedValue?.isEmpty == false else {
2371
+ throw BridgeFailure(message: "axWaitFor requires role, text, or value", code: "invalid_args")
2372
+ }
2373
+ guard let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef) else {
2374
+ return ["found": false, "reason": "window_not_found"]
2375
+ }
2376
+ let rootElement: AXUIElement
2377
+ if let scopeRef = optionalStringArg(request, "scopeRef") {
2378
+ guard let scoped = refStore.element(for: scopeRef), isElement(scoped, descendantOf: window) else {
2379
+ throw BridgeFailure(message: "Condition scope ref is stale or outside the target root", code: "element_ref_invalid")
2380
+ }
2381
+ rootElement = scoped
2382
+ } else {
2383
+ rootElement = window
2384
+ }
2385
+ _ = ensureRootObserver(pid: pid)
2386
+
2387
+ func matches(_ element: AXUIElement) -> Bool {
2388
+ let candidateRole = self.stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2389
+ if let role, !role.isEmpty, candidateRole != role { return false }
2390
+ if let text, !text.isEmpty {
2391
+ let subrole = self.stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
2392
+ let haystack = [
2393
+ self.stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? "",
2394
+ self.stringAttribute(element, attribute: kAXDescriptionAttribute as CFString) ?? "",
2395
+ self.displayValue(element, role: candidateRole, subrole: subrole),
2396
+ ].joined(separator: "\n").lowercased()
2397
+ if !haystack.contains(text) { return false }
2398
+ }
2399
+ if let expectedValue, !expectedValue.isEmpty {
2400
+ let subrole = self.stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
2401
+ if self.displayValue(element, role: candidateRole, subrole: subrole).trimmingCharacters(in: .whitespacesAndNewlines).lowercased() != expectedValue { return false }
2402
+ }
2403
+ return true
2404
+ }
2405
+
2406
+ var lastCount = 0
2407
+ repeat {
2408
+ let changeGeneration = rootChangeGeneration(pid: pid)
2409
+ let collected = collectDescendantsWithContext(startingAt: rootElement, maxDepth: 12, maxNodes: 2000)
2410
+ let descendants = scopeExact ? Array(collected.prefix(1)) : collected
2411
+ lastCount = descendants.count
2412
+ if let match = descendants.first(where: { matches($0.element) }) {
2413
+ if waitForGone {
2414
+ waitForRootChange(pid: pid, since: changeGeneration, until: deadline)
2415
+ continue
2416
+ }
2417
+ let candidateRole = self.stringAttribute(match.element, attribute: kAXRoleAttribute as CFString) ?? ""
2418
+ let isBrowser = isBrowser(pid: pid)
2419
+ let containsWebArea = descendants.contains { self.stringAttribute($0.element, attribute: kAXRoleAttribute as CFString) == "AXWebArea" }
2420
+ return [
2421
+ "found": true,
2422
+ "target": self.elementPayload(
2423
+ element: match.element,
2424
+ key: "target",
2425
+ source: self.axSource(role: candidateRole, insideWebArea: match.insideWebArea, isBrowser: isBrowser, containsWebArea: containsWebArea)
2426
+ ),
2427
+ "nodeCount": lastCount,
2428
+ ]
2429
+ }
2430
+ if waitForGone {
2431
+ return ["found": true, "gone": true, "nodeCount": lastCount]
2432
+ }
2433
+ waitForRootChange(pid: pid, since: changeGeneration, until: deadline)
2434
+ } while Date() < deadline
2435
+
2436
+ return ["found": false, "timedOut": true, "nodeCount": lastCount]
2437
+ }
2438
+
2439
+ private func hitTestElement(at point: CGPoint) -> AXUIElement? {
2440
+ let systemWide = AXUIElementCreateSystemWide()
2441
+ var hitElement: AXUIElement?
2442
+ let status = AXUIElementCopyElementAtPosition(systemWide, Float(point.x), Float(point.y), &hitElement)
2443
+ guard status == .success, let hitElement else { return nil }
2444
+ return hitElement
2445
+ }
2446
+
2447
+ private let axScrollDownAction = "AXScrollDown" as CFString
2448
+ private let axScrollUpAction = "AXScrollUp" as CFString
2449
+ private let axScrollLeftAction = "AXScrollLeft" as CFString
2450
+ private let axScrollRightAction = "AXScrollRight" as CFString
2451
+
2452
+ private func scrollActionNames(scrollX: Int, scrollY: Int) -> [CFString] {
2453
+ var actions: [CFString] = []
2454
+ if scrollY > 0 { actions.append(axScrollDownAction) }
2455
+ if scrollY < 0 { actions.append(axScrollUpAction) }
2456
+ if scrollX > 0 { actions.append(axScrollRightAction) }
2457
+ if scrollX < 0 { actions.append(axScrollLeftAction) }
2458
+ return actions
2459
+ }
2460
+
2461
+ private func supportsAnyScrollAction(_ element: AXUIElement) -> Bool {
2462
+ let actions = Set(actionNames(element))
2463
+ return actions.contains(axScrollDownAction as String) || actions.contains(axScrollUpAction as String) || actions.contains(axScrollLeftAction as String) || actions.contains(axScrollRightAction as String)
2464
+ }
2465
+
2466
+ private func performScrollActionOrAncestor(startingAt element: AXUIElement, targetPid: Int32, scrollX: Int, scrollY: Int, steps: Int) -> [String: Any] {
2467
+ let actions = scrollActionNames(scrollX: scrollX, scrollY: scrollY)
2468
+ guard !actions.isEmpty else { return ["scrolled": false, "reason": "zero_delta"] }
2469
+ var current: AXUIElement? = element
2470
+ var depth = 0
2471
+
2472
+ while let candidate = current, depth < 10 {
2473
+ if let pid = pidForElement(candidate), pid != targetPid {
2474
+ return ["scrolled": false, "reason": "pid_mismatch", "ownerPid": Int(pid)]
2475
+ }
2476
+ var didScroll = false
2477
+ for _ in 0..<steps {
2478
+ for action in actions where supportsAction(candidate, action: action) {
2479
+ let status = AXUIElementPerformAction(candidate, action)
2480
+ if status == .success { didScroll = true }
2481
+ }
2482
+ }
2483
+ if didScroll { return ["scrolled": true] }
2484
+ current = parentElement(candidate)
2485
+ depth += 1
2486
+ }
2487
+
2488
+ return ["scrolled": false, "reason": "no_scroll_action"]
2489
+ }
2490
+
2491
+ private func performActionOrAncestor(startingAt element: AXUIElement, action: CFString, targetPid: Int32) -> [String: Any] {
2492
+ var current: AXUIElement? = element
2493
+ var depth = 0
2494
+
2495
+ while let candidate = current, depth < 10 {
2496
+ if let pid = pidForElement(candidate), pid != targetPid {
2497
+ return ["performed": false, "reason": "pid_mismatch", "ownerPid": Int(pid)]
2498
+ }
2499
+
2500
+ if supportsAction(candidate, action: action) {
2501
+ let actionStatus = AXUIElementPerformAction(candidate, action)
2502
+ if actionStatus == .success {
2503
+ return ["performed": true]
2504
+ }
2505
+ }
2506
+
2507
+ current = parentElement(candidate)
2508
+ depth += 1
2509
+ }
2510
+
2511
+ return ["performed": false, "reason": "no_matching_action"]
2512
+ }
2513
+
2514
+ private func windowElement(pid: Int32, windowId: UInt32?, windowRef: String? = nil) -> AXUIElement? {
2515
+ if let windowRef, let stored = refStore.window(for: windowRef) {
2516
+ AXUIElementSetMessagingTimeout(stored, 1.0)
2517
+ var ownerPid: pid_t = 0
2518
+ if AXUIElementGetPid(stored, &ownerPid) == .success, ownerPid == pid {
2519
+ return stored
2520
+ }
2521
+ }
2522
+
2523
+ let appElement = AXUIElementCreateApplication(pid)
2524
+ AXUIElementSetMessagingTimeout(appElement, 1.0)
2525
+ let windows = Array(axElementArray(appElement, attribute: kAXWindowsAttribute as CFString).prefix(128))
2526
+ guard !windows.isEmpty else { return nil }
2527
+ guard let windowId else {
2528
+ return windowRef == nil ? windows.first : nil
2529
+ }
2530
+ let candidates = cgWindowCandidates(pid: pid)
2531
+ let pairings = windowPairings(windows: windows, candidates: candidates)
2532
+ for window in windows {
2533
+ if pairings[ObjectIdentifier(window)]?.candidate?.windowId == windowId {
2534
+ return window
2535
+ }
2536
+ for sheet in sheetElements(of: window) {
2537
+ if bestCandidate(for: sheet, candidates: candidates)?.windowId == windowId {
2538
+ return sheet
2539
+ }
2540
+ }
2541
+ }
2542
+ return nil
2543
+ }
2544
+
2545
+ private func findDescendant(startingAt root: AXUIElement, maxDepth: Int, predicate: (AXUIElement) -> Bool) -> AXUIElement? {
2546
+ collectDescendants(startingAt: root, maxDepth: maxDepth).first(where: predicate)
2547
+ }
2548
+
2549
+ private func ensureEnhancedAccessibility(pid: Int32) {
2550
+ enhancedAccessibilityLock.lock()
2551
+ let inserted = enhancedAccessibilityPids.insert(pid).inserted
2552
+ enhancedAccessibilityLock.unlock()
2553
+ if !inserted { return }
2554
+ let appElement = AXUIElementCreateApplication(pid)
2555
+ AXUIElementSetMessagingTimeout(appElement, 0.25)
2556
+ let enhancedStatus = AXUIElementSetAttributeValue(appElement, "AXEnhancedUserInterface" as CFString, kCFBooleanTrue)
2557
+ let manualStatus = AXUIElementSetAttributeValue(appElement, "AXManualAccessibility" as CFString, kCFBooleanTrue)
2558
+ // Chromium-family apps often materialize web-content AX asynchronously
2559
+ // after these toggles. Pay a small one-time settle cost per pid so the
2560
+ // first tree walk is less likely to see browser chrome only.
2561
+ if isBrowser(pid: pid) && (enhancedStatus == .success || manualStatus == .success) {
2562
+ Thread.sleep(forTimeInterval: 0.35)
2563
+ }
2564
+ }
2565
+
2566
+ private func isBrowser(pid: Int32) -> Bool {
2567
+ let app = NSRunningApplication(processIdentifier: pid)
2568
+ if browserBundleIds.contains(app?.bundleIdentifier ?? "") { return true }
2569
+ let name = (app?.localizedName ?? processName(pid: pid) ?? "").lowercased()
2570
+ return ["chrome", "chromium", "brave", "edge", "vivaldi", "opera", "firefox", "helium"].contains { name.contains($0) }
2571
+ }
2572
+
2573
+ private func collectDescendants(startingAt root: AXUIElement, maxDepth: Int, maxNodes: Int = 5000) -> [AXUIElement] {
2574
+ collectDescendantsWithContext(startingAt: root, maxDepth: maxDepth, maxNodes: maxNodes).map(\.element)
2575
+ }
2576
+
2577
+ private func collectDescendantsWithContext(startingAt root: AXUIElement, maxDepth: Int, maxNodes: Int = 5000) -> [AXDescendant] {
2578
+ let nodeLimit = max(1, maxNodes)
2579
+ var queue: [(AXUIElement, Int, Bool, Bool)] = [(root, 0, false, true)]
2580
+ var seen = Set<ObjectIdentifier>()
2581
+ var index = 0
2582
+ var output: [AXDescendant] = []
2583
+ while index < queue.count && output.count < nodeLimit {
2584
+ let (element, depth, parentInsideWebArea, inheritedVisible) = queue[index]
2585
+ index += 1
2586
+ let identity = ObjectIdentifier(element)
2587
+ if seen.contains(identity) { continue }
2588
+ seen.insert(identity)
2589
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2590
+ let insideWebArea = parentInsideWebArea || role == "AXWebArea"
2591
+ output.append(AXDescendant(element: element, depth: depth, insideWebArea: insideWebArea, axVisible: inheritedVisible))
2592
+ if depth >= maxDepth { continue }
2593
+ let children = axElementArray(element, attribute: kAXChildrenAttribute as CFString)
2594
+ let visibleChildren = visibleAXChildren(element)
2595
+ for child in children {
2596
+ if queue.count >= nodeLimit { break }
2597
+ let childVisible = inheritedVisible && (visibleChildren.map { set in set.contains { self.sameElement($0, child) } } ?? true)
2598
+ queue.append((child, depth + 1, insideWebArea, childVisible))
2599
+ }
2600
+ }
2601
+ return output
2602
+ }
2603
+
2604
+ private func visibleAXChildren(_ element: AXUIElement) -> [AXUIElement]? {
2605
+ let attributes: [CFString] = [
2606
+ kAXVisibleChildrenAttribute as CFString,
2607
+ kAXVisibleRowsAttribute as CFString,
2608
+ kAXVisibleColumnsAttribute as CFString,
2609
+ kAXVisibleCellsAttribute as CFString,
2610
+ ]
2611
+ let visible = attributes.flatMap { axElementArray(element, attribute: $0) }
2612
+ return visible.isEmpty ? nil : visible
2613
+ }
2614
+
2615
+ private func insideWebAreaMap(_ descendants: [AXDescendant]) -> [ObjectIdentifier: Bool] {
2616
+ var output: [ObjectIdentifier: Bool] = [:]
2617
+ for descendant in descendants {
2618
+ let key = ObjectIdentifier(descendant.element)
2619
+ output[key] = (output[key] ?? false) || descendant.insideWebArea
2620
+ }
2621
+ return output
2622
+ }
2623
+
2624
+ private func axSource(role: String, insideWebArea: Bool, isBrowser: Bool, containsWebArea: Bool) -> String {
2625
+ if insideWebArea || role == "AXWebArea" { return "web_content_ax" }
2626
+ if isBrowser || containsWebArea { return "browser_chrome_ax" }
2627
+ return "desktop_ax"
2628
+ }
2629
+
2630
+ private func frameForElement(_ element: AXUIElement) -> CGRect? {
2631
+ let origin = pointAttribute(element, attribute: kAXPositionAttribute as CFString)
2632
+ let size = sizeAttribute(element, attribute: kAXSizeAttribute as CFString)
2633
+ guard let origin, let size, size.width > 0, size.height > 0 else { return nil }
2634
+ return CGRect(origin: origin, size: size)
2635
+ }
2636
+
2637
+ private func elementPayload(element: AXUIElement, key: String, score: Double? = nil, source: String? = nil, axVisible: Bool = true) -> [String: Any] {
2638
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2639
+ let subrole = stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
2640
+ let title = stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? ""
2641
+ let description = stringAttribute(element, attribute: kAXDescriptionAttribute as CFString) ?? ""
2642
+ let identifier = stringAttribute(element, attribute: "AXIdentifier" as CFString) ?? ""
2643
+ let value = displayValue(element, role: role, subrole: subrole)
2644
+ let frame = frameForElement(element)
2645
+ let parentFrame = copyAttribute(element, attribute: kAXParentAttribute as CFString).flatMap(asAXElement).flatMap(frameForElement)
2646
+ let centerX = frame.map { $0.midX } ?? 0
2647
+ let centerY = frame.map { $0.midY } ?? 0
2648
+ var valueSettable = DarwinBoolean(false)
2649
+ let valueStatus = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &valueSettable)
2650
+ var focusedSettable = DarwinBoolean(false)
2651
+ let focusedStatus = AXUIElementIsAttributeSettable(element, kAXFocusedAttribute as CFString, &focusedSettable)
2652
+ let actions = actionNames(element)
2653
+ let canSetValue = valueStatus == .success && valueSettable.boolValue
2654
+ let textRoles: Set<String> = [
2655
+ "AXTextField", "AXTextArea", "AXTextView", "AXSearchField", "AXComboBox", "AXEditableText", "AXSecureTextField",
2656
+ ]
2657
+ var payload: [String: Any] = [
2658
+ key: true,
2659
+ "elementRef": refStore.storeElement(element),
2660
+ "role": role,
2661
+ "subrole": subrole,
2662
+ "title": title,
2663
+ "description": description,
2664
+ "identifier": identifier,
2665
+ "value": value,
2666
+ "actions": actions,
2667
+ "isTextInput": textRoles.contains(role),
2668
+ "canSetValue": canSetValue,
2669
+ "canFocus": focusedStatus == .success && focusedSettable.boolValue,
2670
+ "canPress": actions.contains(kAXPressAction as String),
2671
+ "canScroll": supportsAnyScrollAction(element),
2672
+ "canIncrement": actions.contains(kAXIncrementAction as String),
2673
+ "canDecrement": actions.contains(kAXDecrementAction as String),
2674
+ "axVisible": axVisible,
2675
+ "x": centerX,
2676
+ "y": centerY,
2677
+ ]
2678
+ if let frame {
2679
+ payload["frame"] = ["x": frame.origin.x, "y": frame.origin.y, "w": frame.width, "h": frame.height]
2680
+ }
2681
+ if let parentFrame {
2682
+ payload["parentFrame"] = ["x": parentFrame.origin.x, "y": parentFrame.origin.y, "w": parentFrame.width, "h": parentFrame.height]
2683
+ }
2684
+ if let score {
2685
+ payload["score"] = score
2686
+ }
2687
+ if let source {
2688
+ payload["source"] = source
2689
+ }
2690
+ return payload
2691
+ }
2692
+
2693
+ private func pidForElement(_ element: AXUIElement) -> Int32? {
2694
+ var pid: pid_t = 0
2695
+ let status = AXUIElementGetPid(element, &pid)
2696
+ guard status == .success else { return nil }
2697
+ return Int32(pid)
2698
+ }
2699
+
2700
+ private func parentElement(_ element: AXUIElement) -> AXUIElement? {
2701
+ guard let value = copyAttribute(element, attribute: kAXParentAttribute as CFString) else {
2702
+ return nil
2703
+ }
2704
+ return asAXElement(value)
2705
+ }
2706
+
2707
+ private func sameElement(_ lhs: AXUIElement, _ rhs: AXUIElement) -> Bool {
2708
+ CFEqual(lhs as CFTypeRef, rhs as CFTypeRef)
2709
+ }
2710
+
2711
+ private func isElement(_ element: AXUIElement, descendantOf ancestor: AXUIElement) -> Bool {
2712
+ var current: AXUIElement? = element
2713
+ var depth = 0
2714
+ while let candidate = current, depth < 20 {
2715
+ if sameElement(candidate, ancestor) {
2716
+ return true
2717
+ }
2718
+ current = parentElement(candidate)
2719
+ depth += 1
2720
+ }
2721
+ return false
2722
+ }
2723
+
2724
+ private func hasAncestorRole(_ element: AXUIElement, role: String) -> Bool {
2725
+ var current: AXUIElement? = element
2726
+ var depth = 0
2727
+ while let candidate = current, depth < 30 {
2728
+ if stringAttribute(candidate, attribute: kAXRoleAttribute as CFString) == role { return true }
2729
+ current = parentElement(candidate)
2730
+ depth += 1
2731
+ }
2732
+ return false
2733
+ }
2734
+
2735
+ private func actionNames(_ element: AXUIElement) -> [String] {
2736
+ var actionsValue: CFArray?
2737
+ let status = AXUIElementCopyActionNames(element, &actionsValue)
2738
+ guard status == .success else { return [] }
2739
+ guard let actionsArray = actionsValue as? [AnyObject] else { return [] }
2740
+ return actionsArray.compactMap { $0 as? String }
2741
+ }
2742
+
2743
+ private func supportsAction(_ element: AXUIElement, action: CFString) -> Bool {
2744
+ actionNames(element).contains(action as String)
2745
+ }
2746
+
2747
+ private func focusedElement(_ request: [String: Any]) throws -> [String: Any] {
2748
+ let pid = Int32(try intArg(request, "pid"))
2749
+ let windowId = optionalIntArg(request, "windowId").map { UInt32($0) }
2750
+ let windowRef = optionalStringArg(request, "windowRef")
2751
+ let app = AXUIElementCreateApplication(pid)
2752
+ guard let focusedValue = copyAttribute(app, attribute: kAXFocusedUIElementAttribute as CFString),
2753
+ let element = asAXElement(focusedValue)
2754
+ else {
2755
+ return ["exists": false]
2756
+ }
2757
+ if windowId != nil || windowRef != nil {
2758
+ guard let window = windowElement(pid: pid, windowId: windowId, windowRef: windowRef) else {
2759
+ return ["exists": false, "reason": "window_not_found"]
2760
+ }
2761
+ guard isElement(element, descendantOf: window) else {
2762
+ return ["exists": false, "reason": "focused_element_outside_window"]
2763
+ }
2764
+ }
2765
+
2766
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2767
+ let subrole = stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
2768
+ let secure = role == "AXSecureTextField" || subrole == "AXSecureTextField"
2769
+
2770
+ var settable = DarwinBoolean(false)
2771
+ let settableStatus = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &settable)
2772
+ let canSetValue = settableStatus == .success && settable.boolValue
2773
+
2774
+ let textRoles: Set<String> = [
2775
+ "AXTextField",
2776
+ "AXTextArea",
2777
+ "AXTextView",
2778
+ "AXSearchField",
2779
+ "AXComboBox",
2780
+ "AXEditableText",
2781
+ "AXSecureTextField",
2782
+ ]
2783
+
2784
+ let isTextInput = textRoles.contains(role) || canSetValue
2785
+ let elementRef = refStore.storeElement(element)
2786
+
2787
+ return [
2788
+ "exists": true,
2789
+ "elementRef": elementRef,
2790
+ "role": role,
2791
+ "subrole": subrole,
2792
+ "isTextInput": isTextInput,
2793
+ "isSecure": secure,
2794
+ "canSetValue": canSetValue,
2795
+ ]
2796
+ }
2797
+
2798
+ private func axReadText(_ request: [String: Any]) throws -> [String: Any] {
2799
+ let elementRef = try stringArg(request, "elementRef")
2800
+ let offset = max(0, optionalIntArg(request, "offset") ?? 0)
2801
+ let limit = max(1, min(100_000, optionalIntArg(request, "limit") ?? 4_000))
2802
+ guard let element = refStore.element(for: elementRef) else {
2803
+ throw BridgeFailure(message: "Element reference is no longer valid", code: "element_ref_invalid")
2804
+ }
2805
+ let role = stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? ""
2806
+ let subrole = stringAttribute(element, attribute: kAXSubroleAttribute as CFString) ?? ""
2807
+ guard !isSecureTextElement(role: role, subrole: subrole) else {
2808
+ throw BridgeFailure(message: "Refers to a secure text field; refusing to read its value", code: "secure_text_unreadable")
2809
+ }
2810
+ guard let value = stringAttribute(element, attribute: kAXValueAttribute as CFString) else {
2811
+ throw BridgeFailure(message: "Element has no readable AXValue. Call snapshot/screenshot and choose a text-bearing ref.", code: "text_unavailable")
2812
+ }
2813
+ let characters = Array(value)
2814
+ if offset >= characters.count {
2815
+ return ["text": "", "offset": offset, "limit": limit, "totalChars": characters.count, "hasMore": false]
2816
+ }
2817
+ let end = min(characters.count, offset + limit)
2818
+ return [
2819
+ "text": String(characters[offset..<end]),
2820
+ "offset": offset,
2821
+ "limit": limit,
2822
+ "totalChars": characters.count,
2823
+ "hasMore": end < characters.count,
2824
+ ]
2825
+ }
2826
+
2827
+ private func getMousePosition() -> [String: Any] {
2828
+ let position = NSEvent.mouseLocation
2829
+ return ["x": position.x, "y": position.y]
2830
+ }
2831
+
2832
+ private func copyAttribute(_ element: AXUIElement, attribute: CFString) -> AnyObject? {
2833
+ var value: AnyObject?
2834
+ let status = AXUIElementCopyAttributeValue(element, attribute, &value)
2835
+ guard status == .success else { return nil }
2836
+ return value
2837
+ }
2838
+
2839
+ private func boolAttribute(_ element: AXUIElement, attribute: CFString) -> Bool? {
2840
+ guard let value = copyAttribute(element, attribute: attribute) else { return nil }
2841
+ if let boolValue = value as? Bool {
2842
+ return boolValue
2843
+ }
2844
+ if let number = value as? NSNumber {
2845
+ return number.boolValue
2846
+ }
2847
+ return nil
2848
+ }
2849
+
2850
+ private func stringAttribute(_ element: AXUIElement, attribute: CFString) -> String? {
2851
+ copyAttribute(element, attribute: attribute) as? String
2852
+ }
2853
+
2854
+ // Secure fields can expose plaintext through AX value in non-native apps,
2855
+ // and serialized values flow into the model conversation. Never emit them.
2856
+ private func isSecureTextElement(role: String, subrole: String) -> Bool {
2857
+ role == "AXSecureTextField" || subrole == "AXSecureTextField"
2858
+ }
2859
+
2860
+ private func displayValue(_ element: AXUIElement, role: String, subrole: String) -> String {
2861
+ if isSecureTextElement(role: role, subrole: subrole) { return "" }
2862
+ return stringAttribute(element, attribute: kAXValueAttribute as CFString) ?? ""
2863
+ }
2864
+
2865
+ // kAXSheetsAttribute is unsupported (-25205) on recent macOS; sheets are
2866
+ // exposed only as AXSheet-role children. Merge both sources so sheet
2867
+ // discovery works across versions.
2868
+ private func sheetElements(of window: AXUIElement) -> [AXUIElement] {
2869
+ var sheets = axElementArray(window, attribute: "AXSheets" as CFString)
2870
+ for child in axElementArray(window, attribute: kAXChildrenAttribute as CFString) {
2871
+ guard (stringAttribute(child, attribute: kAXRoleAttribute as CFString) ?? "") == "AXSheet" else { continue }
2872
+ if !sheets.contains(where: { CFEqual($0, child) }) { sheets.append(child) }
2873
+ }
2874
+ return sheets
2875
+ }
2876
+
2877
+ private func axElementArray(_ element: AXUIElement, attribute: CFString) -> [AXUIElement] {
2878
+ guard let value = copyAttribute(element, attribute: attribute) else { return [] }
2879
+ if let array = value as? [AXUIElement] {
2880
+ return array
2881
+ }
2882
+ if let anyArray = value as? [AnyObject] {
2883
+ return anyArray.compactMap(asAXElement)
2884
+ }
2885
+ return []
2886
+ }
2887
+
2888
+ private func axElementArrayIfPresent(_ element: AXUIElement, attribute: CFString) -> [AXUIElement]? {
2889
+ var value: CFTypeRef?
2890
+ let status = AXUIElementCopyAttributeValue(element, attribute, &value)
2891
+ guard status == .success, let value else { return nil }
2892
+ if let array = value as? [AXUIElement] {
2893
+ return array
2894
+ }
2895
+ if let anyArray = value as? [AnyObject] {
2896
+ return anyArray.compactMap(asAXElement)
2897
+ }
2898
+ return []
2899
+ }
2900
+
2901
+ private func asAXElement(_ value: AnyObject) -> AXUIElement? {
2902
+ let cfValue = value as CFTypeRef
2903
+ guard CFGetTypeID(cfValue) == AXUIElementGetTypeID() else { return nil }
2904
+ return unsafeBitCast(cfValue, to: AXUIElement.self)
2905
+ }
2906
+
2907
+ private func pointAttribute(_ element: AXUIElement, attribute: CFString) -> CGPoint? {
2908
+ guard let value = copyAttribute(element, attribute: attribute) else { return nil }
2909
+ let cfValue = value as CFTypeRef
2910
+ guard CFGetTypeID(cfValue) == AXValueGetTypeID() else { return nil }
2911
+ let axValue = unsafeBitCast(cfValue, to: AXValue.self)
2912
+ guard AXValueGetType(axValue) == .cgPoint else { return nil }
2913
+ var point = CGPoint.zero
2914
+ guard AXValueGetValue(axValue, .cgPoint, &point) else { return nil }
2915
+ return point
2916
+ }
2917
+
2918
+ private func sizeAttribute(_ element: AXUIElement, attribute: CFString) -> CGSize? {
2919
+ guard let value = copyAttribute(element, attribute: attribute) else { return nil }
2920
+ let cfValue = value as CFTypeRef
2921
+ guard CFGetTypeID(cfValue) == AXValueGetTypeID() else { return nil }
2922
+ let axValue = unsafeBitCast(cfValue, to: AXValue.self)
2923
+ guard AXValueGetType(axValue) == .cgSize else { return nil }
2924
+ var size = CGSize.zero
2925
+ guard AXValueGetValue(axValue, .cgSize, &size) else { return nil }
2926
+ return size
2927
+ }
2928
+
2929
+ private func frameForWindow(_ window: AXUIElement) -> CGRect {
2930
+ let origin = pointAttribute(window, attribute: kAXPositionAttribute as CFString) ?? .zero
2931
+ let size = sizeAttribute(window, attribute: kAXSizeAttribute as CFString) ?? .zero
2932
+ return CGRect(origin: origin, size: size)
2933
+ }
2934
+
2935
+ private func allCGWindowEntries() -> [[String: Any]] {
2936
+ (CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]]) ?? []
2937
+ }
2938
+
2939
+ private func cgWindowOwners(entries suppliedEntries: [[String: Any]]? = nil) -> [CGWindowOwnerSummary] {
2940
+ let entries = suppliedEntries ?? allCGWindowEntries()
2941
+ var seen = Set<Int32>()
2942
+ var owners: [CGWindowOwnerSummary] = []
2943
+ for entry in entries {
2944
+ guard let ownerPid = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { continue }
2945
+ let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
2946
+ if layer != 0 || seen.contains(ownerPid) { continue }
2947
+ guard let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
2948
+ let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary),
2949
+ bounds.width >= 100,
2950
+ bounds.height >= 80
2951
+ else {
2952
+ continue
2953
+ }
2954
+ let ownerName = (entry[kCGWindowOwnerName as String] as? String) ?? processName(pid: ownerPid) ?? "Unknown App"
2955
+ seen.insert(ownerPid)
2956
+ owners.append(CGWindowOwnerSummary(pid: ownerPid, name: ownerName))
2957
+ }
2958
+ return owners
2959
+ }
2960
+
2961
+ private func pidForWindowId(_ windowId: UInt32) -> Int32? {
2962
+ windowInfo(windowId: windowId)?.pid
2963
+ }
2964
+
2965
+ private func cgWindowCandidates(pid: Int32, entries suppliedEntries: [[String: Any]]? = nil) -> [CGWindowCandidate] {
2966
+ let entries = suppliedEntries ?? allCGWindowEntries()
2967
+ var candidates: [CGWindowCandidate] = []
2968
+ for (zOrder, entry) in entries.enumerated() {
2969
+ guard let ownerPid = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
2970
+ ownerPid == pid
2971
+ else {
2972
+ continue
2973
+ }
2974
+ let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
2975
+ if layer != 0 { continue }
2976
+
2977
+ guard let windowNumber = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value else {
2978
+ continue
2979
+ }
2980
+ guard let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
2981
+ let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
2982
+ else {
2983
+ continue
2984
+ }
2985
+
2986
+ let title = (entry[kCGWindowName as String] as? String) ?? ""
2987
+ let isOnscreen = (entry[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue ?? true
2988
+ candidates.append(
2989
+ CGWindowCandidate(
2990
+ windowId: windowNumber,
2991
+ title: title,
2992
+ bounds: bounds,
2993
+ isOnscreen: isOnscreen,
2994
+ layer: layer,
2995
+ zOrder: zOrder
2996
+ )
2997
+ )
2998
+ if candidates.count == 128 { break }
2999
+ }
3000
+ return candidates
3001
+ }
3002
+
3003
+ private func cgBroadRootOwners(entries: [[String: Any]]) -> [CGWindowOwnerSummary] {
3004
+ let popupLevel = Int(CGWindowLevelForKey(.popUpMenuWindow))
3005
+ var seen = Set<Int32>()
3006
+ return entries.compactMap { entry -> CGWindowOwnerSummary? in
3007
+ let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
3008
+ guard layer == 0 || layer == popupLevel,
3009
+ let pid = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value
3010
+ else { return nil }
3011
+ if layer == popupLevel {
3012
+ guard (entry[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue == true else { return nil }
3013
+ } else {
3014
+ guard let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
3015
+ let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary),
3016
+ bounds.width >= 100,
3017
+ bounds.height >= 80
3018
+ else { return nil }
3019
+ }
3020
+ guard seen.insert(pid).inserted else { return nil }
3021
+ let name = (entry[kCGWindowOwnerName as String] as? String) ?? processName(pid: pid) ?? "Unknown App"
3022
+ return CGWindowOwnerSummary(pid: pid, name: name)
3023
+ }
3024
+ }
3025
+
3026
+ private func cgPopupMenuCandidates(pid: Int32?, entries: [[String: Any]]) -> [CGWindowCandidate] {
3027
+ let popupLevel = Int(CGWindowLevelForKey(.popUpMenuWindow))
3028
+ var candidates: [CGWindowCandidate] = []
3029
+ for (zOrder, entry) in entries.enumerated() {
3030
+ guard let ownerPid = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { continue }
3031
+ if let pid, ownerPid != pid { continue }
3032
+ let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
3033
+ if layer != popupLevel { continue }
3034
+ guard let windowNumber = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value,
3035
+ let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
3036
+ let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
3037
+ else { continue }
3038
+ let title = (entry[kCGWindowName as String] as? String) ?? ""
3039
+ let isOnscreen = (entry[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue ?? false
3040
+ guard isOnscreen else { continue }
3041
+ candidates.append(CGWindowCandidate(windowId: windowNumber, title: title, bounds: bounds, isOnscreen: isOnscreen, layer: layer, zOrder: zOrder))
3042
+ if candidates.count == 128 { break }
3043
+ }
3044
+ return candidates
3045
+ }
3046
+
3047
+ private func openMenuElements(pid: Int32, messagingTimeout: Float = 1.0) -> [AXUIElement] {
3048
+ let app = AXUIElementCreateApplication(pid)
3049
+ AXUIElementSetMessagingTimeout(app, messagingTimeout)
3050
+ let descendants = collectDescendants(startingAt: app, maxDepth: 6)
3051
+ var menus = descendants.filter { (stringAttribute($0, attribute: kAXRoleAttribute as CFString) ?? "") == "AXMenu" }
3052
+ if menus.isEmpty,
3053
+ let focused = copyAttribute(app, attribute: kAXFocusedUIElementAttribute as CFString).flatMap(asAXElement)
3054
+ {
3055
+ var current: AXUIElement? = focused
3056
+ while let element = current {
3057
+ if (stringAttribute(element, attribute: kAXRoleAttribute as CFString) ?? "") == "AXMenu" {
3058
+ menus.append(element)
3059
+ break
3060
+ }
3061
+ current = copyAttribute(element, attribute: kAXParentAttribute as CFString).flatMap(asAXElement)
3062
+ }
3063
+ }
3064
+ return menus
3065
+ }
3066
+
3067
+ private func bestCandidate(for element: AXUIElement, candidates: [CGWindowCandidate]) -> CGWindowCandidate? {
3068
+ let title = stringAttribute(element, attribute: kAXTitleAttribute as CFString) ?? ""
3069
+ let frame = frameForWindow(element)
3070
+ return candidates.max { left, right in
3071
+ windowPairScore(frame: frame, title: title, candidate: left) < windowPairScore(frame: frame, title: title, candidate: right)
3072
+ }
3073
+ }
3074
+
3075
+ private func pairingForWindow(_ window: AXUIElement, pid: Int32) -> WindowPairing {
3076
+ windowPairings(windows: [window], candidates: cgWindowCandidates(pid: pid))[ObjectIdentifier(window)] ?? WindowPairing(candidate: nil, score: -Double.greatestFiniteMagnitude, confidence: "low")
3077
+ }
3078
+
3079
+ private func windowPairings(windows: [AXUIElement], candidates: [CGWindowCandidate]) -> [ObjectIdentifier: WindowPairing] {
3080
+ var pairs: [(window: AXUIElement, candidate: CGWindowCandidate, score: Double)] = []
3081
+ for window in windows {
3082
+ let title = stringAttribute(window, attribute: kAXTitleAttribute as CFString) ?? ""
3083
+ let frame = frameForWindow(window)
3084
+ for candidate in candidates {
3085
+ pairs.append((window, candidate, windowPairScore(frame: frame, title: title, candidate: candidate)))
3086
+ }
3087
+ }
3088
+ pairs.sort { $0.score > $1.score }
3089
+ var output: [ObjectIdentifier: WindowPairing] = [:]
3090
+ var usedWindows = Set<ObjectIdentifier>()
3091
+ var usedCandidateIds = Set<UInt32>()
3092
+ for pair in pairs {
3093
+ let key = ObjectIdentifier(pair.window)
3094
+ if usedWindows.contains(key) || usedCandidateIds.contains(pair.candidate.windowId) { continue }
3095
+ usedWindows.insert(key)
3096
+ usedCandidateIds.insert(pair.candidate.windowId)
3097
+ let frame = frameForWindow(pair.window)
3098
+ let title = stringAttribute(pair.window, attribute: kAXTitleAttribute as CFString) ?? ""
3099
+ output[key] = WindowPairing(candidate: pair.score >= 0 ? pair.candidate : nil, score: pair.score, confidence: pairingConfidence(frame: frame, title: title, candidate: pair.candidate, score: pair.score))
3100
+ }
3101
+ for window in windows {
3102
+ let key = ObjectIdentifier(window)
3103
+ if output[key] == nil {
3104
+ output[key] = WindowPairing(candidate: nil, score: -Double.greatestFiniteMagnitude, confidence: "low")
3105
+ }
3106
+ }
3107
+ return output
3108
+ }
3109
+
3110
+ private func windowPairScore(frame: CGRect, title: String, candidate: CGWindowCandidate) -> Double {
3111
+ var score = 0.0
3112
+ let normalizedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
3113
+ let candidateTitle = candidate.title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
3114
+ if !normalizedTitle.isEmpty && !candidateTitle.isEmpty {
3115
+ if normalizedTitle == candidateTitle {
3116
+ score += 100
3117
+ } else if normalizedTitle.contains(candidateTitle) || candidateTitle.contains(normalizedTitle) {
3118
+ score += 50
3119
+ }
3120
+ }
3121
+ if frame.width > 1 && frame.height > 1 {
3122
+ let dx = abs(candidate.bounds.origin.x - frame.origin.x)
3123
+ let dy = abs(candidate.bounds.origin.y - frame.origin.y)
3124
+ let dw = abs(candidate.bounds.size.width - frame.size.width)
3125
+ let dh = abs(candidate.bounds.size.height - frame.size.height)
3126
+ score -= Double(dx + dy + dw + dh) / 20.0
3127
+ }
3128
+ if candidate.isOnscreen { score += 10 }
3129
+ return score
3130
+ }
3131
+
3132
+ private func pairingConfidence(frame: CGRect, title: String, candidate: CGWindowCandidate, score: Double) -> String {
3133
+ guard frame.width > 1 && frame.height > 1 else { return "low" }
3134
+ let normalizedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
3135
+ let candidateTitle = candidate.title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
3136
+ let titleEqual = !normalizedTitle.isEmpty && !candidateTitle.isEmpty && normalizedTitle == candidateTitle
3137
+ let geometryExact = abs(frame.origin.x - candidate.bounds.origin.x) <= 2 && abs(frame.origin.y - candidate.bounds.origin.y) <= 2 && abs(frame.width - candidate.bounds.width) <= 2 && abs(frame.height - candidate.bounds.height) <= 2
3138
+ if titleEqual && geometryExact { return "exact" }
3139
+ if score >= 50 { return "high" }
3140
+ return "low"
3141
+ }
3142
+
3143
+ private func displayScaleFactor(for frame: CGRect) -> Double {
3144
+ var displayCount: UInt32 = 0
3145
+ guard CGGetOnlineDisplayList(0, nil, &displayCount) == .success, displayCount > 0 else {
3146
+ return Double(NSScreen.main?.backingScaleFactor ?? 1.0)
3147
+ }
3148
+
3149
+ var displays = Array(repeating: CGDirectDisplayID(), count: Int(displayCount))
3150
+ guard CGGetOnlineDisplayList(displayCount, &displays, &displayCount) == .success else {
3151
+ return Double(NSScreen.main?.backingScaleFactor ?? 1.0)
3152
+ }
3153
+
3154
+ var chosenDisplay: CGDirectDisplayID?
3155
+ var chosenArea: CGFloat = -1
3156
+ for display in displays {
3157
+ let bounds = CGDisplayBounds(display)
3158
+ let overlap = bounds.intersection(frame)
3159
+ let area = overlap.isNull ? 0 : overlap.width * overlap.height
3160
+ if area > chosenArea {
3161
+ chosenArea = area
3162
+ chosenDisplay = display
3163
+ }
3164
+ }
3165
+
3166
+ guard let display = chosenDisplay, let mode = CGDisplayCopyDisplayMode(display) else {
3167
+ return Double(NSScreen.main?.backingScaleFactor ?? 1.0)
3168
+ }
3169
+
3170
+ let width = Double(mode.width)
3171
+ guard width > 0 else { return 1.0 }
3172
+ let scale = Double(mode.pixelWidth) / width
3173
+ return scale > 0 ? scale : 1.0
3174
+ }
3175
+
3176
+ private func captureWindow(windowId: UInt32) throws -> CapturedWindowImage {
3177
+ if #available(macOS 14.0, *) {
3178
+ let semaphore = DispatchSemaphore(value: 0)
3179
+ let capturedImage = Box<CGImage?>(nil)
3180
+ let capturedError = Box<Error?>(nil)
3181
+
3182
+ let task = Task {
3183
+ defer { semaphore.signal() }
3184
+ do {
3185
+ if Task.isCancelled {
3186
+ return
3187
+ }
3188
+ let shareable = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
3189
+ guard let window = shareable.windows.first(where: { $0.windowID == windowId }) else {
3190
+ throw BridgeFailure(message: "Window \(windowId) is not available for capture", code: "window_not_found")
3191
+ }
3192
+
3193
+ let filter = SCContentFilter(desktopIndependentWindow: window)
3194
+ let config = SCStreamConfiguration()
3195
+ // Avoid ScreenCaptureKit's default 1920x1080 canvas for window captures.
3196
+ let scale = displayScaleFactor(for: window.frame)
3197
+ config.width = max(1, Int((window.frame.width * scale).rounded()))
3198
+ config.height = max(1, Int((window.frame.height * scale).rounded()))
3199
+ config.showsCursor = false
3200
+ config.ignoreShadowsSingleWindow = true
3201
+
3202
+ let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
3203
+ capturedImage.value = image
3204
+ } catch {
3205
+ capturedError.value = error
3206
+ }
3207
+ }
3208
+
3209
+ if semaphore.wait(timeout: .now() + .seconds(8)) == .timedOut {
3210
+ task.cancel()
3211
+ if let payload = try cgWindowScreenshotFallback(windowId: windowId) {
3212
+ return payload
3213
+ }
3214
+ throw BridgeFailure(message: "Capture timed out while capturing window \(windowId)", code: "capture_timeout")
3215
+ }
3216
+
3217
+ if let error = capturedError.value {
3218
+ if let payload = try cgWindowScreenshotFallback(windowId: windowId) {
3219
+ return payload
3220
+ }
3221
+ if let failure = error as? BridgeFailure {
3222
+ throw failure
3223
+ }
3224
+ throw BridgeFailure(message: "Capture failed: \(error.localizedDescription)", code: "capture_failed")
3225
+ }
3226
+
3227
+ guard let image = capturedImage.value else {
3228
+ if let payload = try cgWindowScreenshotFallback(windowId: windowId) {
3229
+ return payload
3230
+ }
3231
+ throw BridgeFailure(message: "Capture failed", code: "capture_failed")
3232
+ }
3233
+
3234
+ return CapturedWindowImage(image: image, windowId: windowId, frame: currentWindowBounds(windowId: windowId) ?? CGRect(x: 0, y: 0, width: image.width, height: image.height))
3235
+ }
3236
+ if let payload = try cgWindowScreenshotFallback(windowId: windowId) {
3237
+ return payload
3238
+ }
3239
+ throw BridgeFailure(message: "Capture failed", code: "capture_failed")
3240
+ }
3241
+
3242
+ private func jpegData(image: CGImage, quality: Double) -> Data? {
3243
+ let data = NSMutableData()
3244
+ guard let destination = CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil) else { return nil }
3245
+ CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
3246
+ guard CGImageDestinationFinalize(destination) else { return nil }
3247
+ return data as Data
3248
+ }
3249
+
3250
+ private func downscaledImage(_ image: CGImage, maxDimension: Int?) -> CGImage? {
3251
+ guard let maxDimension, max(image.width, image.height) > maxDimension else { return nil }
3252
+ let scale = Double(maxDimension) / Double(max(image.width, image.height))
3253
+ let width = max(1, Int(Double(image.width) * scale))
3254
+ let height = max(1, Int(Double(image.height) * scale))
3255
+ guard let context = CGContext(
3256
+ data: nil,
3257
+ width: width,
3258
+ height: height,
3259
+ bitsPerComponent: image.bitsPerComponent,
3260
+ bytesPerRow: 0,
3261
+ space: image.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
3262
+ bitmapInfo: image.bitmapInfo.rawValue
3263
+ ) else { return nil }
3264
+ context.interpolationQuality = .medium
3265
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
3266
+ return context.makeImage()
3267
+ }
3268
+
3269
+ private func cgWindowScreenshotFallback(windowId: UInt32) throws -> CapturedWindowImage? {
3270
+ if let payload = try systemScreenshotWindow(windowId: windowId) {
3271
+ return payload
3272
+ }
3273
+ return nil
3274
+ }
3275
+
3276
+ private func systemScreenshotWindow(windowId: UInt32) throws -> CapturedWindowImage? {
3277
+ let tempUrl = FileManager.default.temporaryDirectory.appendingPathComponent("pi-cu-\(UUID().uuidString).png")
3278
+ defer { try? FileManager.default.removeItem(at: tempUrl) }
3279
+ // Owner-only perms in case TMPDIR ever resolves to a shared directory.
3280
+ FileManager.default.createFile(atPath: tempUrl.path, contents: nil, attributes: [.posixPermissions: 0o600])
3281
+
3282
+ let process = Process()
3283
+ process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
3284
+ process.arguments = ["-x", "-l", String(windowId), tempUrl.path]
3285
+ try process.run()
3286
+ let deadline = Date().addingTimeInterval(5)
3287
+ while process.isRunning && Date() < deadline {
3288
+ Thread.sleep(forTimeInterval: 0.05)
3289
+ }
3290
+ if process.isRunning {
3291
+ process.terminate()
3292
+ Thread.sleep(forTimeInterval: 0.1)
3293
+ if process.isRunning { process.interrupt() }
3294
+ return nil
3295
+ }
3296
+ guard process.terminationStatus == 0 else { return nil }
3297
+ guard let data = try? Data(contentsOf: tempUrl), !data.isEmpty else { return nil }
3298
+ guard let imageRep = NSBitmapImageRep(data: data), let cgImage = imageRep.cgImage else { return nil }
3299
+ return CapturedWindowImage(image: cgImage, windowId: windowId, frame: currentWindowBounds(windowId: windowId) ?? CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
3300
+ }
3301
+
3302
+ private func currentWindowBounds(windowId: UInt32) -> CGRect? {
3303
+ if #available(macOS 14.0, *), let scBounds = currentWindowBoundsViaScreenCaptureKit(windowId: windowId) {
3304
+ return scBounds
3305
+ }
3306
+ return windowInfo(windowId: windowId)?.bounds
3307
+ }
3308
+
3309
+ private func windowInfo(windowId: UInt32) -> (pid: Int32, bounds: CGRect)? {
3310
+ func matchingEntry(_ entries: [[String: Any]]?) -> [String: Any]? {
3311
+ entries?.first {
3312
+ ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value == windowId
3313
+ }
3314
+ }
3315
+
3316
+ let requestedIds = [NSNumber(value: windowId)] as CFArray
3317
+ let targetedEntries = CGWindowListCreateDescriptionFromArray(requestedIds) as? [[String: Any]]
3318
+ let entry = matchingEntry(targetedEntries) ?? matchingEntry(
3319
+ CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as? [[String: Any]]
3320
+ )
3321
+ guard let entry,
3322
+ let pid = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
3323
+ let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
3324
+ let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
3325
+ else {
3326
+ return nil
3327
+ }
3328
+ return (pid, bounds)
3329
+ }
3330
+
3331
+ @available(macOS 14.0, *)
3332
+ private func currentWindowBoundsViaScreenCaptureKit(windowId: UInt32) -> CGRect? {
3333
+ let semaphore = DispatchSemaphore(value: 0)
3334
+ let output = Box<CGRect?>(nil)
3335
+
3336
+ let task = Task {
3337
+ defer { semaphore.signal() }
3338
+ do {
3339
+ if Task.isCancelled {
3340
+ return
3341
+ }
3342
+ let shareable = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
3343
+ if let window = shareable.windows.first(where: { $0.windowID == windowId }) {
3344
+ output.value = window.frame
3345
+ }
3346
+ } catch {
3347
+ output.value = nil
3348
+ }
3349
+ }
3350
+
3351
+ if semaphore.wait(timeout: .now() + .seconds(2)) == .timedOut {
3352
+ task.cancel()
3353
+ return nil
3354
+ }
3355
+ return output.value
3356
+ }
3357
+
3358
+ private func eventDelivery(_ request: [String: Any]) -> String {
3359
+ optionalStringArg(request, "delivery") == "pid" ? "pid" : "hid"
3360
+ }
3361
+
3362
+ private func postEvent(_ event: CGEvent, pid: Int32, delivery: String = "hid") {
3363
+ if delivery == "pid" {
3364
+ event.postToPid(pid)
3365
+ return
3366
+ }
3367
+ // Post as a real foreground HID event. AppKit views with mouseDown handlers
3368
+ // can ignore pid-targeted CGEvents even though postToPid reports success.
3369
+ // Keep the target app frontmost so the HID event is delivered to the intended
3370
+ // window, then post at the session event tap.
3371
+ if let app = NSRunningApplication(processIdentifier: pid), !app.isActive {
3372
+ if #available(macOS 14.0, *) {
3373
+ _ = app.activate()
3374
+ } else {
3375
+ _ = app.activate(options: [.activateIgnoringOtherApps])
3376
+ }
3377
+ usleep(20_000)
3378
+ }
3379
+ event.post(tap: .cghidEventTap)
3380
+ }
3381
+
3382
+ private func postMouseMove(to point: CGPoint, pid: Int32, delivery: String = "hid") throws {
3383
+ if delivery == "hid" { physicalInputLock.lock() }
3384
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3385
+ guard let move = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left) else {
3386
+ throw BridgeFailure(message: "Failed to create mouse move event", code: "input_failed")
3387
+ }
3388
+ postEvent(move, pid: pid, delivery: delivery)
3389
+ }
3390
+
3391
+ private func mouseButton(_ name: String) -> CGMouseButton {
3392
+ switch name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
3393
+ case "right":
3394
+ return .right
3395
+ case "middle", "center":
3396
+ return .center
3397
+ default:
3398
+ return .left
3399
+ }
3400
+ }
3401
+
3402
+ private func mouseDownType(for button: CGMouseButton) -> CGEventType {
3403
+ switch button {
3404
+ case .right:
3405
+ return .rightMouseDown
3406
+ case .center:
3407
+ return .otherMouseDown
3408
+ default:
3409
+ return .leftMouseDown
3410
+ }
3411
+ }
3412
+
3413
+ private func mouseUpType(for button: CGMouseButton) -> CGEventType {
3414
+ switch button {
3415
+ case .right:
3416
+ return .rightMouseUp
3417
+ case .center:
3418
+ return .otherMouseUp
3419
+ default:
3420
+ return .leftMouseUp
3421
+ }
3422
+ }
3423
+
3424
+ private func mouseDraggedType(for button: CGMouseButton) -> CGEventType {
3425
+ switch button {
3426
+ case .right:
3427
+ return .rightMouseDragged
3428
+ case .center:
3429
+ return .otherMouseDragged
3430
+ default:
3431
+ return .leftMouseDragged
3432
+ }
3433
+ }
3434
+
3435
+ private func postMouseClick(at point: CGPoint, pid: Int32, button: CGMouseButton = .left, clickCount: Int = 1, delivery: String = "hid") throws {
3436
+ if delivery == "hid" { physicalInputLock.lock() }
3437
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3438
+ try postMouseMove(to: point, pid: pid, delivery: delivery)
3439
+ for index in 1...max(1, clickCount) {
3440
+ guard let down = CGEvent(mouseEventSource: nil, mouseType: mouseDownType(for: button), mouseCursorPosition: point, mouseButton: button),
3441
+ let up = CGEvent(mouseEventSource: nil, mouseType: mouseUpType(for: button), mouseCursorPosition: point, mouseButton: button)
3442
+ else {
3443
+ throw BridgeFailure(message: "Failed to create mouse click event", code: "input_failed")
3444
+ }
3445
+ down.setIntegerValueField(.mouseEventClickState, value: Int64(index))
3446
+ up.setIntegerValueField(.mouseEventClickState, value: Int64(index))
3447
+ postEvent(down, pid: pid, delivery: delivery)
3448
+ usleep(12_000)
3449
+ postEvent(up, pid: pid, delivery: delivery)
3450
+ if index < clickCount {
3451
+ usleep(70_000)
3452
+ }
3453
+ }
3454
+ }
3455
+
3456
+ private func postMouseDrag(points: [CGPoint], pid: Int32, delivery: String = "hid") throws {
3457
+ if delivery == "hid" { physicalInputLock.lock() }
3458
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3459
+ guard points.count >= 2, let first = points.first else {
3460
+ throw BridgeFailure(message: "Drag requires at least two points", code: "invalid_args")
3461
+ }
3462
+ try postMouseMove(to: first, pid: pid, delivery: delivery)
3463
+ guard let down = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: first, mouseButton: .left) else {
3464
+ throw BridgeFailure(message: "Failed to create mouse down event", code: "input_failed")
3465
+ }
3466
+ postEvent(down, pid: pid, delivery: delivery)
3467
+ usleep(12_000)
3468
+
3469
+ for point in points.dropFirst() {
3470
+ guard let drag = CGEvent(mouseEventSource: nil, mouseType: mouseDraggedType(for: .left), mouseCursorPosition: point, mouseButton: .left) else {
3471
+ throw BridgeFailure(message: "Failed to create mouse drag event", code: "input_failed")
3472
+ }
3473
+ postEvent(drag, pid: pid, delivery: delivery)
3474
+ usleep(8_000)
3475
+ }
3476
+
3477
+ guard let last = points.last,
3478
+ let up = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: last, mouseButton: .left)
3479
+ else {
3480
+ throw BridgeFailure(message: "Failed to create mouse up event", code: "input_failed")
3481
+ }
3482
+ postEvent(up, pid: pid, delivery: delivery)
3483
+ }
3484
+
3485
+ private func postScrollWheel(at point: CGPoint, deltaX: Int, deltaY: Int, pid: Int32, delivery: String = "hid") throws {
3486
+ if delivery == "hid" { physicalInputLock.lock() }
3487
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3488
+ try postMouseMove(to: point, pid: pid, delivery: delivery)
3489
+ guard let event = CGEvent(
3490
+ scrollWheelEvent2Source: nil,
3491
+ units: .pixel,
3492
+ wheelCount: 2,
3493
+ wheel1: Int32(-deltaY),
3494
+ wheel2: Int32(deltaX),
3495
+ wheel3: 0
3496
+ ) else {
3497
+ throw BridgeFailure(message: "Failed to create scroll event", code: "input_failed")
3498
+ }
3499
+ event.location = point
3500
+ postEvent(event, pid: pid, delivery: delivery)
3501
+ }
3502
+
3503
+ private func modifierFlag(_ key: String) -> CGEventFlags? {
3504
+ switch key.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
3505
+ case "cmd", "command", "meta":
3506
+ return .maskCommand
3507
+ case "ctrl", "control":
3508
+ return .maskControl
3509
+ case "shift":
3510
+ return .maskShift
3511
+ case "option", "alt":
3512
+ return .maskAlternate
3513
+ default:
3514
+ return nil
3515
+ }
3516
+ }
3517
+
3518
+ private func keyCode(_ key: String) -> CGKeyCode? {
3519
+ let normalized = key.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
3520
+ let table: [String: CGKeyCode] = [
3521
+ "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, "b": 11,
3522
+ "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, "1": 18, "2": 19, "3": 20, "4": 21,
3523
+ "6": 22, "5": 23, "=": 24, "+": 24, "9": 25, "7": 26, "-": 27, "8": 28, "0": 29,
3524
+ "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35, "return": 36, "enter": 36,
3525
+ "l": 37, "j": 38, "'": 39, "\"": 39, "k": 40, ";": 41, "\\": 42, ",": 43, "/": 44,
3526
+ "n": 45, "m": 46, ".": 47, "tab": 48, "space": 49, " ": 49, "`": 50, "~": 50,
3527
+ "backspace": 51, "delete": 51, "del": 51, "esc": 53, "escape": 53,
3528
+ "f1": 122, "f2": 120, "f3": 99, "f4": 118, "f5": 96, "f6": 97, "f7": 98, "f8": 100,
3529
+ "f9": 101, "f10": 109, "f11": 103, "f12": 111,
3530
+ "home": 115, "pageup": 116, "page_up": 116, "page down": 121, "pagedown": 121, "page_down": 121,
3531
+ "forwarddelete": 117, "forward_delete": 117, "end": 119,
3532
+ "left": 123, "arrowleft": 123, "arrow_left": 123,
3533
+ "right": 124, "arrowright": 124, "arrow_right": 124,
3534
+ "down": 125, "arrowdown": 125, "arrow_down": 125,
3535
+ "up": 126, "arrowup": 126, "arrow_up": 126,
3536
+ ]
3537
+ return table[normalized]
3538
+ }
3539
+
3540
+ private func keyChord(_ keys: [String]) -> (flags: CGEventFlags, key: String)? {
3541
+ guard keys.count >= 2 else { return nil }
3542
+ var flags = CGEventFlags()
3543
+ for key in keys.dropLast() {
3544
+ guard let flag = modifierFlag(key) else {
3545
+ return nil
3546
+ }
3547
+ flags.insert(flag)
3548
+ }
3549
+ return (flags, keys.last ?? "")
3550
+ }
3551
+
3552
+ private func postKeyPress(keys: [String], pid: Int32, delivery: String = "hid") throws {
3553
+ if delivery == "hid" { physicalInputLock.lock() }
3554
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3555
+ if let chord = keyChord(keys) {
3556
+ try postKey(chord.key, flags: chord.flags, pid: pid, delivery: delivery)
3557
+ return
3558
+ }
3559
+
3560
+ for key in keys {
3561
+ let parts = key
3562
+ .split(separator: "+")
3563
+ .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
3564
+ .filter { !$0.isEmpty }
3565
+ if let chord = keyChord(parts) {
3566
+ try postKey(chord.key, flags: chord.flags, pid: pid, delivery: delivery)
3567
+ } else {
3568
+ try postKey(key, flags: [], pid: pid, delivery: delivery)
3569
+ }
3570
+ }
3571
+ }
3572
+
3573
+ private func postKey(_ key: String, flags: CGEventFlags, pid: Int32, delivery: String = "hid") throws {
3574
+ if delivery == "hid" { physicalInputLock.lock() }
3575
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3576
+ guard let code = keyCode(key) else {
3577
+ if key.count == 1 {
3578
+ try postUnicodeText(key, pid: pid, delivery: delivery)
3579
+ return
3580
+ }
3581
+ throw BridgeFailure(message: "Unsupported key '\(key)'", code: "invalid_args")
3582
+ }
3583
+ guard let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true),
3584
+ let up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)
3585
+ else {
3586
+ throw BridgeFailure(message: "Failed to create key event", code: "input_failed")
3587
+ }
3588
+ down.flags = flags
3589
+ up.flags = flags
3590
+ postEvent(down, pid: pid, delivery: delivery)
3591
+ postEvent(up, pid: pid, delivery: delivery)
3592
+ usleep(8_000)
3593
+ }
3594
+
3595
+ private func postUnicodeText(_ text: String, pid: Int32, delivery: String = "hid") throws {
3596
+ if delivery == "hid" { physicalInputLock.lock() }
3597
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3598
+ for scalar in text.unicodeScalars {
3599
+ let char = String(scalar)
3600
+ if let stroke = physicalKeyStroke(for: char) {
3601
+ try postKey(stroke.key, flags: stroke.flags, pid: pid, delivery: delivery)
3602
+ continue
3603
+ }
3604
+ guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
3605
+ let up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
3606
+ else {
3607
+ throw BridgeFailure(message: "Failed to create unicode key event", code: "input_failed")
3608
+ }
3609
+ setUnicodeString(event: down, text: char)
3610
+ setUnicodeString(event: up, text: char)
3611
+ postEvent(down, pid: pid, delivery: delivery)
3612
+ postEvent(up, pid: pid, delivery: delivery)
3613
+ usleep(8_000)
3614
+ }
3615
+ }
3616
+
3617
+ private func postAtomicUnicodeText(_ text: String, pid: Int32, delivery: String = "hid") throws {
3618
+ if delivery == "hid" { physicalInputLock.lock() }
3619
+ defer { if delivery == "hid" { physicalInputLock.unlock() } }
3620
+ guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
3621
+ let up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
3622
+ else { throw BridgeFailure(message: "Failed to create unicode text event", code: "input_failed") }
3623
+ setUnicodeString(event: down, text: text)
3624
+ setUnicodeString(event: up, text: text)
3625
+ postEvent(down, pid: pid, delivery: delivery)
3626
+ usleep(8_000)
3627
+ postEvent(up, pid: pid, delivery: delivery)
3628
+ }
3629
+
3630
+ /// Prefer physical key codes for characters represented by the US layout.
3631
+ /// AppKit field editors can observe synthetic Unicode events without applying
3632
+ /// them to the backing value, while normal key codes follow the same input
3633
+ /// path as a user keystroke. Unicode synthesis remains the fallback for text
3634
+ /// that has no direct key representation.
3635
+ private func physicalKeyStroke(for character: String) -> (key: String, flags: CGEventFlags)? {
3636
+ guard character.count == 1 else { return nil }
3637
+ if character >= "a" && character <= "z" { return (character, []) }
3638
+ if character >= "A" && character <= "Z" { return (character.lowercased(), [.maskShift]) }
3639
+ if character >= "0" && character <= "9" { return (character, []) }
3640
+ switch character {
3641
+ case " ": return ("space", [])
3642
+ case ".", ",", "/", "-", "=", ";", "'", "[", "]", "\\", "`": return (character, [])
3643
+ case "_": return ("-", [.maskShift])
3644
+ case "+": return ("=", [.maskShift])
3645
+ case ":": return (";", [.maskShift])
3646
+ case "\"": return ("'", [.maskShift])
3647
+ case "?": return ("/", [.maskShift])
3648
+ case "<": return (",", [.maskShift])
3649
+ case ">": return (".", [.maskShift])
3650
+ default: return nil
3651
+ }
3652
+ }
3653
+
3654
+ private func setUnicodeString(event: CGEvent, text: String) {
3655
+ var utf16 = Array(text.utf16)
3656
+ utf16.withUnsafeMutableBufferPointer { buffer in
3657
+ guard let base = buffer.baseAddress else { return }
3658
+ event.keyboardSetUnicodeString(stringLength: buffer.count, unicodeString: base)
3659
+ }
3660
+ }
3661
+
3662
+ }
3663
+
3664
+ @main
3665
+ struct PiComputerUseHelper {
3666
+ static func main() {
3667
+ _ = NSApplication.shared
3668
+ NSApp.setActivationPolicy(CommandLine.arguments.contains("serve") ? .accessory : .prohibited)
3669
+ Bridge().run()
3670
+ }
3671
+ }
3672
+
3673
+ /*
3674
+ PI_DOCS_REFERENCE_BEGIN reference/platforms/macos/accessibility
3675
+
3676
+ This page is the direct reference for macOS Accessibility, usually abbreviated AX. The implementation lives primarily in [`native/macos/bridge.swift`](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift); the TypeScript platform adapter lives in [`src/platform/macos/`](https://github.com/injaneity/pi-computer-use/tree/main/src/platform/macos).
3677
+
3678
+ ## Trust and permission
3679
+
3680
+ The helper checks trust with [`AXIsProcessTrusted()`](https://developer.apple.com/documentation/applicationservices/1460720-axisprocesstrusted) and requests it with [`AXIsProcessTrustedWithOptions(_:)`](https://developer.apple.com/documentation/applicationservices/1459186-axisprocesstrustedwithoptions). Accessibility permission enables semantic UI observation and AX actions; it does not grant window image capture.
3681
+
3682
+ The grant must apply to the resolved helper app during normal operation. The helper is installed per user at `~/Applications/pi-computer-use.app` by default; existing writable system-wide installs remain at `/Applications/pi-computer-use.app`, and `PI_COMPUTER_USE_HELPER_APP_PATH` selects an explicit location for development or testing. Setup requests trust before opening System Settings and restarts the helper after recheck. Pane names and listing behavior vary by macOS release, so they are not part of the runtime contract.
3683
+
3684
+ ## AX root discovery
3685
+
3686
+ Root discovery combines several APIs rather than treating AX as a window registry:
3687
+
3688
+ 1. [`NSWorkspace.runningApplications`](https://developer.apple.com/documentation/appkit/nsworkspace/runningapplications) supplies process identity and frontmost state.
3689
+ 2. [`AXUIElementCreateApplication`](https://developer.apple.com/documentation/applicationservices/axuielement) creates an application-level AX element for each candidate process.
3690
+ 3. AX window attributes provide controllable windows, roles, frames, state, and child trees. When an app reports an empty `AXWindows` list, the helper falls back to its `AXMainWindow` and `AXFocusedWindow`.
3691
+ 4. Core Graphics window data is paired separately to provide capture IDs and visual ordering.
3692
+
3693
+ Windows, sheets, dialogs, popovers, and open menus can become roots. Menus use the `AXMenu` role when an AX element is available. A visually discovered menu without a matching AX element is returned as `pictureOnly`, so it cannot receive ref-targeted AX actions. An AX root without a matching Core Graphics window is unpaired; the [root targeting reference](./root-targeting.mdx) defines how such roots are addressed and observed.
3694
+
3695
+ ## Tree extraction
3696
+
3697
+ An observation walks the selected AX subtree breadth-first. It reads available roles, subroles, identifiers, titles, descriptions, values, frames, focus state, supported actions, and settable attributes. The native walk stops at 2,000 nodes or 20 seconds; incomplete ancestors are marked `truncated` rather than presented as complete.
3698
+
3699
+ The resulting outline preserves native semantics where they are available. It does not infer that every visible control has an AX node. Web views, custom drawing, games, and apps with incomplete accessibility implementations can expose sparse trees.
3700
+
3701
+ ## Semantic operations
3702
+
3703
+ The helper prefers AX operations before synthesized input:
3704
+
3705
+ - press and eligible click actions call [`AXUIElementPerformAction`](https://developer.apple.com/documentation/applicationservices/1462091-axuielementperformaction) with `AXPress`;
3706
+ - `setText` writes `AXValue` through [`AXUIElementSetAttributeValue`](https://developer.apple.com/documentation/applicationservices/1460434-axuielementsetattributevalue) and reads the value back;
3707
+ - semantic scrolling walks the target and its ancestors for supported AX scroll actions;
3708
+ - foreground coordinate delivery uses `AXUIElementCopyElementAtPosition` as an occlusion preflight.
3709
+
3710
+ An advertised AX action is a delivery capability, not proof of an application-level result. Action outcomes remain `worked`, `didnt`, or `unknown` based on read-back or observable state evidence.
3711
+
3712
+ ## Strict headless behavior
3713
+
3714
+ `headless: true` maps native actions to the `ax_only` policy. AX press, `AXValue` writes outside web content, and semantic scrolling still run. Actions that would fall back to synthesized pointer input, every `typeText` and `keypress`, and web text replacement fail with `foreground_required` before the helper posts events or activates the target. The agent cursor overlay and activity glow are not shown.
3715
+
3716
+ ## Common interpretation rules
3717
+
3718
+ - An empty outline usually indicates missing Accessibility trust, an inaccessible target, or an app that exposes no useful AX hierarchy.
3719
+ - `truncated` means the bounded walk did not retrieve the complete descendant tree.
3720
+ - `pictureOnly` means the element came from visual evidence and cannot be targeted by AX ref.
3721
+ - A supported action describes what the element reports, not whether the app will honor it.
3722
+ - AX frames and Core Graphics windows are paired heuristically; low-confidence pairing must not be treated as exact identity.
3723
+
3724
+ For the image side of an observation, continue to [Capture and OCR](./capture.mdx). For fallback delivery and checked outcomes, continue to [Actions and input delivery](./actions.mdx). The [complete implementation reference](./implementation.mdx) contains line-level source citations and current limits.
3725
+ PI_DOCS_REFERENCE_END
3726
+ */
3727
+
3728
+ /*
3729
+ PI_DOCS_REFERENCE_BEGIN reference/platforms/macos/capture
3730
+
3731
+ macOS image evidence is separate from Accessibility. A target can have a complete AX outline while capture fails, or a valid image while its AX tree is sparse.
3732
+
3733
+ ## Screen Recording permission
3734
+
3735
+ The helper preflights Screen Recording with [`CGPreflightScreenCaptureAccess()`](https://developer.apple.com/documentation/coregraphics/cgpreflightscreencaptureaccess%28%29) and requests it with [`CGRequestScreenCaptureAccess()`](https://developer.apple.com/documentation/coregraphics/cgrequestscreencaptureaccess%28%29). It additionally requires a nonempty [`SCShareableContent`](https://developer.apple.com/documentation/screencapturekit/scshareablecontent) query before reporting capture readiness.
3736
+
3737
+ That content query is a project readiness check, not an Apple-defined permission-status API. Passing it does not guarantee that every later window capture will succeed.
3738
+
3739
+ ## Window identity and pairing
3740
+
3741
+ [`CGWindowListCopyWindowInfo`](https://developer.apple.com/documentation/coregraphics/cgwindowlistcopywindowinfo%28_%3A_%3A%29) supplies window IDs, owner PIDs, bounds, layers, titles, onscreen state, and ordering candidates. AX windows do not expose the same project-owned identifier, so the helper pairs AX and Core Graphics windows using title, geometry, onscreen state, and one-to-one assignment.
3742
+
3743
+ Pairing metadata reports `exact`, `high`, or `low` confidence. A low-confidence match is useful evidence but is not guaranteed identity. A root with no matching Core Graphics window is unpaired and has no `windowId`.
3744
+
3745
+ ## ScreenCaptureKit path
3746
+
3747
+ For a requested image, the helper:
3748
+
3749
+ 1. retrieves the matching `SCWindow` from `SCShareableContent`;
3750
+ 2. creates an `SCContentFilter` for that desktop-independent window;
3751
+ 3. disables cursor rendering and ignores single-window shadows;
3752
+ 4. captures one frame with [`SCScreenshotManager.captureImage`](https://developer.apple.com/documentation/screencapturekit/scscreenshotmanager/captureimage%28contentfilter%3Aconfiguration%3Acompletionhandler%3A%29).
3753
+
3754
+ `SCScreenshotManager` requires macOS 14, which is why the helper's deployment target is macOS 14 or newer.
3755
+
3756
+ Visual observation of an unpaired root fails with `root_not_capturable`; use semantic observation (`image: never`). No other window is captured in its place.
3757
+
3758
+ ## Fallback capture
3759
+
3760
+ If ScreenCaptureKit times out or fails, the helper invokes `/usr/sbin/screencapture -x -l <window-id>` and reads an owner-only temporary PNG. This is a fallback implementation detail, not a guarantee that capture will work after a ScreenCaptureKit failure.
3761
+
3762
+ ## OCR and picture-only nodes
3763
+
3764
+ Forced visual observation runs Vision's accurate [`VNRecognizeTextRequest`](https://developer.apple.com/documentation/vision/vnrecognizetextrequest), with language correction disabled. Nonduplicate recognized text boxes are attached to the outline.
3765
+
3766
+ OCR-derived nodes are marked `pictureOnly`. They can provide text and geometry evidence, but ref-targeted Accessibility actions are blocked because no corresponding AX element exists. A coordinate action can use visual evidence only when the saved observation includes the required image geometry.
3767
+
3768
+ ## Failure boundaries
3769
+
3770
+ - A successful permission readiness check does not guarantee capture of every window.
3771
+ - Protected, remote, transient, or rapidly closing surfaces may not produce an image.
3772
+ - AX-to-Core-Graphics pairing can be uncertain, and unpaired roots are never capturable.
3773
+ - OCR recognizes pixels, not control semantics.
3774
+ - Outline-only menu roots cannot be coordinate targets without image geometry.
3775
+
3776
+ For semantic UI structure, use [Accessibility and AX](./accessibility.mdx). For coordinate delivery and outcome evidence, use [Actions and input delivery](./actions.mdx).
3777
+ PI_DOCS_REFERENCE_END
3778
+ */
3779
+
3780
+ /*
3781
+ PI_DOCS_REFERENCE_BEGIN reference/platforms/macos/actions
3782
+
3783
+ Action delivery is divided between model-level coordination in [`src/bridge.ts`](https://github.com/injaneity/pi-computer-use/blob/main/src/bridge.ts) and native grounding, delivery, and verification in [`native/macos/bridge.swift`](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift).
3784
+
3785
+ ## Delivery order
3786
+
3787
+ Ref-based actions prefer the least disruptive credible strategy:
3788
+
3789
+ 1. use a supported semantic AX operation;
3790
+ 2. use background event delivery when semantic delivery is unavailable and policy permits it;
3791
+ 3. request foreground delivery only when the action requires focus or a checked background attempt proves it had no effect.
3792
+
3793
+ Coordinate clicks and focus-dependent steps can begin in the foreground. Ambiguous pointer outcomes are not replayed because repeating an uncertain click can duplicate a side effect.
3794
+
3795
+ Actions and the successor capture stay on the root the state belongs to; `act_ui` does not redirect to a foreground modal. A modal that appears afterwards is reported in `rootDelta` as `appeared`.
3796
+
3797
+ ## AX delivery
3798
+
3799
+ Eligible presses use `AXPress`, text replacement writes `AXValue`, and semantic scrolling searches the target and ancestor chain for AX scroll actions. These paths are described in [Accessibility and AX](./accessibility.mdx).
3800
+
3801
+ ## Synthesized delivery
3802
+
3803
+ Web-backed editable controls and controls without usable AX actions can require synthesized keyboard or pointer events. Background events use [`CGEvent.postToPid(_:)`](https://developer.apple.com/documentation/coregraphics/cgevent/posttopid%28_%3A%29). Foreground delivery activates and raises the target before posting at the [CG event tap](https://developer.apple.com/documentation/coregraphics/cgevent/post%28tap%3A%29).
3804
+
3805
+ These are synthesized events, not physical hardware input. Before foreground coordinate delivery, the helper hit-tests the intended point with AX. An unrelated resolved element produces `occluded_target`; an unavailable or coarse result remains unknown rather than proving visibility.
3806
+
3807
+ ## Headless policy
3808
+
3809
+ `headless: true` is a strict prohibition, not a preference. It maps the transaction to the native `ax_only` policy. The helper fails these actions with `foreground_required` before it posts events or activates the target:
3810
+
3811
+ - coordinate delivery: raw `x`/`y` targets, `moveMouse`, `drag`, and press, click, `setText`, or scroll requests whose Accessibility operation is unavailable or fails;
3812
+ - `typeText` and `keypress`, including ref-targeted requests;
3813
+ - `setText` inside web content, which needs synthesized keyboard input.
3814
+
3815
+ The bridge returns that error instead of retrying in the foreground. `ax_only` actions never display the agent cursor overlay.
3816
+
3817
+ Without strict headless mode, ref-based work normally starts in the background and can escalate only through checked fallback rules.
3818
+
3819
+ ## Outcome evidence
3820
+
3821
+ Native results distinguish:
3822
+
3823
+ - `worked`: observable evidence supports the intended effect;
3824
+ - `didnt`: checked evidence supports that the intended effect did not occur;
3825
+ - `unknown`: delivery happened, but available evidence cannot prove the application-level result.
3826
+
3827
+ Text writes and text entry can use read-back evidence. Pointer actions often need value, selection, focused-window, sheet, or root-delta changes; a successfully posted event alone is not universal proof. When the source root disappears after delivery, the result reports `target_closed` with its cause, as described in the [root targeting reference](./root-targeting.mdx#post-action-outcomes).
3828
+
3829
+ ## Agent cursor overlay
3830
+
3831
+ When `cursor_overlay` is enabled, non-headless pointer actions delivered in the background with `postToPid` schedule the noninteractive AppKit/SwiftUI agent cursor at the grounded point. Foreground actions that control the physical cursor don't display the overlay. The overlay ignores mouse events, cannot become key or main, and hides automatically. It is visual only and currently limited to the main display.
3832
+
3833
+ For state ownership, batching, and successor observations, use the generated [agent state and action contract](../../agent/contract.mdx). For line-level implementation citations and every current limit, use the [complete macOS implementation reference](./implementation.mdx).
3834
+ PI_DOCS_REFERENCE_END
3835
+ */
3836
+
3837
+ /*
3838
+ PI_DOCS_REFERENCE_BEGIN reference/platforms/macos/root-targeting
3839
+
3840
+ These are the target, capture, modality, and post-action contracts the macOS path guarantees.
3841
+
3842
+ ## Target contract
3843
+
3844
+ - A root target is `{ pid, windowId?, rootRef?, windowRef? }`. `windowId` is present only when positive. An unpaired root (no matching CG window) has no `windowId`, never `0`.
3845
+ - `rootRef` and `windowRef` are the same native ref. Every macOS helper call (`look`, `focusWindow`, `axWaitFor`) goes through `normalizeTarget()` in [`src/platform/macos/backend.ts`](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/backend.ts), which sends only `windowRef`.
3846
+ - The helper treats `windowId <= 0` as absent. A `windowRef` that no longer resolves fails; it never falls back to the app's first window.
3847
+ - Looks remember their `windowRef`, so `act` resolves the root by ref for unpaired roots.
3848
+
3849
+ ## Capture
3850
+
3851
+ - Paired root: semantic and visual observation work.
3852
+ - Unpaired root: semantic works. Visual fails with `root_not_capturable`; use `image: never`. No other window is ever captured in its place.
3853
+
3854
+ ## Modality
3855
+
3856
+ `isModal` is true for: a sheet child, role `AXSheet`, or `AXModal == true`. When the app does not report `AXModal` at all, a dialog-like role/subrole still counts. An explicit `AXModal == false` wins: Fusion's BROWSER sidebar (subrole `AXDialog`, `AXModal=0`) is nonmodal.
3857
+
3858
+ `act_ui` no longer redirects to a foreground modal. Actions and the successor capture stay on the root the state belongs to; a modal that appears afterwards shows up in `rootDelta` as `appeared`. `observe_ui` without a root may still prefer a confirmed foreground modal.
3859
+
3860
+ ## Post-action outcomes
3861
+
3862
+ Terminal `act_ui` results always say the action was delivered, and:
3863
+
3864
+ - `target_closed`, `cause: replaced`, `successors: [...]`: source root gone and new roots of the same pid appeared. Observe a successor via `find_roots`.
3865
+ - `target_closed`, `cause: closed`: source root gone, nothing replaced it.
3866
+ - `post_action_observation_failed` with code `root_stale`: root still listed or unknown but the ref no longer resolves. Rediscover with `find_roots`.
3867
+
3868
+ ## Ref lifecycle
3869
+
3870
+ Native refs live in the helper's `refStore` and are only valid while the helper process and the AX element live. Refs from earlier sessions, pids and state ids are stale: rediscover with `find_roots`.
3871
+
3872
+ ## Tests
3873
+
3874
+ `npm run test:macos-target`, `test:macos-native` (compiles the `PURE` region of `bridge.swift`), `test:act-outcomes`.
3875
+ PI_DOCS_REFERENCE_END
3876
+ */
3877
+
3878
+ /*
3879
+ PI_DOCS_REFERENCE_BEGIN reference/platforms/macos/implementation
3880
+
3881
+ This page describes the current macOS implementation, not an intended design. Apple links establish the platform API semantics; source links establish what this project actually does.
3882
+
3883
+ For focused lookup, use [Accessibility and AX](./accessibility.mdx), [Capture and OCR](./capture.mdx), [Actions and input delivery](./actions.mdx), or [Root targeting](./root-targeting.mdx). This complete page remains the source-backed inventory of requirements, helper behavior, and current limits.
3884
+
3885
+ ## Support boundary
3886
+
3887
+ The helper requires macOS 14 or newer because it is compiled with a `14.0` deployment target and uses `SCScreenshotManager`, which Apple introduced in macOS 14 ([Apple: `SCScreenshotManager`](https://developer.apple.com/documentation/screencapturekit/scscreenshotmanager), [setup-helper.mjs](https://github.com/injaneity/pi-computer-use/blob/main/scripts/setup-helper.mjs#L46), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3177)). Builds target Apple silicon and Intel (`arm64` and `x86_64`) ([setup-helper.mjs](https://github.com/injaneity/pi-computer-use/blob/main/scripts/setup-helper.mjs#L42)).
3888
+
3889
+ The normal runtime uses the per-user `~/Applications/pi-computer-use.app`; existing writable system-wide installs remain at `/Applications/pi-computer-use.app`, and `PI_COMPUTER_USE_HELPER_APP_PATH` selects an explicit location ([helper-path.mjs](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/helper-path.mjs#L15)). The bundle identifier is `com.injaneity.pi-computer-use`, and the daemon listens on a Unix-domain socket below `~/Library/Caches/pi-computer-use/`. The TypeScript client launches the resolved app with `open -n -g <app> --args serve …` and communicates with its daemon over that socket ([helper.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/helper.ts#L19), [helper.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/helper.ts#L169)). The app is an `LSUIElement`, so it is packaged as an agent-style app rather than a normal Dock app ([setup-helper.mjs](https://github.com/injaneity/pi-computer-use/blob/main/scripts/setup-helper.mjs#L405)).
3890
+
3891
+ ## Permissions
3892
+
3893
+ Two grants are required for the complete feature set:
3894
+
3895
+ - Accessibility is checked with `AXIsProcessTrusted()` and requested with `AXIsProcessTrustedWithOptions(_:)` ([Apple: `AXIsProcessTrusted`](https://developer.apple.com/documentation/applicationservices/1460720-axisprocesstrusted), [Apple: `AXIsProcessTrustedWithOptions`](https://developer.apple.com/documentation/applicationservices/1459186-axisprocesstrustedwithoptions), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L872)). It enables Accessibility API observation and actions.
3896
+ - Screen Recording is preflighted and requested with `CGPreflightScreenCaptureAccess()` and `CGRequestScreenCaptureAccess()` ([Apple: preflight](https://developer.apple.com/documentation/coregraphics/cgpreflightscreencaptureaccess%28%29), [Apple: request](https://developer.apple.com/documentation/coregraphics/cgrequestscreencaptureaccess%28%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L872)). It enables window image capture.
3897
+
3898
+ The extension reports Screen Recording as ready only when the helper can also retrieve nonempty display content through `SCShareableContent`. Apple documents that API as retrieving matching displays, apps, and windows; the project uses it as an additional readiness check, not as an Apple-defined permission-status API ([Apple: `getExcludingDesktopWindows`](https://developer.apple.com/documentation/screencapturekit/scshareablecontent/getexcludingdesktopwindows%28_%3Aonscreenwindowsonly%3Acompletionhandler%3A%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L812)).
3899
+
3900
+ Setup invokes the request APIs before opening the relevant System Settings pane, then restarts the helper after the user chooses recheck ([permissions.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/permissions.ts#L82), [permissions.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/platform/macos/permissions.ts#L136)). The helper reports `source.attribution: helper-app` only when its executable path is inside the installed bundle and its parent PID is 1; every other launch reports `caller` ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L836)). This is a project launch diagnostic, not an Apple API statement about grant ownership.
3901
+
3902
+ The documentation does not promise a particular pane label, automatic listing behavior, or grant persistence across re-signing because those details are not stable API contracts.
3903
+
3904
+ ## Root discovery
3905
+
3906
+ Discovery combines three sources:
3907
+
3908
+ 1. `NSWorkspace.runningApplications` supplies running-process identity and frontmost state ([Apple: `runningApplications`](https://developer.apple.com/documentation/appkit/nsworkspace/runningapplications), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L951)).
3909
+ 2. `AXUIElementCreateApplication` plus Accessibility window attributes supplies controllable windows, roles, state, and element trees. An empty `AXWindows` list falls back to `AXMainWindow` and `AXFocusedWindow` ([Apple: `AXUIElement`](https://developer.apple.com/documentation/applicationservices/axuielement), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1260)).
3910
+ 3. `CGWindowListCopyWindowInfo` supplies session window IDs, bounds, layers, owner PIDs, titles, onscreen state, and ordering candidates ([Apple: `CGWindowListCopyWindowInfo`](https://developer.apple.com/documentation/coregraphics/cgwindowlistcopywindowinfo%28_%3A_%3A%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2936)).
3911
+
3912
+ Single-window lookups call `CGWindowListCreateDescriptionFromArray(_:)` for the requested window ID first and fall back to an all-window `CGWindowListCopyWindowInfo` query when that returns no match ([Apple: `CGWindowListCreateDescriptionFromArray`](https://developer.apple.com/documentation/coregraphics/cgwindowlistcreatedescriptionfromarray%28_%3A%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3317)).
3913
+
3914
+ Accessibility windows and Core Graphics windows do not share one project-owned identifier, so the helper pairs them heuristically using title, frame geometry, onscreen state, and one-to-one assignment. The returned metadata exposes `exact`, `high`, or `low` pairing confidence instead of presenting every match as certain ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3080)). Roots without a match are unpaired and omit `windowId`; the [root targeting reference](./root-targeting.mdx) defines how they are addressed.
3915
+
3916
+ Windows, sheets, dialogs, popovers, and open menus can become roots. Menus are identified by the Accessibility `AXMenu` role and Core Graphics popup-menu window level; a menu with no matching Accessibility element remains an outline-only, `pictureOnly` root ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1232), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3004)).
3917
+
3918
+ ## Observation and capture
3919
+
3920
+ A look walks the target Accessibility subtree breadth-first and reads roles, subroles, identifiers, titles, descriptions, values, frames, focus, actions, and settable attributes. The walk stops at 2,000 nodes or 20 seconds and marks incomplete ancestors as `truncated` ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1533)).
3921
+
3922
+ When an image is requested, the helper:
3923
+
3924
+ 1. retrieves the matching `SCWindow` from `SCShareableContent`;
3925
+ 2. builds an `SCContentFilter` for that desktop-independent window;
3926
+ 3. sets `showsCursor = false` and `ignoreShadowsSingleWindow = true`;
3927
+ 4. captures one frame with `SCScreenshotManager.captureImage` ([Apple: capture one image](https://developer.apple.com/documentation/screencapturekit/scscreenshotmanager/captureimage%28contentfilter%3Aconfiguration%3Acompletionhandler%3A%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3202)).
3928
+
3929
+ If ScreenCaptureKit times out or fails, the helper tries `/usr/sbin/screencapture -x -l <window-id>` and reads the temporary PNG with owner-only file permissions ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3277)). The fallback is an implementation detail, not a guarantee that capture succeeds when ScreenCaptureKit fails. Unpaired roots fail visual observation with `root_not_capturable` instead of capturing another window ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1367)).
3930
+
3931
+ Forced visual text recognition uses Vision's accurate `VNRecognizeTextRequest`, disables language correction, and attaches nonduplicate text boxes to the Accessibility outline. Apple defines that request as finding and recognizing text in an image ([Apple: `VNRecognizeTextRequest`](https://developer.apple.com/documentation/vision/vnrecognizetextrequest), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1637)). OCR-only nodes are marked `pictureOnly` and cannot receive ref-targeted Accessibility actions.
3932
+
3933
+ ## Actions and delivery
3934
+
3935
+ The helper prefers Accessibility operations where the target exposes them:
3936
+
3937
+ - press and eligible click actions use `AXUIElementPerformAction` with `AXPress` ([Apple: `AXUIElementPerformAction`](https://developer.apple.com/documentation/applicationservices/1462091-axuielementperformaction), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2079));
3938
+ - `setText` writes `AXValue` and reads it back ([Apple: `AXUIElementSetAttributeValue`](https://developer.apple.com/documentation/applicationservices/1460434-axuielementsetattributevalue), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2093));
3939
+ - semantic scrolling walks the target and its ancestors looking for supported Accessibility scroll actions ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2467)).
3940
+
3941
+ Web-backed editable controls and controls without a usable Accessibility action can require synthesized keyboard or pointer events. Background event delivery uses `CGEvent.postToPid(_:)`; foreground delivery activates and raises the target, then posts the synthesized event at `.cghidEventTap` ([Apple: `postToPid`](https://developer.apple.com/documentation/coregraphics/cgevent/posttopid%28_%3A%29), [Apple: `post(tap:)`](https://developer.apple.com/documentation/coregraphics/cgevent/post%28tap%3A%29), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L3362)). These are synthesized events; this documentation does not describe them as physical hardware input.
3942
+
3943
+ `headless: true` maps every native action to the `ax_only` policy. The helper rejects coordinate delivery, `typeText`, `keypress`, and web text replacement with `foreground_required` before posting synthesized events, and the bridge does not escalate that error ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1922)). Without strict headless mode, ref-based actions normally start with background delivery; coordinate clicks and focus-dependent steps can start in foreground, while checked keyboard failures and explicit `foreground_required` errors can escalate there ([bridge.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/bridge.ts#L1185), [bridge.ts](https://github.com/injaneity/pi-computer-use/blob/main/src/bridge.ts#L1208)).
3944
+
3945
+ Before foreground coordinate delivery, the helper uses `AXUIElementCopyElementAtPosition` to check whether the point resolves to the intended element or a related ancestor or descendant. An unrelated resolved element produces `occluded_target`; an unavailable or coarse hit test produces an unknown preflight rather than proof of visibility ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2021), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2440)).
3946
+
3947
+ Action results distinguish `worked`, `didnt`, and `unknown`. A successful API call or posted event is not universally treated as proof of application-level effect: value writes and text entry get read-back evidence, while pointer actions can remain unknown unless value, selection, focused-window, or sheet state changes ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2079), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L2197)).
3948
+
3949
+ ## Agent cursor overlay
3950
+
3951
+ When `cursor_overlay` is enabled, non-headless pointer-oriented actions delivered in the background with `postToPid` schedule the AppKit/SwiftUI `AgentCursor` overlay at the grounded point; foreground actions that control the physical cursor and `ax_only` actions don't display it ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L1982)). The overlay ignores mouse events, cannot become key or main, and hides after eight seconds ([Apple: `ignoresMouseEvents`](https://developer.apple.com/documentation/appkit/nswindow/ignoresmouseevents), [agent_cursor.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/agent_cursor.swift#L6)). It is visual only; action delivery remains in `bridge.swift`.
3952
+
3953
+ The current overlay is main-display-only because its frame is created from `NSScreen.main`. The helper excludes its own process from app discovery, but the overlay is not a supported target ([agent_cursor.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/agent_cursor.swift#L61), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L951)).
3954
+
3955
+ ## Activity glow
3956
+
3957
+ `activity_glow` defaults to `false`. When it is enabled and `headless` is `false`, the extension sends `setActivityGlow` over a persistent helper connection when a computer-use tool starts and clears it when the agent run ends ([computer-use.ts](https://github.com/injaneity/pi-computer-use/blob/main/extensions/computer-use.ts#L207)). The helper's `ActivityGlowController` tracks active connections and shows the glow while any is active; a closed connection removes its state ([bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L485), [bridge.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/bridge.swift#L634), [activity_glow.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/activity_glow.swift#L74)). It creates one borderless window per `NSScreen`, rebuilt when screen parameters change. Each window ignores mouse events, is excluded from Accessibility, and sits at the screen-saver level ([activity_glow.swift](https://github.com/injaneity/pi-computer-use/blob/main/native/macos/activity_glow.swift#L130)).
3958
+
3959
+ ## Current limits
3960
+
3961
+ - Accessibility completeness and supported actions depend on what the target app exposes; sparse or web-backed trees can require image evidence or foreground event delivery.
3962
+ - Accessibility-to-Core-Graphics window pairing is heuristic, and callers must treat low-confidence pairing accordingly. Unpaired roots support semantic observation only.
3963
+ - Raw coordinate targets require an image-bearing look; outline-only menu roots cannot be coordinate targets.
3964
+ - ScreenCaptureKit readiness, capture, and the command-line screenshot fallback are separate checks, so one successful check does not guarantee every later window capture.
3965
+ - The visual agent cursor only covers the main display.
3966
+ - Strict headless mode rejects actions that need synthesized pointer or keyboard input, including every `typeText` and `keypress`.
3967
+ PI_DOCS_REFERENCE_END
3968
+ */