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.
package/src/server.mjs CHANGED
@@ -27,8 +27,8 @@ import { createRequire } from "node:module";
27
27
 
28
28
  // ── 配置(开源友好:环境变量覆盖 + 同级目录解析)──
29
29
  const __dirname = fileURLToPath(new URL(".", import.meta.url));
30
- // imctl 默认按同级 checkout 解析(…/code/noracu → …/code/imctl),可用 NORACU_IMCTL_DIR 覆盖
31
- const IMCTL_DIR = process.env.NORACU_IMCTL_DIR || join(__dirname, "..", "..", "imctl");
30
+ // imctl (the iPhone Mirroring driver, Python) ships inside the package at imctl/; NORACU_IMCTL_DIR overrides it (e.g. a dev checkout)
31
+ const IMCTL_DIR = process.env.NORACU_IMCTL_DIR || join(__dirname, "..", "imctl");
32
32
  const CLICLICK = process.env.NORACU_CLICLICK || "/opt/homebrew/bin/cliclick";
33
33
  if (!existsSync(IMCTL_DIR)) {
34
34
  process.stderr.write(`[noracu] warning: imctl not found at ${IMCTL_DIR} — phone_* tools will fail. Set NORACU_IMCTL_DIR.\n`);
@@ -47,23 +47,54 @@ function sh(cmd, args, timeoutMs = 15000) {
47
47
  }
48
48
  }
49
49
 
