noracu 0.1.0 → 0.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.
@@ -0,0 +1,77 @@
1
+ """Pixel-level action verification.
2
+
3
+ Each gesture is followed by a screenshot hash comparison to confirm the
4
+ screen actually changed. This closes the loop: an action that reports
5
+ success but leaves the screen identical is a dropped event, and callers
6
+ should retry or re-observe — the same observe-act-re-observe discipline
7
+ that OpenAI's Computer Use enforces with its revision mechanism.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import subprocess
14
+ import tempfile
15
+ from dataclasses import dataclass
16
+
17
+ from .window import get_bounds
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ScreenState:
22
+ """A fingerprint of the mirroring window content."""
23
+
24
+ md5: str
25
+ width: int
26
+ height: int
27
+
28
+
29
+ def capture_hash() -> ScreenState:
30
+ """Capture the window and return a content fingerprint.
31
+
32
+ The hash is computed over a downsampled copy: full-resolution
33
+ hashes are sensitive to video-stream noise (compression flicker)
34
+ even when nothing meaningful changed.
35
+ """
36
+ b = get_bounds()
37
+ raw = tempfile.mktemp(prefix="imctl_verify_", suffix=".png")
38
+ small = tempfile.mktemp(prefix="imctl_verify_s_", suffix=".png")
39
+ try:
40
+ subprocess.run(
41
+ ["screencapture", "-x", f"-R{b.x},{b.y},{b.width},{b.height}", raw],
42
+ check=True,
43
+ timeout=10,
44
+ )
45
+ # Downsample to ~163x360 (half window) to suppress stream noise.
46
+ subprocess.run(
47
+ ["sips", "-z", "360", "163", raw, "--out", small],
48
+ check=True,
49
+ capture_output=True,
50
+ timeout=10,
51
+ )
52
+ with open(small, "rb") as f:
53
+ digest = hashlib.md5(f.read()).hexdigest()
54
+ return ScreenState(md5=digest, width=b.width, height=b.height)
55
+ finally:
56
+ subprocess.run(["rm", "-f", raw, small], capture_output=True)
57
+
58
+
59
+ def changed(before: ScreenState, after: ScreenState) -> bool:
60
+ """True if the screen content differs between two states."""
61
+ return before.md5 != after.md5
62
+
63
+
64
+ def verify_action(action, *args, settle_s: float = 1.5, **kwargs) -> bool:
65
+ """Run an action and report whether the screen changed.
66
+
67
+ Usage:
68
+ ok = verify_action(gestures.home)
69
+ Returns True if the screen content changed after the action.
70
+ """
71
+ before = capture_hash()
72
+ action(*args, **kwargs)
73
+ import time
74
+
75
+ time.sleep(settle_s)
76
+ after = capture_hash()
77
+ return changed(before, after)
@@ -0,0 +1,138 @@
1
+ """Local OCR via the macOS Vision framework.
2
+
3
+ Runs VNRecognizeTextRequest on a screenshot of the mirroring window
4
+ and returns text with normalized (0-1) coordinates, ready to feed into
5
+ input.tap(). Everything runs locally — no network, no API keys.
6
+
7
+ Coordinate convention: Vision returns bottom-left-origin bounding
8
+ boxes; we convert to top-left-origin (screen convention) and normalize
9
+ to the window size so results map directly onto tap(nx, ny).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import subprocess
16
+ import tempfile
17
+ from dataclasses import dataclass
18
+
19
+ from .window import get_bounds, get_window_info
20
+
21
+
22
+ class OCRError(RuntimeError):
23
+ """Raised when OCR fails."""
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class OCRHit:
28
+ text: str
29
+ nx: float # normalized x of the text center (0-1)
30
+ ny: float # normalized y of the text center (0-1)
31
+ confidence: float
32
+
33
+ def __str__(self) -> str:
34
+ return f"({self.nx:.2f},{self.ny:.2f}) {self.text!r} [{self.confidence:.2f}]"
35
+
36
+
37
+ def capture_window(path: str | None = None) -> str:
38
+ """Screenshot the mirroring window to a PNG file; returns the path.
39
+
40
+ Captures by CGWindow id (``screencapture -l``) so the image is the window's own content even when
41
+ other windows cover it or it is not frontmost. Falls back to a screen-region capture of the AX bounds
42
+ when the window id cannot be resolved.
43
+ """
44
+ if path is None:
45
+ path = tempfile.mktemp(prefix="imctl_", suffix=".png")
46
+ info = get_window_info()
47
+ if info is not None:
48
+ r = subprocess.run(
49
+ ["screencapture", "-x", "-o", "-l", str(info["id"]), path],
50
+ capture_output=True,
51
+ timeout=10,
52
+ )
53
+ if r.returncode == 0 and os.path.exists(path) and os.path.getsize(path) > 0:
54
+ return path
55
+ b = get_bounds()
56
+ subprocess.run(
57
+ ["screencapture", "-x", f"-R{b.x},{b.y},{b.width},{b.height}", path],
58
+ check=True,
59
+ timeout=10,
60
+ )
61
+ return path
62
+
63
+
64
+ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> list[OCRHit]:
65
+ """Run Vision OCR on an image; return hits sorted reading-order.
66
+
67
+ Uses the pyobjc Vision bindings (no subprocess Swift compile).
68
+ """
69
+ try:
70
+ import Vision
71
+ from Foundation import NSURL
72
+ from Quartz import (
73
+ CGImageSourceCreateWithURL,
74
+ CGImageSourceCreateImageAtIndex,
75
+ CGImageGetWidth,
76
+ CGImageGetHeight,
77
+ )
78
+ except ImportError as exc: # pragma: no cover
79
+ raise OCRError(f"pyobjc frameworks missing: {exc}") from exc
80
+
81
+ url = NSURL.fileURLWithPath_(image_path)
82
+ src = CGImageSourceCreateWithURL(url, None)
83
+ if src is None:
84
+ raise OCRError(f"cannot open image: {image_path}")
85
+ cg_image = CGImageSourceCreateImageAtIndex(src, 0, None)
86
+ if cg_image is None:
87
+ raise OCRError(f"cannot decode image: {image_path}")
88
+
89
+ request = Vision.VNRecognizeTextRequest.alloc().init()
90
+ request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
91
+ if hasattr(request, "setRecognitionLanguages_"):
92
+ request.setRecognitionLanguages_(list(languages))
93
+ request.setUsesLanguageCorrection_(True)
94
+
95
+ handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
96
+ cg_image, None
97
+ )
98
+ ok = handler.performRequests_error_([request], None)
99
+ if not ok:
100
+ raise OCRError("VNImageRequestHandler.performRequests failed")
101
+
102
+ results = request.results() or []
103
+ hits: list[OCRHit] = []
104
+ for obs in results:
105
+ cand = obs.topCandidates_(1)
106
+ if not cand:
107
+ continue
108
+ cand = cand[0]
109
+ box = obs.boundingBox() # bottom-left origin, normalized
110
+ cx = box.origin.x + box.size.width / 2
111
+ cy_top = 1.0 - (box.origin.y + box.size.height / 2) # flip to top-left
112
+ hits.append(
113
+ OCRHit(
114
+ text=str(cand.string()),
115
+ nx=cx,
116
+ ny=cy_top,
117
+ confidence=float(cand.confidence()),
118
+ )
119
+ )
120
+
121
+ # Reading order: group by row (within 3% height), then left-to-right.
122
+ hits.sort(key=lambda h: (round(h.ny / 0.03), h.nx))
123
+ return hits
124
+
125
+
126
+ def find(text: str, image_path: str | None = None,
127
+ exact: bool = False) -> OCRHit | None:
128
+ """Find the first OCR hit matching text; returns None if absent."""
129
+ path = image_path or capture_window()
130
+ for hit in ocr(path):
131
+ if (hit.text == text) if exact else (text in hit.text):
132
+ return hit
133
+ return None
134
+
135
+
136
+ def read_screen() -> list[OCRHit]:
137
+ """Convenience: capture + OCR the current mirroring window."""
138
+ return ocr(capture_window())
@@ -0,0 +1,352 @@
1
+ """Window management for the iPhone Mirroring app.
2
+
3
+ Resolves the iPhone Mirroring window bounds dynamically before every
4
+ gesture. The window can be moved, minimized, or closed between actions,
5
+ so callers must never cache bounds across gestures.
6
+
7
+ Uses System Events (AppleScript) rather than the raw AX C API: it is
8
+ the most reliable way to enumerate windows of another process and
9
+ survives permission quirks better than direct AXUIElement calls.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import subprocess
15
+ from dataclasses import dataclass
16
+
17
+ APP_NAME = "iPhone Mirroring"
18
+ PROCESS_NAME = "iPhone Mirroring"
19
+
20
+
21
+ class WindowError(RuntimeError):
22
+ """Raised when the iPhone Mirroring window cannot be found or used."""
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class WindowBounds:
27
+ x: int
28
+ y: int
29
+ width: int
30
+ height: int
31
+
32
+ @property
33
+ def center(self) -> tuple[int, int]:
34
+ return (self.x + self.width // 2, self.y + self.height // 2)
35
+
36
+ def denormalize(self, nx: float, ny: float) -> tuple[int, int]:
37
+ """Convert normalized (0-1) coordinates to screen coordinates."""
38
+ if not (0.0 <= nx <= 1.0 and 0.0 <= ny <= 1.0):
39
+ raise ValueError(f"normalized coords out of range: ({nx}, {ny})")
40
+ return (
41
+ round(self.x + nx * self.width),
42
+ round(self.y + ny * self.height),
43
+ )
44
+
45
+
46
+ _GET_BOUNDS_SCRIPT = '''
47
+ tell application "System Events"
48
+ tell process "iPhone Mirroring"
49
+ set winCount to count of windows
50
+ if winCount is 0 then return "NO_WINDOW"
51
+ set {x, y} to position of window 1
52
+ set {w, h} to size of window 1
53
+ return (x as text) & "," & (y as text) & "," & (w as text) & "," & (h as text)
54
+ end tell
55
+ end tell
56
+ '''
57
+
58
+ _FRONTMOST_SCRIPT = '''
59
+ tell application "System Events"
60
+ tell process "iPhone Mirroring"
61
+ return frontmost as text
62
+ end tell
63
+ end tell
64
+ '''
65
+
66
+
67
+ def _run_osascript(script: str, *, strip: bool = True) -> str:
68
+ result = subprocess.run(
69
+ ["osascript", "-e", script],
70
+ capture_output=True,
71
+ text=True,
72
+ timeout=10,
73
+ )
74
+ if result.returncode != 0:
75
+ raise WindowError(f"osascript failed: {result.stderr.strip()}")
76
+ return result.stdout.strip() if strip else result.stdout
77
+
78
+
79
+ def is_running() -> bool:
80
+ """Return True if the iPhone Mirroring process is alive."""
81
+ result = subprocess.run(
82
+ ["pgrep", "-x", PROCESS_NAME], capture_output=True
83
+ )
84
+ return result.returncode == 0
85
+
86
+
87
+ def ensure_running() -> None:
88
+ """Launch iPhone Mirroring if it is not running."""
89
+ if is_running():
90
+ return
91
+ subprocess.run(
92
+ ["open", "-a", APP_NAME], check=True, timeout=15
93
+ )
94
+ import time
95
+
96
+ for _ in range(20): # wait up to ~10s for the process
97
+ if is_running():
98
+ break
99
+ time.sleep(0.5)
100
+ else:
101
+ raise WindowError("iPhone Mirroring did not start within 10s")
102
+
103
+
104
+ def ensure_frontmost() -> None:
105
+ """Bring the iPhone Mirroring window to the front.
106
+
107
+ CGEvents are delivered to the frontmost app; if another window
108
+ covers the mirroring window, taps would land on the wrong target.
109
+ """
110
+ if _run_osascript(_FRONTMOST_SCRIPT) == "true":
111
+ return
112
+ subprocess.run(
113
+ ["osascript", "-e", f'tell application "{APP_NAME}" to activate'],
114
+ capture_output=True,
115
+ timeout=10,
116
+ )
117
+ import time
118
+
119
+ time.sleep(0.4) # let the window server settle
120
+ if _run_osascript(_FRONTMOST_SCRIPT) != "true":
121
+ raise WindowError("could not bring iPhone Mirroring to front")
122
+
123
+
124
+ def get_bounds() -> WindowBounds:
125
+ """Return current bounds of the mirroring window.
126
+
127
+ Raises WindowError if the app is not running or has no window
128
+ (e.g. the window was closed but the process lives on).
129
+ """
130
+ out = _run_osascript(_GET_BOUNDS_SCRIPT)
131
+ if out == "NO_WINDOW":
132
+ # Window closed but process alive: re-activate to restore it.
133
+ subprocess.run(
134
+ ["osascript", "-e", f'tell application "{APP_NAME}" to activate'],
135
+ capture_output=True,
136
+ timeout=10,
137
+ )
138
+ import time
139
+
140
+ time.sleep(1.0)
141
+ out = _run_osascript(_GET_BOUNDS_SCRIPT)
142
+ if out == "NO_WINDOW":
143
+ raise WindowError(
144
+ "iPhone Mirroring window not found (app running, no window)"
145
+ )
146
+ try:
147
+ x, y, w, h = (int(v) for v in out.split(","))
148
+ except ValueError as exc:
149
+ raise WindowError(f"unexpected bounds format: {out!r}") from exc
150
+ if w <= 0 or h <= 0:
151
+ raise WindowError(f"degenerate window size: {w}x{h}")
152
+ return WindowBounds(x=x, y=y, width=w, height=h)
153
+
154
+
155
+ # Language-independent mirror-state probe. When the mirroring session is live, window 1 contains a
156
+ # single group (the AXHostingView) with no children; when an overlay is shown (paused, connecting,
157
+ # "iPhone in use", …) that group gains child elements (image / static text / button). Overlay text
158
+ # is localized, so the decision never matches on text — only on structure (child count, classes).
159
+ # Labels can span multiple lines and nameless elements coerce to the literal "missing value";
160
+ # both are normalized so one element = exactly one `<class>\t<label>` line.
161
+ _OVERLAY_SCRIPT = '''
162
+ on collapseBreaks(s)
163
+ set tid to AppleScript's text item delimiters
164
+ set AppleScript's text item delimiters to linefeed
165
+ set parts to text items of s
166
+ set AppleScript's text item delimiters to " "
167
+ set s to parts as text
168
+ set AppleScript's text item delimiters to return
169
+ set parts to text items of s
170
+ set AppleScript's text item delimiters to " "
171
+ set s to parts as text
172
+ set AppleScript's text item delimiters to tid
173
+ return s
174
+ end collapseBreaks
175
+
176
+ tell application "System Events"
177
+ tell process "iPhone Mirroring"
178
+ set winCount to count of windows
179
+ if winCount is 0 then return "NO_WINDOW"
180
+ tell window 1
181
+ if not (exists group 1) then return "NO_GROUP"
182
+ set els to UI elements of group 1
183
+ if (count of els) is 0 then return ""
184
+ set out to ""
185
+ repeat with e in els
186
+ set c to (class of e) as text
187
+ set lbl to ""
188
+ try
189
+ set n to (name of e) as text
190
+ if n is not "missing value" then set lbl to n
191
+ end try
192
+ if lbl is "" then
193
+ try
194
+ set v to (value of e) as text
195
+ if v is not "missing value" then set lbl to v
196
+ end try
197
+ end if
198
+ set out to out & c & tab & (my collapseBreaks(lbl)) & linefeed
199
+ end repeat
200
+ return out
201
+ end tell
202
+ end tell
203
+ end tell
204
+ '''
205
+
206
+ # Clicks the Resume control of the paused overlay. Only ever invoked after _OVERLAY_SCRIPT
207
+ # reported exactly one button under group 1 (static script, no interpolated parameters).
208
+ _CLICK_RESUME_SCRIPT = '''
209
+ tell application "System Events"
210
+ tell process "iPhone Mirroring"
211
+ tell window 1
212
+ click button 1 of group 1
213
+ end tell
214
+ end tell
215
+ end tell
216
+ '''
217
+
218
+
219
+ def get_window_info() -> dict | None:
220
+ """Return the mirroring window's CGWindow record: {"id", "x", "y", "w", "h", "onscreen"}.
221
+
222
+ Uses Quartz (pyobjc). Prefers the window literally named "iPhone Mirroring"; otherwise the largest
223
+ normal-layer window of the process. Returns None when nothing qualifies. The id is what
224
+ ``screencapture -l`` needs to capture the window's own pixels even when other windows cover it.
225
+ """
226
+ try:
227
+ import Quartz # type: ignore
228
+ except ImportError:
229
+ return None
230
+ opts = Quartz.kCGWindowListOptionAll | Quartz.kCGWindowListExcludeDesktopElements
231
+ best = None
232
+ for w in Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []:
233
+ if w.get("kCGWindowOwnerName") != PROCESS_NAME or w.get("kCGWindowLayer", 0) != 0:
234
+ continue
235
+ b = w.get("kCGWindowBounds") or {}
236
+ rec = {
237
+ "id": int(w["kCGWindowNumber"]),
238
+ "x": int(b.get("X", 0)),
239
+ "y": int(b.get("Y", 0)),
240
+ "w": int(b.get("Width", 0)),
241
+ "h": int(b.get("Height", 0)),
242
+ "onscreen": bool(w.get("kCGWindowIsOnscreen", False)),
243
+ }
244
+ if rec["w"] < 50 or rec["h"] < 50:
245
+ continue
246
+ if w.get("kCGWindowName") == APP_NAME:
247
+ return rec
248
+ if best is None or rec["w"] * rec["h"] > best["w"] * best["h"]:
249
+ best = rec
250
+ return best
251
+
252
+
253
+ def is_frontmost() -> bool:
254
+ """True when iPhone Mirroring is the frontmost application."""
255
+ try:
256
+ return _run_osascript(_FRONTMOST_SCRIPT) == "true"
257
+ except WindowError:
258
+ return False
259
+
260
+
261
+ def parse_overlay(raw: str) -> dict:
262
+ """Parse _OVERLAY_SCRIPT output into {"live", "overlay", "buttons"}.
263
+
264
+ Rules (structure only, never localized text):
265
+ - "" (group 1 has no children) -> live=True, overlay=None, buttons=0
266
+ - child lines "<class>\t<name-or-value>" -> live=False, overlay=static texts joined with " / "
267
+ (None when no text), buttons=button count
268
+ - "NO_WINDOW" / "NO_GROUP" / unparseable -> live=None, overlay=None, buttons=0
269
+ """
270
+ unknown = {"live": None, "overlay": None, "buttons": 0}
271
+ if raw is None:
272
+ return unknown
273
+ if raw.strip() in ("NO_WINDOW", "NO_GROUP"):
274
+ return unknown
275
+ # Keep lines as-is (a trailing tab is significant: "button\t" means a nameless button);
276
+ # only filter out blank lines.
277
+ lines = [ln for ln in raw.split("\n") if ln.strip()]
278
+ if not lines:
279
+ return {"live": True, "overlay": None, "buttons": 0}
280
+ buttons = 0
281
+ texts: list[str] = []
282
+ for ln in lines:
283
+ parts = ln.split("\t", 1)
284
+ if len(parts) != 2:
285
+ return unknown # unexpected format -> unknown, never guess
286
+ cls, label = parts[0].strip(), parts[1].strip()
287
+ if cls == "button":
288
+ buttons += 1
289
+ elif cls == "static text" and label:
290
+ texts.append(label)
291
+ return {
292
+ "live": False,
293
+ "overlay": " / ".join(texts) if texts else None,
294
+ "buttons": buttons,
295
+ }
296
+
297
+
298
+ def get_overlay() -> dict:
299
+ """Return the current overlay state: {"live", "overlay", "buttons"}.
300
+
301
+ Fail-open: any osascript failure (app not running, AX hiccup, timeout) returns
302
+ live=None so callers can decide; this never raises.
303
+ """
304
+ try:
305
+ # strip=False: a trailing "<class>\t" line (nameless button) must keep its tab —
306
+ # str.strip() would eat it and make the last line unparseable.
307
+ raw = _run_osascript(_OVERLAY_SCRIPT, strip=False)
308
+ except Exception:
309
+ return {"live": None, "overlay": None, "buttons": 0}
310
+ return parse_overlay(raw)
311
+
312
+
313
+ def is_paused(overlay: dict | None = None) -> bool | None:
314
+ """True when the overlay shows a Resume control; False when live; None when unknown.
315
+
316
+ Language-independent: derived from the overlay structure (live flag + button count),
317
+ not from localized text such as "Connection Paused". Accepts a pre-fetched overlay
318
+ dict (as returned by get_overlay) so status can report one consistent snapshot.
319
+ """
320
+ if overlay is None:
321
+ overlay = get_overlay()
322
+ if overlay["live"] is False and overlay["buttons"] >= 1:
323
+ return True
324
+ if overlay["live"] is True:
325
+ return False
326
+ return None
327
+
328
+
329
+ def resume() -> bool:
330
+ """Click the Resume control when the session is paused (language-independent).
331
+
332
+ Live already -> True. Paused overlay with exactly one button -> click it, then poll up
333
+ to ~6 s (0.5 s interval) until the stream is live again. Anything else (multiple
334
+ buttons, no button, unknown state) -> do not click, return False. The phone may still
335
+ ask for Face ID / passcode on its own screen; that part cannot be automated from the Mac.
336
+ """
337
+ import time
338
+
339
+ overlay = get_overlay()
340
+ if overlay["live"] is True:
341
+ return True
342
+ if overlay["live"] is not False or overlay["buttons"] != 1:
343
+ return False
344
+ try:
345
+ _run_osascript(_CLICK_RESUME_SCRIPT)
346
+ except WindowError:
347
+ return False
348
+ for _ in range(12): # up to ~6 s for the stream to come back
349
+ time.sleep(0.5)
350
+ if get_overlay()["live"] is True:
351
+ return True
352
+ return False
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.1.0",
4
- "description": "Local, no-cloud MCP server for macOS and Playwright computer-use, plus experimental iPhone. Acts by element index.",
3
+ "version": "0.1.2",
4
+ "mcpName": "io.github.sgInnora/noracu",
5
+ "description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
5
6
  "type": "module",
6
7
  "main": "src/server.mjs",
7
8
  "bin": {
@@ -28,7 +29,9 @@
28
29
  "claude",
29
30
  "claude-desktop",
30
31
  "claude-code",
31
- "cursor"
32
+ "cursor",
33
+ "iphone",
34
+ "iphone-mirroring"
32
35
  ],
33
36
  "license": "MIT",
34
37
  "dependencies": {
@@ -52,6 +55,10 @@
52
55
  "README.zh-CN.md",
53
56
  "LICENSE",
54
57
  "CHANGELOG.md",
55
- "SECURITY.md"
58
+ "SECURITY.md",
59
+ "imctl/README.md",
60
+ "imctl/LICENSE",
61
+ "imctl/pyproject.toml",
62
+ "imctl/src/imctl/*.py"
56
63
  ]
57
64
  }