nini-computer-use 0.4.4__py3-none-any.whl
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.
- nini_computer_use/__init__.py +21 -0
- nini_computer_use/__main__.py +131 -0
- nini_computer_use/audit.py +131 -0
- nini_computer_use/errors.py +92 -0
- nini_computer_use/helper.py +271 -0
- nini_computer_use/native/main.swift +618 -0
- nini_computer_use/paths.py +112 -0
- nini_computer_use/permissions.py +225 -0
- nini_computer_use/safety.py +157 -0
- nini_computer_use/server.py +213 -0
- nini_computer_use/tools.py +542 -0
- nini_computer_use/validate.py +306 -0
- nini_computer_use-0.4.4.dist-info/METADATA +38 -0
- nini_computer_use-0.4.4.dist-info/RECORD +17 -0
- nini_computer_use-0.4.4.dist-info/WHEEL +4 -0
- nini_computer_use-0.4.4.dist-info/entry_points.txt +2 -0
- nini_computer_use-0.4.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
// nini-cu — privileged native helper for the Nini computer-use MCP server.
|
|
2
|
+
//
|
|
3
|
+
// One process, one subcommand, one JSON object on stdout. The Python side owns
|
|
4
|
+
// the MCP protocol, argument validation, audit logging and policy; this helper
|
|
5
|
+
// owns only what needs a real macOS process: CGEvent input injection,
|
|
6
|
+
// CGWindowList enumeration, permission probes and `screencapture`.
|
|
7
|
+
//
|
|
8
|
+
// Every successful call prints ``{"ok": true, ...}`` and exits 0. Failures
|
|
9
|
+
// print ``{"ok": false, "error": {"code": "...", "message": "..."}}`` and exit
|
|
10
|
+
// 3 (permission), 4 (bad input) or 5 (runtime failure) so callers can branch on
|
|
11
|
+
// the exit code without parsing prose.
|
|
12
|
+
//
|
|
13
|
+
// Build: `swiftc -O native/main.swift -o nini-cu` (the Python side does this
|
|
14
|
+
// once, into ~/.nini/computer-use/bin/nini-cu).
|
|
15
|
+
|
|
16
|
+
import AppKit
|
|
17
|
+
import ApplicationServices
|
|
18
|
+
import CoreGraphics
|
|
19
|
+
import Darwin
|
|
20
|
+
import Foundation
|
|
21
|
+
import ImageIO
|
|
22
|
+
|
|
23
|
+
// MARK: - output
|
|
24
|
+
|
|
25
|
+
func emit(_ payload: [String: Any]) {
|
|
26
|
+
guard
|
|
27
|
+
let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys])
|
|
28
|
+
else {
|
|
29
|
+
FileHandle.standardOutput.write(#"{"ok":false,"error":{"code":"encode_failed"}}"#
|
|
30
|
+
.data(using: .utf8)!)
|
|
31
|
+
FileHandle.standardOutput.write("\n".data(using: .utf8)!)
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
FileHandle.standardOutput.write(data)
|
|
35
|
+
FileHandle.standardOutput.write("\n".data(using: .utf8)!)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
func die(_ code: String, _ message: String, exit status: Int32) -> Never {
|
|
39
|
+
emit(["ok": false, "error": ["code": code, "message": message]])
|
|
40
|
+
FileHandle.standardError.write("nini-cu: \(code): \(message)\n".data(using: .utf8)!)
|
|
41
|
+
exit(status)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// MARK: - arguments
|
|
45
|
+
|
|
46
|
+
struct Options {
|
|
47
|
+
var values: [String: String] = [:]
|
|
48
|
+
var flags: Set<String> = []
|
|
49
|
+
|
|
50
|
+
init(_ args: [String]) {
|
|
51
|
+
var index = 0
|
|
52
|
+
while index < args.count {
|
|
53
|
+
let arg = args[index]
|
|
54
|
+
if arg.hasPrefix("--") {
|
|
55
|
+
let name = String(arg.dropFirst(2))
|
|
56
|
+
// A negative number (`-100`) is a value, not a flag: only `--`
|
|
57
|
+
// introduces a new option.
|
|
58
|
+
if index + 1 < args.count, !args[index + 1].hasPrefix("--") {
|
|
59
|
+
values[name] = args[index + 1]
|
|
60
|
+
index += 2
|
|
61
|
+
} else {
|
|
62
|
+
flags.insert(name)
|
|
63
|
+
index += 1
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
index += 1
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
func string(_ key: String) -> String? { values[key] }
|
|
72
|
+
|
|
73
|
+
func required(_ key: String) -> String {
|
|
74
|
+
guard let value = values[key], !value.isEmpty else {
|
|
75
|
+
die("bad_arguments", "missing --\(key)", exit: 4)
|
|
76
|
+
}
|
|
77
|
+
return value
|
|
78
|
+
}
|
|
79
|
+
func has(_ key: String) -> Bool { flags.contains(key) || values[key] != nil }
|
|
80
|
+
|
|
81
|
+
func int(_ key: String, _ fallback: Int? = nil) -> Int {
|
|
82
|
+
guard let raw = values[key] else {
|
|
83
|
+
if let fallback { return fallback }
|
|
84
|
+
die("bad_arguments", "missing --\(key)", exit: 4)
|
|
85
|
+
}
|
|
86
|
+
guard let value = Int(raw) else {
|
|
87
|
+
die("bad_arguments", "--\(key) must be an integer, got \(raw)", exit: 4)
|
|
88
|
+
}
|
|
89
|
+
return value
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
func double(_ key: String, _ fallback: Double? = nil) -> Double {
|
|
93
|
+
guard let raw = values[key] else {
|
|
94
|
+
if let fallback { return fallback }
|
|
95
|
+
die("bad_arguments", "missing --\(key)", exit: 4)
|
|
96
|
+
}
|
|
97
|
+
guard let value = Double(raw) else {
|
|
98
|
+
die("bad_arguments", "--\(key) must be a number, got \(raw)", exit: 4)
|
|
99
|
+
}
|
|
100
|
+
return value
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// MARK: - permissions
|
|
105
|
+
|
|
106
|
+
/// Return the parent pid of ``pid`` (0 when unknown, e.g. launchd's parent).
|
|
107
|
+
func parentPid(of pid: Int32) -> Int32 {
|
|
108
|
+
var info = proc_bsdinfo()
|
|
109
|
+
let size = proc_pidinfo(
|
|
110
|
+
pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout<proc_bsdinfo>.size)
|
|
111
|
+
)
|
|
112
|
+
guard size > 0 else { return 0 }
|
|
113
|
+
return Int32(info.pbi_ppid)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// Executable name (``python``, ``Terminal``, …) even for CLI processes that
|
|
117
|
+
/// ``NSRunningApplication`` does not register as apps.
|
|
118
|
+
func processName(of pid: Int32) -> String {
|
|
119
|
+
var buffer = [CChar](repeating: 0, count: 64)
|
|
120
|
+
guard proc_name(pid, &buffer, UInt32(buffer.count)) > 0 else { return "" }
|
|
121
|
+
return String(cString: buffer)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// Walk from this helper's parent towards launchd.
|
|
125
|
+
///
|
|
126
|
+
/// macOS attributes TCC to the *responsible* process, which in practice is the
|
|
127
|
+
/// first ancestor with a real app identity (Terminal, iTerm2, Nini desktop…),
|
|
128
|
+
/// not this bare ``nini-cu`` executable. The walk reports that process plus the
|
|
129
|
+
/// full chain so ``--doctor`` can tell a human *who* to enable in System
|
|
130
|
+
/// Settings instead of leaving them guessing.
|
|
131
|
+
func hostProcessChain() -> (host: [String: Any], chain: [[String: Any]]) {
|
|
132
|
+
var chain: [[String: Any]] = []
|
|
133
|
+
var host: [String: Any] = [:]
|
|
134
|
+
var pid = getppid()
|
|
135
|
+
var seen = Set<Int32>()
|
|
136
|
+
var depth = 0
|
|
137
|
+
|
|
138
|
+
while pid > 1 && !seen.contains(pid) && depth < 16 {
|
|
139
|
+
seen.insert(pid)
|
|
140
|
+
depth += 1
|
|
141
|
+
|
|
142
|
+
let app = NSRunningApplication(processIdentifier: pid)
|
|
143
|
+
let appName = app?.localizedName ?? ""
|
|
144
|
+
let name = !appName.isEmpty ? appName : processName(of: pid)
|
|
145
|
+
let bundle = app?.bundleIdentifier ?? ""
|
|
146
|
+
var entry: [String: Any] = ["pid": Int(pid)]
|
|
147
|
+
if !name.isEmpty { entry["name"] = name }
|
|
148
|
+
if !bundle.isEmpty { entry["bundle_id"] = bundle }
|
|
149
|
+
chain.append(entry)
|
|
150
|
+
|
|
151
|
+
if host.isEmpty && !bundle.isEmpty {
|
|
152
|
+
host = entry
|
|
153
|
+
}
|
|
154
|
+
pid = parentPid(of: pid)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if host.isEmpty {
|
|
158
|
+
host = chain.last ?? [:]
|
|
159
|
+
}
|
|
160
|
+
return (host, chain)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
func permissionsSnapshot() -> [String: Any] {
|
|
164
|
+
let accessibility = AXIsProcessTrusted()
|
|
165
|
+
let screenRecording = CGPreflightScreenCaptureAccess()
|
|
166
|
+
let (host, chain) = hostProcessChain()
|
|
167
|
+
return [
|
|
168
|
+
"ok": true,
|
|
169
|
+
"accessibility": accessibility,
|
|
170
|
+
"screen_recording": screenRecording,
|
|
171
|
+
"bundle_id": Bundle.main.bundleIdentifier ?? "",
|
|
172
|
+
"pid": Int(ProcessInfo.processInfo.processIdentifier),
|
|
173
|
+
"host": host,
|
|
174
|
+
"chain": chain,
|
|
175
|
+
]
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/// Preflight is *advisory* by default but gating: macOS attributes TCC to the
|
|
179
|
+
/// responsible parent process (the terminal or the MCP host), so a probe from
|
|
180
|
+
/// this child can read `false` while input still works. Setting
|
|
181
|
+
/// `NINI_CU_SKIP_PERMISSION_PRECHECK=1` turns the probes into hints and lets the
|
|
182
|
+
/// OS decide (it drops unpermitted events silently).
|
|
183
|
+
func preflightBypassed() -> Bool {
|
|
184
|
+
let raw = ProcessInfo.processInfo.environment["NINI_CU_SKIP_PERMISSION_PRECHECK"] ?? ""
|
|
185
|
+
return ["1", "true", "yes", "on"].contains(raw.lowercased())
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
func requireAccessibility() {
|
|
189
|
+
if preflightBypassed() { return }
|
|
190
|
+
if !AXIsProcessTrusted() {
|
|
191
|
+
die(
|
|
192
|
+
"permission_denied",
|
|
193
|
+
"Accessibility permission is required for input injection",
|
|
194
|
+
exit: 3
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
func requireScreenRecording() {
|
|
200
|
+
if preflightBypassed() { return }
|
|
201
|
+
if !CGPreflightScreenCaptureAccess() {
|
|
202
|
+
die(
|
|
203
|
+
"permission_denied",
|
|
204
|
+
"Screen Recording permission is required for screenshots and window titles",
|
|
205
|
+
exit: 3
|
|
206
|
+
)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// MARK: - windows
|
|
211
|
+
|
|
212
|
+
func windowList() -> [[String: Any]] {
|
|
213
|
+
let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
|
|
214
|
+
guard
|
|
215
|
+
let raw = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]]
|
|
216
|
+
else { return [] }
|
|
217
|
+
var out: [[String: Any]] = []
|
|
218
|
+
for item in raw {
|
|
219
|
+
let layer = (item[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
|
|
220
|
+
guard layer == 0 else { continue }
|
|
221
|
+
let boundsDict = item[kCGWindowBounds as String] as? [String: Any] ?? [:]
|
|
222
|
+
let x = (boundsDict["X"] as? NSNumber)?.doubleValue ?? 0
|
|
223
|
+
let y = (boundsDict["Y"] as? NSNumber)?.doubleValue ?? 0
|
|
224
|
+
let width = (boundsDict["Width"] as? NSNumber)?.doubleValue ?? 0
|
|
225
|
+
let height = (boundsDict["Height"] as? NSNumber)?.doubleValue ?? 0
|
|
226
|
+
guard width >= 1, height >= 1 else { continue }
|
|
227
|
+
let alpha = (item[kCGWindowAlpha as String] as? NSNumber)?.doubleValue ?? 1
|
|
228
|
+
guard alpha > 0 else { continue }
|
|
229
|
+
out.append([
|
|
230
|
+
"app": (item[kCGWindowOwnerName as String] as? String) ?? "",
|
|
231
|
+
"title": (item[kCGWindowName as String] as? String) ?? "",
|
|
232
|
+
"pid": (item[kCGWindowOwnerPID as String] as? NSNumber)?.intValue ?? 0,
|
|
233
|
+
"layer": layer,
|
|
234
|
+
"alpha": alpha,
|
|
235
|
+
"bounds": [
|
|
236
|
+
"x": Int(x.rounded()),
|
|
237
|
+
"y": Int(y.rounded()),
|
|
238
|
+
"w": Int(width.rounded()),
|
|
239
|
+
"h": Int(height.rounded()),
|
|
240
|
+
],
|
|
241
|
+
])
|
|
242
|
+
}
|
|
243
|
+
// Frontmost app first — that is what an agent usually cares about.
|
|
244
|
+
let front = frontmostAppName()
|
|
245
|
+
out.sort { lhs, rhs in
|
|
246
|
+
let lhsFront = (lhs["app"] as? String) == front
|
|
247
|
+
let rhsFront = (rhs["app"] as? String) == front
|
|
248
|
+
if lhsFront != rhsFront { return lhsFront }
|
|
249
|
+
return ((lhs["bounds"] as? [String: Int])?["w"] ?? 0) > ((rhs["bounds"] as? [String: Int])?["w"] ?? 0)
|
|
250
|
+
}
|
|
251
|
+
return out
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
func frontmostAppName() -> String {
|
|
255
|
+
NSWorkspace.shared.frontmostApplication?.localizedName ?? ""
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// MARK: - mouse
|
|
259
|
+
|
|
260
|
+
func currentPosition() -> CGPoint {
|
|
261
|
+
CGEvent(source: nil)?.location ?? .zero
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
func postMouse(_ type: CGEventType, _ point: CGPoint, _ button: CGMouseButton, click: Int64 = 1) {
|
|
265
|
+
guard
|
|
266
|
+
let event = CGEvent(
|
|
267
|
+
mouseEventSource: nil,
|
|
268
|
+
mouseType: type,
|
|
269
|
+
mouseCursorPosition: point,
|
|
270
|
+
mouseButton: button
|
|
271
|
+
)
|
|
272
|
+
else {
|
|
273
|
+
die("event_failed", "could not create a mouse event", exit: 5)
|
|
274
|
+
}
|
|
275
|
+
if click > 1 { event.setIntegerValueField(.mouseEventClickState, value: click) }
|
|
276
|
+
event.post(tap: .cghidEventTap)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
func moveMouse(x: Double, y: Double) {
|
|
280
|
+
let point = CGPoint(x: x, y: y)
|
|
281
|
+
postMouse(.mouseMoved, point, .left)
|
|
282
|
+
usleep(20_000)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
func clickMouse(x: Double, y: Double, button: String, count: Int) {
|
|
286
|
+
let point = CGPoint(x: x, y: y)
|
|
287
|
+
let (down, up, cgButton): (CGEventType, CGEventType, CGMouseButton)
|
|
288
|
+
switch button {
|
|
289
|
+
case "left":
|
|
290
|
+
(down, up, cgButton) = (.leftMouseDown, .leftMouseUp, .left)
|
|
291
|
+
case "right":
|
|
292
|
+
(down, up, cgButton) = (.rightMouseDown, .rightMouseUp, .right)
|
|
293
|
+
default:
|
|
294
|
+
die("bad_arguments", "--button must be left or right, got \(button)", exit: 4)
|
|
295
|
+
}
|
|
296
|
+
// Park the cursor first: a click is delivered at the event location on
|
|
297
|
+
// some apps' hit-testing paths, so the down event must carry the target.
|
|
298
|
+
moveMouse(x: x, y: y)
|
|
299
|
+
for step in 1...max(1, count) {
|
|
300
|
+
postMouse(down, point, cgButton, click: Int64(step))
|
|
301
|
+
usleep(30_000)
|
|
302
|
+
postMouse(up, point, cgButton, click: Int64(step))
|
|
303
|
+
if step < count { usleep(60_000) }
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
func dragMouse(fromX: Double, fromY: Double, toX: Double, toY: Double, button: String, durationMs: Int) {
|
|
308
|
+
let start = CGPoint(x: fromX, y: fromY)
|
|
309
|
+
let end = CGPoint(x: toX, y: toY)
|
|
310
|
+
let cgButton: CGMouseButton = button == "right" ? .right : .left
|
|
311
|
+
let downType: CGEventType = button == "right" ? .rightMouseDown : .leftMouseDown
|
|
312
|
+
let dragType: CGEventType = button == "right" ? .rightMouseDragged : .leftMouseDragged
|
|
313
|
+
let upType: CGEventType = button == "right" ? .rightMouseUp : .leftMouseUp
|
|
314
|
+
if button != "left" && button != "right" {
|
|
315
|
+
die("bad_arguments", "--button must be left or right, got \(button)", exit: 4)
|
|
316
|
+
}
|
|
317
|
+
moveMouse(x: fromX, y: fromY)
|
|
318
|
+
postMouse(downType, start, cgButton)
|
|
319
|
+
let steps = max(2, min(60, durationMs / 10))
|
|
320
|
+
for step in 1...steps {
|
|
321
|
+
let t = Double(step) / Double(steps)
|
|
322
|
+
let point = CGPoint(x: fromX + (toX - fromX) * t, y: fromY + (toY - fromY) * t)
|
|
323
|
+
postMouse(dragType, point, cgButton)
|
|
324
|
+
usleep(10_000)
|
|
325
|
+
}
|
|
326
|
+
postMouse(upType, end, cgButton)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// MARK: - keyboard
|
|
330
|
+
|
|
331
|
+
let modifierMasks: [String: CGEventFlags] = [
|
|
332
|
+
"cmd": .maskCommand,
|
|
333
|
+
"command": .maskCommand,
|
|
334
|
+
"ctrl": .maskControl,
|
|
335
|
+
"control": .maskControl,
|
|
336
|
+
"alt": .maskAlternate,
|
|
337
|
+
"option": .maskAlternate,
|
|
338
|
+
"opt": .maskAlternate,
|
|
339
|
+
"shift": .maskShift,
|
|
340
|
+
"fn": .maskSecondaryFn,
|
|
341
|
+
]
|
|
342
|
+
|
|
343
|
+
let keyCodes: [String: CGKeyCode] = [
|
|
344
|
+
"a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9,
|
|
345
|
+
"b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, "1": 18, "2": 19,
|
|
346
|
+
"3": 20, "4": 21, "6": 22, "5": 23, "equal": 24, "=": 24, "9": 25, "7": 26,
|
|
347
|
+
"minus": 27, "-": 27, "8": 28, "0": 29, "rightbracket": 30, "]": 30, "o": 31,
|
|
348
|
+
"u": 32, "leftbracket": 33, "[": 33, "i": 34, "p": 35, "return": 36, "enter": 36,
|
|
349
|
+
"l": 37, "j": 38, "quote": 39, "'": 39, "k": 40, "semicolon": 41, ";": 41,
|
|
350
|
+
"backslash": 42, "\\": 42, "comma": 43, ",": 43, "slash": 44, "/": 44, "n": 45,
|
|
351
|
+
"m": 46, "period": 47, ".": 47, "tab": 48, "space": 49, "grave": 50, "`": 50,
|
|
352
|
+
"backspace": 51, "delete": 51, "esc": 53, "escape": 53,
|
|
353
|
+
"f1": 122, "f2": 120, "f3": 99, "f4": 118, "f5": 96, "f6": 97, "f7": 98,
|
|
354
|
+
"f8": 100, "f9": 101, "f10": 109, "f11": 103, "f12": 111, "f13": 105,
|
|
355
|
+
"f14": 107, "f15": 113, "f16": 106, "f17": 64, "f18": 79, "f19": 80, "f20": 90,
|
|
356
|
+
"left": 123, "right": 124, "down": 125, "up": 126,
|
|
357
|
+
"home": 115, "end": 119, "pageup": 116, "pagedown": 121,
|
|
358
|
+
"forwarddelete": 117, "help": 114,
|
|
359
|
+
]
|
|
360
|
+
|
|
361
|
+
struct KeyStroke {
|
|
362
|
+
var key: String
|
|
363
|
+
var flags: CGEventFlags
|
|
364
|
+
var code: CGKeyCode
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
func parseCombo(_ combo: String) -> KeyStroke {
|
|
368
|
+
let parts = combo.lowercased().split(separator: "+").map { String($0).trimmingCharacters(in: .whitespaces) }
|
|
369
|
+
guard let last = parts.last, !last.isEmpty else {
|
|
370
|
+
die("bad_arguments", "empty key combo", exit: 4)
|
|
371
|
+
}
|
|
372
|
+
var flags: CGEventFlags = []
|
|
373
|
+
for token in parts.dropLast() {
|
|
374
|
+
guard let mask = modifierMasks[token] else {
|
|
375
|
+
die("bad_arguments", "unknown modifier '\(token)' in '\(combo)'", exit: 4)
|
|
376
|
+
}
|
|
377
|
+
flags.insert(mask)
|
|
378
|
+
}
|
|
379
|
+
let keyName = last
|
|
380
|
+
guard let code = keyCodes[keyName] else {
|
|
381
|
+
die("bad_arguments", "unknown key '\(keyName)' in '\(combo)'", exit: 4)
|
|
382
|
+
}
|
|
383
|
+
return KeyStroke(key: keyName, flags: flags, code: code)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
func press(_ stroke: KeyStroke) {
|
|
387
|
+
guard
|
|
388
|
+
let down = CGEvent(keyboardEventSource: nil, virtualKey: stroke.code, keyDown: true),
|
|
389
|
+
let up = CGEvent(keyboardEventSource: nil, virtualKey: stroke.code, keyDown: false)
|
|
390
|
+
else {
|
|
391
|
+
die("event_failed", "could not create a keyboard event", exit: 5)
|
|
392
|
+
}
|
|
393
|
+
down.flags = stroke.flags
|
|
394
|
+
up.flags = stroke.flags
|
|
395
|
+
down.post(tap: .cghidEventTap)
|
|
396
|
+
usleep(15_000)
|
|
397
|
+
up.post(tap: .cghidEventTap)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
func typeUnicode(_ text: String) {
|
|
401
|
+
let units = Array(text.utf16)
|
|
402
|
+
var index = 0
|
|
403
|
+
while index < units.count {
|
|
404
|
+
let end = min(index + 16, units.count)
|
|
405
|
+
let chunk = Array(units[index..<end])
|
|
406
|
+
guard
|
|
407
|
+
let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
|
|
408
|
+
let up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
|
|
409
|
+
else {
|
|
410
|
+
die("event_failed", "could not create a keyboard event", exit: 5)
|
|
411
|
+
}
|
|
412
|
+
chunk.withUnsafeBufferPointer { buffer in
|
|
413
|
+
down.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: buffer.baseAddress)
|
|
414
|
+
up.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: buffer.baseAddress)
|
|
415
|
+
}
|
|
416
|
+
down.post(tap: .cghidEventTap)
|
|
417
|
+
up.post(tap: .cghidEventTap)
|
|
418
|
+
index = end
|
|
419
|
+
usleep(6_000)
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
func pasteText(_ text: String) {
|
|
424
|
+
let pasteboard = NSPasteboard.general
|
|
425
|
+
let saved = pasteboard.string(forType: .string)
|
|
426
|
+
pasteboard.clearContents()
|
|
427
|
+
pasteboard.setString(text, forType: .string)
|
|
428
|
+
usleep(40_000)
|
|
429
|
+
press(parseCombo("cmd+v"))
|
|
430
|
+
usleep(180_000)
|
|
431
|
+
// Restore what was there before: typing must not destroy the user's
|
|
432
|
+
// clipboard. An image clipboard cannot be restored (Pasteboard exposes it
|
|
433
|
+
// as data we did not snapshot); documented in docs/COMPUTER_USE.md.
|
|
434
|
+
pasteboard.clearContents()
|
|
435
|
+
if let saved { pasteboard.setString(saved, forType: .string) }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// MARK: - screenshot
|
|
439
|
+
|
|
440
|
+
func pngSize(_ path: String) -> (Int, Int)? {
|
|
441
|
+
guard
|
|
442
|
+
let source = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil),
|
|
443
|
+
let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
|
|
444
|
+
else { return nil }
|
|
445
|
+
let width = (props[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue ?? 0
|
|
446
|
+
let height = (props[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue ?? 0
|
|
447
|
+
if width > 0 && height > 0 { return (width, height) }
|
|
448
|
+
return nil
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
func captureScreenshot(out: String, display: Int, region: [Int]?) {
|
|
452
|
+
requireScreenRecording()
|
|
453
|
+
var args = ["-x", "-o", "-t", "png"]
|
|
454
|
+
if display > 0 { args += ["-D", String(display + 1)] } // screencapture is 1-based
|
|
455
|
+
if let region, region.count == 4 {
|
|
456
|
+
args += ["-R", "\(region[0]),\(region[1]),\(region[2]),\(region[3])"]
|
|
457
|
+
}
|
|
458
|
+
args.append(out)
|
|
459
|
+
let process = Process()
|
|
460
|
+
process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
|
|
461
|
+
process.arguments = args
|
|
462
|
+
let pipe = Pipe()
|
|
463
|
+
process.standardError = pipe
|
|
464
|
+
do {
|
|
465
|
+
try process.run()
|
|
466
|
+
} catch {
|
|
467
|
+
die("capture_failed", "could not launch screencapture: \(error)", exit: 5)
|
|
468
|
+
}
|
|
469
|
+
process.waitUntilExit()
|
|
470
|
+
if process.terminationStatus != 0 {
|
|
471
|
+
let stderr = String(
|
|
472
|
+
data: pipe.fileHandleForReading.readDataToEndOfFile(),
|
|
473
|
+
encoding: .utf8
|
|
474
|
+
) ?? ""
|
|
475
|
+
die(
|
|
476
|
+
"capture_failed",
|
|
477
|
+
"screencapture exited \(process.terminationStatus): \(stderr.trimmingCharacters(in: .whitespacesAndNewlines))",
|
|
478
|
+
exit: 5
|
|
479
|
+
)
|
|
480
|
+
}
|
|
481
|
+
guard let (width, height) = pngSize(out) else {
|
|
482
|
+
die("capture_failed", "screencapture produced no readable PNG at \(out)", exit: 5)
|
|
483
|
+
}
|
|
484
|
+
let size = (try? FileManager.default.attributesOfItem(atPath: out)[.size] as? NSNumber)??.intValue ?? 0
|
|
485
|
+
let main = NSScreen.main
|
|
486
|
+
let pointWidth = main.map { Int($0.frame.width) } ?? 0
|
|
487
|
+
let scale = pointWidth > 0 ? Double(width) / Double(pointWidth) : 1
|
|
488
|
+
emit([
|
|
489
|
+
"ok": true,
|
|
490
|
+
"path": out,
|
|
491
|
+
"width": width,
|
|
492
|
+
"height": height,
|
|
493
|
+
"bytes": size,
|
|
494
|
+
"scale": scale,
|
|
495
|
+
"display": display,
|
|
496
|
+
"region": region ?? [],
|
|
497
|
+
])
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// MARK: - main
|
|
501
|
+
|
|
502
|
+
let rawArgs = Array(CommandLine.arguments.dropFirst())
|
|
503
|
+
guard let command = rawArgs.first else {
|
|
504
|
+
die("usage", "usage: nini-cu <permissions|frontmost|windows|position|screenshot|move|click|drag|type|key|scroll>", exit: 4)
|
|
505
|
+
}
|
|
506
|
+
let opts = Options(Array(rawArgs.dropFirst()))
|
|
507
|
+
|
|
508
|
+
switch command {
|
|
509
|
+
case "permissions":
|
|
510
|
+
emit(permissionsSnapshot())
|
|
511
|
+
|
|
512
|
+
case "frontmost":
|
|
513
|
+
let app = NSWorkspace.shared.frontmostApplication
|
|
514
|
+
emit([
|
|
515
|
+
"ok": true,
|
|
516
|
+
"app": app?.localizedName ?? "",
|
|
517
|
+
"bundle_id": app?.bundleIdentifier ?? "",
|
|
518
|
+
"pid": app.map { Int($0.processIdentifier) } ?? 0,
|
|
519
|
+
])
|
|
520
|
+
|
|
521
|
+
case "windows":
|
|
522
|
+
requireScreenRecording()
|
|
523
|
+
emit(["ok": true, "windows": windowList()])
|
|
524
|
+
|
|
525
|
+
case "position":
|
|
526
|
+
let point = currentPosition()
|
|
527
|
+
emit(["ok": true, "x": Int(point.x.rounded()), "y": Int(point.y.rounded())])
|
|
528
|
+
|
|
529
|
+
case "screenshot":
|
|
530
|
+
let out = opts.required("out")
|
|
531
|
+
let display = opts.int("display", 0)
|
|
532
|
+
var region: [Int]? = nil
|
|
533
|
+
if let raw = opts.string("region") {
|
|
534
|
+
let parts = raw.split(separator: ",").map { String($0) }
|
|
535
|
+
guard parts.count == 4 else {
|
|
536
|
+
die("bad_arguments", "--region must be x,y,w,h", exit: 4)
|
|
537
|
+
}
|
|
538
|
+
let numbers = parts.map { Int($0) ?? Int.min }
|
|
539
|
+
guard !numbers.contains(Int.min) else {
|
|
540
|
+
die("bad_arguments", "--region must be x,y,w,h in integers", exit: 4)
|
|
541
|
+
}
|
|
542
|
+
region = numbers
|
|
543
|
+
}
|
|
544
|
+
captureScreenshot(out: out, display: display, region: region)
|
|
545
|
+
|
|
546
|
+
case "move":
|
|
547
|
+
requireAccessibility()
|
|
548
|
+
let x = opts.double("x")
|
|
549
|
+
let y = opts.double("y")
|
|
550
|
+
moveMouse(x: x, y: y)
|
|
551
|
+
let actual = currentPosition()
|
|
552
|
+
emit(["ok": true, "x": Int(actual.x.rounded()), "y": Int(actual.y.rounded())])
|
|
553
|
+
|
|
554
|
+
case "click":
|
|
555
|
+
requireAccessibility()
|
|
556
|
+
let x = opts.double("x")
|
|
557
|
+
let y = opts.double("y")
|
|
558
|
+
let button = opts.string("button") ?? "left"
|
|
559
|
+
let count = opts.int("count", 1)
|
|
560
|
+
clickMouse(x: x, y: y, button: button, count: count)
|
|
561
|
+
emit(["ok": true, "x": Int(x.rounded()), "y": Int(y.rounded()), "button": button, "count": count])
|
|
562
|
+
|
|
563
|
+
case "drag":
|
|
564
|
+
requireAccessibility()
|
|
565
|
+
let fromX = opts.double("from-x")
|
|
566
|
+
let fromY = opts.double("from-y")
|
|
567
|
+
let toX = opts.double("to-x")
|
|
568
|
+
let toY = opts.double("to-y")
|
|
569
|
+
let button = opts.string("button") ?? "left"
|
|
570
|
+
let duration = opts.int("duration-ms", 250)
|
|
571
|
+
dragMouse(
|
|
572
|
+
fromX: fromX, fromY: fromY, toX: toX, toY: toY,
|
|
573
|
+
button: button, durationMs: duration
|
|
574
|
+
)
|
|
575
|
+
emit(["ok": true])
|
|
576
|
+
|
|
577
|
+
case "type":
|
|
578
|
+
requireAccessibility()
|
|
579
|
+
let text = opts.string("text") ?? ""
|
|
580
|
+
if text.isEmpty { die("bad_arguments", "empty --text", exit: 4) }
|
|
581
|
+
if opts.has("paste") {
|
|
582
|
+
pasteText(text)
|
|
583
|
+
emit(["ok": true, "mode": "paste", "chars": text.count])
|
|
584
|
+
} else {
|
|
585
|
+
typeUnicode(text)
|
|
586
|
+
emit(["ok": true, "mode": "unicode", "chars": text.count])
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
case "key":
|
|
590
|
+
requireAccessibility()
|
|
591
|
+
let combo = opts.required("combo")
|
|
592
|
+
let stroke = parseCombo(combo)
|
|
593
|
+
press(stroke)
|
|
594
|
+
emit(["ok": true, "combo": combo])
|
|
595
|
+
|
|
596
|
+
case "scroll":
|
|
597
|
+
requireAccessibility()
|
|
598
|
+
let dx = opts.double("dx", 0)
|
|
599
|
+
let dy = opts.double("dy", 0)
|
|
600
|
+
guard
|
|
601
|
+
let event = CGEvent(
|
|
602
|
+
scrollWheelEvent2Source: nil,
|
|
603
|
+
units: .pixel,
|
|
604
|
+
wheelCount: 2,
|
|
605
|
+
wheel1: Int32(dy),
|
|
606
|
+
wheel2: Int32(dx),
|
|
607
|
+
wheel3: 0
|
|
608
|
+
)
|
|
609
|
+
else {
|
|
610
|
+
die("event_failed", "could not create a scroll event", exit: 5)
|
|
611
|
+
}
|
|
612
|
+
event.location = currentPosition()
|
|
613
|
+
event.post(tap: .cghidEventTap)
|
|
614
|
+
emit(["ok": true, "dx": dx, "dy": dy])
|
|
615
|
+
|
|
616
|
+
default:
|
|
617
|
+
die("bad_arguments", "unknown command '\(command)'", exit: 4)
|
|
618
|
+
}
|