u-foo 4.0.10 → 4.1.2

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 (71) hide show
  1. package/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
  2. package/README.md +279 -789
  3. package/README.zh-CN.md +290 -439
  4. package/SKILLS/ufoo/SKILL.md +7 -0
  5. package/bin/ufoo.js +36 -3
  6. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  7. package/docs/OBSERVABILITY.md +4 -2
  8. package/docs/README.md +1 -0
  9. package/package.json +6 -2
  10. package/scripts/pack-desktop.js +174 -0
  11. package/src/agents/capabilities/coding/index.js +26 -3
  12. package/src/agents/capabilities/index.js +2 -1
  13. package/src/agents/capabilities/mac/index.js +145 -0
  14. package/src/agents/capabilities/planning/index.js +1 -1
  15. package/src/agents/capabilities/turnRecall/index.js +5 -16
  16. package/src/agents/profiles/coding.js +1 -1
  17. package/src/agents/profiles/main.js +1 -1
  18. package/src/agents/providers/nativeTransport.js +105 -116
  19. package/src/agents/providers/runtimeConfig.js +15 -4
  20. package/src/agents/providers/transports/anthropicCache.js +78 -0
  21. package/src/agents/providers/transports/antigravityTransport.js +3 -2
  22. package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
  23. package/src/agents/providers/transports/requestCacheObservation.js +61 -0
  24. package/src/agents/providers/transports/responsesProtocol.js +54 -46
  25. package/src/agents/providers/upstreamRuntime.js +2 -2
  26. package/src/agents/runtime/context/contextWindow.js +10 -0
  27. package/src/agents/runtime/context/slidingWindowManager.js +97 -41
  28. package/src/agents/runtime/context/topicSelector.js +4 -2
  29. package/src/agents/runtime/context/turnAnalyzer.js +17 -29
  30. package/src/agents/runtime/core/agentLoop.js +23 -7
  31. package/src/agents/runtime/createAgentRuntime.js +1 -1
  32. package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
  33. package/src/app/chat/ChatController.js +1 -0
  34. package/src/app/chat/commandExecutor.js +25 -0
  35. package/src/app/chat/commands.js +2 -0
  36. package/src/app/chat/daemonMessageRouter.js +30 -3
  37. package/src/app/cli/appCommands.js +107 -0
  38. package/src/app/cli/features/skills.js +2 -0
  39. package/src/app/cli/macCommands.js +321 -0
  40. package/src/app/cli/metricsCommands.js +6 -1
  41. package/src/app/cli/run.js +26 -0
  42. package/src/app/cli/setupCommands.js +1 -0
  43. package/src/code/agent.js +1 -0
  44. package/src/code/context/assembler.js +8 -6
  45. package/src/code/context/promptLayers.js +3 -1
  46. package/src/code/context/stateCommit.js +2 -2
  47. package/src/code/context/transcript.js +11 -5
  48. package/src/code/nativeRunner.js +25 -5
  49. package/src/code/skills/loader.js +10 -2
  50. package/src/code/skills/render.js +8 -1
  51. package/src/config.js +42 -0
  52. package/src/coordination/bus/activate.js +44 -19
  53. package/src/coordination/history/agentPerformance.js +88 -11
  54. package/src/coordination/history/agentTrace.js +2 -0
  55. package/src/coordination/history/modelInputCost.js +52 -0
  56. package/src/runtime/contracts/uiProtocol.js +26 -0
  57. package/src/runtime/daemon/agentHost.js +35 -12
  58. package/src/runtime/daemon/mcpStdioProxy.js +3 -2
  59. package/src/runtime/mac/helperClient.js +279 -0
  60. package/src/runtime/mac/helperCompiler.js +235 -0
  61. package/src/runtime/mac/macSession.js +866 -0
  62. package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
  63. package/src/runtime/mac/paths.js +63 -0
  64. package/src/ui/agentSettingsController.js +12 -5
  65. package/src/ui/cliHandoff.js +484 -0
  66. package/src/ui/desktopArchive.js +41 -0
  67. package/src/ui/desktopUiHost.js +1601 -0
  68. package/src/ui/desktopUiHostCli.js +66 -0
  69. package/src/ui/format/index.js +17 -0
  70. package/src/ui/rustChatHost.js +45 -6
  71. package/src/ui/workspaceInspector.js +621 -0
