noracu 0.1.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.2] — 2026-11-02
4
+
5
+ ### Fixed
6
+ - Docs: the iPhone must be **locked** and near the Mac — unlocking it ends
7
+ iPhone Mirroring (Apple). The 0.1.1 README, usage guide, architecture notes
8
+ and release notes said the opposite.
9
+ - `phone_type` sends a real Command-V chord. Before, iPhone Mirroring received
10
+ a plain "v" and the text was never pasted.
11
+ - `phone_scroll` uses trackpad-style scroll events (continuous, with
12
+ began/changed/ended phases). It used a mouse drag, which iPhone Mirroring
13
+ does not turn into a list scroll, so lists never moved. `phone_swipe` stays
14
+ a drag for gestures such as Home Screen paging.
15
+ - `phone_open` opens Spotlight through iPhone Mirroring's own shortcut instead
16
+ of a swipe that could put the Home Screen into edit (jiggle) mode; it taps
17
+ only an exact app-name match above the search field and returns to the Home
18
+ Screen when nothing matches.
19
+ - Phone input (`phone_tap`, `phone_longpress`, `phone_swipe`, `phone_scroll`,
20
+ `phone_type`, `phone_key`, `phone_open`) is refused with `mirror_not_live`
21
+ while iPhone Mirroring shows an overlay ("Connection Paused", "iPhone in
22
+ Use", …) instead of landing on the overlay; `phone_ocr` / `phone_find` start
23
+ with a warning in that state.
24
+
25
+ ### Known issue
26
+ - On one tested setup (iPhone 17 Pro Max, macOS 26) iPhone Mirroring draws the
27
+ phone larger than its window at every View size; the right column and bottom
28
+ row are cut off, so noracu cannot see or tap them. Under investigation.
29
+
30
+ ### Added
31
+ - `phone_status` reports `live` and `overlay`, read from the window's
32
+ structure rather than its language; `paused` now means "an overlay with a
33
+ Resume button is shown", and `resume` clicks that button only when it is the
34
+ single control.
35
+ - Apple's iPhone Mirroring requirements (Apple silicon or T2, macOS 15+,
36
+ iOS 18+ with a passcode, same Apple Account with two-factor authentication,
37
+ not available in the EU), the "Authenticate automatically" trade-off, and
38
+ privacy guidance in the README, usage guide, architecture notes and SECURITY.
39
+ - MCP Registry metadata: `mcpName` `io.github.sgInnora/noracu` in package.json
40
+ and `server.json`.
41
+ - `demo/record-phone.py` (repo only, not in the npm package) reproduces the
42
+ iPhone demo.
43
+
3
44
  ## [0.1.1] — 2026-11-02
4
45
 
5
46
  ### Added
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # noracu
2
2
 
3
- **Local, no-cloud MCP server for computer-use on macOS apps, a Playwright browser, and (experimentally) a mirrored iPhone — the agent reads an accessibility/ARIA tree and acts by `element_index`, not pixels. No API key, no telemetry.**
3
+ **A local MCP server that lets Claude, Cursor, or any MCP client operate macOS apps and a Playwright browser by `element_index` — and, experimentally, a real iPhone through Apple's iPhone Mirroring (OCR on the Mac, normalized taps). No API key; no telemetry from the server.**
4
4
 