50
+ // The iPhone layer runs the bundled imctl (Python) and needs an interpreter that has pyobjc (Quartz, Vision, AppKit).
51
+ // Resolution: NORACU_PYTHON if set, else the first candidate that imports Quartz. Probed once, lazily, on the first
52
+ // phone_* call, so the Mac and browser layers pay nothing. Apple's /usr/bin/python3 usually lacks pyobjc; Homebrew's
53
+ // python3 plus the three pyobjc-framework-* packages is the common working setup.
54
+ const PYTHON_CANDIDATES = ["/opt/homebrew/bin/python3", "/usr/local/bin/python3", "python3", "/usr/bin/python3"];
55
+ const PYOBJC_INSTALL = "python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit";
56
+ let pythonProbe = null; // { path, tried } once resolved; path === null when nothing qualified
57
+ function pythonArgv(path) { return path === "python3" ? ["/usr/bin/env", ["python3"]] : [path, []]; }
58
+ function resolvePython() {
59
+ if (pythonProbe) return pythonProbe;
60
+ const tried = [];
61
+ for (const cand of (process.env.NORACU_PYTHON ? [process.env.NORACU_PYTHON] : PYTHON_CANDIDATES)) {
62
+ const [cmd, pre] = pythonArgv(cand);
63
+ try {
64
+ execFileSync(cmd, [...pre, "-c", "import Quartz, Vision, AppKit"], { timeout: 20000, stdio: ["ignore", "ignore", "ignore"] });
65
+ pythonProbe = { path: cand, tried };
66
+ return pythonProbe;
67
+ } catch { tried.push(cand); }
68
+ }
69
+ pythonProbe = { path: null, tried };
70
+ return pythonProbe;
71
+ }
72
+
50
73
  function imctl(...args) {
74
+ const py = resolvePython();
75
+ if (!py.path) {
76
+ return { ok: false, out: `imctl unavailable: no python3 with pyobjc found (tried ${py.tried.join(", ")}) — run \`${PYOBJC_INSTALL}\` for the python3 you want, or set NORACU_PYTHON=/path/to/python3 (see README)` };
77
+ }
78
+ const [cmd, pre] = pythonArgv(py.path);
51
79
  try {
52
- const out = execFileSync("/usr/bin/env", ["python3", "-m", "imctl.cli", ...args], {
80
+ const out = execFileSync(cmd, [...pre, "-m", "imctl.cli", ...args], {
53
81
  timeout: 30000, encoding: "utf8", maxBuffer: 10 * 1024 * 1024,
54
- cwd: IMCTL_DIR, env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src") },
82
+ cwd: IMCTL_DIR, env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src"), PYTHONDONTWRITEBYTECODE: "1" },
55
83
  });
56
84
  return { ok: true, out: out.trim() };
57
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() };
58
90
  const raw = String(e.stderr || e.stdout || e.message);
59
- // imctl 不可用 —— checkout 缺失,或 python3 没有 pyobjc(Quartz)。
60
- // 把 Python traceback / spawn 错误收敛成一行可操作信息,phone_* 因此干净失败、测试可据此跳过(优雅降级)。
91
+ // Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
61
92
  if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
62
93
  const mod = (raw.match(/No module named '([^']+)'/) || [])[1];
63
- return { ok: false, out: `imctl unavailable: its python3 is missing ${mod ? `the ${mod} module (pyobjc)` : "pyobjc"} — install pyobjc for that python, or point NORACU_IMCTL_DIR at a checkout whose python has it (see README)` };
94
+ return { ok: false, out: `imctl unavailable: ${py.path} is missing ${mod ? `the ${mod} module` : "a module"} — run \`${PYOBJC_INSTALL}\` for that python, or set NORACU_PYTHON (see README)` };
64
95
  }
65
96
  if (/ENOENT|No such file or directory/.test(raw)) {
66
- return { ok: false, out: `imctl unavailable: cannot run python3 for imctl at ${IMCTL_DIR} — install imctl or set NORACU_IMCTL_DIR (see README)` };
97
+ return { ok: false, out: `imctl unavailable: cannot run imctl at ${IMCTL_DIR} — the bundled imctl/ directory is missing or NORACU_IMCTL_DIR points to the wrong place (see README)` };
67
98
  }
68
99
  return { ok: false, out: raw.slice(0, 500) };
69
100
  }
@@ -700,21 +731,16 @@ function phoneOpen(args) {
700
731
  return imctl("open", args.app);
701
732
  }
702
733
  function phoneScreenshot() {
703
- // Mirroring 窗口截图(imctl status 拿窗口 frame → screencapture -R)
704
- const st = imctl("status");
705
- if (!st.ok) return { error: "imctl status failed: " + st.out.slice(0, 150) };
734
+ // Captured by imctl by CGWindow id, so it is the Mirroring window's own pixels even when another window covers it.
735
+ const file = join(tmpdir(), `noracu-phone-${randomUUID().slice(0, 8)}.png`);
736
+ const r = imctl("screenshot", file);
737
+ if (!r.ok) return { error: r.out.slice(0, 300) };
706
738
  try {
707
- const j = JSON.parse(st.out);
708
- const w = j.window;
709
- if (!w) return { error: "no mirroring window" };
710
- const file = join(tmpdir(), `noracu-phone-${randomUUID().slice(0, 8)}.png`);
711
- const r = sh("/usr/sbin/screencapture", ["-x", "-R", `${w.x},${w.y},${w.w},${w.h}`, file]);
712
- if (!r.ok) return { error: r.out };
713
739
  const data = readFileSync(file).toString("base64");
714
740
  unlinkSync(file);
715
741
  return { image: data, mime: "image/png" };
716
742
  } catch (e) {
717
- return { error: "parse status failed: " + String(e.message).slice(0, 150) };
743
+ return { error: "screenshot file missing: " + String(e.message).slice(0, 150) };
718
744
  }
719
745
  }
720
746
 
@@ -764,20 +790,20 @@ const TOOLS = [
764
790
  { name: "browser_evaluate", desc: "Evaluate JavaScript in the page and return the result.", args: { js: "string" }, fn: browserEvaluate },
765
791
  { name: "browser_close", desc: "Close the browser.", args: {}, fn: browserClose },
766
792
  // iPhone device-use(imctl)
767
- { name: "phone_status", desc: "EXPERIMENTAL. Requires imctl (not yet public). Return the iPhone Mirroring session status as JSON.", args: {}, fn: phoneStatus },
768
- { name: "phone_launch", desc: "EXPERIMENTAL. Requires imctl (not yet public). Ensure iPhone Mirroring is running and brought to the front.", args: {}, fn: phoneLaunch },
769
- { name: "phone_screenshot", desc: "EXPERIMENTAL. Requires imctl (not yet public). Screenshot the iPhone screen (the Mirroring window region).", args: {}, fn: phoneScreenshot },
770
- { name: "phone_ocr", desc: "EXPERIMENTAL. Requires imctl (not yet public). OCR the iPhone screen into text with coordinates.", args: {}, fn: phoneOcr },
771
- { name: "phone_find", desc: "EXPERIMENTAL. Requires imctl (not yet public). Locate text on the iPhone screen.", args: { text: "string" }, fn: phoneFind },
772
- { name: "phone_tap", desc: "EXPERIMENTAL. Requires imctl (not yet public). Tap at {x, y} in normalized 0-1 coordinates.", args: { x: "number", y: "number" }, fn: phoneTap },
773
- { name: "phone_longpress", desc: "EXPERIMENTAL. Requires imctl (not yet public). Long-press at {x, y} for an optional duration in seconds.", args: { x: "number", y: "number", duration: "number?" }, fn: phoneLongpress },
774
- { name: "phone_swipe", desc: "EXPERIMENTAL. Requires imctl (not yet public). Swipe from [x,y] to [x,y] over an optional duration in ms.", args: { from: "array", to: "array", ms: "number?" }, fn: phoneSwipe },
775
- { name: "phone_home", desc: "EXPERIMENTAL. Go to the iPhone Home Screen via the iPhone Mirroring menu (works without imctl when the mirror is connected); falls back to an imctl swipe.", args: {}, fn: phoneHome },
776
- { name: "phone_app_switcher", desc: "EXPERIMENTAL. Open the iPhone App Switcher via the iPhone Mirroring menu (works without imctl when the mirror is connected); falls back to an imctl gesture.", args: {}, fn: phoneAppSwitcher },
777
- { name: "phone_scroll", desc: "EXPERIMENTAL. Requires imctl (not yet public). Scroll up or down by a distance.", args: { direction: "string?", distance: "number?" }, fn: phoneScroll },
778
- { name: "phone_type", desc: "EXPERIMENTAL. Requires imctl (not yet public). Type text via the clipboard (IME-safe).", args: { text: "string" }, fn: phoneType },
779
- { name: "phone_key", desc: "EXPERIMENTAL. Requires imctl (not yet public). Press a key: return, delete, up, down, left, or right.", args: { key: "string" }, fn: phoneKey },
780
- { name: "phone_open", desc: "EXPERIMENTAL. Requires imctl (not yet public). Open an app via Spotlight search plus OCR-guided tap.", args: { app: "string" }, fn: phoneOpen },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
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 },
781
807
  ];
782
808
 
783
809
  // ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──