@@ -0,0 +1,2493 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+ import CoreGraphics
4
+ import Darwin
5
+ import Foundation
6
+ import ImageIO
7
+ import UniformTypeIdentifiers
8
+
9
+ private let UFOO_EVENT_TAG: Int64 = 0x5546_4F4F // "UFOO"
10
+ private let HELPER_VERSION = "1.1.0"
11
+
12
+ // Cross-process NSEvent routing needs a window-local point in addition to its
13
+ // public global location. Resolve the macOS SPI at runtime; never substitute
14
+ // global HID posting when an OS version does not provide it.
15
+ private typealias SetWindowLocation = @convention(c) (CGEvent, Double, Double) -> Void
16
+ private let setEventWindowLocation: SetWindowLocation? = {
17
+ guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "CGEventSetWindowLocation") else { return nil }
18
+ return unsafeBitCast(symbol, to: SetWindowLocation.self)
19
+ }()
20
+
21
+ // MARK: - Coordinate Helpers (CoreGraphics top-left <-> AppKit bottom-left)
22
+
23
+ private func primaryScreenHeight() -> CGFloat {
24
+ if let first = NSScreen.screens.first {
25
+ return first.frame.height
26
+ }
27
+ return CGFloat(CGDisplayPixelsHigh(CGMainDisplayID()))
28
+ }
29
+
30
+ private func cgPointToNS(_ pt: CGPoint) -> NSPoint {
31
+ return NSPoint(x: pt.x, y: primaryScreenHeight() - pt.y)
32
+ }
33
+
34
+ private func nsPointToCG(_ pt: NSPoint) -> CGPoint {
35
+ return CGPoint(x: pt.x, y: primaryScreenHeight() - pt.y)
36
+ }
37
+
38
+ private func cgRectToNS(_ rect: CGRect) -> NSRect {
39
+ return NSRect(
40
+ x: rect.origin.x,
41
+ y: primaryScreenHeight() - rect.origin.y - rect.size.height,
42
+ width: rect.size.width,
43
+ height: rect.size.height
44
+ )
45
+ }
46
+
47
+ private func nsRectToCG(_ rect: NSRect) -> CGRect {
48
+ return CGRect(
49
+ x: rect.origin.x,
50
+ y: primaryScreenHeight() - rect.origin.y - rect.size.height,
51
+ width: rect.size.width,
52
+ height: rect.size.height
53
+ )
54
+ }
55
+
56
+ private func rectDict(_ rect: CGRect) -> [String: Any] {
57
+ return [
58
+ "x": Int(rect.origin.x.rounded()),
59
+ "y": Int(rect.origin.y.rounded()),
60
+ "width": Int(rect.size.width.rounded()),
61
+ "height": Int(rect.size.height.rounded()),
62
+ ]
63
+ }
64
+
65
+ private func currentCGMouseLocation() -> CGPoint {
66
+ if let ev = CGEvent(source: nil) {
67
+ return ev.location
68
+ }
69
+ return nsPointToCG(NSEvent.mouseLocation)
70
+ }
71
+
72
+ // MARK: - Human Takeover Monitor
73
+
74
+ final class TakeoverMonitor {
75
+ struct TakeoverState {
76
+ let reason: String
77
+ let detail: String
78
+ let timestamp: Double
79
+ let turnScope: String
80
+ }
81
+
82
+ private let lock = NSLock()
83
+ private var enabled: Bool = true
84
+ private var isPerformingInput: Bool = false
85
+ private var activeTurnScope: String = ""
86
+ private var lastAgentPoint: CGPoint?
87
+ private var lastAgentActionTime: Double = 0
88
+ private var accumulatedPhysicalDelta: CGFloat = 0
89
+ private var lastObservedPhysicalPoint: CGPoint?
90
+ private var lastPhysicalDelta: CGPoint?
91
+ private var shakeStartedAt: Double = 0
92
+ private var shakeReversals = 0
93
+ private var targetBounds: CGRect?
94
+ private var latched: TakeoverState?
95
+ private var mouseMonitor: Any?
96
+ private var keyMonitor: Any?
97
+ var onTakeover: ((TakeoverState) -> Void)?
98
+
99
+ func setTargetBounds(_ bounds: CGRect?) {
100
+ lock.lock()
101
+ targetBounds = bounds
102
+ lock.unlock()
103
+ }
104
+
105
+ func startMonitorsOnMain() {
106
+ if mouseMonitor == nil {
107
+ let mask: NSEvent.EventTypeMask = [
108
+ .mouseMoved, .leftMouseDragged, .rightMouseDragged, .leftMouseDown, .rightMouseDown,
109
+ ]
110
+ mouseMonitor = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] event in
111
+ self?.handleGlobalMouseEvent(event)
112
+ }
113
+ }
114
+ if keyMonitor == nil {
115
+ keyMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.keyDown]) { [weak self] event in
116
+ self?.handleGlobalKeyEvent(event)
117
+ }
118
+ }
119
+ }
120
+
121
+ func setEnabled(_ flag: Bool) {
122
+ lock.lock()
123
+ enabled = flag
124
+ if !flag {
125
+ latched = nil
126
+ accumulatedPhysicalDelta = 0
127
+ }
128
+ lock.unlock()
129
+ }
130
+
131
+ func syncTurnScope(_ scope: String) {
132
+ let trimmed = scope.trimmingCharacters(in: .whitespacesAndNewlines)
133
+ if trimmed.isEmpty { return }
134
+ lock.lock()
135
+ if !activeTurnScope.isEmpty && activeTurnScope != trimmed {
136
+ // A new user request/turn clears prior turn's takeover latch automatically.
137
+ if let current = latched, current.turnScope != trimmed {
138
+ latched = nil
139
+ accumulatedPhysicalDelta = 0
140
+ }
141
+ }
142
+ activeTurnScope = trimmed
143
+ lock.unlock()
144
+ }
145
+
146
+ func clear() {
147
+ lock.lock()
148
+ latched = nil
149
+ accumulatedPhysicalDelta = 0
150
+ lastObservedPhysicalPoint = nil
151
+ lock.unlock()
152
+ }
153
+
154
+ func currentTakeover() -> [String: Any]? {
155
+ lock.lock()
156
+ defer { lock.unlock() }
157
+ guard let st = latched else { return nil }
158
+ return [
159
+ "reason": st.reason,
160
+ "detail": st.detail,
161
+ "timestamp": Int((st.timestamp * 1000).rounded()),
162
+ "turnScope": st.turnScope,
163
+ ]
164
+ }
165
+
166
+ func beginAgentInput(at point: CGPoint?) -> TakeoverState? {
167
+ lock.lock()
168
+ defer { lock.unlock() }
169
+ if enabled, let st = latched {
170
+ return st
171
+ }
172
+ isPerformingInput = true
173
+ accumulatedPhysicalDelta = 0
174
+ lastObservedPhysicalPoint = nil
175
+ lastPhysicalDelta = nil
176
+ shakeReversals = 0
177
+ shakeStartedAt = CFAbsoluteTimeGetCurrent()
178
+ if let pt = point {
179
+ lastAgentPoint = pt
180
+ }
181
+ lastAgentActionTime = CFAbsoluteTimeGetCurrent()
182
+ return nil
183
+ }
184
+
185
+ func recordAgentMouseStep(_ pt: CGPoint) {
186
+ lock.lock()
187
+ lastAgentPoint = pt
188
+ lastAgentActionTime = CFAbsoluteTimeGetCurrent()
189
+ lock.unlock()
190
+ }
191
+
192
+ func endAgentInput(finalPoint: CGPoint?) {
193
+ lock.lock()
194
+ isPerformingInput = false
195
+ if let pt = finalPoint {
196
+ lastAgentPoint = pt
197
+ }
198
+ lastAgentActionTime = CFAbsoluteTimeGetCurrent()
199
+ accumulatedPhysicalDelta = 0
200
+ lastObservedPhysicalPoint = nil
201
+ lock.unlock()
202
+ }
203
+
204
+ func checkStepOrAbort(expectedNear expected: CGPoint?) -> TakeoverState? {
205
+ lock.lock()
206
+ if !enabled {
207
+ lock.unlock()
208
+ return nil
209
+ }
210
+ if let st = latched {
211
+ lock.unlock()
212
+ return st
213
+ }
214
+ lock.unlock()
215
+ // Agent and physical cursor positions are independent. Comparing them
216
+ // would falsely treat every agent move as a user takeover.
217
+ return nil
218
+ }
219
+
220
+ private func latch(_ state: TakeoverState) {
221
+ var shouldNotify = false
222
+ lock.lock()
223
+ if latched == nil {
224
+ latched = state
225
+ shouldNotify = true
226
+ }
227
+ lock.unlock()
228
+ if shouldNotify {
229
+ onTakeover?(state)
230
+ }
231
+ }
232
+
233
+ private func handleGlobalMouseEvent(_ event: NSEvent) {
234
+ if let cg = event.cgEvent, cg.getIntegerValueField(.eventSourceUserData) == UFOO_EVENT_TAG {
235
+ return
236
+ }
237
+ let now = CFAbsoluteTimeGetCurrent()
238
+ let pt = event.cgEvent?.location ?? nsPointToCG(NSEvent.mouseLocation)
239
+
240
+ lock.lock()
241
+ guard enabled, latched == nil else {
242
+ lock.unlock()
243
+ return
244
+ }
245
+ let active = isPerformingInput
246
+ let recent = (now - lastAgentActionTime) < 1.8
247
+ guard active || recent else {
248
+ lock.unlock()
249
+ return
250
+ }
251
+ let scope = activeTurnScope
252
+
253
+ if event.type == .leftMouseDown || event.type == .rightMouseDown {
254
+ let inTarget = targetBounds?.contains(pt) == true
255
+ lock.unlock()
256
+ guard inTarget else { return }
257
+ latch(TakeoverState(
258
+ reason: "user_mouse_clicked",
259
+ detail: "User clicked inside the agent's target window",
260
+ timestamp: now,
261
+ turnScope: scope
262
+ ))
263
+ return
264
+ }
265
+
266
+ if now - shakeStartedAt > 0.8 {
267
+ shakeStartedAt = now
268
+ shakeReversals = 0
269
+ accumulatedPhysicalDelta = 0
270
+ lastPhysicalDelta = nil
271
+ }
272
+ if let prev = lastObservedPhysicalPoint {
273
+ let delta = CGPoint(x: pt.x - prev.x, y: pt.y - prev.y)
274
+ if hypot(delta.x, delta.y) >= 4 {
275
+ accumulatedPhysicalDelta += hypot(delta.x, delta.y)
276
+ if let prior = lastPhysicalDelta, delta.x * prior.x + delta.y * prior.y < 0 {
277
+ shakeReversals += 1
278
+ }
279
+ lastPhysicalDelta = delta
280
+ }
281
+ }
282
+ lastObservedPhysicalPoint = pt
283
+ let delta = accumulatedPhysicalDelta
284
+ let shaking = shakeReversals >= 3 && delta >= 160
285
+ lock.unlock()
286
+
287
+ if shaking {
288
+ latch(TakeoverState(
289
+ reason: "user_mouse_shake",
290
+ detail: "User shook physical mouse (\(Int(delta.rounded()))pt)",
291
+ timestamp: now,
292
+ turnScope: scope
293
+ ))
294
+ }
295
+ }
296
+
297
+ private func handleGlobalKeyEvent(_ event: NSEvent) {
298
+ if let cg = event.cgEvent, cg.getIntegerValueField(.eventSourceUserData) == UFOO_EVENT_TAG {
299
+ return
300
+ }
301
+ guard event.keyCode == 53 else { return } // Escape key
302
+ let now = CFAbsoluteTimeGetCurrent()
303
+ lock.lock()
304
+ guard enabled, latched == nil else {
305
+ lock.unlock()
306
+ return
307
+ }
308
+ let active = isPerformingInput || (now - lastAgentActionTime) < 4.0
309
+ let scope = activeTurnScope
310
+ lock.unlock()
311
+
312
+ if active {
313
+ latch(TakeoverState(
314
+ reason: "user_pressed_escape",
315
+ detail: "User pressed Esc emergency yield shortcut",
316
+ timestamp: now,
317
+ turnScope: scope
318
+ ))
319
+ }
320
+ }
321
+ }
322
+
323
+ // MARK: - Agent Mouse & Highlight Visual HUD (Main Thread)
324
+
325
+ private enum AgentMouseTheme {
326
+ // Dominant orange from extensions/ufoo-browser/icons/toolbar-logo.png.
327
+ static let orange = NSColor(srgbRed: 252.0 / 255, green: 93.0 / 255, blue: 35.0 / 255, alpha: 1)
328
+ }
329
+
330
+ private final class AgentCursorView: NSView {
331
+ var hotSpot: NSPoint = NSPoint(x: 48, y: 72)
332
+ var clickProgress: CGFloat?
333
+
334
+ override var isOpaque: Bool { false }
335
+
336
+ override func draw(_ dirtyRect: NSRect) {
337
+ guard let ctx = NSGraphicsContext.current?.cgContext else { return }
338
+ ctx.clear(bounds)
339
+ ctx.setAllowsAntialiasing(true)
340
+ ctx.setShouldAntialias(true)
341
+
342
+ // Three compact, translucent ripples; no ring while moving or idle.
343
+ if let progress = clickProgress {
344
+ for layer in 0..<3 {
345
+ let phase = (progress - CGFloat(layer) * 0.16) / 0.68
346
+ guard phase > 0, phase < 1 else { continue }
347
+ let radius = 3 + 25 * (1 - pow(1 - phase, 1.4))
348
+ let opacity = 0.30 * sin(.pi * phase)
349
+ let ring = NSBezierPath(ovalIn: NSRect(
350
+ x: hotSpot.x - radius, y: hotSpot.y - radius,
351
+ width: radius * 2, height: radius * 2
352
+ ))
353
+ AgentMouseTheme.orange.withAlphaComponent(opacity).setStroke()
354
+ ring.lineWidth = 1.15
355
+ ring.stroke()
356
+ }
357
+ }
358
+
359
+ // The top vertex is the exact input coordinate.
360
+ let pointer = NSBezierPath()
361
+ pointer.move(to: hotSpot)
362
+ pointer.line(to: NSPoint(x: hotSpot.x, y: hotSpot.y - 16))
363
+ pointer.line(to: NSPoint(x: hotSpot.x + 4.5, y: hotSpot.y - 12.2))
364
+ pointer.line(to: NSPoint(x: hotSpot.x + 11.5, y: hotSpot.y - 13.5))
365
+ pointer.close()
366
+ AgentMouseTheme.orange.setFill()
367
+ pointer.fill()
368
+ NSColor.white.withAlphaComponent(0.95).setStroke()
369
+ pointer.lineWidth = 1.3
370
+ pointer.stroke()
371
+ }
372
+ }
373
+
374
+ private final class HighlightFrameView: NSView {
375
+ override var isOpaque: Bool { false }
376
+ override func draw(_ dirtyRect: NSRect) {
377
+ let inset = bounds.insetBy(dx: 2, dy: 2)
378
+ guard inset.width > 2, inset.height > 2 else { return }
379
+ let accent = AgentMouseTheme.orange
380
+ let path = NSBezierPath(roundedRect: inset, xRadius: 6, yRadius: 6)
381
+ accent.withAlphaComponent(0.10).setFill()
382
+ path.fill()
383
+ accent.withAlphaComponent(0.92).setStroke()
384
+ path.lineWidth = 2.2
385
+ path.stroke()
386
+ }
387
+ }
388
+
389
+ final class AgentHudController {
390
+ var enabled: Bool = true
391
+ var agentName: String = "ufoo"
392
+
393
+ private var cursorWindow: NSWindow?
394
+ private var cursorView: AgentCursorView?
395
+ private var highlightWindow: NSWindow?
396
+ private var idleHideWorkItem: DispatchWorkItem?
397
+ private var highlightHideWorkItem: DispatchWorkItem?
398
+ private var rippleTimer: Timer?
399
+ private let canvasSize = NSSize(width: 112, height: 112)
400
+
401
+ private func ensureCursorWindowOnMain() {
402
+ if cursorWindow != nil { return }
403
+ let win = NSWindow(
404
+ contentRect: NSRect(origin: .zero, size: canvasSize),
405
+ styleMask: .borderless,
406
+ backing: .buffered,
407
+ defer: false
408
+ )
409
+ win.isReleasedWhenClosed = false
410
+ win.isOpaque = false
411
+ win.backgroundColor = .clear
412
+ win.hasShadow = false
413
+ win.ignoresMouseEvents = true
414
+ win.level = .screenSaver
415
+ win.sharingType = .none
416
+ win.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
417
+ let view = AgentCursorView(frame: NSRect(origin: .zero, size: canvasSize))
418
+ win.contentView = view
419
+ cursorWindow = win
420
+ cursorView = view
421
+ }
422
+
423
+ private func ensureHighlightWindowOnMain() {
424
+ if highlightWindow != nil { return }
425
+ let win = NSWindow(
426
+ contentRect: NSRect(x: 0, y: 0, width: 60, height: 30),
427
+ styleMask: .borderless,
428
+ backing: .buffered,
429
+ defer: false
430
+ )
431
+ win.isReleasedWhenClosed = false
432
+ win.isOpaque = false
433
+ win.backgroundColor = .clear
434
+ win.hasShadow = false
435
+ win.ignoresMouseEvents = true
436
+ win.level = .screenSaver
437
+ win.sharingType = .none
438
+ win.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
439
+ win.contentView = HighlightFrameView(frame: NSRect(x: 0, y: 0, width: 60, height: 30))
440
+ highlightWindow = win
441
+ }
442
+
443
+ func updateCursor(cgPoint: CGPoint, actionLabel: String = "", mode: String = "normal", idleHideAfter: Double = 3.2) {
444
+ guard enabled else { return }
445
+ DispatchQueue.main.async { [weak self] in
446
+ guard let self = self, self.enabled else { return }
447
+ self.ensureCursorWindowOnMain()
448
+ guard let win = self.cursorWindow, let view = self.cursorView else { return }
449
+ self.stopRippleOnMain()
450
+ let nsPt = cgPointToNS(cgPoint)
451
+ // Leave room around the click point for the expanding pulse.
452
+ let anchorX = self.canvasSize.width / 2
453
+ let anchorY = self.canvasSize.height / 2
454
+ let origin = NSPoint(x: nsPt.x - anchorX, y: nsPt.y - anchorY)
455
+ win.setFrameOrigin(origin)
456
+ view.hotSpot = NSPoint(x: anchorX, y: anchorY)
457
+ view.needsDisplay = true
458
+ win.alphaValue = 1.0
459
+ win.orderFrontRegardless()
460
+ self.scheduleIdleHideOnMain(after: idleHideAfter)
461
+ }
462
+ }
463
+
464
+ func pulseClick(cgPoint: CGPoint, actionLabel: String, rightClick: Bool = false, doubleClick: Bool = false) {
465
+ updateCursor(cgPoint: cgPoint)
466
+ DispatchQueue.main.async { [weak self] in
467
+ guard let self = self, self.enabled, let view = self.cursorView else { return }
468
+ self.stopRippleOnMain()
469
+ view.clickProgress = 0
470
+ view.needsDisplay = true
471
+ let started = ProcessInfo.processInfo.systemUptime
472
+ let duration = doubleClick ? 1.25 : 1.1
473
+ let timer = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] timer in
474
+ guard let self = self else { timer.invalidate(); return }
475
+ let progress = (ProcessInfo.processInfo.systemUptime - started) / duration
476
+ if progress >= 1 {
477
+ self.stopRippleOnMain()
478
+ } else {
479
+ self.cursorView?.clickProgress = CGFloat(progress)
480
+ self.cursorView?.needsDisplay = true
481
+ }
482
+ }
483
+ self.rippleTimer = timer
484
+ RunLoop.main.add(timer, forMode: .common)
485
+ }
486
+ }
487
+
488
+ private func stopRippleOnMain() {
489
+ rippleTimer?.invalidate()
490
+ rippleTimer = nil
491
+ cursorView?.clickProgress = nil
492
+ cursorView?.needsDisplay = true
493
+ }
494
+
495
+ func flashHighlight(cgRect: CGRect, duration: Double = 0.65) {
496
+ guard enabled, cgRect.width > 2, cgRect.height > 2 else { return }
497
+ DispatchQueue.main.async { [weak self] in
498
+ guard let self = self, self.enabled else { return }
499
+ self.ensureHighlightWindowOnMain()
500
+ guard let win = self.highlightWindow else { return }
501
+ let nsRect = cgRectToNS(cgRect).insetBy(dx: -4, dy: -4)
502
+ win.setFrame(nsRect, display: true)
503
+ win.contentView?.needsDisplay = true
504
+ win.alphaValue = 1.0
505
+ win.orderFrontRegardless()
506
+ self.highlightHideWorkItem?.cancel()
507
+ let item = DispatchWorkItem { [weak self] in
508
+ self?.highlightWindow?.orderOut(nil)
509
+ }
510
+ self.highlightHideWorkItem = item
511
+ DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: item)
512
+ }
513
+ }
514
+
515
+ func showTakeoverPaused() {
516
+ hideImmediatelySync()
517
+ }
518
+
519
+ func hideImmediatelySync() {
520
+ if Thread.isMainThread {
521
+ stopRippleOnMain()
522
+ idleHideWorkItem?.cancel()
523
+ highlightHideWorkItem?.cancel()
524
+ cursorWindow?.orderOut(nil)
525
+ highlightWindow?.orderOut(nil)
526
+ } else {
527
+ DispatchQueue.main.sync {
528
+ self.stopRippleOnMain()
529
+ self.idleHideWorkItem?.cancel()
530
+ self.highlightHideWorkItem?.cancel()
531
+ self.cursorWindow?.orderOut(nil)
532
+ self.highlightWindow?.orderOut(nil)
533
+ }
534
+ }
535
+ }
536
+
537
+ private func scheduleIdleHideOnMain(after seconds: Double) {
538
+ idleHideWorkItem?.cancel()
539
+ let item = DispatchWorkItem { [weak self] in
540
+ self?.cursorWindow?.orderOut(nil)
541
+ }
542
+ idleHideWorkItem = item
543
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: item)
544
+ }
545
+ }
546
+
547
+ // MARK: - Keycode & Modifier Mapping
548
+
549
+ private let KEYCODE_MAP: [String: CGKeyCode] = [
550
+ "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9,
551
+ "b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17,
552
+ "1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25, "7": 26,
553
+ "-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35,
554
+ "return": 36, "enter": 36, "l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42,
555
+ ",": 43, "/": 44, "n": 45, "m": 46, ".": 47, "tab": 48, "space": 49, "`": 50,
556
+ "delete": 51, "backspace": 51, "escape": 53, "esc": 53,
557
+ "f17": 64, "f18": 79, "f19": 80, "f20": 90,
558
+ "f5": 96, "f6": 97, "f7": 98, "f3": 99, "f8": 100, "f9": 101, "f11": 103,
559
+ "f13": 105, "f16": 106, "f14": 107, "f10": 109, "f12": 111, "f15": 113,
560
+ "help": 114, "home": 115, "pageup": 116, "forwarddelete": 117, "f4": 118,
561
+ "end": 119, "f2": 120, "pagedown": 121, "f1": 122,
562
+ "left": 123, "arrowleft": 123, "right": 124, "arrowright": 124,
563
+ "down": 125, "arrowdown": 125, "up": 126, "arrowup": 126,
564
+ ]
565
+
566
+ private func parseKeyAndModifiers(keyRaw: String, modifiersRaw: [String]) -> (CGKeyCode?, CGEventFlags) {
567
+ var modTokens = modifiersRaw.map { $0.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) }
568
+ var baseKey = keyRaw.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
569
+ if baseKey.contains("+") && baseKey != "+" {
570
+ let parts = baseKey.split(separator: "+").map(String.init)
571
+ if let last = parts.last {
572
+ modTokens.append(contentsOf: parts.dropLast())
573
+ baseKey = last
574
+ }
575
+ }
576
+ var flags = CGEventFlags()
577
+ for tok in modTokens {
578
+ switch tok {
579
+ case "cmd", "command", "meta", "super":
580
+ flags.insert(.maskCommand)
581
+ case "shift":
582
+ flags.insert(.maskShift)
583
+ case "alt", "opt", "option":
584
+ flags.insert(.maskAlternate)
585
+ case "ctrl", "control":
586
+ flags.insert(.maskControl)
587
+ default:
588
+ break
589
+ }
590
+ }
591
+ return (KEYCODE_MAP[baseKey], flags)
592
+ }
593
+
594
+ private func parseModifierFlags(_ modifiersRaw: [String]) -> CGEventFlags {
595
+ return parseKeyAndModifiers(keyRaw: "", modifiersRaw: modifiersRaw).1
596
+ }
597
+
598
+ // MARK: - Accessibility (AXUIElement) Helpers
599
+
600
+ @_silgen_name("_AXUIElementGetWindow")
601
+ private func _AXUIElementGetWindow(_ element: AXUIElement, _ windowID: UnsafeMutablePointer<CGWindowID>) -> AXError
602
+
603
+ private func axCopyAttr(_ element: AXUIElement, _ attr: String) -> CFTypeRef? {
604
+ var out: CFTypeRef?
605
+ let err = AXUIElementCopyAttributeValue(element, attr as CFString, &out)
606
+ return err == .success ? out : nil
607
+ }
608
+
609
+ private func axString(_ element: AXUIElement, _ attr: String) -> String {
610
+ guard let val = axCopyAttr(element, attr) else { return "" }
611
+ if let str = val as? String { return str }
612
+ if let num = val as? NSNumber { return num.stringValue }
613
+ return ""
614
+ }
615
+
616
+ private func axBool(_ element: AXUIElement, _ attr: String, defaultValue: Bool = false) -> Bool {
617
+ guard let val = axCopyAttr(element, attr) else { return defaultValue }
618
+ if let b = val as? Bool { return b }
619
+ if let n = val as? NSNumber { return n.boolValue }
620
+ return defaultValue
621
+ }
622
+
623
+ private func axFrame(_ element: AXUIElement) -> CGRect? {
624
+ guard
625
+ let posRef = axCopyAttr(element, kAXPositionAttribute),
626
+ let sizeRef = axCopyAttr(element, kAXSizeAttribute),
627
+ CFGetTypeID(posRef) == AXValueGetTypeID(),
628
+ CFGetTypeID(sizeRef) == AXValueGetTypeID()
629
+ else {
630
+ return nil
631
+ }
632
+ var pt = CGPoint.zero
633
+ var sz = CGSize.zero
634
+ guard
635
+ AXValueGetValue(posRef as! AXValue, .cgPoint, &pt),
636
+ AXValueGetValue(sizeRef as! AXValue, .cgSize, &sz)
637
+ else {
638
+ return nil
639
+ }
640
+ return CGRect(origin: pt, size: sz)
641
+ }
642
+
643
+ private func axChildren(_ element: AXUIElement) -> [AXUIElement] {
644
+ if let arr = axCopyAttr(element, kAXChildrenAttribute) as? [AXUIElement] {
645
+ return arr
646
+ }
647
+ return []
648
+ }
649
+
650
+ // A known window ID remains authoritative after windows close or reorder.
651
+ private func snapshotWindow<T>(_ windows: [T], windowId: Int, rootIndex: Int, id: (T) -> Int) -> T? {
652
+ if windowId > 0 {
653
+ return windows.first(where: { id($0) == windowId })
654
+ }
655
+ return windows.indices.contains(rootIndex) ? windows[rootIndex] : nil
656
+ }
657
+
658
+ private func axActions(_ element: AXUIElement) -> [String] {
659
+ var namesRef: CFArray?
660
+ guard AXUIElementCopyActionNames(element, &namesRef) == .success,
661
+ let names = namesRef as? [String]
662
+ else {
663
+ return []
664
+ }
665
+ let keep: Set<String> = [
666
+ kAXPressAction, kAXConfirmAction, kAXCancelAction, kAXPickAction,
667
+ kAXShowMenuAction, kAXIncrementAction, kAXDecrementAction, kAXRaiseAction,
668
+ ]
669
+ return names.filter { keep.contains($0) }
670
+ }
671
+
672
+ private let INTERACTIVE_ROLES: Set<String> = [
673
+ "AXButton", "AXRadioButton", "AXCheckBox", "AXPopUpButton", "AXMenuButton",
674
+ "AXMenuItem", "AXMenuBarItem", "AXTextField", "AXTextArea", "AXSearchField",
675
+ "AXComboBox", "AXSlider", "AXLink", "AXTab", "AXTabGroup", "AXDisclosureTriangle",
676
+ "AXIncrementor", "AXColorWell", "AXCell", "AXRow", "AXOutlineRow",
677
+ ]
678
+
679
+ // MARK: - Core Operations Engine
680
+
681
+ final class MacAutomationEngine {
682
+ let takeover = TakeoverMonitor()
683
+ let hud = AgentHudController()
684
+ private struct InputTarget {
685
+ let pid: pid_t
686
+ let windowId: Int
687
+ let bounds: CGRect
688
+ }
689
+ private var inputTarget: InputTarget?
690
+ private var inputSession = "default"
691
+ private var cursorPositions: [String: CGPoint] = [:]
692
+ private var agentPoint: CGPoint? {
693
+ get { cursorPositions[inputSession] }
694
+ set {
695
+ if cursorPositions.count >= 128 && cursorPositions[inputSession] == nil {
696
+ cursorPositions.removeValue(forKey: cursorPositions.keys.first!)
697
+ }
698
+ cursorPositions[inputSession] = newValue
699
+ }
700
+ }
701
+
702
+ init() {
703
+ takeover.onTakeover = { [weak self] _ in
704
+ self?.hud.showTakeoverPaused()
705
+ }
706
+ }
707
+
708
+ func collectPermissions(prompt: Bool = false, openSettings: Bool = false) -> [String: Any] {
709
+ let axTrusted: Bool
710
+ if prompt {
711
+ let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
712
+ axTrusted = AXIsProcessTrustedWithOptions(opts)
713
+ } else {
714
+ axTrusted = AXIsProcessTrusted()
715
+ }
716
+
717
+ let screenTrusted: Bool
718
+ if prompt {
719
+ screenTrusted = CGPreflightScreenCaptureAccess() || CGRequestScreenCaptureAccess()
720
+ } else {
721
+ screenTrusted = CGPreflightScreenCaptureAccess()
722
+ }
723
+
724
+ if openSettings {
725
+ if !axTrusted, let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") {
726
+ NSWorkspace.shared.open(url)
727
+ } else if !screenTrusted, let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") {
728
+ NSWorkspace.shared.open(url)
729
+ }
730
+ }
731
+
732
+ return [
733
+ "accessibility": axTrusted,
734
+ "screenRecording": screenTrusted,
735
+ ]
736
+ }
737
+
738
+ func collectDisplays() -> [[String: Any]] {
739
+ var out: [[String: Any]] = []
740
+ for (idx, screen) in NSScreen.screens.enumerated() {
741
+ let cgBounds = nsRectToCG(screen.frame)
742
+ let screenNumber = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value ?? 0
743
+ out.append([
744
+ "index": idx + 1,
745
+ "displayId": screenNumber,
746
+ "main": idx == 0,
747
+ "bounds": rectDict(cgBounds),
748
+ "scaleFactor": Double(screen.backingScaleFactor),
749
+ ])
750
+ }
751
+ return out
752
+ }
753
+
754
+ func frontmostAppDict() -> [String: Any]? {
755
+ guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
756
+ return [
757
+ "name": app.localizedName ?? "",
758
+ "bundleId": app.bundleIdentifier ?? "",
759
+ "pid": Int(app.processIdentifier),
760
+ ]
761
+ }
762
+
763
+ func statusPayload(prompt: Bool = false, openSettings: Bool = false) -> [String: Any] {
764
+ let perms = collectPermissions(prompt: prompt, openSettings: openSettings)
765
+ let cursor = currentCGMouseLocation()
766
+ var res: [String: Any] = [
767
+ "helperVersion": HELPER_VERSION,
768
+ "pid": Int(ProcessInfo.processInfo.processIdentifier),
769
+ "osVersion": ProcessInfo.processInfo.operatingSystemVersionString,
770
+ "permissions": perms,
771
+ "displays": collectDisplays(),
772
+ "cursor": ["x": Int(cursor.x.rounded()), "y": Int(cursor.y.rounded())],
773
+ "hudEnabled": hud.enabled,
774
+ "pointerMode": "independent",
775
+ ]
776
+ if let front = frontmostAppDict() {
777
+ res["frontmostApp"] = front
778
+ }
779
+ if let tk = takeover.currentTakeover() {
780
+ res["takeover"] = tk
781
+ }
782
+ return res
783
+ }
784
+
785
+ private func rawWindowList(includeOffscreen: Bool = false) -> [[String: Any]] {
786
+ let opts: CGWindowListOption = includeOffscreen
787
+ ? [.optionAll, .excludeDesktopElements]
788
+ : [.optionOnScreenOnly, .excludeDesktopElements]
789
+ guard let info = CGWindowListCopyWindowInfo(opts, kCGNullWindowID) as? [[String: Any]] else {
790
+ return []
791
+ }
792
+ return info
793
+ }
794
+
795
+ private func resolveRunningApps() -> [pid_t: NSRunningApplication] {
796
+ var map: [pid_t: NSRunningApplication] = [:]
797
+ for app in NSWorkspace.shared.runningApplications {
798
+ map[app.processIdentifier] = app
799
+ }
800
+ return map
801
+ }
802
+
803
+ private func appMatches(_ app: NSRunningApplication?, ownerName: String, filterApp: String, filterBundleId: String, filterPid: Int) -> Bool {
804
+ if filterPid > 0 {
805
+ guard let p = app?.processIdentifier, Int(p) == filterPid else { return false }
806
+ }
807
+ if !filterBundleId.isEmpty {
808
+ let bid = (app?.bundleIdentifier ?? "").lowercased()
809
+ if bid != filterBundleId.lowercased() { return false }
810
+ }
811
+ if !filterApp.isEmpty {
812
+ let needle = filterApp.lowercased()
813
+ let name = (app?.localizedName ?? ownerName).lowercased()
814
+ let bid = (app?.bundleIdentifier ?? "").lowercased()
815
+ if !name.contains(needle) && bid != needle && !bid.hasSuffix(".\(needle)") {
816
+ return false
817
+ }
818
+ }
819
+ return true
820
+ }
821
+
822
+ func listApps(includeBackground: Bool = false) -> [[String: Any]] {
823
+ let windows = rawWindowList(includeOffscreen: false)
824
+ var winCountByPid: [Int: Int] = [:]
825
+ for w in windows {
826
+ let layer = (w[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
827
+ if layer != 0 { continue }
828
+ if let pid = (w[kCGWindowOwnerPID as String] as? NSNumber)?.intValue {
829
+ winCountByPid[pid, default: 0] += 1
830
+ }
831
+ }
832
+ var rows: [[String: Any]] = []
833
+ for app in NSWorkspace.shared.runningApplications {
834
+ if app.isTerminated { continue }
835
+ let policy = app.activationPolicy
836
+ if !includeBackground && policy != .regular { continue }
837
+ let pid = Int(app.processIdentifier)
838
+ rows.append([
839
+ "name": app.localizedName ?? "",
840
+ "bundleId": app.bundleIdentifier ?? "",
841
+ "pid": pid,
842
+ "active": app.isActive,
843
+ "hidden": app.isHidden,
844
+ "windowCount": winCountByPid[pid] ?? 0,
845
+ ])
846
+ }
847
+ rows.sort { a, b in
848
+ let aActive = (a["active"] as? Bool) ?? false
849
+ let bActive = (b["active"] as? Bool) ?? false
850
+ if aActive != bActive { return aActive && !bActive }
851
+ let aWins = (a["windowCount"] as? Int) ?? 0
852
+ let bWins = (b["windowCount"] as? Int) ?? 0
853
+ if (aWins > 0) != (bWins > 0) { return aWins > 0 }
854
+ return ((a["name"] as? String) ?? "") < ((b["name"] as? String) ?? "")
855
+ }
856
+ return rows
857
+ }
858
+
859
+ func listWindows(appFilter: String = "", bundleIdFilter: String = "", pidFilter: Int = 0, windowIdFilter: Int = 0, includeOffscreen: Bool = false) -> [[String: Any]] {
860
+ let appMap = resolveRunningApps()
861
+ let frontPid = Int(NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1)
862
+ var out: [[String: Any]] = []
863
+ var seenFrontForApp = false
864
+
865
+ for w in rawWindowList(includeOffscreen: includeOffscreen) {
866
+ let winId = (w[kCGWindowNumber as String] as? NSNumber)?.intValue ?? 0
867
+ if windowIdFilter > 0 && winId != windowIdFilter { continue }
868
+ let layer = (w[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
869
+ // Keep normal app windows (layer == 0) unless explicitly querying a windowId
870
+ if windowIdFilter <= 0 && layer != 0 { continue }
871
+ let pid = (w[kCGWindowOwnerPID as String] as? NSNumber)?.intValue ?? 0
872
+ if pid == Int(ProcessInfo.processInfo.processIdentifier) { continue }
873
+ let ownerName = (w[kCGWindowOwnerName as String] as? String) ?? ""
874
+ let runningApp = appMap[pid_t(pid)]
875
+ if !appMatches(runningApp, ownerName: ownerName, filterApp: appFilter, filterBundleId: bundleIdFilter, filterPid: pidFilter) {
876
+ continue
877
+ }
878
+ var bounds = CGRect.zero
879
+ if let bDict = w[kCGWindowBounds as String] as? NSDictionary {
880
+ CGRectMakeWithDictionaryRepresentation(bDict, &bounds)
881
+ }
882
+ if windowIdFilter <= 0 && (bounds.width < 24 || bounds.height < 24) { continue }
883
+ let alpha = (w[kCGWindowAlpha as String] as? NSNumber)?.doubleValue ?? 1.0
884
+ if windowIdFilter <= 0 && alpha <= 0.01 { continue }
885
+
886
+ let isFront = (pid == frontPid) && !seenFrontForApp
887
+ if isFront { seenFrontForApp = true }
888
+
889
+ out.append([
890
+ "windowId": winId,
891
+ "title": (w[kCGWindowName as String] as? String) ?? "",
892
+ "app": runningApp?.localizedName ?? ownerName,
893
+ "bundleId": runningApp?.bundleIdentifier ?? "",
894
+ "pid": pid,
895
+ "bounds": rectDict(bounds),
896
+ "layer": layer,
897
+ "onScreen": (w[kCGWindowIsOnscreen as String] as? Bool) ?? true,
898
+ "frontmost": isFront,
899
+ ])
900
+ }
901
+ return out
902
+ }
903
+
904
+ func resolveTargetApp(appName: String = "", bundleId: String = "", pid: Int = 0, windowId: Int = 0) -> NSRunningApplication? {
905
+ if pid > 0 {
906
+ return NSRunningApplication(processIdentifier: pid_t(pid))
907
+ }
908
+ if windowId > 0 {
909
+ let wins = listWindows(windowIdFilter: windowId, includeOffscreen: true)
910
+ if let wPid = wins.first?["pid"] as? Int, wPid > 0 {
911
+ return NSRunningApplication(processIdentifier: pid_t(wPid))
912
+ }
913
+ return nil
914
+ }
915
+ let apps = NSWorkspace.shared.runningApplications.filter { !$0.isTerminated }
916
+ if !bundleId.isEmpty {
917
+ if let exact = apps.first(where: { ($0.bundleIdentifier ?? "").caseInsensitiveCompare(bundleId) == .orderedSame }) {
918
+ return exact
919
+ }
920
+ return nil
921
+ }
922
+ if !appName.isEmpty {
923
+ let needle = appName.lowercased()
924
+ if let exact = apps.first(where: { ($0.localizedName ?? "").lowercased() == needle }) {
925
+ return exact
926
+ }
927
+ if let partial = apps.first(where: {
928
+ ($0.localizedName ?? "").lowercased().contains(needle)
929
+ || ($0.bundleIdentifier ?? "").lowercased().contains(needle)
930
+ }) {
931
+ return partial
932
+ }
933
+ return nil
934
+ }
935
+ return NSWorkspace.shared.frontmostApplication
936
+ }
937
+
938
+ private func activateRunningApp(_ app: NSRunningApplication) {
939
+ app.unhide()
940
+ if AXIsProcessTrusted() {
941
+ let appElem = AXUIElementCreateApplication(app.processIdentifier)
942
+ AXUIElementSetMessagingTimeout(appElem, 1.0)
943
+ _ = AXUIElementSetAttributeValue(appElem, kAXFrontmostAttribute as CFString, kCFBooleanTrue)
944
+ }
945
+ if #available(macOS 14.0, *) {
946
+ _ = app.activate()
947
+ } else {
948
+ _ = app.activate(options: [.activateIgnoringOtherApps])
949
+ }
950
+ if !app.isActive {
951
+ let proc = Process()
952
+ proc.executableURL = URL(fileURLWithPath: "/usr/bin/open")
953
+ if let bid = app.bundleIdentifier, !bid.isEmpty {
954
+ proc.arguments = ["-b", bid]
955
+ } else if let url = app.bundleURL {
956
+ proc.arguments = ["-a", url.path]
957
+ }
958
+ if proc.arguments != nil {
959
+ proc.standardOutput = FileHandle.nullDevice
960
+ proc.standardError = FileHandle.nullDevice
961
+ try? proc.run()
962
+ proc.waitUntilExit()
963
+ }
964
+ }
965
+ }
966
+
967
+ func launchOrFocusApp(appName: String, bundleId: String, waitMs: Int = 4000) throws -> [String: Any] {
968
+ if let existing = resolveTargetApp(appName: appName, bundleId: bundleId),
969
+ (!appName.isEmpty || !bundleId.isEmpty)
970
+ {
971
+ let matchesExplicit: Bool = {
972
+ if !bundleId.isEmpty {
973
+ return (existing.bundleIdentifier ?? "").caseInsensitiveCompare(bundleId) == .orderedSame
974
+ }
975
+ let needle = appName.lowercased()
976
+ let name = (existing.localizedName ?? "").lowercased()
977
+ return name == needle || name.contains(needle)
978
+ }()
979
+ if matchesExplicit {
980
+ activateRunningApp(existing)
981
+ Thread.sleep(forTimeInterval: 0.15)
982
+ let pid = Int(existing.processIdentifier)
983
+ return [
984
+ "launched": false,
985
+ "activated": true,
986
+ "name": existing.localizedName ?? appName,
987
+ "bundleId": existing.bundleIdentifier ?? bundleId,
988
+ "pid": pid,
989
+ "windows": listWindows(pidFilter: pid),
990
+ ]
991
+ }
992
+ }
993
+
994
+ let proc = Process()
995
+ proc.executableURL = URL(fileURLWithPath: "/usr/bin/open")
996
+ if !bundleId.isEmpty {
997
+ proc.arguments = ["-b", bundleId]
998
+ } else if !appName.isEmpty {
999
+ proc.arguments = ["-a", appName]
1000
+ } else {
1001
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Provide app or bundleId to launch_app"])
1002
+ }
1003
+ let errPipe = Pipe()
1004
+ proc.standardError = errPipe
1005
+ try proc.run()
1006
+ proc.waitUntilExit()
1007
+ if proc.terminationStatus != 0 {
1008
+ let errText = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "open failed"
1009
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: errText])
1010
+ }
1011
+
1012
+ let deadline = CFAbsoluteTimeGetCurrent() + Double(max(200, min(waitMs, 15000))) / 1000.0
1013
+ var target: NSRunningApplication?
1014
+ while CFAbsoluteTimeGetCurrent() < deadline {
1015
+ if let found = resolveTargetApp(appName: appName, bundleId: bundleId) {
1016
+ let okMatch = !bundleId.isEmpty
1017
+ ? (found.bundleIdentifier ?? "").caseInsensitiveCompare(bundleId) == .orderedSame
1018
+ : (found.localizedName ?? "").lowercased().contains(appName.lowercased())
1019
+ if okMatch {
1020
+ target = found
1021
+ activateRunningApp(found)
1022
+ let wins = listWindows(pidFilter: Int(found.processIdentifier))
1023
+ if !wins.isEmpty { break }
1024
+ }
1025
+ }
1026
+ Thread.sleep(forTimeInterval: 0.12)
1027
+ }
1028
+
1029
+ let pid = Int(target?.processIdentifier ?? 0)
1030
+ return [
1031
+ "launched": true,
1032
+ "activated": target?.isActive ?? false,
1033
+ "name": target?.localizedName ?? appName,
1034
+ "bundleId": target?.bundleIdentifier ?? bundleId,
1035
+ "pid": pid,
1036
+ "windows": pid > 0 ? listWindows(pidFilter: pid) : [],
1037
+ ]
1038
+ }
1039
+
1040
+ func focusAppOrWindow(appName: String = "", bundleId: String = "", pid: Int = 0, windowId: Int = 0) throws -> [String: Any] {
1041
+ guard let app = resolveTargetApp(appName: appName, bundleId: bundleId, pid: pid, windowId: windowId) else {
1042
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "Target application not found"])
1043
+ }
1044
+ var targetWindow: AXUIElement?
1045
+ if windowId > 0 {
1046
+ guard AXIsProcessTrusted() else {
1047
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1048
+ NSLocalizedDescriptionKey: "Accessibility permission is required to focus a specific window.",
1049
+ "permission": "accessibility",
1050
+ ])
1051
+ }
1052
+ let appElem = AXUIElementCreateApplication(app.processIdentifier)
1053
+ AXUIElementSetMessagingTimeout(appElem, 1.5)
1054
+ let axWins = (axCopyAttr(appElem, kAXWindowsAttribute) as? [AXUIElement]) ?? []
1055
+ targetWindow = snapshotWindow(axWins, windowId: windowId, rootIndex: 0) { w in
1056
+ var wid: CGWindowID = 0
1057
+ return _AXUIElementGetWindow(w, &wid) == .success ? Int(wid) : 0
1058
+ }
1059
+ guard targetWindow != nil else {
1060
+ throw NSError(domain: "ufoo.mac.stale", code: 409, userInfo: [NSLocalizedDescriptionKey: "Target window no longer exists; take a fresh snapshot."])
1061
+ }
1062
+ }
1063
+ activateRunningApp(app)
1064
+ if let window = targetWindow {
1065
+ let raised = AXUIElementPerformAction(window, kAXRaiseAction as CFString)
1066
+ guard raised == .success else {
1067
+ throw NSError(domain: "ufoo.mac", code: 422, userInfo: [NSLocalizedDescriptionKey: "Could not focus target window (AXError \(raised.rawValue))."])
1068
+ }
1069
+ _ = AXUIElementSetAttributeValue(window, kAXMainAttribute as CFString, kCFBooleanTrue)
1070
+ }
1071
+ Thread.sleep(forTimeInterval: 0.08)
1072
+ guard app.isActive else {
1073
+ throw NSError(domain: "ufoo.mac", code: 409, userInfo: [NSLocalizedDescriptionKey: "Target application did not become active; input was not sent."])
1074
+ }
1075
+ let resolvedPid = Int(app.processIdentifier)
1076
+ return [
1077
+ "name": app.localizedName ?? "",
1078
+ "bundleId": app.bundleIdentifier ?? "",
1079
+ "pid": resolvedPid,
1080
+ "windows": listWindows(pidFilter: resolvedPid),
1081
+ ]
1082
+ }
1083
+
1084
+ func manageWindow(action: String, appName: String = "", bundleId: String = "", pid: Int = 0, windowId: Int = 0, x: Double?, y: Double?, width: Double?, height: Double?) throws -> [String: Any] {
1085
+ guard AXIsProcessTrusted() else {
1086
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1087
+ NSLocalizedDescriptionKey: "Accessibility permission is required to manage windows. Run `ufoo mac permissions` to grant access.",
1088
+ "permission": "accessibility",
1089
+ ])
1090
+ }
1091
+ guard let app = resolveTargetApp(appName: appName, bundleId: bundleId, pid: pid, windowId: windowId) else {
1092
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "Target application not found"])
1093
+ }
1094
+ let appElem = AXUIElementCreateApplication(app.processIdentifier)
1095
+ AXUIElementSetMessagingTimeout(appElem, 1.5)
1096
+ guard let axWins = axCopyAttr(appElem, kAXWindowsAttribute) as? [AXUIElement], !axWins.isEmpty else {
1097
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "No accessible window found for \(app.localizedName ?? "application")"])
1098
+ }
1099
+ var targetWin = axWins[0]
1100
+ var matchedWid: Int = 0
1101
+ if windowId > 0 {
1102
+ var found = false
1103
+ for w in axWins {
1104
+ var wid: CGWindowID = 0
1105
+ if _AXUIElementGetWindow(w, &wid) == .success && Int(wid) == windowId {
1106
+ targetWin = w
1107
+ matchedWid = Int(wid)
1108
+ found = true
1109
+ break
1110
+ }
1111
+ }
1112
+ if !found {
1113
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "Window \(windowId) not found in \(app.localizedName ?? "application")"])
1114
+ }
1115
+ } else {
1116
+ var wid: CGWindowID = 0
1117
+ if _AXUIElementGetWindow(targetWin, &wid) == .success {
1118
+ matchedWid = Int(wid)
1119
+ }
1120
+ }
1121
+
1122
+ switch action {
1123
+ case "focus":
1124
+ activateRunningApp(app)
1125
+ _ = AXUIElementPerformAction(targetWin, kAXRaiseAction as CFString)
1126
+ _ = AXUIElementSetAttributeValue(targetWin, kAXMainAttribute as CFString, kCFBooleanTrue)
1127
+ case "move", "resize", "set_bounds":
1128
+ if let nx = x, let ny = y {
1129
+ var pt = CGPoint(x: nx, y: ny)
1130
+ if let val = AXValueCreate(.cgPoint, &pt) {
1131
+ _ = AXUIElementSetAttributeValue(targetWin, kAXPositionAttribute as CFString, val)
1132
+ }
1133
+ }
1134
+ if let nw = width, let nh = height {
1135
+ var sz = CGSize(width: max(80, nw), height: max(60, nh))
1136
+ if let val = AXValueCreate(.cgSize, &sz) {
1137
+ _ = AXUIElementSetAttributeValue(targetWin, kAXSizeAttribute as CFString, val)
1138
+ }
1139
+ }
1140
+ case "minimize":
1141
+ _ = AXUIElementSetAttributeValue(targetWin, kAXMinimizedAttribute as CFString, kCFBooleanTrue)
1142
+ case "close":
1143
+ if let closeBtn = axCopyAttr(targetWin, kAXCloseButtonAttribute) {
1144
+ _ = AXUIElementPerformAction(closeBtn as! AXUIElement, kAXPressAction as CFString)
1145
+ } else {
1146
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Window does not expose a close button"])
1147
+ }
1148
+ case "fullscreen":
1149
+ let cur = axBool(targetWin, "AXFullScreen")
1150
+ _ = AXUIElementSetAttributeValue(targetWin, "AXFullScreen" as CFString, (!cur) as CFBoolean)
1151
+ default:
1152
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Unsupported windowAction: \(action)"])
1153
+ }
1154
+
1155
+ Thread.sleep(forTimeInterval: 0.08)
1156
+ let frame = axFrame(targetWin) ?? .zero
1157
+ return [
1158
+ "windowAction": action,
1159
+ "windowId": matchedWid,
1160
+ "app": app.localizedName ?? "",
1161
+ "pid": Int(app.processIdentifier),
1162
+ "bounds": rectDict(frame),
1163
+ ]
1164
+ }
1165
+
1166
+ // MARK: - AX Snapshot & AX Action
1167
+
1168
+ func snapshotAX(
1169
+ appName: String = "",
1170
+ bundleId: String = "",
1171
+ pid: Int = 0,
1172
+ windowId: Int = 0,
1173
+ maxDepth: Int = 7,
1174
+ maxNodes: Int = 350,
1175
+ interactiveOnly: Bool = false,
1176
+ includeMenuBar: Bool = false,
1177
+ query: String = ""
1178
+ ) throws -> [String: Any] {
1179
+ guard AXIsProcessTrusted() else {
1180
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1181
+ NSLocalizedDescriptionKey: "Accessibility permission is required for UI tree snapshots. Run `ufoo mac permissions` to grant access.",
1182
+ "permission": "accessibility",
1183
+ ])
1184
+ }
1185
+ guard let app = resolveTargetApp(appName: appName, bundleId: bundleId, pid: pid, windowId: windowId) else {
1186
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "Target application not found"])
1187
+ }
1188
+ let targetPid = app.processIdentifier
1189
+ let appElem = AXUIElementCreateApplication(targetPid)
1190
+ AXUIElementSetMessagingTimeout(appElem, 1.5)
1191
+ // Wake Chromium / Electron accessibility trees when queried
1192
+ _ = AXUIElementSetAttributeValue(appElem, "AXManualAccessibility" as CFString, kCFBooleanTrue)
1193
+
1194
+ let boundedDepth = max(1, min(maxDepth, 14))
1195
+ let boundedNodes = max(20, min(maxNodes, 1000))
1196
+ let queryLower = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
1197
+
1198
+ var roots: [(rootKind: String, rootIndex: Int, winId: Int, elem: AXUIElement)] = []
1199
+ if let axWins = axCopyAttr(appElem, kAXWindowsAttribute) as? [AXUIElement] {
1200
+ for (idx, w) in axWins.enumerated() {
1201
+ var wid: CGWindowID = 0
1202
+ _ = _AXUIElementGetWindow(w, &wid)
1203
+ if windowId > 0 && Int(wid) != windowId { continue }
1204
+ roots.append(("window", idx, Int(wid), w))
1205
+ }
1206
+ }
1207
+ if includeMenuBar, let menuBar = axCopyAttr(appElem, kAXMenuBarAttribute) {
1208
+ roots.append(("menubar", 0, 0, menuBar as! AXUIElement))
1209
+ }
1210
+
1211
+ var elements: [[String: Any]] = []
1212
+ var truncated = false
1213
+
1214
+ func visit(_ elem: AXUIElement, rootKind: String, rootIndex: Int, winId: Int, path: [Int], depth: Int) {
1215
+ if elements.count >= boundedNodes {
1216
+ truncated = true
1217
+ return
1218
+ }
1219
+ let role = axString(elem, kAXRoleAttribute)
1220
+ let subrole = axString(elem, kAXSubroleAttribute)
1221
+ let title = axString(elem, kAXTitleAttribute)
1222
+ let desc = axString(elem, kAXDescriptionAttribute)
1223
+ let rawVal = axString(elem, kAXValueAttribute)
1224
+ let val = rawVal.count > 120 ? String(rawVal.prefix(120)) + "…" : rawVal
1225
+ let ident = axString(elem, "AXIdentifier")
1226
+ let actions = axActions(elem)
1227
+ let frame = axFrame(elem)
1228
+ let enabled = axBool(elem, kAXEnabledAttribute, defaultValue: true)
1229
+ let focused = axBool(elem, kAXFocusedAttribute, defaultValue: false)
1230
+
1231
+ let isInteractive = INTERACTIVE_ROLES.contains(role) || !actions.isEmpty
1232
+ let hasSemanticText = !title.isEmpty || !desc.isEmpty || (!val.isEmpty && role != "AXGroup")
1233
+ let shouldConsider = depth == 0 || (interactiveOnly ? isInteractive : (isInteractive || hasSemanticText))
1234
+
1235
+ let matchesQuery: Bool = {
1236
+ if queryLower.isEmpty { return true }
1237
+ let hay = "\(role) \(subrole) \(title) \(desc) \(val) \(ident)".lowercased()
1238
+ return hay.contains(queryLower)
1239
+ }()
1240
+
1241
+ if shouldConsider && matchesQuery {
1242
+ var item: [String: Any] = [
1243
+ "role": role.isEmpty ? "AXElement" : role,
1244
+ "depth": depth,
1245
+ "rootKind": rootKind,
1246
+ "rootIndex": rootIndex,
1247
+ "windowId": winId,
1248
+ "axPath": path,
1249
+ "enabled": enabled,
1250
+ "focused": focused,
1251
+ "actions": actions,
1252
+ ]
1253
+ if !subrole.isEmpty { item["subrole"] = subrole }
1254
+ if !title.isEmpty { item["title"] = title }
1255
+ if !desc.isEmpty && desc != title { item["label"] = desc }
1256
+ if !val.isEmpty && val != title { item["value"] = val }
1257
+ if !ident.isEmpty { item["identifier"] = ident }
1258
+ if let f = frame, f.width > 0, f.height > 0 {
1259
+ item["frame"] = rectDict(f)
1260
+ item["center"] = [
1261
+ "x": Int(f.midX.rounded()),
1262
+ "y": Int(f.midY.rounded()),
1263
+ ]
1264
+ }
1265
+ elements.append(item)
1266
+ }
1267
+
1268
+ if depth >= boundedDepth { return }
1269
+ let children = axChildren(elem)
1270
+ for (cIdx, child) in children.enumerated() {
1271
+ if elements.count >= boundedNodes {
1272
+ truncated = true
1273
+ return
1274
+ }
1275
+ visit(child, rootKind: rootKind, rootIndex: rootIndex, winId: winId, path: path + [cIdx], depth: depth + 1)
1276
+ }
1277
+ }
1278
+
1279
+ for root in roots {
1280
+ visit(root.elem, rootKind: root.rootKind, rootIndex: root.rootIndex, winId: root.winId, path: [], depth: 0)
1281
+ if truncated { break }
1282
+ }
1283
+
1284
+ return [
1285
+ "app": app.localizedName ?? "",
1286
+ "bundleId": app.bundleIdentifier ?? "",
1287
+ "pid": Int(targetPid),
1288
+ "windowCount": roots.filter { $0.rootKind == "window" }.count,
1289
+ "truncated": truncated,
1290
+ "elements": elements,
1291
+ ]
1292
+ }
1293
+
1294
+ func performAXAction(
1295
+ pid: Int,
1296
+ rootKind: String,
1297
+ rootIndex: Int,
1298
+ windowId: Int,
1299
+ axPath: [Int],
1300
+ expectedRole: String = "",
1301
+ axAction: String,
1302
+ value: String = ""
1303
+ ) throws -> [String: Any] {
1304
+ guard AXIsProcessTrusted() else {
1305
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1306
+ NSLocalizedDescriptionKey: "Accessibility permission is required for ax_action.",
1307
+ "permission": "accessibility",
1308
+ ])
1309
+ }
1310
+ let appElem = AXUIElementCreateApplication(pid_t(pid))
1311
+ AXUIElementSetMessagingTimeout(appElem, 1.5)
1312
+
1313
+ var current: AXUIElement?
1314
+ if rootKind == "menubar" {
1315
+ if let mb = axCopyAttr(appElem, kAXMenuBarAttribute) {
1316
+ current = (mb as! AXUIElement)
1317
+ }
1318
+ } else if let axWins = axCopyAttr(appElem, kAXWindowsAttribute) as? [AXUIElement] {
1319
+ current = snapshotWindow(axWins, windowId: windowId, rootIndex: rootIndex) { w in
1320
+ var wid: CGWindowID = 0
1321
+ return _AXUIElementGetWindow(w, &wid) == .success ? Int(wid) : 0
1322
+ }
1323
+ }
1324
+
1325
+ guard var elem = current else {
1326
+ throw NSError(domain: "ufoo.mac.stale", code: 409, userInfo: [
1327
+ NSLocalizedDescriptionKey: "Target window/menu root no longer exists; take a fresh snapshot.",
1328
+ ])
1329
+ }
1330
+
1331
+ for idx in axPath {
1332
+ let children = axChildren(elem)
1333
+ guard idx >= 0 && idx < children.count else {
1334
+ throw NSError(domain: "ufoo.mac.stale", code: 409, userInfo: [
1335
+ NSLocalizedDescriptionKey: "UI hierarchy changed since snapshot; call snapshot again to refresh element refs.",
1336
+ ])
1337
+ }
1338
+ elem = children[idx]
1339
+ }
1340
+
1341
+ let actualRole = axString(elem, kAXRoleAttribute)
1342
+ if !expectedRole.isEmpty && !actualRole.isEmpty && actualRole != expectedRole {
1343
+ throw NSError(domain: "ufoo.mac.stale", code: 409, userInfo: [
1344
+ NSLocalizedDescriptionKey: "Element at snapshot path changed from \(expectedRole) to \(actualRole); call snapshot again.",
1345
+ ])
1346
+ }
1347
+
1348
+ if let frame = axFrame(elem), frame.width > 1, frame.height > 1 {
1349
+ hud.flashHighlight(cgRect: frame)
1350
+ }
1351
+
1352
+ let err: AXError
1353
+ switch axAction {
1354
+ case "press":
1355
+ err = AXUIElementPerformAction(elem, kAXPressAction as CFString)
1356
+ case "confirm":
1357
+ err = AXUIElementPerformAction(elem, kAXConfirmAction as CFString)
1358
+ case "cancel":
1359
+ err = AXUIElementPerformAction(elem, kAXCancelAction as CFString)
1360
+ case "pick":
1361
+ err = AXUIElementPerformAction(elem, kAXPickAction as CFString)
1362
+ case "show_menu":
1363
+ err = AXUIElementPerformAction(elem, kAXShowMenuAction as CFString)
1364
+ case "increment":
1365
+ err = AXUIElementPerformAction(elem, kAXIncrementAction as CFString)
1366
+ case "decrement":
1367
+ err = AXUIElementPerformAction(elem, kAXDecrementAction as CFString)
1368
+ case "focus":
1369
+ if let app = NSRunningApplication(processIdentifier: pid_t(pid)) {
1370
+ activateRunningApp(app)
1371
+ }
1372
+ err = AXUIElementSetAttributeValue(elem, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1373
+ case "set_value":
1374
+ err = AXUIElementSetAttributeValue(elem, kAXValueAttribute as CFString, value as CFTypeRef)
1375
+ default:
1376
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Unsupported axAction: \(axAction)"])
1377
+ }
1378
+
1379
+ if err != .success {
1380
+ throw NSError(domain: "ufoo.mac", code: 422, userInfo: [
1381
+ NSLocalizedDescriptionKey: "AX action '\(axAction)' failed on \(actualRole.isEmpty ? "element" : actualRole) (AXError \(err.rawValue)). Try click with ref or coordinates if the control is custom-rendered.",
1382
+ ])
1383
+ }
1384
+
1385
+ let updatedFrame = axFrame(elem)
1386
+ var out: [String: Any] = [
1387
+ "axAction": axAction,
1388
+ "role": actualRole,
1389
+ "title": axString(elem, kAXTitleAttribute),
1390
+ ]
1391
+ if let f = updatedFrame {
1392
+ out["frame"] = rectDict(f)
1393
+ }
1394
+ return out
1395
+ }
1396
+
1397
+ // MARK: - Screenshot (Shadowless Window / Region / Display + 1x Logical Scaling)
1398
+
1399
+ func captureScreenshot(
1400
+ outputPath: String,
1401
+ appName: String = "",
1402
+ bundleId: String = "",
1403
+ pid: Int = 0,
1404
+ windowId: Int = 0,
1405
+ displayIndex: Int = 1,
1406
+ region: CGRect? = nil,
1407
+ retina: Bool = false
1408
+ ) throws -> [String: Any] {
1409
+ guard CGPreflightScreenCaptureAccess() else {
1410
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1411
+ NSLocalizedDescriptionKey: "Screen Recording permission is required to capture Mac screenshots. Run `ufoo mac permissions` and grant Screen Recording to your terminal/host app, then restart if prompted.",
1412
+ "permission": "screen_recording",
1413
+ ])
1414
+ }
1415
+
1416
+ var resolvedWindowId = windowId
1417
+ var windowMeta: [String: Any]?
1418
+ if resolvedWindowId > 0 {
1419
+ windowMeta = listWindows(windowIdFilter: resolvedWindowId, includeOffscreen: true).first
1420
+ if windowMeta == nil {
1421
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "Window \(resolvedWindowId) not found"])
1422
+ }
1423
+ } else if !appName.isEmpty || !bundleId.isEmpty || pid > 0 {
1424
+ let wins = listWindows(appFilter: appName, bundleIdFilter: bundleId, pidFilter: pid, includeOffscreen: false)
1425
+ guard let first = wins.first, let wid = first["windowId"] as? Int else {
1426
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey: "No visible on-screen window found for requested app"])
1427
+ }
1428
+ resolvedWindowId = wid
1429
+ windowMeta = first
1430
+ }
1431
+
1432
+ var logicalBounds = CGRect.zero
1433
+ var captureKind = "screen"
1434
+ var args: [String] = ["-x"]
1435
+
1436
+ if let reg = region, reg.width > 1, reg.height > 1 {
1437
+ captureKind = "region"
1438
+ logicalBounds = reg
1439
+ let rx = Int(reg.origin.x.rounded())
1440
+ let ry = Int(reg.origin.y.rounded())
1441
+ let rw = max(1, Int(reg.size.width.rounded()))
1442
+ let rh = max(1, Int(reg.size.height.rounded()))
1443
+ args.append("-R\(rx),\(ry),\(rw),\(rh)")
1444
+ } else if resolvedWindowId > 0, let meta = windowMeta {
1445
+ captureKind = "window"
1446
+ if let b = meta["bounds"] as? [String: Int] {
1447
+ logicalBounds = CGRect(
1448
+ x: b["x"] ?? 0,
1449
+ y: b["y"] ?? 0,
1450
+ width: b["width"] ?? 0,
1451
+ height: b["height"] ?? 0
1452
+ )
1453
+ }
1454
+ args.append(contentsOf: ["-o", "-l\(resolvedWindowId)"])
1455
+ } else {
1456
+ let screens = collectDisplays()
1457
+ let chosen = screens.first(where: { ($0["index"] as? Int) == displayIndex }) ?? screens.first
1458
+ if let b = chosen?["bounds"] as? [String: Int] {
1459
+ logicalBounds = CGRect(
1460
+ x: b["x"] ?? 0,
1461
+ y: b["y"] ?? 0,
1462
+ width: b["width"] ?? 1440,
1463
+ height: b["height"] ?? 900
1464
+ )
1465
+ }
1466
+ let idx = (chosen?["index"] as? Int) ?? 1
1467
+ args.append("-D\(idx)")
1468
+ }
1469
+
1470
+ let rawTempPath = outputPath + ".raw.png"
1471
+ defer { try? FileManager.default.removeItem(atPath: rawTempPath) }
1472
+
1473
+ // Ensure HUD overlays are completely hidden around capture
1474
+ hud.hideImmediatelySync()
1475
+
1476
+ let proc = Process()
1477
+ proc.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
1478
+ proc.arguments = args + [rawTempPath]
1479
+ let errPipe = Pipe()
1480
+ proc.standardError = errPipe
1481
+ try proc.run()
1482
+ proc.waitUntilExit()
1483
+ if proc.terminationStatus != 0 || !FileManager.default.fileExists(atPath: rawTempPath) {
1484
+ let errStr = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "screencapture failed"
1485
+ throw NSError(domain: "ufoo.mac", code: 500, userInfo: [NSLocalizedDescriptionKey: "Screenshot capture failed: \(errStr)"])
1486
+ }
1487
+
1488
+ let rawURL = URL(fileURLWithPath: rawTempPath)
1489
+ guard let src = CGImageSourceCreateWithURL(rawURL as CFURL, nil),
1490
+ let cgImg = CGImageSourceCreateImageAtIndex(src, 0, nil)
1491
+ else {
1492
+ throw NSError(domain: "ufoo.mac", code: 500, userInfo: [NSLocalizedDescriptionKey: "Failed to decode captured screenshot"])
1493
+ }
1494
+
1495
+ let targetW: Int
1496
+ let targetH: Int
1497
+ if !retina && logicalBounds.width > 1 && logicalBounds.height > 1 && cgImg.width > Int(logicalBounds.width * 1.05) {
1498
+ targetW = max(1, Int(logicalBounds.width.rounded()))
1499
+ targetH = max(1, Int(logicalBounds.height.rounded()))
1500
+ } else {
1501
+ targetW = cgImg.width
1502
+ targetH = cgImg.height
1503
+ if logicalBounds.width <= 1 || logicalBounds.height <= 1 {
1504
+ logicalBounds = CGRect(x: logicalBounds.origin.x, y: logicalBounds.origin.y, width: CGFloat(targetW), height: CGFloat(targetH))
1505
+ }
1506
+ }
1507
+
1508
+ var finalImage = cgImg
1509
+ if targetW != cgImg.width || targetH != cgImg.height {
1510
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
1511
+ if let ctx = CGContext(
1512
+ data: nil,
1513
+ width: targetW,
1514
+ height: targetH,
1515
+ bitsPerComponent: 8,
1516
+ bytesPerRow: 0,
1517
+ space: colorSpace,
1518
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
1519
+ ) {
1520
+ ctx.interpolationQuality = .high
1521
+ ctx.draw(cgImg, in: CGRect(x: 0, y: 0, width: targetW, height: targetH))
1522
+ if let scaled = ctx.makeImage() {
1523
+ finalImage = scaled
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ let outURL = URL(fileURLWithPath: outputPath)
1529
+ var mediaType = "image/png"
1530
+ guard let pngDest = CGImageDestinationCreateWithURL(outURL as CFURL, UTType.png.identifier as CFString, 1, nil) else {
1531
+ throw NSError(domain: "ufoo.mac", code: 500, userInfo: [NSLocalizedDescriptionKey: "Failed to create PNG image destination"])
1532
+ }
1533
+ CGImageDestinationAddImage(pngDest, finalImage, nil)
1534
+ guard CGImageDestinationFinalize(pngDest) else {
1535
+ throw NSError(domain: "ufoo.mac", code: 500, userInfo: [NSLocalizedDescriptionKey: "Failed to write PNG screenshot"])
1536
+ }
1537
+
1538
+ // Keep well below the 5 MiB provider vision limit
1539
+ let attrs = try FileManager.default.attributesOfItem(atPath: outputPath)
1540
+ let sizeBytes = (attrs[.size] as? NSNumber)?.intValue ?? 0
1541
+ var finalPath = outputPath
1542
+ if sizeBytes > 4_600_000 {
1543
+ let jpgPath = (outputPath as NSString).deletingPathExtension + ".jpg"
1544
+ let jpgURL = URL(fileURLWithPath: jpgPath)
1545
+ if let jpgDest = CGImageDestinationCreateWithURL(jpgURL as CFURL, UTType.jpeg.identifier as CFString, 1, nil) {
1546
+ let props = [kCGImageDestinationLossyCompressionQuality: 0.84] as CFDictionary
1547
+ CGImageDestinationAddImage(jpgDest, finalImage, props)
1548
+ if CGImageDestinationFinalize(jpgDest) {
1549
+ try? FileManager.default.removeItem(atPath: outputPath)
1550
+ finalPath = jpgPath
1551
+ mediaType = "image/jpeg"
1552
+ }
1553
+ }
1554
+ }
1555
+
1556
+ let scaleX = Double(logicalBounds.width) / Double(max(1, finalImage.width))
1557
+ let scaleY = Double(logicalBounds.height) / Double(max(1, finalImage.height))
1558
+
1559
+ var result: [String: Any] = [
1560
+ "captureKind": captureKind,
1561
+ "coordinateSpace": (captureKind == "screen" && logicalBounds.origin.x == 0 && logicalBounds.origin.y == 0) ? "screen" : "window",
1562
+ "bounds": rectDict(logicalBounds),
1563
+ "imageWidth": finalImage.width,
1564
+ "imageHeight": finalImage.height,
1565
+ "scaleX": scaleX,
1566
+ "scaleY": scaleY,
1567
+ "path": finalPath,
1568
+ "mediaType": mediaType,
1569
+ ]
1570
+ if resolvedWindowId > 0 {
1571
+ result["windowId"] = resolvedWindowId
1572
+ }
1573
+ if let meta = windowMeta {
1574
+ result["app"] = meta["app"] ?? ""
1575
+ result["title"] = meta["title"] ?? ""
1576
+ result["pid"] = meta["pid"] ?? 0
1577
+ }
1578
+ return result
1579
+ }
1580
+
1581
+ // MARK: - Agent Mouse & Keyboard Injection (CGEvent + Smooth Glide + Takeover Guard)
1582
+
1583
+ private func ensureAccessibilityForInput() throws {
1584
+ guard AXIsProcessTrusted() else {
1585
+ throw NSError(domain: "ufoo.mac.permission", code: 403, userInfo: [
1586
+ NSLocalizedDescriptionKey: "Accessibility permission is required to control the Mac mouse/keyboard. Run `ufoo mac permissions` to grant access.",
1587
+ "permission": "accessibility",
1588
+ ])
1589
+ }
1590
+ }
1591
+
1592
+ private func throwTakeover(_ st: TakeoverMonitor.TakeoverState) throws -> Never {
1593
+ throw NSError(domain: "ufoo.mac.takeover", code: 409, userInfo: [
1594
+ NSLocalizedDescriptionKey: "Agent yielded control (\(st.reason)): \(st.detail). Stop current GUI actions and ask or wait for the user before continuing.",
1595
+ "reason": st.reason,
1596
+ "detail": st.detail,
1597
+ ])
1598
+ }
1599
+
1600
+ private func resolveInputTarget(params: [String: Any], point: CGPoint?) throws -> InputTarget {
1601
+ let pid = (params["pid"] as? NSNumber)?.intValue ?? 0
1602
+ let windowId = (params["windowId"] as? NSNumber)?.intValue ?? 0
1603
+ let app = (params["app"] as? String) ?? ""
1604
+ let bundleId = (params["bundleId"] as? String) ?? ""
1605
+ let explicit = pid > 0 || windowId > 0 || !app.isEmpty || !bundleId.isEmpty
1606
+ let windows = listWindows(appFilter: app, bundleIdFilter: bundleId, pidFilter: pid,
1607
+ windowIdFilter: windowId, includeOffscreen: explicit)
1608
+ func bounds(_ window: [String: Any]) -> CGRect {
1609
+ let b = (window["bounds"] as? [String: Int]) ?? [:]
1610
+ return CGRect(x: b["x"] ?? 0, y: b["y"] ?? 0, width: b["width"] ?? 0, height: b["height"] ?? 0)
1611
+ }
1612
+ // Coordinates without an explicit target hit-test a window, never the
1613
+ // physical pointer or whichever application happens to be frontmost.
1614
+ let window = point.flatMap { p in windows.first(where: { bounds($0).contains(p) }) }
1615
+ ?? (explicit ? windows.first : nil)
1616
+ guard let selected = window, let targetPid = selected["pid"] as? Int,
1617
+ let targetId = selected["windowId"] as? Int, targetPid > 0,
1618
+ targetPid != Int(getpid()), targetId > 0 else {
1619
+ throw NSError(domain: "ufoo.mac", code: 404, userInfo: [NSLocalizedDescriptionKey:
1620
+ "No target window found for independent input. Specify app/windowId or take a fresh snapshot; system input is never used as a fallback."])
1621
+ }
1622
+ return InputTarget(pid: pid_t(targetPid), windowId: targetId, bounds: bounds(selected))
1623
+ }
1624
+
1625
+ private func postTagged(_ event: CGEvent?, flags: CGEventFlags? = nil) throws {
1626
+ guard let original = event, let target = inputTarget else {
1627
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Input requires a live target window."])
1628
+ }
1629
+ let cleanFlags = flags ?? []
1630
+ let ev: CGEvent
1631
+ if original.type == .keyDown || original.type == .keyUp {
1632
+ ev = original
1633
+ } else {
1634
+ guard let setWindowLocation = setEventWindowLocation else {
1635
+ throw NSError(domain: "ufoo.mac.independent", code: 501, userInfo: [NSLocalizedDescriptionKey:
1636
+ "Independent mouse input is unavailable on this macOS version. Use Accessibility actions; system mouse fallback is disabled."])
1637
+ }
1638
+ // NSEvent supplies both the window number and window-local coordinates.
1639
+ // Posting that event to the PID avoids WindowServer's physical HID path.
1640
+ let local = NSPoint(x: original.location.x - target.bounds.minX,
1641
+ y: target.bounds.maxY - original.location.y)
1642
+ let type = original.type == .scrollWheel ? NSEvent.EventType.mouseMoved
1643
+ : NSEvent.EventType(rawValue: UInt(original.type.rawValue))
1644
+ guard let type = type,
1645
+ let routed = NSEvent.mouseEvent(with: type, location: local,
1646
+ modifierFlags: NSEvent.ModifierFlags(rawValue: UInt(cleanFlags.rawValue)),
1647
+ timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: target.windowId,
1648
+ context: nil, eventNumber: 0,
1649
+ clickCount: Int(original.getIntegerValueField(.mouseEventClickState)), pressure: 1)?.cgEvent else {
1650
+ throw NSError(domain: "ufoo.mac", code: 422, userInfo: [NSLocalizedDescriptionKey: "Could not construct a window-targeted mouse event."])
1651
+ }
1652
+ ev = routed
1653
+ ev.location = original.location
1654
+ ev.type = original.type
1655
+ setWindowLocation(ev, original.location.x - target.bounds.minX, original.location.y - target.bounds.minY)
1656
+ ev.setIntegerValueField(.mouseEventSubtype, value: 3)
1657
+ ev.setIntegerValueField(.mouseEventButtonNumber, value: original.getIntegerValueField(.mouseEventButtonNumber))
1658
+ ev.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(target.windowId))
1659
+ ev.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(target.windowId))
1660
+ if original.type == .scrollWheel {
1661
+ for field: CGEventField in [.scrollWheelEventDeltaAxis1, .scrollWheelEventDeltaAxis2,
1662
+ .scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis2,
1663
+ .scrollWheelEventPointDeltaAxis1, .scrollWheelEventPointDeltaAxis2, .scrollWheelEventIsContinuous] {
1664
+ ev.setIntegerValueField(field, value: original.getIntegerValueField(field))
1665
+ }
1666
+ }
1667
+ }
1668
+ ev.flags = cleanFlags
1669
+ ev.setIntegerValueField(.eventSourceUserData, value: UFOO_EVENT_TAG)
1670
+ ev.postToPid(target.pid)
1671
+ }
1672
+
1673
+ private func glideCursor(to target: CGPoint, eventType: CGEventType = .mouseMoved, button: CGMouseButton = .left, actionLabel: String = "Move", durationMs: Int = 135, flags: CGEventFlags = []) throws {
1674
+ let start = agentPoint ?? target
1675
+ let dist = hypot(target.x - start.x, target.y - start.y)
1676
+ let steps = dist < 4 ? 1 : max(4, min(14, Int((dist / 45.0).rounded()) + 4))
1677
+ let stepSleep = Double(max(16, durationMs)) / 1000.0 / Double(steps)
1678
+ let src = CGEventSource(stateID: .privateState)
1679
+
1680
+ for i in 1...steps {
1681
+ if let tk = takeover.checkStepOrAbort(expectedNear: nil) {
1682
+ try throwTakeover(tk)
1683
+ }
1684
+ let t = CGFloat(i) / CGFloat(steps)
1685
+ // Cubic ease-out: 1 - (1 - t)^3
1686
+ let eased = 1.0 - pow(1.0 - t, 3.0)
1687
+ let pt = CGPoint(
1688
+ x: start.x + (target.x - start.x) * eased,
1689
+ y: start.y + (target.y - start.y) * eased
1690
+ )
1691
+ takeover.recordAgentMouseStep(pt)
1692
+ let ev = CGEvent(mouseEventSource: src, mouseType: eventType, mouseCursorPosition: pt, mouseButton: button)
1693
+ try postTagged(ev, flags: flags)
1694
+ hud.updateCursor(cgPoint: pt, actionLabel: actionLabel)
1695
+ agentPoint = pt
1696
+ if i < steps {
1697
+ Thread.sleep(forTimeInterval: stepSleep)
1698
+ }
1699
+ }
1700
+ }
1701
+
1702
+ func mouseMove(to target: CGPoint, turnScope: String = "") throws -> [String: Any] {
1703
+ try ensureAccessibilityForInput()
1704
+ takeover.syncTurnScope(turnScope)
1705
+ if let tk = takeover.beginAgentInput(at: nil) {
1706
+ try throwTakeover(tk)
1707
+ }
1708
+ defer { takeover.endAgentInput(finalPoint: target) }
1709
+
1710
+ try glideCursor(to: target, eventType: .mouseMoved, button: .left, actionLabel: "Move")
1711
+ return ["x": Int(target.x.rounded()), "y": Int(target.y.rounded())]
1712
+ }
1713
+
1714
+ func mouseClick(
1715
+ at target: CGPoint,
1716
+ buttonName: String = "left",
1717
+ clickCount: Int = 1,
1718
+ modifiersRaw: [String] = [],
1719
+ turnScope: String = ""
1720
+ ) throws -> [String: Any] {
1721
+ try ensureAccessibilityForInput()
1722
+ takeover.syncTurnScope(turnScope)
1723
+ if let tk = takeover.beginAgentInput(at: nil) {
1724
+ try throwTakeover(tk)
1725
+ }
1726
+ defer { takeover.endAgentInput(finalPoint: target) }
1727
+
1728
+ let isRight = buttonName == "right"
1729
+ let isMiddle = buttonName == "middle"
1730
+ let cgButton: CGMouseButton = isRight ? .right : (isMiddle ? .center : .left)
1731
+ let downType: CGEventType = isRight ? .rightMouseDown : (isMiddle ? .otherMouseDown : .leftMouseDown)
1732
+ let upType: CGEventType = isRight ? .rightMouseUp : (isMiddle ? .otherMouseUp : .leftMouseUp)
1733
+ let count = max(1, min(clickCount, 3))
1734
+ let label = isRight ? "Right Click" : (count == 2 ? "Double Click" : (count == 3 ? "Triple Click" : "Click"))
1735
+
1736
+ try glideCursor(to: target, eventType: .mouseMoved, button: .left, actionLabel: label)
1737
+ if let tk = takeover.checkStepOrAbort(expectedNear: nil) {
1738
+ try throwTakeover(tk)
1739
+ }
1740
+
1741
+ let flags = parseModifierFlags(modifiersRaw)
1742
+ let src = CGEventSource(stateID: .privateState)
1743
+ hud.pulseClick(cgPoint: target, actionLabel: label, rightClick: isRight, doubleClick: count >= 2)
1744
+
1745
+ for c in 1...count {
1746
+ let down = CGEvent(mouseEventSource: src, mouseType: downType, mouseCursorPosition: target, mouseButton: cgButton)
1747
+ down?.setIntegerValueField(.mouseEventClickState, value: Int64(c))
1748
+ try postTagged(down, flags: flags)
1749
+ Thread.sleep(forTimeInterval: 0.028)
1750
+ let up = CGEvent(mouseEventSource: src, mouseType: upType, mouseCursorPosition: target, mouseButton: cgButton)
1751
+ up?.setIntegerValueField(.mouseEventClickState, value: Int64(c))
1752
+ try postTagged(up, flags: flags)
1753
+ if c < count {
1754
+ Thread.sleep(forTimeInterval: 0.045)
1755
+ }
1756
+ }
1757
+
1758
+ return [
1759
+ "x": Int(target.x.rounded()),
1760
+ "y": Int(target.y.rounded()),
1761
+ "button": buttonName,
1762
+ "clickCount": count,
1763
+ ]
1764
+ }
1765
+
1766
+ func mouseDrag(
1767
+ from startPt: CGPoint,
1768
+ to endPt: CGPoint,
1769
+ holdMs: Int = 80,
1770
+ modifiersRaw: [String] = [],
1771
+ turnScope: String = ""
1772
+ ) throws -> [String: Any] {
1773
+ try ensureAccessibilityForInput()
1774
+ takeover.syncTurnScope(turnScope)
1775
+ if let tk = takeover.beginAgentInput(at: nil) {
1776
+ try throwTakeover(tk)
1777
+ }
1778
+ defer { takeover.endAgentInput(finalPoint: endPt) }
1779
+
1780
+ let flags = parseModifierFlags(modifiersRaw)
1781
+ let src = CGEventSource(stateID: .privateState)
1782
+
1783
+ try glideCursor(to: startPt, eventType: .mouseMoved, button: .left, actionLabel: "Drag")
1784
+ hud.pulseClick(cgPoint: startPt, actionLabel: "Drag")
1785
+ let down = CGEvent(mouseEventSource: src, mouseType: .leftMouseDown, mouseCursorPosition: startPt, mouseButton: .left)
1786
+ try postTagged(down, flags: flags)
1787
+ Thread.sleep(forTimeInterval: Double(max(30, min(holdMs, 1000))) / 1000.0)
1788
+
1789
+ do {
1790
+ try glideCursor(to: endPt, eventType: .leftMouseDragged, button: .left, actionLabel: "Dragging", durationMs: 220, flags: flags)
1791
+ } catch {
1792
+ // Always release mouse button if aborted mid-drag!
1793
+ let cur = agentPoint ?? startPt
1794
+ let upAbort = CGEvent(mouseEventSource: src, mouseType: .leftMouseUp, mouseCursorPosition: cur, mouseButton: .left)
1795
+ try? postTagged(upAbort)
1796
+ throw error
1797
+ }
1798
+
1799
+ Thread.sleep(forTimeInterval: 0.04)
1800
+ let up = CGEvent(mouseEventSource: src, mouseType: .leftMouseUp, mouseCursorPosition: endPt, mouseButton: .left)
1801
+ try postTagged(up, flags: flags)
1802
+
1803
+ return [
1804
+ "from": ["x": Int(startPt.x.rounded()), "y": Int(startPt.y.rounded())],
1805
+ "to": ["x": Int(endPt.x.rounded()), "y": Int(endPt.y.rounded())],
1806
+ ]
1807
+ }
1808
+
1809
+ func mouseScroll(
1810
+ at target: CGPoint?,
1811
+ deltaX: Int,
1812
+ deltaY: Int,
1813
+ turnScope: String = ""
1814
+ ) throws -> [String: Any] {
1815
+ try ensureAccessibilityForInput()
1816
+ takeover.syncTurnScope(turnScope)
1817
+ if let tk = takeover.beginAgentInput(at: nil) {
1818
+ try throwTakeover(tk)
1819
+ }
1820
+ let retainedPoint = agentPoint.flatMap { inputTarget!.bounds.contains($0) ? $0 : nil }
1821
+ let finalPt = target ?? retainedPoint ?? CGPoint(x: inputTarget!.bounds.midX, y: inputTarget!.bounds.midY)
1822
+ defer { takeover.endAgentInput(finalPoint: finalPt) }
1823
+
1824
+ if let pt = target {
1825
+ try glideCursor(to: pt, eventType: .mouseMoved, button: .left, actionLabel: "Scroll")
1826
+ } else {
1827
+ hud.updateCursor(cgPoint: finalPt, actionLabel: "Scroll")
1828
+ }
1829
+
1830
+ let src = CGEventSource(stateID: .privateState)
1831
+ let steps = 4
1832
+ let stepY = Int32((Double(deltaY) / Double(steps)).rounded())
1833
+ let stepX = Int32((Double(deltaX) / Double(steps)).rounded())
1834
+ for _ in 0..<steps {
1835
+ if let tk = takeover.checkStepOrAbort(expectedNear: nil) {
1836
+ try throwTakeover(tk)
1837
+ }
1838
+ if let ev = CGEvent(
1839
+ scrollWheelEvent2Source: src,
1840
+ units: .pixel,
1841
+ wheelCount: 2,
1842
+ wheel1: stepY,
1843
+ wheel2: stepX,
1844
+ wheel3: 0
1845
+ ) {
1846
+ ev.location = finalPt
1847
+ try postTagged(ev)
1848
+ }
1849
+ Thread.sleep(forTimeInterval: 0.018)
1850
+ }
1851
+
1852
+ return [
1853
+ "x": Int(finalPt.x.rounded()),
1854
+ "y": Int(finalPt.y.rounded()),
1855
+ "deltaX": deltaX,
1856
+ "deltaY": deltaY,
1857
+ ]
1858
+ }
1859
+
1860
+ func typeText(text: String, submit: Bool = false, turnScope: String = "") throws -> [String: Any] {
1861
+ try ensureAccessibilityForInput()
1862
+ takeover.syncTurnScope(turnScope)
1863
+ if let tk = takeover.beginAgentInput(at: nil) {
1864
+ try throwTakeover(tk)
1865
+ }
1866
+ defer { takeover.endAgentInput(finalPoint: nil) }
1867
+
1868
+ hud.updateCursor(cgPoint: agentPoint ?? CGPoint(x: inputTarget!.bounds.midX, y: inputTarget!.bounds.midY), actionLabel: "Type")
1869
+ let src = CGEventSource(stateID: .privateState)
1870
+
1871
+ for ch in text {
1872
+ if let tk = takeover.checkStepOrAbort(expectedNear: nil) {
1873
+ try throwTakeover(tk)
1874
+ }
1875
+ if ch == "\n" || ch == "\r" {
1876
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 36, keyDown: true))
1877
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 36, keyDown: false))
1878
+ } else if ch == "\t" {
1879
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 48, keyDown: true))
1880
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 48, keyDown: false))
1881
+ } else {
1882
+ var utf16 = Array(String(ch).utf16)
1883
+ if let down = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: true),
1884
+ let up = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: false)
1885
+ {
1886
+ down.keyboardSetUnicodeString(stringLength: utf16.count, unicodeString: &utf16)
1887
+ up.keyboardSetUnicodeString(stringLength: utf16.count, unicodeString: &utf16)
1888
+ try postTagged(down)
1889
+ try postTagged(up)
1890
+ }
1891
+ }
1892
+ Thread.sleep(forTimeInterval: 0.008)
1893
+ }
1894
+
1895
+ if submit {
1896
+ Thread.sleep(forTimeInterval: 0.025)
1897
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 36, keyDown: true))
1898
+ try postTagged(CGEvent(keyboardEventSource: src, virtualKey: 36, keyDown: false))
1899
+ }
1900
+
1901
+ return [
1902
+ "typedLength": text.count,
1903
+ "submitted": submit,
1904
+ ]
1905
+ }
1906
+
1907
+ func pressKey(keyRaw: String, modifiersRaw: [String] = [], repeatCount: Int = 1, turnScope: String = "") throws -> [String: Any] {
1908
+ try ensureAccessibilityForInput()
1909
+ takeover.syncTurnScope(turnScope)
1910
+ if let tk = takeover.beginAgentInput(at: nil) {
1911
+ try throwTakeover(tk)
1912
+ }
1913
+ defer { takeover.endAgentInput(finalPoint: nil) }
1914
+
1915
+ let (codeOpt, flags) = parseKeyAndModifiers(keyRaw: keyRaw, modifiersRaw: modifiersRaw)
1916
+ guard let keyCode = codeOpt else {
1917
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [
1918
+ NSLocalizedDescriptionKey: "Unknown key '\(keyRaw)'. Use standard key names like return, escape, tab, space, backspace, up, down, left, right, f1-f12, or single characters a-z / 0-9.",
1919
+ ])
1920
+ }
1921
+
1922
+ let label = modifiersRaw.isEmpty ? "Key \(keyRaw)" : "Shortcut"
1923
+ hud.updateCursor(cgPoint: agentPoint ?? CGPoint(x: inputTarget!.bounds.midX, y: inputTarget!.bounds.midY), actionLabel: label)
1924
+ let src = CGEventSource(stateID: .privateState)
1925
+ let times = max(1, min(repeatCount, 20))
1926
+
1927
+ for i in 0..<times {
1928
+ if let tk = takeover.checkStepOrAbort(expectedNear: nil) {
1929
+ try throwTakeover(tk)
1930
+ }
1931
+ let down = CGEvent(keyboardEventSource: src, virtualKey: keyCode, keyDown: true)
1932
+ let up = CGEvent(keyboardEventSource: src, virtualKey: keyCode, keyDown: false)
1933
+ try postTagged(down, flags: flags)
1934
+ Thread.sleep(forTimeInterval: 0.02)
1935
+ try postTagged(up, flags: flags)
1936
+ if i + 1 < times {
1937
+ Thread.sleep(forTimeInterval: 0.03)
1938
+ }
1939
+ }
1940
+
1941
+ return [
1942
+ "key": keyRaw,
1943
+ "modifiers": modifiersRaw,
1944
+ "repeat": times,
1945
+ ]
1946
+ }
1947
+
1948
+ // MARK: - RPC Dispatcher
1949
+
1950
+ func dispatch(method: String, params: [String: Any]) throws -> [String: Any] {
1951
+ if let hudFlag = params["hud"] as? Bool {
1952
+ hud.enabled = hudFlag
1953
+ if !hudFlag { hud.hideImmediatelySync() }
1954
+ }
1955
+ if let tkFlag = params["takeoverGuard"] as? Bool {
1956
+ takeover.setEnabled(tkFlag)
1957
+ }
1958
+ if let agentLabel = params["agentLabel"] as? String, !agentLabel.isEmpty {
1959
+ hud.agentName = agentLabel
1960
+ }
1961
+
1962
+ let str = { (key: String) -> String in
1963
+ (params[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
1964
+ }
1965
+ let intVal = { (key: String, def: Int) -> Int in
1966
+ if let n = params[key] as? NSNumber { return n.intValue }
1967
+ if let s = params[key] as? String, let n = Int(s) { return n }
1968
+ return def
1969
+ }
1970
+ let dblOpt = { (key: String) -> Double? in
1971
+ if let n = params[key] as? NSNumber { return n.doubleValue }
1972
+ if let s = params[key] as? String, let n = Double(s) { return n }
1973
+ return nil
1974
+ }
1975
+ let boolVal = { (key: String, def: Bool) -> Bool in
1976
+ (params[key] as? Bool) ?? def
1977
+ }
1978
+ let strArr = { (key: String) -> [String] in
1979
+ (params[key] as? [String]) ?? []
1980
+ }
1981
+
1982
+ inputSession = str("sessionId").isEmpty ? "default" : str("sessionId")
1983
+ inputTarget = nil
1984
+ if method.hasPrefix("mouse_") || method.hasPrefix("key_") {
1985
+ let x = dblOpt("fromX") ?? dblOpt("x")
1986
+ let y = dblOpt("fromY") ?? dblOpt("y")
1987
+ let point: CGPoint? = x.flatMap { px in y.map { CGPoint(x: px, y: $0) } }
1988
+ let target = try resolveInputTarget(params: params, point: point ?? (method == "mouse_scroll" ? agentPoint : nil))
1989
+ if method.hasPrefix("key_") {
1990
+ let appElement = AXUIElementCreateApplication(target.pid)
1991
+ AXUIElementSetMessagingTimeout(appElement, 1.0)
1992
+ var focusedId: CGWindowID = 0
1993
+ guard let focused = axCopyAttr(appElement, kAXFocusedWindowAttribute),
1994
+ _AXUIElementGetWindow(focused as! AXUIElement, &focusedId) == .success,
1995
+ Int(focusedId) == target.windowId else {
1996
+ throw NSError(domain: "ufoo.mac", code: 409, userInfo: [NSLocalizedDescriptionKey:
1997
+ "Target window does not own keyboard focus. Use an AX action or explicitly request focusApp=true; keys were not sent."])
1998
+ }
1999
+ }
2000
+ inputTarget = target
2001
+ takeover.setTargetBounds(target.bounds)
2002
+ }
2003
+ defer { inputTarget = nil }
2004
+
2005
+ func perform() throws -> [String: Any] {
2006
+ switch method {
2007
+ case "ping", "status":
2008
+ return statusPayload(prompt: boolVal("prompt", false), openSettings: boolVal("openSettings", false))
2009
+
2010
+ case "request_permissions":
2011
+ return statusPayload(prompt: true, openSettings: boolVal("openSettings", true))
2012
+
2013
+ case "configure":
2014
+ return statusPayload()
2015
+
2016
+ case "clear_takeover":
2017
+ takeover.clear()
2018
+ return statusPayload()
2019
+
2020
+ case "hide_hud":
2021
+ hud.hideImmediatelySync()
2022
+ return ["hidden": true]
2023
+
2024
+ case "list_apps":
2025
+ return ["apps": listApps(includeBackground: boolVal("includeBackground", false))]
2026
+
2027
+ case "list_windows":
2028
+ return [
2029
+ "windows": listWindows(
2030
+ appFilter: str("app"),
2031
+ bundleIdFilter: str("bundleId"),
2032
+ pidFilter: intVal("pid", 0),
2033
+ windowIdFilter: intVal("windowId", 0),
2034
+ includeOffscreen: boolVal("includeOffscreen", false)
2035
+ ),
2036
+ ]
2037
+
2038
+ case "launch_app":
2039
+ return try launchOrFocusApp(
2040
+ appName: str("app"),
2041
+ bundleId: str("bundleId"),
2042
+ waitMs: intVal("waitMs", 4000)
2043
+ )
2044
+
2045
+ case "focus_app":
2046
+ return try focusAppOrWindow(
2047
+ appName: str("app"),
2048
+ bundleId: str("bundleId"),
2049
+ pid: intVal("pid", 0),
2050
+ windowId: intVal("windowId", 0)
2051
+ )
2052
+
2053
+ case "manage_window":
2054
+ return try manageWindow(
2055
+ action: str("windowAction"),
2056
+ appName: str("app"),
2057
+ bundleId: str("bundleId"),
2058
+ pid: intVal("pid", 0),
2059
+ windowId: intVal("windowId", 0),
2060
+ x: dblOpt("x"),
2061
+ y: dblOpt("y"),
2062
+ width: dblOpt("width"),
2063
+ height: dblOpt("height")
2064
+ )
2065
+
2066
+ case "snapshot":
2067
+ return try snapshotAX(
2068
+ appName: str("app"),
2069
+ bundleId: str("bundleId"),
2070
+ pid: intVal("pid", 0),
2071
+ windowId: intVal("windowId", 0),
2072
+ maxDepth: intVal("maxDepth", 7),
2073
+ maxNodes: intVal("maxNodes", 350),
2074
+ interactiveOnly: boolVal("interactiveOnly", false),
2075
+ includeMenuBar: boolVal("includeMenuBar", false),
2076
+ query: str("query")
2077
+ )
2078
+
2079
+ case "ax_action":
2080
+ let axPath = (params["axPath"] as? [NSNumber])?.map { $0.intValue } ?? []
2081
+ return try performAXAction(
2082
+ pid: intVal("pid", 0),
2083
+ rootKind: str("rootKind"),
2084
+ rootIndex: intVal("rootIndex", 0),
2085
+ windowId: intVal("windowId", 0),
2086
+ axPath: axPath,
2087
+ expectedRole: str("expectedRole"),
2088
+ axAction: str("axAction"),
2089
+ value: (params["value"] as? String) ?? ""
2090
+ )
2091
+
2092
+ case "screenshot":
2093
+ var regionRect: CGRect?
2094
+ if let reg = params["region"] as? [String: Any],
2095
+ let rx = (reg["x"] as? NSNumber)?.doubleValue,
2096
+ let ry = (reg["y"] as? NSNumber)?.doubleValue,
2097
+ let rw = (reg["width"] as? NSNumber)?.doubleValue,
2098
+ let rh = (reg["height"] as? NSNumber)?.doubleValue
2099
+ {
2100
+ regionRect = CGRect(x: rx, y: ry, width: rw, height: rh)
2101
+ }
2102
+ return try captureScreenshot(
2103
+ outputPath: str("outputPath"),
2104
+ appName: str("app"),
2105
+ bundleId: str("bundleId"),
2106
+ pid: intVal("pid", 0),
2107
+ windowId: intVal("windowId", 0),
2108
+ displayIndex: intVal("display", 1),
2109
+ region: regionRect,
2110
+ retina: boolVal("retina", false)
2111
+ )
2112
+
2113
+ case "mouse_move":
2114
+ guard let x = dblOpt("x"), let y = dblOpt("y") else {
2115
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "x and y are required"])
2116
+ }
2117
+ return try mouseMove(to: CGPoint(x: x, y: y), turnScope: str("turnScope"))
2118
+
2119
+ case "mouse_click":
2120
+ guard let x = dblOpt("x"), let y = dblOpt("y") else {
2121
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "x and y are required"])
2122
+ }
2123
+ if boolVal("focusFirst", false) {
2124
+ _ = try focusAppOrWindow(
2125
+ appName: str("app"),
2126
+ bundleId: str("bundleId"),
2127
+ pid: intVal("pid", 0),
2128
+ windowId: intVal("windowId", 0)
2129
+ )
2130
+ }
2131
+ return try mouseClick(
2132
+ at: CGPoint(x: x, y: y),
2133
+ buttonName: str("button").isEmpty ? "left" : str("button"),
2134
+ clickCount: intVal("clickCount", 1),
2135
+ modifiersRaw: strArr("modifiers"),
2136
+ turnScope: str("turnScope")
2137
+ )
2138
+
2139
+ case "mouse_drag":
2140
+ guard let fx = dblOpt("fromX"), let fy = dblOpt("fromY"),
2141
+ let tx = dblOpt("toX"), let ty = dblOpt("toY")
2142
+ else {
2143
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "fromX, fromY, toX, toY are required"])
2144
+ }
2145
+ return try mouseDrag(
2146
+ from: CGPoint(x: fx, y: fy),
2147
+ to: CGPoint(x: tx, y: ty),
2148
+ holdMs: intVal("holdMs", 80),
2149
+ modifiersRaw: strArr("modifiers"),
2150
+ turnScope: str("turnScope")
2151
+ )
2152
+
2153
+ case "mouse_scroll":
2154
+ var pt: CGPoint?
2155
+ if let x = dblOpt("x"), let y = dblOpt("y") {
2156
+ pt = CGPoint(x: x, y: y)
2157
+ }
2158
+ return try mouseScroll(
2159
+ at: pt,
2160
+ deltaX: intVal("deltaX", 0),
2161
+ deltaY: intVal("deltaY", -240),
2162
+ turnScope: str("turnScope")
2163
+ )
2164
+
2165
+ case "key_type":
2166
+ let rawText = (params["text"] as? String) ?? ""
2167
+ if rawText.isEmpty && !boolVal("submit", false) {
2168
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "text is required for type"])
2169
+ }
2170
+ return try typeText(text: rawText, submit: boolVal("submit", false), turnScope: str("turnScope"))
2171
+
2172
+ case "key_press":
2173
+ let key = str("key")
2174
+ if key.isEmpty {
2175
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "key is required for press_key"])
2176
+ }
2177
+ return try pressKey(
2178
+ keyRaw: key,
2179
+ modifiersRaw: strArr("modifiers"),
2180
+ repeatCount: intVal("repeat", 1),
2181
+ turnScope: str("turnScope")
2182
+ )
2183
+
2184
+ default:
2185
+ throw NSError(domain: "ufoo.mac", code: 400, userInfo: [NSLocalizedDescriptionKey: "Unknown helper method: \(method)"])
2186
+ }
2187
+ }
2188
+ var result = try perform()
2189
+ if let target = inputTarget {
2190
+ result["pid"] = Int(target.pid)
2191
+ result["windowId"] = target.windowId
2192
+ result["pointerMode"] = "independent"
2193
+ result["delivery"] = "posted" // Posting does not prove the app acted; inspect its result.
2194
+ }
2195
+ return result
2196
+ }
2197
+ }
2198
+
2199
+ // MARK: - Unix Domain Socket Daemon Server
2200
+
2201
+ final class UnixSocketDaemon {
2202
+ private let socketPath: String
2203
+ private let idleTimeoutSec: Double
2204
+ private let engine = MacAutomationEngine()
2205
+ private let rpcQueue = DispatchQueue(label: "com.ufoo.mac.rpc")
2206
+ private var listenFD: Int32 = -1
2207
+ private var acceptSource: DispatchSourceRead?
2208
+ private var idleTimer: DispatchSourceTimer?
2209
+ private var sigIntSource: DispatchSourceSignal?
2210
+ private var sigTermSource: DispatchSourceSignal?
2211
+
2212
+ init(socketPath: String, idleMs: Int) {
2213
+ self.socketPath = socketPath
2214
+ self.idleTimeoutSec = Double(max(1_000, idleMs)) / 1000.0
2215
+ }
2216
+
2217
+ func start() throws {
2218
+ let dir = (socketPath as NSString).deletingLastPathComponent
2219
+ try FileManager.default.createDirectory(
2220
+ atPath: dir,
2221
+ withIntermediateDirectories: true,
2222
+ attributes: [.posixPermissions: 0o700]
2223
+ )
2224
+ unlink(socketPath)
2225
+
2226
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
2227
+ guard fd >= 0 else {
2228
+ throw NSError(domain: "ufoo.mac.socket", code: Int(errno), userInfo: [NSLocalizedDescriptionKey: "socket() failed"])
2229
+ }
2230
+ listenFD = fd
2231
+
2232
+ var addr = sockaddr_un()
2233
+ addr.sun_family = sa_family_t(AF_UNIX)
2234
+ let pathBytes = Array(socketPath.utf8CString)
2235
+ let maxLen = MemoryLayout.size(ofValue: addr.sun_path)
2236
+ guard pathBytes.count <= maxLen else {
2237
+ close(fd)
2238
+ throw NSError(domain: "ufoo.mac.socket", code: 63, userInfo: [NSLocalizedDescriptionKey: "Socket path exceeds sun_path limit"])
2239
+ }
2240
+ withUnsafeMutablePointer(to: &addr.sun_path) { ptr in
2241
+ ptr.withMemoryRebound(to: CChar.self, capacity: maxLen) { dst in
2242
+ dst.initialize(repeating: 0, count: maxLen)
2243
+ for (i, ch) in pathBytes.enumerated() {
2244
+ dst[i] = ch
2245
+ }
2246
+ }
2247
+ }
2248
+
2249
+ let bindRes = withUnsafePointer(to: &addr) { ptr -> Int32 in
2250
+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
2251
+ Darwin.bind(fd, sa, socklen_t(MemoryLayout<sockaddr_un>.size))
2252
+ }
2253
+ }
2254
+ guard bindRes == 0 else {
2255
+ let code = errno
2256
+ close(fd)
2257
+ throw NSError(domain: "ufoo.mac.socket", code: Int(code), userInfo: [NSLocalizedDescriptionKey: "bind() failed (\(code))"])
2258
+ }
2259
+ chmod(socketPath, 0o600)
2260
+ guard Darwin.listen(fd, 16) == 0 else {
2261
+ let code = errno
2262
+ close(fd)
2263
+ unlink(socketPath)
2264
+ throw NSError(domain: "ufoo.mac.socket", code: Int(code), userInfo: [NSLocalizedDescriptionKey: "listen() failed (\(code))"])
2265
+ }
2266
+
2267
+ let flags = fcntl(fd, F_GETFL, 0)
2268
+ _ = fcntl(fd, F_SETFL, flags | O_NONBLOCK)
2269
+
2270
+ let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: DispatchQueue.global(qos: .userInitiated))
2271
+ source.setEventHandler { [weak self] in
2272
+ self?.acceptPendingClients()
2273
+ }
2274
+ source.resume()
2275
+ acceptSource = source
2276
+
2277
+ engine.takeover.startMonitorsOnMain()
2278
+ installSignalHandlers()
2279
+ touchIdleTimer()
2280
+ }
2281
+
2282
+ private func installSignalHandlers() {
2283
+ signal(SIGPIPE, SIG_IGN)
2284
+ signal(SIGINT, SIG_IGN)
2285
+ signal(SIGTERM, SIG_IGN)
2286
+ let sInt = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
2287
+ sInt.setEventHandler { [weak self] in self?.shutdownAndExit() }
2288
+ sInt.resume()
2289
+ sigIntSource = sInt
2290
+
2291
+ let sTerm = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)
2292
+ sTerm.setEventHandler { [weak self] in self?.shutdownAndExit() }
2293
+ sTerm.resume()
2294
+ sigTermSource = sTerm
2295
+ }
2296
+
2297
+ private func touchIdleTimer() {
2298
+ idleTimer?.cancel()
2299
+ let t = DispatchSource.makeTimerSource(queue: .main)
2300
+ t.schedule(deadline: .now() + idleTimeoutSec)
2301
+ t.setEventHandler { [weak self] in
2302
+ self?.shutdownAndExit()
2303
+ }
2304
+ t.resume()
2305
+ idleTimer = t
2306
+ }
2307
+
2308
+ private func acceptPendingClients() {
2309
+ while true {
2310
+ var clientAddr = sockaddr_un()
2311
+ var len = socklen_t(MemoryLayout<sockaddr_un>.size)
2312
+ let clientFD = withUnsafeMutablePointer(to: &clientAddr) { ptr -> Int32 in
2313
+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
2314
+ Darwin.accept(listenFD, sa, &len)
2315
+ }
2316
+ }
2317
+ if clientFD < 0 { break }
2318
+ // On Darwin/BSD, accepted sockets inherit O_NONBLOCK from listenFD; restore blocking mode for worker thread reads.
2319
+ let cFlags = fcntl(clientFD, F_GETFL, 0)
2320
+ if cFlags >= 0 {
2321
+ _ = fcntl(clientFD, F_SETFL, cFlags & ~O_NONBLOCK)
2322
+ }
2323
+ var noSigPipe: Int32 = 1
2324
+ setsockopt(clientFD, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout<Int32>.size))
2325
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
2326
+ self?.handleClientConnection(clientFD)
2327
+ }
2328
+ }
2329
+ }
2330
+
2331
+ private func handleClientConnection(_ fd: Int32) {
2332
+ defer { close(fd) }
2333
+ var buffer = Data()
2334
+ var chunk = [UInt8](repeating: 0, count: 8192)
2335
+ while true {
2336
+ let n = Darwin.read(fd, &chunk, chunk.count)
2337
+ if n < 0 && errno == EINTR { continue }
2338
+ if n <= 0 { break }
2339
+ buffer.append(contentsOf: chunk[0..<n])
2340
+ while let nlIndex = buffer.firstIndex(of: 0x0A) {
2341
+ let lineData = buffer.subdata(in: 0..<nlIndex)
2342
+ buffer.removeSubrange(0...nlIndex)
2343
+ if lineData.isEmpty { continue }
2344
+ let shouldShutdown = processLine(lineData, clientFD: fd)
2345
+ if shouldShutdown {
2346
+ DispatchQueue.main.async { [weak self] in
2347
+ self?.shutdownAndExit()
2348
+ }
2349
+ return
2350
+ }
2351
+ }
2352
+ }
2353
+ }
2354
+
2355
+ private func processLine(_ lineData: Data, clientFD: Int32) -> Bool {
2356
+ DispatchQueue.main.async { [weak self] in
2357
+ self?.touchIdleTimer()
2358
+ }
2359
+ guard
2360
+ let obj = (try? JSONSerialization.jsonObject(with: lineData)) as? [String: Any]
2361
+ else {
2362
+ writeJSON(["id": "", "ok": false, "code": "invalid_json", "error": "Malformed JSON request"], to: clientFD)
2363
+ return false
2364
+ }
2365
+ let id = (obj["id"] as? String) ?? ""
2366
+ let method = (obj["method"] as? String) ?? ""
2367
+ let params = (obj["params"] as? [String: Any]) ?? [:]
2368
+
2369
+ if method == "shutdown" {
2370
+ engine.hud.hideImmediatelySync()
2371
+ writeJSON(["id": id, "ok": true, "result": ["stopped": true]], to: clientFD)
2372
+ return true
2373
+ }
2374
+
2375
+ var response: [String: Any] = ["id": id]
2376
+ rpcQueue.sync {
2377
+ do {
2378
+ let res = try engine.dispatch(method: method, params: params)
2379
+ response["ok"] = true
2380
+ response["result"] = res
2381
+ } catch let err as NSError {
2382
+ response["ok"] = false
2383
+ response["error"] = err.localizedDescription
2384
+ if err.domain == "ufoo.mac.permission" {
2385
+ response["code"] = "permission_denied"
2386
+ if let perm = err.userInfo["permission"] as? String {
2387
+ response["permission"] = perm
2388
+ }
2389
+ } else if err.domain == "ufoo.mac.takeover" {
2390
+ response["code"] = "user_takeover"
2391
+ response["reason"] = err.userInfo["reason"] as? String ?? "user_takeover"
2392
+ } else if err.domain == "ufoo.mac.stale" {
2393
+ response["code"] = "stale_element_ref"
2394
+ } else if err.domain == "ufoo.mac.independent" {
2395
+ response["code"] = "independent_input_unavailable"
2396
+ } else {
2397
+ response["code"] = "mac_action_failed"
2398
+ }
2399
+ }
2400
+ }
2401
+ writeJSON(response, to: clientFD)
2402
+ return false
2403
+ }
2404
+
2405
+ private func writeJSON(_ dict: [String: Any], to fd: Int32) {
2406
+ guard var data = try? JSONSerialization.data(withJSONObject: dict) else { return }
2407
+ data.append(0x0A)
2408
+ data.withUnsafeBytes { rawBuf in
2409
+ guard let base = rawBuf.baseAddress else { return }
2410
+ var sent = 0
2411
+ while sent < rawBuf.count {
2412
+ let written = Darwin.write(fd, base.advanced(by: sent), rawBuf.count - sent)
2413
+ if written <= 0 { break }
2414
+ sent += written
2415
+ }
2416
+ }
2417
+ }
2418
+
2419
+ func shutdownAndExit() {
2420
+ engine.hud.hideImmediatelySync()
2421
+ acceptSource?.cancel()
2422
+ if listenFD >= 0 {
2423
+ close(listenFD)
2424
+ listenFD = -1
2425
+ }
2426
+ unlink(socketPath)
2427
+ exit(0)
2428
+ }
2429
+ }
2430
+
2431
+ // MARK: - CLI Entrypoint
2432
+
2433
+ @main
2434
+ struct UfooMacHelperMain {
2435
+ static func main() {
2436
+ let args = Array(CommandLine.arguments.dropFirst())
2437
+ let subcmd = args.first ?? "check"
2438
+
2439
+ if subcmd == "check" {
2440
+ let prompt = args.contains("--prompt")
2441
+ let openSettings = args.contains("--open-settings")
2442
+ let engine = MacAutomationEngine()
2443
+ let payload: [String: Any] = [
2444
+ "ok": true,
2445
+ "status": engine.statusPayload(prompt: prompt, openSettings: openSettings),
2446
+ ]
2447
+ if let data = try? JSONSerialization.data(withJSONObject: payload),
2448
+ let str = String(data: data, encoding: .utf8)
2449
+ {
2450
+ print(str)
2451
+ }
2452
+ return
2453
+ }
2454
+
2455
+ if subcmd == "daemon" {
2456
+ var sockPath = ""
2457
+ var idleMs = 600_000
2458
+ var i = 1
2459
+ while i < args.count {
2460
+ if args[i] == "--socket", i + 1 < args.count {
2461
+ sockPath = args[i + 1]
2462
+ i += 2
2463
+ } else if args[i] == "--idle-ms", i + 1 < args.count {
2464
+ idleMs = Int(args[i + 1]) ?? 600_000
2465
+ i += 2
2466
+ } else {
2467
+ i += 1
2468
+ }
2469
+ }
2470
+ guard !sockPath.isEmpty else {
2471
+ fputs("Missing --socket <path>\n", stderr)
2472
+ exit(2)
2473
+ }
2474
+
2475
+ let app = NSApplication.shared
2476
+ app.setActivationPolicy(.accessory)
2477
+ let daemon = UnixSocketDaemon(socketPath: sockPath, idleMs: idleMs)
2478
+ do {
2479
+ try daemon.start()
2480
+ } catch {
2481
+ fputs("Failed to start ufoo-mac-helper daemon: \(error.localizedDescription)\n", stderr)
2482
+ exit(1)
2483
+ }
2484
+ withExtendedLifetime(daemon) {
2485
+ app.run()
2486
+ }
2487
+ return
2488
+ }
2489
+
2490
+ fputs("Usage: ufoo-mac-helper [check [--prompt] [--open-settings] | daemon --socket <path> [--idle-ms <ms>]]\n", stderr)
2491
+ exit(2)
2492
+ }
2493
+ }