5
5
  [![CI](https://github.com/sgInnora/noracu/actions/workflows/ci.yml/badge.svg)](https://github.com/sgInnora/noracu/actions/workflows/ci.yml)
6
6
  [![npm](https://img.shields.io/npm/v/noracu.svg)](https://www.npmjs.com/package/noracu)
@@ -9,7 +9,7 @@
9
9
 
10
10
  中文说明见 [README.zh-CN.md](README.zh-CN.md)。
11
11
 
12
- One stdio MCP server. The agent snapshots a tree, gets an indexed element list, then clicks or types by `element_index` instead of raw pixels — the same observe/act split on the Mac and in the browser.
12
+ One stdio MCP server. The agent snapshots a tree, gets an indexed element list, then clicks or types by `element_index` instead of raw pixels — the same observe/act split on the Mac and in the browser. The experimental iPhone layer runs the same observe → act loop over OCR text and normalized coordinates.
13
13
 
14
14
  ![browser element_index demo](https://raw.githubusercontent.com/sgInnora/noracu/v0.1.0/docs/demo-browser.gif)
15
15
 
@@ -25,20 +25,20 @@ One MCP server, three control surfaces:
25
25
  | **Browser** | 12 (`browser_*`) | Playwright (persistent profile) | stable |
26
26
  | **iPhone** | 14 (`phone_*`) | iPhone Mirroring via the bundled imctl driver (Python + pyobjc) | experimental |
27
27
 
28
- The iPhone layer is experimental and ships with its driver, imctl (bundled in `imctl/`). It needs an active iPhone Mirroring session on this Mac and a python3 with pyobjc; when no such python is found, `phone_*` tools return a one-line `imctl unavailable` error with the install command, and the Mac and browser layers are unaffected (`phone_home` / `phone_app_switcher` work through the iPhone Mirroring menu even then). The observe/act vocabulary follows the action/observation split popularized by ChatGPT's computer-use, re-implemented on open local tooling.
28
+ The iPhone layer is experimental and ships with its driver (imctl, in `imctl/`). It needs Apple's iPhone Mirroring with the iPhone **locked and near the Mac**, and a python3 with pyobjc; it observes with OCR and acts on normalized coordinates rather than `element_index`. Without pyobjc, `phone_*` tools return a one-line `imctl unavailable` error with the install command, and the Mac and browser layers are unaffected. The observe/act vocabulary follows the action/observation split popularized by ChatGPT's computer-use, re-implemented on open local tooling.
29
29
 
30
30
  ## Why noracu
31
31
 
32
32
  noracu is the local hands, not the model. Your MCP client (Claude Desktop, Claude Code, Cursor) decides what to do; this server only observes and acts on this machine.
33
33
 
34
- - **Runs entirely on your machine.** No cloud, no API key, no telemetry, no postinstall scripts. Sole runtime dependency: Playwright. noracu makes no network calls of its own; the only automatic one is the one-time Chromium download on the first `browser_launch` (`NORACU_DISABLE_AUTO_INSTALL=1` turns that off). The browser still fetches the pages you point it at.
34
+ - **The server runs entirely on your machine.** No cloud service, no API key, no telemetry, no postinstall scripts. Sole runtime dependency: Playwright. noracu makes no network calls of its own; the only automatic one is the one-time Chromium download on the first `browser_launch` (`NORACU_DISABLE_AUTO_INSTALL=1` turns that off). The browser still fetches the pages you point it at, and your MCP client still sends tool results — screenshots, OCR text — to whatever model it uses.
35
35
  - **Acts on semantics, not pixels.** Observation returns the accessibility tree (Mac) or ARIA tree (browser) as an indexed list — text, not screenshots. Actions reference `element_index`; indices expire after 30 s, and clicks re-verify the target (tag/name/href/position in the browser, frontmost app on the Mac) before firing. A stale reference returns `element_no_longer_valid` instead of clicking the wrong thing. Screenshots are there when the tree is not enough.
36
- - **One protocol, three surfaces — not three scripts.** The same observe/act loop drives native Mac apps, a persistent-profile browser, and (experimentally) a mirrored iPhone. The pattern is identical across surfaces; only the tool names differ (`mac_*` vs `browser_*`).
36
+ - **One loop, three surfaces.** Native Mac apps and a persistent-profile browser share the `element_index` protocol (observe a tree, act by index). The experimental iPhone layer runs the same observe → act loop on Apple's iPhone Mirroring, with OCR text and normalized coordinates, because the phone exposes no accessibility tree to the Mac.
37
37
  - **Uses your real sessions.** Your logged-in browser profile, your Mac apps — not a hosted VM. Compared with cloud computer-use: neither is universally more reliable; they fail differently. noracu keeps the screen on your machine.
38
38
  - **Off switches that are actually off.** `NORACU_READ_ONLY=1` (observation-only, default-deny), `NORACU_DISABLE_EVAL=1`, and `file://` blocked by default. See [Security](#security).
39
- - **Verifiable.** 34 end-to-end checks (`npm test`), CI on macos-latest, MIT, and the whole server is one file: `src/server.mjs`.
39
+ - **Verifiable.** 39 end-to-end checks (`npm test`), CI on macos-latest, MIT, and the whole server is one file: `src/server.mjs`.
40
40
 
41
- **Not a good fit if** you need multiple browser tabs or sessions (single session for now), you're not on macOS (the Mac and iPhone layers are macOS-only; the browser layer is cross-platform), or you need a finished iPhone layer today (it ships, but experimental). If you only need browser automation, playwright-mcp has tab management and selector APIs that noracu v0.1 lacks; noracu is for when one agent also has to leave the browser and drive Mac apps.
41
+ **Not a good fit if** you need multiple browser tabs or sessions (single session for now), you're not on macOS (the Mac and iPhone layers are macOS-only; the browser layer is cross-platform), or you need a finished iPhone layer today (it ships, but experimental — and Apple does not offer iPhone Mirroring in the EU). If you only need browser automation, playwright-mcp has tab management and selector APIs that noracu v0.1 lacks; noracu is for when one agent also has to leave the browser and drive Mac apps.
42
42
 
43
43
  ## Quickstart
44
44
 
@@ -88,6 +88,7 @@ Then **quit the host app completely (including any menu-bar icon) and reopen it.
88
88
  | `spawn node` / `npx` `ENOENT` from a GUI host | use an absolute `node` path in the config — nvm/volta/homebrew shims are not on the GUI `PATH` |
89
89
  | `browser_launch` hangs on first use | one-time Chromium download; or auto-install disabled (`NORACU_DISABLE_AUTO_INSTALL=1`) → run `npx playwright install chromium` |
90
90
  | `phone_*` says `imctl unavailable: no python3 with pyobjc found` | install pyobjc for a python3 (`python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`; Homebrew python3 is the usual choice) or set `NORACU_PYTHON` — see [iPhone layer](#iphone-layer-experimental) |
91
+ | `phone_*` refused with `mirror_not_live: …` ("Connection Paused", "iPhone in Use") | the mirror is paused or the iPhone is unlocked — lock the iPhone, keep it near the Mac, then call `phone_launch` (it clicks Resume) |
91
92
  | Typed text comes out re-spaced (e.g. "no ra cu") | a CJK input method is active — use `mac_paste` instead of `mac_type` |
92
93
  | `element_no_longer_valid` | the snapshot is older than 30 s or the UI changed — re-run `mac_ax_state` / `browser_snapshot` and use a fresh index |
93
94
 
@@ -97,15 +98,21 @@ Full worked examples: [docs/usage.md](docs/usage.md).
97
98
 
98
99
  ## iPhone layer (experimental)
99
100
 
100
- The 14 `phone_*` tools drive iPhone Mirroring through **imctl**, a small Python driver that ships inside this package (`imctl/`, MIT, about 1,000 lines). Nothing else to install on noracu's side; the layer stays experimental because it depends on a live mirror and an unlocked phone.
101
+ noracu can operate a real iPhone through Apple's **iPhone Mirroring**. The agent observes with OCR on the Mac (`phone_screenshot`, `phone_ocr`, `phone_find`), acts at normalized 0–1 coordinates (`phone_tap`, `phone_swipe`, `phone_scroll`), types by pasting (`phone_type`) and opens apps by name (`phone_open`). This is not `element_index`: the phone exposes no accessibility tree to the Mac, so a tap lands where OCR placed the text. The driver (imctl, Python, MIT, about 1,000 lines) ships in `imctl/`.
101
102
 
102
- **Requirements:** macOS 15+ · iPhone Mirroring connected (same Apple Account, Bluetooth + Wi-Fi on) · Accessibility + Screen Recording granted to the host app · a python3 that imports pyobjc (Quartz, Vision, AppKit).
103
+ **Apple's requirements** ([support.apple.com/120421](https://support.apple.com/120421)): a Mac with Apple silicon or a T2 chip on macOS 15 or later; an iPhone on iOS 18 or later with a passcode; both signed in to the same Apple Account with two-factor authentication; Bluetooth and Wi-Fi on; the Mac not sharing its internet connection or using AirPlay or Sidecar. **The iPhone must be locked and near the Mac** — unlocking it, or quitting iPhone Mirroring, ends the session. iPhone Mirroring is currently unavailable in the EU. One Mac and one iPhone at a time; camera and microphone are not mirrored.
103
104
 
104
- **Python:** set `NORACU_PYTHON=/path/to/python3`, or let noracu probe `/opt/homebrew/bin/python3`, `/usr/local/bin/python3`, `python3`, `/usr/bin/python3` once, on the first `phone_*` call. Apple's `/usr/bin/python3` usually lacks pyobjc; the common working setup is Homebrew's python3 plus `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`. When nothing qualifies, every `phone_*` tool returns one line — `imctl unavailable: no python3 with pyobjc found (tried …) — run …` — and the Mac and browser layers are unaffected.
105
+ **Unattended sessions:** in iPhone Mirroring → Settings, "Authenticate automatically" lets a session start without a password prompt. Trade-off: anyone who can use your unlocked Mac can then open your phone.
105
106
 
106
- **First success:** `phone_status` → if `paused` is `true`, `phone_launch` (brings the mirror to the front and clicks Resume) → `phone_screenshot` → `phone_ocr` → `phone_find` / `phone_tap`. Screenshots and OCR capture the Mirroring window by window id, so they are the phone's own pixels even when another window covers the mirror.
107
+ **Python:** the driver needs a python3 that imports pyobjc (Quartz, Vision, AppKit). Set `NORACU_PYTHON`, or noracu probes `/opt/homebrew/bin/python3`, `/usr/local/bin/python3`, `python3`, `/usr/bin/python3` once, on the first `phone_*` call. Apple's `/usr/bin/python3` usually lacks pyobjc; Homebrew's python3 plus `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit` is the common working setup.
107
108
 
108
- **Known limits:** the iPhone must be unlocked (unlocking cannot be driven from the Mac); `paused` reads `null` on non-English macOS; `phone_open` relies on Spotlight + OCR and can miss apps whose labels are truncated. `phone_home` / `phone_app_switcher` go through the iPhone Mirroring menu and work without python when the mirror is connected.
109
+ **Mirror state:** `phone_status` reports `live` (the phone's screen is being streamed), `overlay` (the text iPhone Mirroring shows instead, e.g. "Connection Paused" or "iPhone in Use") and `paused` (that overlay offers a Resume button). Detection reads the window's structure, not its text. While the mirror is not live, `phone_tap`, `phone_longpress`, `phone_swipe`, `phone_scroll`, `phone_type`, `phone_key` and `phone_open` refuse with `mirror_not_live` instead of tapping the overlay, and `phone_ocr` / `phone_find` start their output with a warning. The mirror pauses after inactivity; `phone_launch` brings it forward and clicks Resume.
110
+
111
+ **Privacy:** whatever the phone shows — notifications, messages, mail, one-time codes — becomes tool output that your MCP client sends to its model. Turn on a Focus, open a neutral app before you start, and begin with `NORACU_READ_ONLY=1` (`phone_status`, `phone_screenshot`, `phone_ocr` and `phone_find` stay allowed; all phone input is refused). iPhone notifications also reach the Mac once Mirroring is set up.
112
+
113
+ **First success:** `phone_status` → `phone_launch` if `live` is not `true` → `phone_screenshot` → `phone_ocr` → `phone_find` + `phone_tap`.
114
+
115
+ **Known limits:** a tap goes where OCR saw the text, so repeated or misread labels can be hit wrong; `phone_scroll` moves lists with trackpad-style scroll events (a vertical `phone_swipe` drag does not scroll a list — use it for gestures such as Home Screen paging); on one tested setup (iPhone 17 Pro Max, macOS 26) iPhone Mirroring draws the phone larger than its window at every View size, so the right column and bottom row are cut off and cannot be reached — check `phone_screenshot` if taps near the edges miss; `phone_open` types the app name into Spotlight and taps an exact match, otherwise returns to the Home Screen; `phone_home` / `phone_app_switcher` use the iPhone Mirroring menu (English macOS) and work without python while connected.
109
116
 
110
117
  ## Environment variables
111
118
 
@@ -132,6 +139,7 @@ noracu runs with the privileges of your MCP client. It clicks, types, pastes, an
132
139
  - **`file://` is refused** unless `NORACU_ALLOW_FILE_URL=1`, so a browser agent can't read `~/Documents` by navigating to it. (The initial navigation URL is scheme-checked; redirects are not — see SECURITY.md.)
133
140
  - **Focus guard:** pass `app` to `mac_type` / `mac_paste` / `mac_key` and input is refused unless that app is frontmost. Omit `app` and the guard is off.
134
141
  - **Stale-element protection:** an `element_index` is not a coordinate. It expires after 30 s (`element_no_longer_valid`); a browser click re-checks tag/name/href/position, and a Mac click is refused if the frontmost app changed since the snapshot.
142
+ - **iPhone screen is model input:** `phone_screenshot` / `phone_ocr` / `phone_find` return whatever the phone shows — notifications, messages, one-time codes. Use a Focus and a neutral app, and start with `NORACU_READ_ONLY=1` (phone observation allowed, phone input refused). Phone input is also refused while the mirror is paused (`mirror_not_live`).
135
143
  - **Injection-safe JXA:** string parameters are passed to `osascript` as argv data, never built into the script; the one numeric value (AX read depth) is clamped to 1–10 before use. Regression-tested.
136
144
 
137
145
  These switches do not make observed content trustworthy. Screenshot text, accessibility names, and page content are untrusted input to your model — do not let them override the task. Full threat model and per-threat status: [SECURITY.md](SECURITY.md).
@@ -147,10 +155,11 @@ These switches do not make observed content trustworthy. Screenshot text, access
147
155
  - Browser: tab management (list / select / close)
148
156
  - Act vocabulary (browser): `hover`, `set_value`, `wait_for`
149
157
  - Snapshot diffing to cut token use — pending measurement
158
+ - iPhone: `element_index` over OCR regions, re-checking the text before a tap
150
159
 
151
160
  ## Maintenance
152
161
 
153
- Solo-maintained, no SLA. macOS 15+ for the Mac and iPhone layers; the browser layer runs wherever Playwright does.
162
+ Solo-maintained, no SLA. macOS 15+ for the Mac layer; the iPhone layer also needs Apple silicon or a T2 Mac, iOS 18+ and iPhone Mirroring (not available in the EU); the browser layer runs wherever Playwright does.
154
163
 
155
164
  ## License
156
165
 
package/README.zh-CN.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # noracu
2
2
 
3
- **本地、无云的 computer-use MCP server:在 macOS 原生应用、Playwright 浏览器、以及(实验性的)镜像 iPhone 上操作——agent 读取 accessibility / ARIA 树,按 `element_index` 动作,而非像素坐标。无 API key,无遥测。**
3
+ **一个本地 MCP server:让 Claude、Cursor 或任意 MCP client 按 `element_index` 操作 macOS 应用和 Playwright 浏览器——并且(实验性地)经 Apple 的 iPhone Mirroring 操作真实 iPhone(在 Mac 上 OCR、按归一化坐标点击)。无 API key;server 本身无遥测。**
4
4
 
5
5
  [![CI](https://github.com/sgInnora/noracu/actions/workflows/ci.yml/badge.svg)](https://github.com/sgInnora/noracu/actions/workflows/ci.yml)
6
6
  [![npm](https://img.shields.io/npm/v/noracu.svg)](https://www.npmjs.com/package/noracu)
@@ -25,20 +25,20 @@ For English, see [README.md](README.md).
25
25
  | **Browser** | 12 个(`browser_*`) | Playwright(持久化 profile) | stable |
26
26
  | **iPhone** | 14 个(`phone_*`) | 经随包附带的 imctl 驱动 iPhone Mirroring(Python + pyobjc) | experimental |
27
27
 
28
- iPhone 层是实验性的,驱动 imctl 随包附带(在 `imctl/`)。它需要本 Mac 上有活动的 iPhone Mirroring 会话和一个带 pyobjc 的 python3;找不到这样的 python 时,`phone_*` 工具返回一行带安装命令的 `imctl unavailable` 错误,Mac 层和 Browser 层不受影响(`phone_home` / `phone_app_switcher` 即便如此仍可经 iPhone Mirroring 菜单工作)。observe/act 词汇表沿用 ChatGPT computer-use 推广的 action/observation 拆分思路,在开放的本地工具上重新实现。
28
+ iPhone 层是实验性的,驱动 imctl 随包附带(在 `imctl/`)。它需要 Apple 的 iPhone Mirroring,且 iPhone **锁定并靠近 Mac**,以及一个带 pyobjc 的 python3;它用 OCR 观察、按归一化坐标动作,而不是 `element_index`。没有 pyobjc 时,`phone_*` 工具返回一行带安装命令的 `imctl unavailable` 错误,Mac 层和 Browser 层不受影响。observe/act 词汇表沿用 ChatGPT computer-use 推广的 action/observation 拆分思路,在开放的本地工具上重新实现。
29
29
 
30
30
  ## 为什么用 noracu
31
31
 
32
32
  noracu 是本地的"手",不是"脑"。决策由你的 MCP client(Claude Desktop、Claude Code、Cursor)做;本 server 只在这台机器上观察与动作。
33
33
 
34
- - **完全在本机运行。** 无云、无 API key、无遥测、无 postinstall 脚本。唯一运行期依赖是 Playwright。noracu 自身不发任何网络请求;唯一的自动网络行为是首次 `browser_launch` 时一次性下载 Chromium(`NORACU_DISABLE_AUTO_INSTALL=1` 可关闭)。你让浏览器打开的页面当然会被抓取。
34
+ - **server 完全在本机运行。** 无云服务、无 API key、无遥测、无 postinstall 脚本。唯一运行期依赖是 Playwright。noracu 自身不发任何网络请求;唯一的自动网络行为是首次 `browser_launch` 时一次性下载 Chromium(`NORACU_DISABLE_AUTO_INSTALL=1` 可关闭)。你让浏览器打开的页面当然会被抓取,你的 MCP client 也仍会把工具结果(截图、OCR 文本)发给它所用的模型。
35
35
  - **按语义动作,而非像素。** 观察返回 accessibility 树(Mac)或 ARIA 树(browser)的带索引列表——是文本,不是截图。动作引用 `element_index`;索引 30 秒后过期,点击前会重新校验目标(browser 校验 tag/name/href/位置,Mac 校验 frontmost app)。索引失效时返回 `element_no_longer_valid`,而不是点错位置。树不够用时才用截图。
36
- - **一套协议,三个面——不是三套脚本。** 同一个 observe/act 循环驱动 Mac 原生应用、持久化 profile 的浏览器、以及(实验性的)镜像 iPhone。模式跨面一致,只是工具名不同(`mac_*` vs `browser_*`)。
36
+ - **一个循环,三个面。** Mac 原生应用和持久化 profile 的浏览器共用 `element_index` 协议(观察一棵树、按索引动作)。实验性的 iPhone 层在 Apple 的 iPhone Mirroring 上跑同一个 observe → act 循环,用的是 OCR 文本和归一化坐标——因为手机不向 Mac 暴露 accessibility 树。
37
37
  - **用你真实的会话。** 你已登录的浏览器 profile、你的 Mac 应用——不是托管的 VM。与云端 computer-use 相比:两者没有谁普遍更可靠,只是失败方式不同。noracu 把屏幕留在你本机。
38
38
  - **真正能关掉的开关。** `NORACU_READ_ONLY=1`(只观察,默认拒绝)、`NORACU_DISABLE_EVAL=1`、以及默认封禁 `file://`。见 [安全](#安全)。
39
- - **可验证。** 34 项端到端检查(`npm test`)、CI 跑在 macos-latest、MIT 许可,整个 server 就一个文件:`src/server.mjs`。
39
+ - **可验证。** 39 项端到端检查(`npm test`)、CI 跑在 macos-latest、MIT 许可,整个 server 就一个文件:`src/server.mjs`。
40
40
 
41
- **不适合的场景:** 你需要多个浏览器标签页或会话(当前仅单会话)、你不在 macOS 上(Mac 与 iPhone 层仅限 macOS;Browser 层跨平台)、或你现在就需要一个成品级的 iPhone 层(它已随包附带,但仍是实验性)。如果你只需要浏览器自动化,playwright-mcp 有 noracu v0.1 还没有的 tab 管理和 selector API;noracu 的价值在于:同一个 agent 还得离开浏览器去操作 Mac 应用。
41
+ **不适合的场景:** 你需要多个浏览器标签页或会话(当前仅单会话)、你不在 macOS 上(Mac 与 iPhone 层仅限 macOS;Browser 层跨平台)、或你现在就需要一个成品级的 iPhone 层(它已随包附带,但仍是实验性——而且 Apple 在欧盟不提供 iPhone Mirroring)。如果你只需要浏览器自动化,playwright-mcp 有 noracu v0.1 还没有的 tab 管理和 selector API;noracu 的价值在于:同一个 agent 还得离开浏览器去操作 Mac 应用。
42
42
 
43
43
  ## 快速开始
44
44
 
@@ -88,6 +88,7 @@ Claude Code:`claude mcp add noracu -- /绝对路径/TO/node /绝对路径/nora
88
88
  | GUI 宿主报 `spawn node` / `npx` `ENOENT` | 配置里改用绝对 `node` 路径——nvm/volta/homebrew 的 shim 不在 GUI `PATH` 上 |
89
89
  | 首次 `browser_launch` 卡住 | 一次性 Chromium 下载;或自动安装被关闭(`NORACU_DISABLE_AUTO_INSTALL=1`)→ 执行 `npx playwright install chromium` |
90
90
  | `phone_*` 报 `imctl unavailable: no python3 with pyobjc found` | 给某个 python3 装 pyobjc(`python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`,通常选 Homebrew 的 python3)或设 `NORACU_PYTHON`——见[iPhone 层](#iphone-层实验性) |
91
+ | `phone_*` 被拒并报 `mirror_not_live: …`("Connection Paused"、"iPhone in Use") | 镜像已暂停或 iPhone 被解锁——锁上 iPhone、放在 Mac 旁,然后调用 `phone_launch`(会点击 Resume) |
91
92
  | 输入的文本被重新空格化(如 "no ra cu") | 有 CJK 输入法在激活——用 `mac_paste` 代替 `mac_type` |
92
93
  | `element_no_longer_valid` | 快照超过 30 秒或界面变了——重跑 `mac_ax_state` / `browser_snapshot` 并用新索引 |
93
94
 
@@ -97,15 +98,21 @@ Claude Code:`claude mcp add noracu -- /绝对路径/TO/node /绝对路径/nora
97
98
 
98
99
  ## iPhone 层(实验性)
99
100
 
100
- 14 个 `phone_*` 工具经 **imctl** 驱动 iPhone Mirroring——一个随本包附带的小型 Python 驱动(`imctl/`,MIT,约 1,000 行)。noracu 这边不需要再装别的;该层仍为实验性,因为它依赖在线的镜像会话和已解锁的手机。
101
+ noracu 可以经 Apple 的 **iPhone Mirroring** 操作真实 iPhone。agent 在 Mac 上用 OCR 观察(`phone_screenshot`、`phone_ocr`、`phone_find`),按 0–1 归一化坐标动作(`phone_tap`、`phone_swipe`、`phone_scroll`),用粘贴输入文字(`phone_type`),按名字打开 App(`phone_open`)。这不是 `element_index`:手机不向 Mac 暴露 accessibility 树,所以点击落在 OCR 识别出文字的位置。驱动(imctl,Python,MIT,约 1,000 行)随包附带在 `imctl/`。
101
102
 
102
- **要求:** macOS 15+ · iPhone Mirroring 已连接(同一 Apple 账户,蓝牙 + Wi-Fi 打开)· Accessibility + Screen Recording 授给宿主应用 · 一个能导入 pyobjc(Quartz、Vision、AppKit)的 python3。
103
+ **Apple 的要求**([support.apple.com/120421](https://support.apple.com/120421)):搭载 Apple 芯片或 T2 芯片、运行 macOS 15 或更高版本的 Mac;运行 iOS 18 或更高版本并设置了密码的 iPhone;两台设备登录同一个开启双重认证的 Apple 账户;蓝牙和 Wi-Fi 打开;Mac 没有共享互联网连接、没有使用 AirPlay 或随航(Sidecar)。**iPhone 必须锁定并靠近 Mac**——解锁 iPhone 或退出 iPhone Mirroring 都会结束会话。iPhone Mirroring 目前在欧盟不可用。一次只能一台 Mac 和一台 iPhone;摄像头和麦克风不会被镜像。
103
104
 
104
- **Python:** 设置 `NORACU_PYTHON=/path/to/python3`,或由 noracu 在首次调用 `phone_*` 时依次探测一次 `/opt/homebrew/bin/python3`、`/usr/local/bin/python3`、`python3`、`/usr/bin/python3`。Apple 自带的 `/usr/bin/python3` 通常没有 pyobjc;常见可用配置是 Homebrew 的 python3 加 `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`。都不可用时,每个 `phone_*` 工具返回一行错误——`imctl unavailable: no python3 with pyobjc found (tried …) — run …`——Mac 层与 Browser 层不受影响。
105
+ **无人值守:** 在 iPhone Mirroring → 设置里选「自动认证(Authenticate automatically)」,会话开始时就不再要求输入密码。代价:任何能使用你这台已解锁 Mac 的人都能打开你的手机。
105
106
 
106
- **首次成功路径:** `phone_status` → 若 `paused` 为 `true`,先 `phone_launch`(置前并点击 Resume)→ `phone_screenshot` → `phone_ocr` → `phone_find` / `phone_tap`。截图与 OCR 按窗口 id 截取镜像窗口,即使被其它窗口遮挡,拿到的也是手机自身的画面。
107
+ **Python:** 驱动需要一个能导入 pyobjc(Quartz、Vision、AppKit)的 python3。设置 `NORACU_PYTHON`,或由 noracu 在首次调用 `phone_*` 时依次探测一次 `/opt/homebrew/bin/python3`、`/usr/local/bin/python3`、`python3`、`/usr/bin/python3`。Apple 自带的 `/usr/bin/python3` 通常没有 pyobjc;常见可用配置是 Homebrew 的 python3 加 `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`。
107
108
 
108
- **已知限制:** 手机须处于解锁状态(解锁无法从 Mac 侧代做);非英文 macOS 下 `paused` 读为 `null`;`phone_open` 依赖 Spotlight + OCR,标签被截断的 app 可能找不到。`phone_home` / `phone_app_switcher` 走 iPhone Mirroring 菜单,镜像已连接时无需 python 也能用。
109
+ **镜像状态:** `phone_status` 返回 `live`(手机画面正在推流)、`overlay`(iPhone Mirroring 显示的替代文字,如 "Connection Paused"、"iPhone in Use")和 `paused`(该覆盖层带 Resume 按钮)。判定依据是窗口结构,不是文字。镜像不在线时,`phone_tap`、`phone_longpress`、`phone_swipe`、`phone_scroll`、`phone_type`、`phone_key`、`phone_open` 会以 `mirror_not_live` 拒绝,而不是点到覆盖层上;`phone_ocr` / `phone_find` 的输出首行会给出警告。镜像闲置一段时间后会暂停;`phone_launch` 会把它置前并点击 Resume。
110
+
111
+ **隐私:** 手机上显示的一切——通知、短信、邮件、一次性验证码——都会变成工具输出,由你的 MCP client 发给它所用的模型。开始前打开专注模式、打开一个无关紧要的 App,并先用 `NORACU_READ_ONLY=1`(`phone_status`、`phone_screenshot`、`phone_ocr`、`phone_find` 仍可用;所有手机输入都会被拒绝)。iPhone Mirroring 设置好后,iPhone 的通知也会出现在 Mac 上。
112
+
113
+ **首次成功路径:** `phone_status` → 若 `live` 不是 `true` 先 `phone_launch` → `phone_screenshot` → `phone_ocr` → `phone_find` + `phone_tap`。
114
+
115
+ **已知限制:** 点击落在 OCR 识别到文字的位置,重复或识别错的标签可能点错;`phone_scroll` 用触控板式的滚动事件移动列表(竖向的 `phone_swipe` 拖拽不会滚动列表——它用于主屏翻页这类手势);在一套实测环境(iPhone 17 Pro Max、macOS 26)上,iPhone Mirroring 在所有 View 尺寸下都把手机画面画得比窗口大,右列和最底行被裁掉、无法点到——边缘附近点不中时先看 `phone_screenshot`;`phone_open` 把 App 名输入 Spotlight 并只点击完全匹配的结果,找不到就回到主屏;`phone_home` / `phone_app_switcher` 走 iPhone Mirroring 菜单(英文 macOS),镜像连接时无需 python。
109
116
 
110
117
  ## 环境变量
111
118
 
@@ -132,6 +139,7 @@ noracu 以你 MCP client 的权限运行。它会在本机点击、输入、粘
132
139
  - **`file://` 被拒**,除非 `NORACU_ALLOW_FILE_URL=1`,这样浏览器 agent 无法通过导航到 `~/Documents` 来读本地文件。(仅校验初始导航 URL;重定向不校验——见 SECURITY.md。)
133
140
  - **焦点守卫:** 给 `mac_type` / `mac_paste` / `mac_key` 传 `app`,当该应用不在最前时输入被拒。不传 `app` 则守卫关闭。
134
141
  - **失效元素保护:** `element_index` 不是坐标。它 30 秒后过期(`element_no_longer_valid`);browser 点击会重校验 tag/name/href/位置,Mac 点击在 frontmost app 自快照以来变化时拒绝执行。
142
+ - **iPhone 画面就是模型输入:** `phone_screenshot` / `phone_ocr` / `phone_find` 会返回手机上显示的一切——通知、短信、一次性验证码。请用专注模式和无关紧要的 App,并先用 `NORACU_READ_ONLY=1`(允许观察手机、拒绝手机输入)。镜像暂停时手机输入同样会被拒绝(`mirror_not_live`)。
135
143
  - **防注入 JXA:** 字符串参数以 argv 数据传给 `osascript`,绝不拼进脚本;唯一的数值参数(AX 读取 depth)在使用前 clamp 到 1–10。有回归测试覆盖。
136
144
 
137
145
  这些开关不会让被观察的内容变得可信。截图文字、accessibility 名称、页面内容都是喂给你模型的**不可信输入**——别让它们覆盖任务指令。完整威胁模型与逐条状态见 [SECURITY.md](SECURITY.md)(英文)。
@@ -147,10 +155,11 @@ noracu 以你 MCP client 的权限运行。它会在本机点击、输入、粘
147
155
  - Browser:tab 管理(list / select / close)
148
156
  - 动作词汇(browser):`hover`、`set_value`、`wait_for`
149
157
  - 快照 diffing 以降低 token 消耗——待测量
158
+ - iPhone:在 OCR 区域上提供 `element_index`,点击前重新校验文字
150
159
 
151
160
  ## 维护
152
161
 
153
- 个人维护,无 SLA。Mac 与 iPhone 层需 macOS 15+;Browser 层随 Playwright 跨平台。
162
+ 个人维护,无 SLA。Mac 层需 macOS 15+;iPhone 层另需 Apple 芯片或 T2 的 Mac、iOS 18+ 和 iPhone Mirroring(欧盟不可用);Browser 层随 Playwright 跨平台。
154
163
 
155
164
  ## 许可
156
165
 
package/SECURITY.md CHANGED
@@ -13,7 +13,8 @@ Treat every tool call as privileged.
13
13
  | 3 | **Arbitrary JS in browser** | `browser_evaluate` executes any JavaScript in the page context | **Mitigated (kill switch)** | Set `NORACU_DISABLE_EVAL=1`; `browser_evaluate` then returns an error on every call (it stays listed in `tools/list`) |
14
14
  | 4 | **Input validation gaps** | Malformed arguments (NaN coordinates, oversized strings, `javascript:` URLs) | **Mitigated** | `validateArgs` runs on every tool call; tools with coordinate/enum/length/URL constraints are checked (others pass through) |
15
15
  | 5 | **Screenshot privacy** | `mac_screenshot` / `phone_screenshot` capture the full screen / phone display | **Inherent** | Run in a dedicated macOS user account or virtual display for untrusted automation |
16
- | 6 | **iPhone operations** | `phone_tap` / `phone_type` can interact with payment and SMS-verification UIs | **Inherent** | Consider disconnecting Apple Pay / keeping Mirroring off for untrusted sessions |
16
+ | 6 | **iPhone operations** | `phone_tap` / `phone_type` can interact with payment and SMS-verification UIs; taps go to OCR coordinates with no element re-check | **Inherent** | Keep Mirroring off for untrusted sessions; `NORACU_READ_ONLY=1` refuses all phone input; input is refused while the mirror shows an overlay (`mirror_not_live`); "Authenticate automatically" lets anyone at the unlocked Mac start mirroring |
17
+ | 12 | **Phone screen as model input** | `phone_screenshot` / `phone_ocr` / `phone_find` return notifications, messages, mail and one-time codes visible on the phone | **Inherent** | Use a Focus mode and a neutral app; the MCP client sends tool results to its model; iPhone notifications also reach the Mac once Mirroring is set up |
17
18
  | 7 | **Supply chain** | malicious PRs / dependency poisoning after open-sourcing | **Partially mitigated** | Review all PRs touching `src/server.mjs` argument handling; lockfile committed; no `postinstall` scripts; the only runtime download is the one-time Playwright `chromium` install triggered by `browser_launch`, which can be disabled with `NORACU_DISABLE_AUTO_INSTALL=1` |
18
19
  | 8 | **Local file read via browser** | `browser_navigate` to a `file://` URL, then `browser_read` exfiltrates local files | **Mitigated (default)** | `file://` blocked at the `browser_navigate` argument unless `NORACU_ALLOW_FILE_URL=1` (initial URL only; redirects fall under threat 9) |
19
20
  | 9 | **HTTP GET side effects** | navigation triggers logout links, one-time tokens, private-network / cloud-metadata endpoints | **Not mitigated** | No URL blocklist (redirects and DNS rebinding defeat pre-navigation checks); client-side policy |
@@ -23,6 +24,9 @@ Treat every tool call as privileged.
23
24
  ## Hardening recommendations
24
25
 
25
26
  - Set `NORACU_DISABLE_EVAL=1` unless you actively need `browser_evaluate`.
27
+ - Before an agent touches the iPhone layer: turn on a Focus, open a neutral app,
28
+ and start with `NORACU_READ_ONLY=1`. Prefer "Ask every time" in iPhone
29
+ Mirroring settings unless you need unattended sessions.
26
30
  - Gate `mac_type` / `mac_paste` behind human confirmation when the frontmost
27
31
  app is a password manager or banking site (client-side policy).
28
32
  - Run untrusted automation in a dedicated macOS user account with
@@ -43,7 +43,8 @@ The bundled imctl driver (`imctl/`, Python) runs as a subprocess (`<python3> -m
43
43
 
44
44
  - Observe: `phone_ocr` (coordinates + text), `phone_screenshot` (captures the Mirroring window by CGWindow id, so a covered window still yields its own pixels; region capture is the fallback), `phone_find` (locates text)
45
45
  - Act: `phone_tap/longpress/swipe` (normalized 0-1 coordinates), `phone_home` / `phone_app_switcher` (iPhone Mirroring menu first, imctl gesture fallback), `phone_scroll`, `phone_type` (clipboard-based, IME-safe), `phone_key`
46
- - Session: `phone_status` (running, window, window_id, onscreen, frontmost, paused), `phone_launch` (ensure running + frontmost, clicks Resume when the session shows "Connection Paused"), `phone_open` (Spotlight + OCR + tap)
46
+ - Session: `phone_status` (running, window, window_id, onscreen, frontmost, live, overlay, paused — read from the window's AX structure: a live mirror is one empty AXHostingView group; an overlay such as "Connection Paused" or "iPhone in Use" adds static text and a button), `phone_launch` (ensure running + frontmost, clicks the single Resume button of a paused overlay), `phone_open` (Spotlight via the iPhone Mirroring shortcut, paste the name, tap an exact OCR match above the search field; otherwise back to the Home Screen)
47
+ - Safety: while the mirror is not live, imctl refuses tap/longpress/swipe/scroll/page/type/key/open with exit code 3 and a `mirror_not_live:` line, which the server returns as a tool error; ocr/find prefix a warning. The phone layer has no `element_index`: OCR coordinates are normalized to the window, and nothing re-verifies the target before a tap.
47
48
 
48
49
  ## Configuration
49
50
 
@@ -62,7 +63,7 @@ The bundled imctl driver (`imctl/`, Python) runs as a subprocess (`<python3> -m
62
63
  - Mac-layer actions spawn subprocesses (cliclick/osascript); per-action latency is tens of milliseconds (subprocess spawn; not benchmarked in this release) — a resident FFI process could cut it (see roadmap)
63
64
  - No axState diffing (every observation is a full snapshot)
64
65
  - Single browser session (no tab-level management)
65
- - The iPhone layer requires iPhone Mirroring to be online and the phone unlocked; OCR accuracy depends on screen content; `paused` detection reads the English "Connection Paused" label
66
+ - The iPhone layer requires iPhone Mirroring to be online, with the iPhone locked and near the Mac (unlocking ends mirroring; Apple: unavailable in the EU); OCR accuracy depends on screen content; `paused` detection reads the English "Connection Paused" label
66
67
  - macOS-only (Mac/iPhone layers); the Browser layer is cross-platform
67
68
 
68
69
  ## Roadmap (v2 candidates)
package/docs/tools.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Tool reference
2
2
 
3
3
  > Auto-generated from the running server (`node scripts/gen-tools.mjs`) — always in sync with the implementation.
4
- > noracu v0.1.1 · 35 tools
4
+ > noracu v0.1.2 · 35 tools
5
5
 
6
6
  ## Mac layer (computer-use)
7
7
 
@@ -44,18 +44,18 @@
44
44
 
45
45
  | Tool | Arguments | Description |
46
46
  |---|---|---|
47
- | `phone_status` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, paused). |
48
- | `phone_launch` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and resumed if the connection is paused. |
47
+ | `phone_status` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, live, overlay, paused). |
48
+ | `phone_launch` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and clicks Resume when the connection is paused. |
49
49
  | `phone_screenshot` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered). |
50
50
  | `phone_ocr` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates. |
51
51
  | `phone_find` | text:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen. |
52
- | `phone_tap` | x:number?, y:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. |
52
+ | `phone_tap` | x:number?, y:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused. |
53
53
  | `phone_longpress` | x:number?, y:number?, duration:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds. |
54
- | `phone_swipe` | from:array?, to:array?, ms:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe from [x,y] to [x,y] over an optional duration in ms. |
54
+ | `phone_swipe` | from:array?, to:array?, ms:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll. |
55
55
  | `phone_home` | — | EXPERIMENTAL. Go to the iPhone Home Screen via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl swipe. |
56
56
  | `phone_app_switcher` | — | EXPERIMENTAL. Open the iPhone App Switcher via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl gesture. |
57
- | `phone_scroll` | direction:string?, distance:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by a distance. |
57
+ | `phone_scroll` | direction:string?, distance:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll the list under the mirror up or down by about `distance` window heights (default 0.5), using trackpad-style scroll events. |
58
58
  | `phone_type` | text:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe). |
59
59
  | `phone_key` | key:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. |
60
- | `phone_open` | app:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via Spotlight search plus OCR-guided tap. |
60
+ | `phone_open` | app:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via the mirroring Spotlight menu command/shortcut, type the name, OCR-pick the matching app row and tap it; returns to the home screen when not found. |
61
61
 
package/docs/usage.md CHANGED
@@ -175,24 +175,31 @@ model — don't let it override the task.
175
175
  | `ENOENT` cliclick | `brew install cliclick` or set `NORACU_CLICLICK` |
176
176
  | `… blocked by NORACU_READ_ONLY=1` | you're in observation-only mode — unset it to act |
177
177
  | `browser_evaluate disabled by NORACU_DISABLE_EVAL=1` | eval kill-switch is on |
178
+ | `mirror_not_live: …` | iPhone Mirroring shows an overlay (paused, "iPhone in Use") — lock the iPhone, keep it near the Mac, call `phone_launch` |
178
179
  | `imctl unavailable: no python3 with pyobjc found …` | install pyobjc for a python3 (`python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`) or set `NORACU_PYTHON` |
179
180
 
180
181
  ## 9. iPhone layer
181
182
 
182
- Experimental. The driver (imctl, Python) ships inside the package; the tools
183
- need iPhone Mirroring connected and a python3 with pyobjc (`NORACU_PYTHON`, or
184
- the automatic probe described in the README). A typical session:
183
+ Experimental. The driver (imctl, Python) ships inside the package. The tools
184
+ need Apple's iPhone Mirroring with the iPhone **locked and near the Mac**
185
+ (unlocking it ends the session; not available in the EU) and a python3 with
186
+ pyobjc (`NORACU_PYTHON`, or the automatic probe described in the README).
187
+ The phone exposes no accessibility tree, so this layer is not `element_index`:
188
+ it observes with OCR on the Mac and acts at normalized 0–1 coordinates.
185
189
 
186
190
  ```
187
191
  phone_status
188
- → {"running": true, "window": {...}, "window_id": 275104, "onscreen": true,
189
- "frontmost": false, "paused": true}
192
+ → {"running": true, "window": {...}, "window_id": 278508, "onscreen": true,
193
+ "frontmost": false, "live": false, "overlay": "Connection Paused", "paused": true}
194
+
195
+ phone_tap {"x": 0.5, "y": 0.5} # refused while the mirror is not live
196
+ → ERROR: mirror_not_live: Connection Paused — call phone_launch (or imctl resume) first
190
197
 
191
198
  phone_launch # brings the mirror to the front and clicks Resume
192
199
  → iPhone Mirroring ready
193
200
 
194
201
  phone_status
195
- → {... "paused": false ...}
202
+ → {... "live": true, "overlay": null, "paused": false ...}
196
203
 
197
204
  phone_ocr # OCR of the Mirroring window (captured by window id)
198
205
  → (0.50,0.06) 'Settings' [1.00]
@@ -206,8 +213,27 @@ phone_tap {"x": 0.50, "y": 0.06}
206
213
  → tapped (0.5, 0.06)
207
214
  ```
208
215
 
209
- Coordinates are normalized 0–1 over the mirror window. `phone_screenshot`
210
- returns a PNG of the window's own pixels even when another window covers it.
211
- If the phone is locked, unlock it on the phone; that step cannot be driven
212
- from the Mac. `phone_home` / `phone_app_switcher` go through the iPhone
213
- Mirroring menu and work without python when the mirror is connected.
216
+ `live` / `overlay` / `paused` come from the window's structure, not its
217
+ language: a live mirror is a single empty hosting view; "Connection Paused",
218
+ "iPhone in Use" and similar states add text and a button. While the mirror is
219
+ not live, `phone_tap`, `phone_longpress`, `phone_swipe`, `phone_scroll`,
220
+ `phone_type`, `phone_key` and `phone_open` refuse with `mirror_not_live`, and
221
+ `phone_ocr` / `phone_find` start with a `warning: mirror not live …` line.
222
+
223
+ `phone_scroll {"direction": "down", "distance": 0.5}` moves the list under the
224
+ mirror by about half a window, with trackpad-style scroll events; a vertical
225
+ `phone_swipe` drag does not scroll lists in iPhone Mirroring, so keep swipes
226
+ for gestures such as Home Screen paging.
227
+
228
+ `phone_type` pastes through the clipboard with a real Command-V chord (the
229
+ previous text clipboard is restored). `phone_open {"app": "Calculator"}` opens
230
+ Spotlight through iPhone Mirroring's own shortcut, pastes the name, and taps a
231
+ result whose OCR text matches the name exactly; with no match it returns to the
232
+ Home Screen and reports `app not found`.
233
+
234
+ Privacy: everything the phone shows — notifications, messages, one-time
235
+ codes — becomes tool output that your MCP client sends to its model. Use a
236
+ Focus, open a neutral app first, and start with `NORACU_READ_ONLY=1`
237
+ (phone observation allowed, phone input refused). `phone_home` /
238
+ `phone_app_switcher` go through the iPhone Mirroring menu and work without
239
+ python when the mirror is connected.
package/imctl/README.md CHANGED
@@ -77,7 +77,7 @@ imctl status
77
77
 
78
78
  | Command | Description |
79
79
  |---------|-------------|
80
- | `status` | session + window info (JSON: running, window, window_id, onscreen, frontmost, paused) |
80
+ | `status` | session + window info (JSON: running, window, window_id, onscreen, frontmost, live, overlay, paused) |
81
81
  | `screenshot [PATH]` | capture the mirroring window to PNG by window id (works when covered) |
82
82
  | `resume` | click Resume when the window shows Connection Paused |
83
83
  | `launch` | ensure mirroring is running and frontmost |
@@ -129,8 +129,10 @@ through the Vision framework on-device.
129
129
 
130
130
  ## Limitations
131
131
 
132
- - The iPhone must stay unlocked and connected; lock-screen state is
133
- surfaced by `status` only indirectly (window content freezes).
132
+ - The iPhone must stay **locked** and near the Mac — iPhone Mirroring only
133
+ runs while the phone is locked, and unlocking it ends the session. The
134
+ mirror pauses after inactivity; `status` reports `paused` and `resume`
135
+ clicks Resume. iPhone Mirroring is unavailable in the EU (Apple).
134
136
  - Drag-and-drop between Mac and iPhone is not supported.
135
137
  - Multi-display setups: the window is located by AX query, so it works
136
138
  on any display, but coordinates are always screen-global.
@@ -24,7 +24,37 @@ import json
24
24
  import sys
25
25
 
26
26
  from . import gestures, input, verify, vision
27
- from .window import WindowError
27
+ from .window import WindowError, get_overlay
28
+
29
+
30
+ def _require_live() -> int | None:
31
+ """Refuse phone input while the mirror shows an overlay instead of the phone stream.
32
+
33
+ Returns exit code 3 after printing a `mirror_not_live:` line when the mirror is
34
+ verifiably not live; returns None (allow) when live or unknown (fail-open).
35
+ """
36
+ overlay = get_overlay()
37
+ if overlay["live"] is False:
38
+ label = overlay["overlay"] or "overlay shown"
39
+ print(
40
+ f"mirror_not_live: {label} — call phone_launch (or imctl resume) first",
41
+ file=sys.stderr,
42
+ )
43
+ return 3
44
+ return None
45
+
46
+
47
+ def _warn_if_not_live() -> None:
48
+ """Print a heads-up before ocr/find output when the mirror is not live.
49
+
50
+ The captured pixels then show the overlay (paused/connecting notice), not the phone.
51
+ """
52
+ overlay = get_overlay()
53
+ if overlay["live"] is False:
54
+ print(
55
+ f"warning: mirror not live (overlay: {overlay['overlay'] or 'unknown'}) — "
56
+ "the text below comes from the overlay, not the phone; call phone_launch"
57
+ )
28
58
 
29
59
 
30
60
  def _cmd_status(_args) -> int:
@@ -33,18 +63,27 @@ def _cmd_status(_args) -> int:
33
63
 
34
64
 
35
65
  def _cmd_tap(args) -> int:
66
+ guard = _require_live()
67
+ if guard is not None:
68
+ return guard
36
69
  input.tap(args.x, args.y)
37
70
  print(f"tapped ({args.x}, {args.y})")
38
71
  return 0
39
72
 
40
73
 
41
74
  def _cmd_longpress(args) -> int:
75
+ guard = _require_live()
76
+ if guard is not None:
77
+ return guard
42
78
  input.long_press(args.x, args.y, args.duration)
43
79
  print(f"long-pressed ({args.x}, {args.y}) for {args.duration}s")
44
80
  return 0
45
81
 
46
82
 
47
83
  def _cmd_swipe(args) -> int:
84
+ guard = _require_live()
85
+ if guard is not None:
86
+ return guard
48
87
  input.swipe(args.fx, args.fy, args.tx, args.ty, args.ms)
49
88
  print(f"swiped ({args.fx},{args.fy}) -> ({args.tx},{args.ty})")
50
89
  return 0
@@ -63,6 +102,9 @@ def _cmd_app_switcher(_args) -> int:
63
102
 
64
103
 
65
104
  def _cmd_scroll(args) -> int:
105
+ guard = _require_live()
106
+ if guard is not None:
107
+ return guard
66
108
  if args.direction == "down":
67
109
  gestures.scroll_down(args.distance)
68
110
  else:
@@ -72,6 +114,9 @@ def _cmd_scroll(args) -> int:
72
114
 
73
115
 
74
116
  def _cmd_page(args) -> int:
117
+ guard = _require_live()
118
+ if guard is not None:
119
+ return guard
75
120
  if args.direction == "left":
76
121
  gestures.page_left()
77
122
  else:
@@ -81,18 +126,25 @@ def _cmd_page(args) -> int:
81
126
 
82
127
 
83
128
  def _cmd_type(args) -> int:
129
+ guard = _require_live()
130
+ if guard is not None:
131
+ return guard
84
132
  input.type_text(args.text)
85
133
  print(f"typed {args.text!r}")
86
134
  return 0
87
135
 
88
136
 
89
137
  def _cmd_key(args) -> int:
138
+ guard = _require_live()
139
+ if guard is not None:
140
+ return guard
90
141
  input.press_key(args.key)
91
142
  print(f"pressed {args.key}")
92
143
  return 0
93
144
 
94
145
 
95
146
  def _cmd_ocr(_args) -> int:
147
+ _warn_if_not_live()
96
148
  hits = gestures.read_text()
97
149
  for h in hits:
98
150
  print(h)
@@ -101,6 +153,7 @@ def _cmd_ocr(_args) -> int:
101
153
 
102
154
 
103
155
  def _cmd_find(args) -> int:
156
+ _warn_if_not_live()
104
157
  hit = vision.find(args.text, exact=args.exact)
105
158
  if hit is None:
106
159
  print(f"not found: {args.text!r}", file=sys.stderr)
@@ -110,7 +163,15 @@ def _cmd_find(args) -> int:
110
163
 
111
164
 
112
165
  def _cmd_open(args) -> int:
113
- ok = gestures.open_app(args.app)
166
+ guard = _require_live()
167
+ if guard is not None:
168
+ return guard
169
+ # Open Spotlight here (not inside open_app) so a failure can be
170
+ # reported as its own condition instead of a bogus "app not found".
171
+ if not gestures.open_spotlight():
172
+ print("spotlight unavailable")
173
+ return 1
174
+ ok = gestures.open_app(args.app, spotlight_open=True)
114
175
  print(f"opened {args.app!r}" if ok else f"app not found: {args.app!r}")
115
176
  return 0 if ok else 1
116
177
 
@@ -159,7 +220,7 @@ def build_parser() -> argparse.ArgumentParser:
159
220
  sp = sub.add_parser("screenshot", help="capture the mirroring window to PNG (by window id, works when covered)")
160
221
  sp.add_argument("path", nargs="?", default=None)
161
222
  sp.set_defaults(func=_cmd_screenshot)
162
- sub.add_parser("resume", help="click Resume when the session shows Connection Paused").set_defaults(func=_cmd_resume)
223
+ sub.add_parser("resume", help="click Resume when the session is paused").set_defaults(func=_cmd_resume)
163
224
  sub.add_parser("launch", help="ensure mirroring is running and frontmost").set_defaults(func=_cmd_launch)
164
225
 
165
226
  sp = sub.add_parser("tap", help="tap at normalized coords")
@@ -3,13 +3,20 @@
3
3
  These map to standard iOS interactions. Coordinates are normalized
4
4
  (0-1) within the mirroring window. Gesture start points were chosen to
5
5
  match iOS conventions (e.g. home swipe starts at the very bottom edge).
6
+
7
+ Phone-level actions that the mirroring app exposes as menu commands
8
+ (Spotlight, Home Screen) are triggered through those menus rather than
9
+ synthesized touch gestures — see the menu-command section below.
6
10
  """
7
11
 
8
12
  from __future__ import annotations
9
13
 
14
+ import subprocess
15
+ import time
16
+
10
17
  from . import input as inp
11
18
  from . import vision
12
- from .window import ensure_running, get_bounds
19
+ from .window import WindowError, ensure_frontmost, ensure_running, get_bounds
13
20
 
14
21
 
15
22
  class GestureError(RuntimeError):
@@ -58,16 +65,25 @@ def app_switcher() -> None:
58
65
  ev(kCGEventLeftMouseUp, x1, y1)
59
66
 
60
67
 
68
+ # Wheel pixels per window point of list movement, measured on iPhone Mirroring
69
+ # (Settings list, 524 pt window: between 1.1 and 1.6 px/pt across runs).
70
+ _SCROLL_PX_PER_PT = 1.3
71
+
72
+
61
73
  def scroll_down(distance: float = 0.5) -> None:
62
- """Scroll content down (swipe up) by a normalized distance."""
63
- start = min(0.9, 0.4 + distance / 2)
64
- inp.swipe(0.5, start, 0.5, start - distance, duration_ms=300)
74
+ """Reveal content further down a list by about `distance` window heights.
75
+
76
+ Uses trackpad-style scroll events; a vertical mouse drag does not scroll
77
+ lists in iPhone Mirroring (F16). Swipes stay for gestures such as paging.
78
+ """
79
+ b = get_bounds()
80
+ inp.scroll_trackpad(-distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
65
81
 
66
82
 
67
83
  def scroll_up(distance: float = 0.5) -> None:
68
- """Scroll content up (swipe down) by a normalized distance."""
69
- start = max(0.1, 0.6 - distance / 2)
70
- inp.swipe(0.5, start, 0.5, start + distance, duration_ms=300)
84
+ """Reveal content further up a list by about `distance` window heights."""
85
+ b = get_bounds()
86
+ inp.scroll_trackpad(distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
71
87
 
72
88
 
73
89
  def page_left() -> None:
@@ -81,24 +97,168 @@ def page_right() -> None:
81
97
 
82
98
 
83
99
  def pull_down_search() -> None:
84
- """Swipe down from mid-screen: open Spotlight search."""
100
+ """Swipe down from mid-screen (DEPRECATED — never use for Spotlight).
101
+
102
+ F13: iOS sometimes reads this swipe as an icon long-press-drag, which
103
+ drops the home screen into edit (jiggle) mode — a stray tap on a "−"
104
+ badge there offers to DELETE apps. open_spotlight() replaces it.
105
+ Kept only as a raw gesture primitive; nothing in imctl calls it.
106
+ """
85
107
  inp.swipe(0.5, 0.25, 0.5, 0.75, duration_ms=280)
86
108
 
87
109
 
88
- def open_app(name: str) -> bool:
89
- """Open an app by name via Spotlight + OCR + tap.
110
+ # --- iPhone Mirroring menu commands -----------------------------------------
111
+ #
112
+ # The View menu of iPhone Mirroring exposes phone-level actions (Home
113
+ # Screen, App Switcher, Spotlight) as real menu commands, which iOS
114
+ # cannot misread as touch gestures. We trigger them by keyboard shortcut
115
+ # when one is readable — language-independent, because the shortcut
116
+ # character (AXMenuItemCmdChar), not the localized menu title, drives
117
+ # it — and fall back to clicking the English menu item.
118
+
119
+ # Static AppleScript only (invariant 1): script text is fixed; the menu
120
+ # item name travels as an osascript argument, never interpolated.
121
+ _MENU_SHORTCUT_SCRIPT = '''
122
+ on run(argv)
123
+ tell application "System Events"
124
+ tell process "iPhone Mirroring"
125
+ set cc to ""
126
+ set cm to ""
127
+ try
128
+ set cc to (value of attribute "AXMenuItemCmdChar" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
129
+ end try
130
+ try
131
+ set cm to (value of attribute "AXMenuItemCmdModifiers" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
132
+ end try
133
+ return cc & "," & cm
134
+ end tell
135
+ end tell
136
+ end run
137
+ '''
138
+
139
+ _CLICK_MENU_ITEM_SCRIPT = '''
140
+ on run(argv)
141
+ tell application "System Events"
142
+ tell process "iPhone Mirroring"
143
+ click menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1
144
+ end tell
145
+ end tell
146
+ end run
147
+ '''
148
+
149
+
150
+ def _run_osascript(script: str, args: list[str] | None = None) -> str:
151
+ """Run a static AppleScript; runtime values go through argv only."""
152
+ cmd = ["osascript", "-e", script]
153
+ if args:
154
+ cmd += ["--"] + args
155
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
156
+ if result.returncode != 0:
157
+ raise GestureError(f"osascript failed: {result.stderr.strip()}")
158
+ return result.stdout.strip()
159
+
160
+
161
+ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
162
+ """Read a View menu item's shortcut — read-only, never clicks.
163
+
164
+ Returns (cmdChar, cmdModifiers), or None when unreadable.
165
+ AXMenuItemCmdModifiers uses the Carbon menu-modifier bits: 0 means
166
+ the Command key alone (Spotlight is Cmd+3 here), 1 adds Shift,
167
+ 8 means no key equivalent at all.
168
+ """
169
+ try:
170
+ raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item])
171
+ except (GestureError, OSError, subprocess.TimeoutExpired):
172
+ return None
173
+ char, sep, mods = raw.partition(",")
174
+ if not sep:
175
+ return None
176
+ try:
177
+ return char, int(mods.strip())
178
+ except ValueError: # "missing value" / empty — no usable shortcut
179
+ return None
180
+
181
+
182
+ def _run_view_menu_command(item: str) -> bool:
183
+ """Trigger a View menu command of iPhone Mirroring.
184
+
185
+ Primary: the item's shortcut as a real Command chord (works on any
186
+ UI language). Fallback: clicking the English menu item. Returns
187
+ False when neither path works (app not running, localized menus…).
188
+ """
189
+ shortcut = _view_menu_shortcut(item)
190
+ if shortcut is not None:
191
+ char, mods = shortcut
192
+ keycode = inp.keycode_for_char(char) if mods == 0 else None
193
+ if keycode is not None:
194
+ try:
195
+ ensure_frontmost()
196
+ inp._cmd_chord(keycode)
197
+ return True
198
+ except (inp.InputError, WindowError):
199
+ pass # fall through to clicking the menu item
200
+ try:
201
+ ensure_frontmost()
202
+ _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item])
203
+ return True
204
+ except (GestureError, OSError, subprocess.TimeoutExpired, WindowError):
205
+ return False
206
+
90
207
 
91
- Returns True if the app name was found on screen after typing.
208
+ def open_spotlight() -> bool:
209
+ """Open the phone's Spotlight search (View ▸ Spotlight).
210
+
211
+ Never a swipe: the old pull-down could be misread by iOS as a
212
+ long-press-drag that triggers home-screen edit mode (F13).
92
213
  """
93
- pull_down_search()
94
- import time
214
+ return _run_view_menu_command("Spotlight")
215
+
95
216
 
217
+ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
218
+ """Pick the Spotlight result row for ``name`` from OCR hits.
219
+
220
+ iOS 26 draws the Spotlight search field at the BOTTOM of the screen
221
+ (ny ≈ 0.95) and echoes the typed query inside it, so a plain text
222
+ match finds the field itself. A result row must:
223
+ - equal ``name`` case-insensitively after stripping whitespace, and
224
+ - lie above the bottom search-field zone (ny < 0.88).
225
+ When several rows match, the topmost (smallest ny) wins. Returns
226
+ None when nothing qualifies.
227
+ """
228
+ want = name.strip().lower()
229
+ best = None
230
+ for hit in hits:
231
+ if hit.text.strip().lower() != want:
232
+ continue
233
+ if hit.ny >= 0.88:
234
+ continue # the search field echoing the query
235
+ if best is None or hit.ny < best.ny:
236
+ best = hit
237
+ return best
238
+
239
+
240
+ def open_app(name: str, *, spotlight_open: bool = False) -> bool:
241
+ """Open an app by name: Spotlight → type → OCR → tap the result row.
242
+
243
+ ``spotlight_open`` lets a caller that already ran open_spotlight()
244
+ itself (to tell "spotlight unavailable" apart from "app not found")
245
+ skip the internal call. Returns True when a row matching ``name``
246
+ was tapped; False when Spotlight could not be opened or no row
247
+ matched (after returning to the home screen).
248
+
249
+ The top hit is never opened with Return — it may belong to a
250
+ different app than the requested one.
251
+ """
252
+ if not spotlight_open and not open_spotlight():
253
+ return False
96
254
  time.sleep(1.0)
97
255
  inp.type_text(name)
98
256
  time.sleep(1.5) # wait for Spotlight results
99
257
 
100
- hit = vision.find(name)
258
+ hit = choose_app_hit(vision.read_screen(), name)
101
259
  if hit is None:
260
+ # Leave the phone tidy: back to the home screen (View ▸ Home Screen).
261
+ _run_view_menu_command("Home Screen")
102
262
  return False
103
263
  inp.tap(hit.nx, hit.ny)
104
264
  time.sleep(1.0)
@@ -114,9 +274,12 @@ def status() -> dict:
114
274
  """Return a status dict for the mirroring session.
115
275
 
116
276
  Keys: running; and when running: window {x,y,w,h} (AX bounds), window_id, onscreen, frontmost,
117
- paused (True/False, or null when the "Connection Paused" text cannot be read).
277
+ live (True/False/null — is the phone stream up), overlay (text shown over the stream when not
278
+ live, e.g. a paused/connecting notice), paused (True/False, or null when the state is unknown).
118
279
  """
119
- from .window import get_window_info, is_frontmost, is_paused, is_running
280
+ from .window import (
281
+ get_overlay, get_window_info, is_frontmost, is_paused, is_running,
282
+ )
120
283
 
121
284
  running = is_running()
122
285
  info = {"running": running}
@@ -131,7 +294,10 @@ def status() -> dict:
131
294
  info["window_id"] = wi["id"]
132
295
  info["onscreen"] = wi["onscreen"]
133
296
  info["frontmost"] = is_frontmost()
134
- info["paused"] = is_paused()
297
+ overlay = get_overlay()
298
+ info["live"] = overlay["live"]
299
+ info["overlay"] = overlay["overlay"]
300
+ info["paused"] = is_paused(overlay)
135
301
  return info
136
302
 
137
303
 
@@ -58,6 +58,51 @@ def _source():
58
58
  return CGEventSourceCreate(kCGEventSourceStateHIDSystemState)
59
59
 
60
60
 
61
+ def scroll_steps(total_px: float, steps: int = 24) -> list[int]:
62
+ """Split a scroll distance (wheel pixels) into per-event integer deltas that sum to it."""
63
+ steps = max(4, int(steps))
64
+ target = int(round(total_px))
65
+ out: list[int] = []
66
+ for i in range(1, steps + 1):
67
+ out.append(int(round(target * i / steps)) - sum(out))
68
+ return out
69
+
70
+
71
+ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
72
+ bounds: WindowBounds | None = None) -> None:
73
+ """Scroll like a two-finger trackpad swipe: continuous wheel events with phases.
74
+
75
+ iPhone Mirroring turns these into a touch scroll of the list under the cursor
76
+ (F16: a mouse drag scrolls nothing in a list, and a bare wheel event without a
77
+ phase is ignored). Negative total_px moves the content up, revealing what is
78
+ below. The cursor is moved over the mirror first, because scroll events go to
79
+ the window under the cursor.
80
+ """
81
+ from Quartz import (CGEventCreateScrollWheelEvent, CGEventSetLocation,
82
+ kCGEventMouseMoved, kCGScrollEventUnitPixel,
83
+ kCGScrollWheelEventIsContinuous, kCGScrollWheelEventScrollPhase)
84
+
85
+ ensure_frontmost()
86
+ b = bounds or get_bounds()
87
+ x, y = b.denormalize(nx, ny)
88
+ src = _source()
89
+ _mouse_event(kCGEventMouseMoved, x, y, src)
90
+ time.sleep(0.12)
91
+ deltas = scroll_steps(total_px)
92
+ last = len(deltas) - 1
93
+ for i, d in enumerate(deltas):
94
+ event = CGEventCreateScrollWheelEvent(src, kCGScrollEventUnitPixel, 1, d)
95
+ if event is None:
96
+ raise InputError("CGEventCreateScrollWheelEvent returned None")
97
+ CGEventSetLocation(event, (x, y))
98
+ CGEventSetIntegerValueField(event, kCGScrollWheelEventIsContinuous, 1)
99
+ # NSEvent phases: 1 = began, 2 = changed, 4 = ended
100
+ CGEventSetIntegerValueField(event, kCGScrollWheelEventScrollPhase,
101
+ 1 if i == 0 else (4 if i == last else 2))
102
+ CGEventPost(kCGHIDEventTap, event)
103
+ time.sleep(0.016)
104
+
105
+
61
106
  def _mouse_event(kind: int, x: float, y: float, source) -> None:
62
107
  event = CGEventCreateMouseEvent(
63
108
  source, kind, (x, y), kCGMouseButtonLeft
@@ -170,6 +215,56 @@ _VK_DELETE = 51
170
215
  _VK_ARROW_KEYS = {"up": 126, "down": 125, "left": 123, "right": 124}
171
216
  _VK_V = 9
172
217
  _VK_A = 0
218
+ _VK_COMMAND = 55
219
+
220
+ # ANSI keycodes for digits and letters — the characters a menu-item
221
+ # shortcut can use as its command char (AXMenuItemCmdChar). Translates
222
+ # a shortcut such as Cmd+3 into a keycode for _cmd_chord().
223
+ _ANSI_KEYCODES = {
224
+ "0": 29, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22,
225
+ "7": 26, "8": 28, "9": 25,
226
+ "a": 0, "b": 11, "c": 8, "d": 2, "e": 14, "f": 3, "g": 5, "h": 4,
227
+ "i": 34, "j": 38, "k": 40, "l": 37, "m": 46, "n": 45, "o": 31,
228
+ "p": 35, "q": 12, "r": 15, "s": 1, "t": 17, "u": 32, "v": 9,
229
+ "w": 13, "x": 7, "y": 16, "z": 6,
230
+ }
231
+
232
+
233
+ def keycode_for_char(char: str) -> int | None:
234
+ """ANSI virtual keycode for a single digit/letter, else None."""
235
+ if len(char) != 1:
236
+ return None
237
+ return _ANSI_KEYCODES.get(char.lower())
238
+
239
+
240
+ def _cmd_chord(keycode: int) -> None:
241
+ """Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
242
+
243
+ iPhone Mirroring forwards the *state* of the physical modifier
244
+ keys, not the per-event flag bits: a target-key event that merely
245
+ carries kCGEventFlagMaskCommand arrives on the phone as an
246
+ unmodified keystroke (F14 — a "Cmd+V" paste typed a literal "v").
247
+ The chord therefore presses the Command key itself, keeps the
248
+ flag set on every event, and releases Command last. ~30ms between
249
+ steps, all events from one shared source.
250
+ """
251
+ ensure_frontmost()
252
+ src = _source()
253
+
254
+ def post(code: int, down: bool, flags: int) -> None:
255
+ event = CGEventCreateKeyboardEvent(src, code, down)
256
+ if event is None:
257
+ raise InputError(f"CGEventCreateKeyboardEvent returned None for {code}")
258
+ CGEventSetFlags(event, flags)
259
+ CGEventPost(kCGHIDEventTap, event)
260
+
261
+ post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
262
+ time.sleep(0.03)
263
+ post(keycode, True, kCGEventFlagMaskCommand)
264
+ time.sleep(0.03)
265
+ post(keycode, False, kCGEventFlagMaskCommand)
266
+ time.sleep(0.03)
267
+ post(_VK_COMMAND, False, 0)
173
268
 
174
269
 
175
270
  def press_key(key: str) -> None:
@@ -209,14 +304,7 @@ def type_text(text: str) -> None:
209
304
  pb.setString_forType_(text, "public.utf8-plain-text")
210
305
  time.sleep(0.05)
211
306
 
212
- src = _source()
213
- v_down = CGEventCreateKeyboardEvent(src, _VK_V, True)
214
- CGEventSetFlags(v_down, kCGEventFlagMaskCommand)
215
- CGEventPost(kCGHIDEventTap, v_down)
216
- time.sleep(0.05)
217
- v_up = CGEventCreateKeyboardEvent(src, _VK_V, False)
218
- CGEventSetFlags(v_up, kCGEventFlagMaskCommand)
219
- CGEventPost(kCGHIDEventTap, v_up)
307
+ _cmd_chord(_VK_V) # real ⌘ chord — flags alone reach the phone as "v" (F14)
220
308
  time.sleep(0.15) # let the paste land before restoring
221
309
  finally:
222
310
  # Restore the user's clipboard only if nothing else changed it.
@@ -229,18 +317,9 @@ def type_text(text: str) -> None:
229
317
  def clear_text() -> None:
230
318
  """Select-all and delete in the focused field."""
231
319
  ensure_frontmost()
232
- src = _source()
233
- for keycode, flags in (
234
- (_VK_A, kCGEventFlagMaskCommand), # Cmd+A
235
- ):
236
- e = CGEventCreateKeyboardEvent(src, keycode, True)
237
- CGEventSetFlags(e, flags)
238
- CGEventPost(kCGHIDEventTap, e)
239
- time.sleep(0.03)
240
- e = CGEventCreateKeyboardEvent(src, keycode, False)
241
- CGEventSetFlags(e, flags)
242
- CGEventPost(kCGHIDEventTap, e)
320
+ _cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
243
321
  time.sleep(0.05)
322
+ src = _source()
244
323
  _key_event(_VK_DELETE, True, src)
245
324
  time.sleep(0.02)
246
325
  _key_event(_VK_DELETE, False, src)
@@ -64,7 +64,7 @@ end tell
64
64
  '''
65
65
 
66
66
 
67
- def _run_osascript(script: str) -> str:
67
+ def _run_osascript(script: str, *, strip: bool = True) -> str:
68
68
  result = subprocess.run(
69
69
  ["osascript", "-e", script],
70
70
  capture_output=True,
@@ -73,7 +73,7 @@ def _run_osascript(script: str) -> str:
73
73
  )
74
74
  if result.returncode != 0:
75
75
  raise WindowError(f"osascript failed: {result.stderr.strip()}")
76
- return result.stdout.strip()
76
+ return result.stdout.strip() if strip else result.stdout
77
77
 
78
78
 
79
79
  def is_running() -> bool:
@@ -152,25 +152,64 @@ def get_bounds() -> WindowBounds:
152
152
  return WindowBounds(x=x, y=y, width=w, height=h)
153
153
 
154
154
 
155
- _PAUSED_SCRIPT = '''
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
+
156
176
  tell application "System Events"
157
177
  tell process "iPhone Mirroring"
178
+ set winCount to count of windows
179
+ if winCount is 0 then return "NO_WINDOW"
158
180
  tell window 1
159
- return (exists (static text "Connection Paused" of group 1)) as text
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
160
201
  end tell
161
202
  end tell
162
203
  end tell
163
204
  '''
164
205
 
165
- _RESUME_SCRIPT = '''
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 = '''
166
209
  tell application "System Events"
167
210
  tell process "iPhone Mirroring"
168
211
  tell window 1
169
- if exists (static text "Connection Paused" of group 1) then
170
- click button 1 of group 1
171
- return "clicked"
172
- end if
173
- return "not-paused"
212
+ click button 1 of group 1
174
213
  end tell
175
214
  end tell
176
215
  end tell
@@ -219,30 +258,95 @@ def is_frontmost() -> bool:
219
258
  return False
220
259
 
221
260
 
222
- def is_paused() -> bool | None:
223
- """True when the window shows "Connection Paused"; None when that cannot be read (e.g. localized UI)."""
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
+ """
224
304
  try:
225
- return _run_osascript(_PAUSED_SCRIPT) == "true"
226
- except WindowError:
227
- return None
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
228
327
 
229
328
 
230
329
  def resume() -> bool:
231
- """Click the Resume control when the session is paused.
330
+ """Click the Resume control when the session is paused (language-independent).
232
331
 
233
- Returns True when the session is not paused afterwards (or was never paused). The phone may still
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
234
335
  ask for Face ID / passcode on its own screen; that part cannot be automated from the Mac.
235
336
  """
236
337
  import time
237
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
238
344
  try:
239
- out = _run_osascript(_RESUME_SCRIPT)
345
+ _run_osascript(_CLICK_RESUME_SCRIPT)
240
346
  except WindowError:
241
347
  return False
242
- if out == "not-paused":
243
- return True
244
- for _ in range(10): # up to ~5 s for the stream to come back
348
+ for _ in range(12): # up to ~6 s for the stream to come back
245
349
  time.sleep(0.5)
246
- if is_paused() is False:
350
+ if get_overlay()["live"] is True:
247
351
  return True
248
352
  return False
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.1.1",
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": {
package/src/server.mjs CHANGED
@@ -83,6 +83,10 @@ function imctl(...args) {
83
83
  });
84
84
  return { ok: true, out: out.trim() };
85
85
  } catch (e) {
86
+ // G23(0.1.2):镜像不在线时 imctl 拒绝输入(退出码 3,stderr 带 mirror_not_live: 行)——
87
+ // 原样透传那一行,不归类为 imctl unavailable(这是可恢复的调用方错误,不是环境缺失)
88
+ const guard = (String(e.stderr || "") + "\n" + String(e.stdout || "")).match(/^mirror_not_live:.*$/m);
89
+ if (guard) return { ok: false, out: guard[0].trim() };
86
90
  const raw = String(e.stderr || e.stdout || e.message);
87
91
  // Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
88
92
  if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
@@ -786,20 +790,20 @@ const TOOLS = [
786
790
  { name: "browser_evaluate", desc: "Evaluate JavaScript in the page and return the result.", args: { js: "string" }, fn: browserEvaluate },
787
791
  { name: "browser_close", desc: "Close the browser.", args: {}, fn: browserClose },
788
792
  // iPhone device-use(imctl)
789
- { name: "phone_status", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, paused).", args: {}, fn: phoneStatus },
790
- { name: "phone_launch", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and resumed if the connection is paused.", args: {}, fn: phoneLaunch },
793
+ { name: "phone_status", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, live, overlay, paused).", args: {}, fn: phoneStatus },
794
+ { name: "phone_launch", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and clicks Resume when the connection is paused.", args: {}, fn: phoneLaunch },
791
795
  { name: "phone_screenshot", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered).", args: {}, fn: phoneScreenshot },
792
796
  { name: "phone_ocr", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates.", args: {}, fn: phoneOcr },
793
797
  { name: "phone_find", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen.", args: { text: "string" }, fn: phoneFind },
794
- { name: "phone_tap", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates.", args: { x: "number", y: "number" }, fn: phoneTap },
798
+ { name: "phone_tap", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused.", args: { x: "number", y: "number" }, fn: phoneTap },
795
799
  { name: "phone_longpress", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds.", args: { x: "number", y: "number", duration: "number?" }, fn: phoneLongpress },
796
- { name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe from [x,y] to [x,y] over an optional duration in ms.", args: { from: "array", to: "array", ms: "number?" }, fn: phoneSwipe },
800
+ { name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll.", args: { from: "array", to: "array", ms: "number?" }, fn: phoneSwipe },
797
801
  { name: "phone_home", desc: "EXPERIMENTAL. Go to the iPhone Home Screen via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl swipe.", args: {}, fn: phoneHome },
798
802
  { name: "phone_app_switcher", desc: "EXPERIMENTAL. Open the iPhone App Switcher via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl gesture.", args: {}, fn: phoneAppSwitcher },
799
- { name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by a distance.", args: { direction: "string?", distance: "number?" }, fn: phoneScroll },
803
+ { name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll the list under the mirror up or down by about `distance` window heights (default 0.5), using trackpad-style scroll events.", args: { direction: "string?", distance: "number?" }, fn: phoneScroll },
800
804
  { name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe).", args: { text: "string" }, fn: phoneType },
801
805
  { name: "phone_key", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right.", args: { key: "string" }, fn: phoneKey },
802
- { name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via Spotlight search plus OCR-guided tap.", args: { app: "string" }, fn: phoneOpen },
806
+ { name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via the mirroring Spotlight menu command/shortcut, type the name, OCR-pick the matching app row and tap it; returns to the home screen when not found.", args: { app: "string" }, fn: phoneOpen },
803
807
  ];
804
808
 
805
809
  // ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──