noracu 0.1.2 → 0.1.4

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
@@ -21,7 +21,7 @@ import { spawn, execFileSync, spawnSync } from "node:child_process";
21
21
  import { readFileSync, writeFileSync, unlinkSync, existsSync } from "node:fs";
22
22
  import { homedir, tmpdir } from "node:os";
23
23
  import { join, dirname } from "node:path";
24
- import { randomUUID } from "node:crypto";
24
+ import { randomUUID, createHash } from "node:crypto";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { createRequire } from "node:module";
27
27
 
@@ -34,6 +34,36 @@ 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`);
35
35
  }
36
36
 
37
+ // ── F23:进程/磁盘漂移检测(server 进程比磁盘上的文件旧时提示调用方)──
38
+ // MCP 客户端(如 Claude Desktop)会把 server 进程常驻数小时;磁盘上的 package.json /
39
+ // src/server.mjs 升级后,进程里跑的仍是启动时加载的旧代码(旧版本号、旧工具描述),
40
+ // 实际形成"旧 server + 新 imctl 驱动"混跑,调用方照旧描述传参会踩坑(F20 的根因之一)。
41
+ // 注意:git 切分支同样会改写 src/server.mjs 的内容 —— 这时下面的提示同样成立,因为
42
+ // 进程里的代码确实与磁盘不同。启动时快照一次 LOADED,每次 tools/call 现读磁盘对比
43
+ // (两个文件都很小,不做缓存)。
44
+ const PKG_JSON = join(__dirname, "..", "package.json");
45
+ const SERVER_MJS = join(__dirname, "server.mjs"); // 本文件
46
+ const sha256OfFile = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
47
+ const LOADED = (() => {
48
+ try {
49
+ return { version: JSON.parse(readFileSync(PKG_JSON, "utf8")).version, sha256: sha256OfFile(SERVER_MJS), at: new Date().toISOString() };
50
+ } catch {
51
+ return { version: "0.0.0", sha256: null, at: new Date().toISOString() };
52
+ }
53
+ })();
54
+
55
+ // 版本或哈希任一与磁盘不同 → 一行英文提示;读磁盘失败或一致 → null(不报错、不影响工具执行)
56
+ function staleServerNote() {
57
+ try {
58
+ const diskVersion = JSON.parse(readFileSync(PKG_JSON, "utf8")).version;
59
+ const hashChanged = LOADED.sha256 !== null && LOADED.sha256 !== sha256OfFile(SERVER_MJS);
60
+ if (LOADED.version === diskVersion && !hashChanged) return null;
61
+ return `noracu: this server process is stale: it loaded ${LOADED.version} at ${LOADED.at}, but the files on disk are ${diskVersion}${hashChanged ? " (src/server.mjs changed)" : ""}. Restart the MCP client to load them.`;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
37
67
  // ── 工具实现 ──────────────────────────────────────────────
38
68
 
39
69
  function sh(cmd, args, timeoutMs = 15000) {
@@ -55,49 +85,257 @@ const PYTHON_CANDIDATES = ["/opt/homebrew/bin/python3", "/usr/local/bin/python3"
55
85
  const PYOBJC_INSTALL = "python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit";
56
86
  let pythonProbe = null; // { path, tried } once resolved; path === null when nothing qualified
57
87
  function pythonArgv(path) { return path === "python3" ? ["/usr/bin/env", ["python3"]] : [path, []]; }
88
+ // F39 (2026-11-05): execFileSync's timeout only sends a signal and then keeps waiting for the
89
+ // child to exit. On 2026-11-04 an imctl child stuck in an uninterruptible wait never exited, so
90
+ // the whole server stopped answering — tools/call, tools/list, even ping — for minutes. Every
91
+ // iPhone-layer subprocess now runs asynchronously under its own timer and in its own process
92
+ // group. On expiry the group gets SIGTERM (imctl turns it into SystemExit, so its cleanup runs),
93
+ // then SIGKILL after a short grace; the call resolves at once either way, and the event loop
94
+ // stays free throughout. Invariant 1 holds: an argv array, never a shell string.
95
+ const IMCTL_DEFAULT_TIMEOUT_MS = 30000;
96
+ // open = Spotlight + type + several OCR reads + confirm; type = paste + 2.5 s check + late-paste watch
97
+ const IMCTL_TIMEOUT_MS = new Map([["open", 45000], ["type", 45000]]);
98
+ const IMCTL_MAX_OUTPUT = 10 * 1024 * 1024;
99
+ // NORACU_PHONE_TIMEOUT_MS (an integer 1000–600000) replaces every phone_* subprocess timeout,
100
+ // e.g. for a slow Mac. An invalid value is ignored with a warning on stderr.
101
+ const PHONE_TIMEOUT_OVERRIDE = (() => {
102
+ const raw = process.env.NORACU_PHONE_TIMEOUT_MS;
103
+ if (raw === undefined || raw === "") return null;
104
+ const n = Number(raw);
105
+ if (Number.isInteger(n) && n >= 1000 && n <= 600000) return n;
106
+ process.stderr.write(`[noracu] ignoring NORACU_PHONE_TIMEOUT_MS=${JSON.stringify(raw)}: expected an integer from 1000 to 600000\n`);
107
+ return null;
108
+ })();
109
+ // open_app keeps its own time budget so that it, not the server's kill, ends a slow run (it then
110
+ // goes back to the Home Screen). The server hands it an absolute deadline — counted from the
111
+ // spawn, so interpreter start-up and opening Spotlight are inside it — this far before its own
112
+ // timeout: room for the last tap, its confirmation reads and the trip back to the Home Screen.
113
+ const OPEN_DEADLINE_MARGIN_MS = 15000; // at most 40 % of the timeout (a small NORACU_PHONE_TIMEOUT_MS)
114
+ // The Home Screen trip the server makes itself after an `open` timeout still holds the input
115
+ // queue, so it gets a short limit of its own (a queued call gives up after QUEUE_WAIT_LIMIT_MS).
116
+ const TIDY_MENU_TIMEOUT_MS = 6000;
117
+ // What imctl prints when phone_open could not get back to the Home Screen (cli._open_and_report).
118
+ const OPEN_HOME_FAILED = "could not go back to the Home Screen — Spotlight may still be open";
119
+ const KILL_GRACE_MS = 1500; // SIGTERM → SIGKILL
120
+ const REAP_WAIT_MS = 1000; // after SIGKILL, how long the input queue waits for the group to go
121
+
122
+ // Children that outlived their timeout. The input queue (below) does not start the next phone or
123
+ // Mac action until each of them has exited or was given up on (KILL_GRACE_MS + REAP_WAIT_MS), so a
124
+ // killed imctl can never act at the same time as the next call.
125
+ const lingering = new Set();
126
+ // Every running child, so a server that exits does not leave a detached imctl acting on its own.
127
+ // The exit hook cannot wait for a grace period, so it kills outright (SIGKILL): an imctl that
128
+ // keeps tapping after its server is gone is worse than skipped cleanup.
129
+ const activeChildren = new Set();
130
+ process.on("exit", () => { for (const c of activeChildren) signalGroup(c, "SIGKILL"); });
131
+ // An MCP client usually stops the server with a signal, and "exit" does not fire for an
132
+ // unhandled one. The server then exits as the default action would, killing its children first —
133
+ // unless another listener handles the signal too: Playwright does while it has a browser open,
134
+ // closes that browser gracefully (the persistent profile is flushed) and decides about exiting
135
+ // itself, exactly as before. Then the server stays up, and a running imctl only gets SIGTERM: it
136
+ // tidies up (e.g. leaves Spotlight) and the input queue waits for it as usual. (On SIGINT
137
+ // Playwright exits once the browser is closed, and the exit hook then kills any child still
138
+ // running — its tidy-up is best effort there.)
139
+ for (const [sig, n] of [["SIGTERM", 15], ["SIGINT", 2], ["SIGHUP", 1]]) {
140
+ process.on(sig, () => {
141
+ const exiting = process.listenerCount(sig) <= 1;
142
+ for (const c of activeChildren) signalGroup(c, exiting ? "SIGKILL" : "SIGTERM");
143
+ if (exiting) process.exit(128 + n);
144
+ });
145
+ }
146
+
147
+ function signalGroup(child, sig) {
148
+ try { process.kill(-child.pid, sig); return; } catch { /* no group (spawn failed) or already gone */ }
149
+ try { child.kill(sig); } catch { /* already gone */ }
150
+ }
151
+
152
+ async function runAsync(cmd, argv, opts) {
153
+ // A child left behind by a timed-out step must be gone before the next one starts — across
154
+ // calls (the input queue drains too) and within one call (e.g. phone_home's menu command timing
155
+ // out, then its gesture fallback).
156
+ if (lingering.size) await Promise.all([...lingering]);
157
+ return spawnTimed(cmd, argv, opts);
158
+ }
159
+
160
+ function spawnTimed(cmd, argv, { timeoutMs, cwd, env }) {
161
+ return new Promise((resolve) => {
162
+ let stdout = "", stderr = "", size = 0, done = false, exited = false, child = null, timer = null;
163
+ const finish = (r) => {
164
+ if (done) return;
165
+ done = true;
166
+ clearTimeout(timer);
167
+ resolve({ stdout, stderr, ...r });
168
+ };
169
+ const terminate = () => {
170
+ if (exited) return;
171
+ signalGroup(child, "SIGTERM");
172
+ const gone = new Promise((res) => {
173
+ const killer = setTimeout(() => {
174
+ if (exited) return;
175
+ signalGroup(child, "SIGKILL");
176
+ child.stdout?.destroy(); child.stderr?.destroy(); // let go of a child that will not die
177
+ }, KILL_GRACE_MS);
178
+ const giveUp = setTimeout(res, KILL_GRACE_MS + REAP_WAIT_MS);
179
+ child.once("close", () => { clearTimeout(killer); clearTimeout(giveUp); res(); });
180
+ });
181
+ lingering.add(gone);
182
+ gone.then(() => lingering.delete(gone));
183
+ };
184
+ try {
185
+ // detached: own process group, so osascript / screencapture grandchildren go with it
186
+ child = spawn(cmd, argv, { cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
187
+ } catch (error) {
188
+ finish({ code: null, error });
189
+ return;
190
+ }
191
+ activeChildren.add(child);
192
+ timer = setTimeout(() => { terminate(); finish({ code: null, timedOut: true }); }, timeoutMs);
193
+ const collect = (which) => (chunk) => {
194
+ if (done) return;
195
+ size += chunk.length;
196
+ if (size > IMCTL_MAX_OUTPUT) { terminate(); finish({ code: null, overflow: true }); return; }
197
+ if (which === "out") stdout += chunk; else stderr += chunk;
198
+ };
199
+ child.stdout.setEncoding("utf8");
200
+ child.stderr.setEncoding("utf8");
201
+ child.stdout.on("data", collect("out"));
202
+ child.stderr.on("data", collect("err"));
203
+ child.on("error", (error) => { activeChildren.delete(child); finish({ code: null, error }); });
204
+ child.on("close", (code, signal) => { exited = true; activeChildren.delete(child); finish({ code, signal }); });
205
+ });
206
+ }
207
+
208
+ // The probe result is cached for the life of the process only when it is definite: a candidate
209
+ // that imports pyobjc, or every candidate failing outright (missing, or exiting non-zero). A probe
210
+ // that timed out (a loaded or stuck Mac) is not cached, so the next phone_* call probes again
211
+ // instead of reporting "imctl unavailable" until a restart.
212
+ let pythonProbing = null; // the in-flight probe, so concurrent first calls share one
58
213
  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);
214
+ if (pythonProbe) return Promise.resolve(pythonProbe);
215
+ if (pythonProbing) return pythonProbing;
216
+ const probing = (async () => {
217
+ const tried = [];
218
+ let definite = true;
63
219
  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;
220
+ for (const cand of (process.env.NORACU_PYTHON ? [process.env.NORACU_PYTHON] : PYTHON_CANDIDATES)) {
221
+ const [cmd, pre] = pythonArgv(cand);
222
+ const r = await runAsync(cmd, [...pre, "-c", "import Quartz, Vision, AppKit"], { timeoutMs: 20000 });
223
+ if (!r.error && !r.timedOut && r.code === 0) { pythonProbe = { path: cand, tried }; return pythonProbe; }
224
+ // definite: the interpreter is missing (ENOENT) or ran and exited non-zero; a timeout, a
225
+ // signal or any other spawn error says nothing lasting about it
226
+ if (!(r.error?.code === "ENOENT" || (!r.error && !r.timedOut && r.code !== null && !r.signal))) definite = false;
227
+ tried.push(r.timedOut ? `${cand} (timed out)` : cand);
228
+ }
229
+ } catch { definite = false; }
230
+ const result = { path: null, tried };
231
+ if (definite) pythonProbe = result;
232
+ return result;
233
+ })();
234
+ pythonProbing = probing;
235
+ const clear = () => { if (pythonProbing === probing) pythonProbing = null; };
236
+ probing.then(clear, clear);
237
+ return probing;
71
238
  }
72
239
 
73
- function imctl(...args) {
74
- const py = resolvePython();
240
+ // imctl 拒绝输入时在 stderr 打印 `前缀: 说明` 行。这些是可恢复的调用方错误(不是环境缺失),
241
+ // 原样透传匹配到的那一行,不归类为 imctl unavailable。后续任务会往列表里追加更多前缀。
242
+ // "app not found" (phone_open, printed on stdout) is taken from stdout or stderr as one whole line, so a
243
+ // warning on stderr or a long label list cannot hide the "could not go back" note retryOpenHome looks for.
244
+ const IMCTL_PASS_THROUGH = ["mirror_not_live", "mirror_setup_required", "type_not_confirmed", "scroll_no_effect", "expect_not_found", "capture_failed", "open_not_confirmed", "focus_lost", "app not found"];
245
+
246
+ // What a timed-out command may have left behind, appended to imctl_timeout.
247
+ const IMCTL_TIMEOUT_HINT = new Map([
248
+ ["type", " — the clipboard may still hold the typed text"],
249
+ ["open", " — Spotlight may still be open"],
250
+ ]);
251
+
252
+ async function imctl(...args) {
253
+ const py = await resolvePython();
75
254
  if (!py.path) {
76
255
  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
256
  }
78
257
  const [cmd, pre] = pythonArgv(py.path);
79
- try {
80
- const out = execFileSync(cmd, [...pre, "-m", "imctl.cli", ...args], {
81
- timeout: 30000, encoding: "utf8", maxBuffer: 10 * 1024 * 1024,
82
- cwd: IMCTL_DIR, env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src"), PYTHONDONTWRITEBYTECODE: "1" },
83
- });
84
- return { ok: true, out: out.trim() };
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() };
90
- const raw = String(e.stderr || e.stdout || e.message);
91
- // Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
92
- if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
93
- const mod = (raw.match(/No module named '([^']+)'/) || [])[1];
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)` };
95
- }
96
- if (/ENOENT|No such file or directory/.test(raw)) {
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)` };
258
+ const timeoutMs = PHONE_TIMEOUT_OVERRIDE ?? IMCTL_TIMEOUT_MS.get(args[0]) ?? IMCTL_DEFAULT_TIMEOUT_MS;
259
+ // wait for any lingering child first, so the deadline below is counted from the actual spawn
260
+ if (lingering.size) await Promise.all([...lingering]);
261
+ const marginMs = Math.min(OPEN_DEADLINE_MARGIN_MS, timeoutMs * 0.4);
262
+ const r = await runAsync(cmd, [...pre, "-m", "imctl.cli", ...args], {
263
+ timeoutMs, cwd: IMCTL_DIR,
264
+ env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src"), PYTHONDONTWRITEBYTECODE: "1",
265
+ NORACU_OPEN_DEADLINE_EPOCH: String((Date.now() + timeoutMs - marginMs) / 1000) },
266
+ });
267
+ if (r.timedOut) {
268
+ let hint = IMCTL_TIMEOUT_HINT.get(args[0]) ?? "";
269
+ if (args[0] === "open") {
270
+ // the killed imctl had no time to tidy up: once it is gone, go to the Home Screen from here
271
+ if (lingering.size) await Promise.all([...lingering]);
272
+ hint = (await mirrorMenu("Home Screen", TIDY_MENU_TIMEOUT_MS)) ? " — noracu then returned the phone to the Home Screen" : hint;
98
273
  }
99
- return { ok: false, out: raw.slice(0, 500) };
274
+ return { ok: false, out: `imctl_timeout: phone ${args[0]} did not finish within ${timeoutMs / 1000}s (the Mac may be under heavy load) — the action may have partly run${hint}; check phone_status / phone_screenshot before retrying` };
275
+ }
276
+ if (r.overflow) {
277
+ return { ok: false, out: `imctl_output_overflow: phone ${args[0]} printed more than 10 MB and was stopped` };
278
+ }
279
+ if (!r.error && r.code === 0) return { ok: true, out: r.stdout.trim() };
280
+ const message = r.error ? String(r.error.message || r.error) : `imctl exited with code ${r.code}${r.signal ? ` (${r.signal})` : ""}`;
281
+ // G23(0.1.2)/ G26:镜像不在线(mirror_not_live)或粘贴未上屏(type_not_confirmed)时
282
+ // imctl 拒绝输入并在 stderr 带前缀行 —— 原样透传那一行,不归类为 imctl unavailable
283
+ const combined = String(r.stderr || "") + "\n" + String(r.stdout || "");
284
+ for (const prefix of IMCTL_PASS_THROUGH) {
285
+ const line = combined.split("\n").find((l) => l.startsWith(prefix + ":"));
286
+ if (line) return { ok: false, out: await retryOpenHome(args, line.trim()) };
100
287
  }
288
+ const raw = String(r.stderr || r.stdout || message);
289
+ // Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
290
+ if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
291
+ const mod = (raw.match(/No module named '([^']+)'/) || [])[1];
292
+ 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)` };
293
+ }
294
+ if (/ENOENT|No such file or directory/.test(raw)) {
295
+ 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)` };
296
+ }
297
+ return { ok: false, out: await retryOpenHome(args, raw.slice(0, 500)) };
298
+ }
299
+
300
+ // phone_open could not get back to the Home Screen (its menu trip failed on a loaded Mac): try once
301
+ // more from here, with the menu command that needs no frontmost window.
302
+ async function retryOpenHome(args, out) {
303
+ if (args[0] !== "open" || !out.includes(OPEN_HOME_FAILED)) return out;
304
+ if (!(await mirrorMenu("Home Screen", TIDY_MENU_TIMEOUT_MS))) return out;
305
+ return out.replace(OPEN_HOME_FAILED, "noracu then returned the phone to the Home Screen");
306
+ }
307
+
308
+ // F40: phone_* and mac_* drive the same real mouse, keyboard, clipboard and windows. Until F39
309
+ // every one of them ran synchronously, so tool calls were implicitly serialized; now that imctl
310
+ // runs asynchronously, two concurrent calls (MCP clients do issue parallel tool calls) could
311
+ // interleave taps and pastes and race on the clipboard. They go through one FIFO queue instead.
312
+ // A job's own timeout starts when it runs, not while it waits; the next job also waits for any
313
+ // child a timed-out job left behind (see `lingering`). ping, tools/list and browser_* never wait.
314
+ // A queued job that the client cancelled (notifications/cancelled), or that waited longer than
315
+ // QUEUE_WAIT_LIMIT_MS, is dropped without acting: a tap or paste that runs long after the client
316
+ // gave up would land on whatever is on screen by then.
317
+ const QUEUE_WAIT_LIMIT_MS = 60000;
318
+ const CANCELLED = Symbol("cancelled"); // a skipped job's result: the dispatcher sends nothing
319
+ const queuedRequests = new Set(); // ids of jobs waiting in the queue (not yet started)
320
+ const cancelledRequests = new Set(); // ids among them the client cancelled
321
+ let inputChain = Promise.resolve();
322
+ function serializedInput(fn, requestId) {
323
+ const queuedAt = Date.now();
324
+ if (requestId !== undefined) queuedRequests.add(requestId);
325
+ // setImmediate: after a synchronous mac_* job the event loop polls I/O once before the next job
326
+ // starts, so a notifications/cancelled line already sent for it is read first
327
+ const result = inputChain.then(() => new Promise((r) => setImmediate(r))).then(() => {
328
+ queuedRequests.delete(requestId);
329
+ if (requestId !== undefined && cancelledRequests.delete(requestId)) return CANCELLED;
330
+ const waited = Date.now() - queuedAt;
331
+ if (waited > QUEUE_WAIT_LIMIT_MS) {
332
+ return { error: `input_busy: an earlier phone/Mac action kept the input queue busy for ${Math.round(waited / 1000)}s; nothing was done — retry` };
333
+ }
334
+ return fn();
335
+ });
336
+ const drain = () => Promise.all([...lingering]).then(() => {});
337
+ inputChain = result.then(drain, drain);
338
+ return result;
101
339
  }
102
340
 
103
341
  // ── Mac 层 ──
@@ -403,12 +641,9 @@ async function macPasteImpl(args) {
403
641
  return { text: `pasted ${text.length} chars (clipboard restored: ${restored}) (frontmost: ${g.fm ?? "unknown"})` };
404
642
  }
405
643
 
406
- function macMenuCommand(args) {
407
- // AX 菜单栏遍历找命令并 AXPress(本地化安全)
408
- // 安全:静态脚本 + argv 传参(结构性消除 JXA 注入)
409
- const { app, command } = args;
410
- if (!app || !command) return { error: "app + command required" };
411
- const script = `
644
+ // AX 菜单栏遍历找命令并 AXPress(本地化安全)
645
+ // 安全:静态脚本 + argv 传参(结构性消除 JXA 注入)
646
+ const MENU_COMMAND_SCRIPT = `
412
647
  function run(argv) {
413
648
  const se = Application("System Events");
414
649
  const proc = se.processes.byName(argv[0]);
@@ -423,7 +658,10 @@ function macMenuCommand(args) {
423
658
  }
424
659
  return "not-found";
425
660
  }`;
426
- const r = sh("/usr/bin/osascript", ["-l", "JavaScript", "-e", script, "--", String(app), String(command)], 15000);
661
+ function macMenuCommand(args) {
662
+ const { app, command } = args;
663
+ if (!app || !command) return { error: "app + command required" };
664
+ const r = sh("/usr/bin/osascript", ["-l", "JavaScript", "-e", MENU_COMMAND_SCRIPT, "--", String(app), String(command)], 15000);
427
665
  return { text: r.ok ? r.out : "menu command failed: " + r.out.slice(0, 150) };
428
666
  }
429
667
 
@@ -683,43 +921,61 @@ function phoneStatus() { return imctl("status"); }
683
921
  function phoneLaunch() { return imctl("launch"); }
684
922
  function phoneTap(args) {
685
923
  if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y (0-1 normalized) required" };
686
- return imctl("tap", String(args.x), String(args.y));
924
+ const a = ["tap", String(args.x), String(args.y)];
925
+ if (args.expect) a.push("--expect", args.expect);
926
+ return imctl(...a);
687
927
  }
688
928
  function phoneLongpress(args) {
689
929
  if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y required" };
690
- return imctl("longpress", String(args.x), String(args.y), String(args.duration || 0.8));
930
+ const a = ["longpress", String(args.x), String(args.y), String(args.duration || 0.8)];
931
+ if (args.expect) a.push("--expect", args.expect);
932
+ return imctl(...a);
691
933
  }
692
934
  function phoneSwipe(args) {
693
935
  const { from, to, ms } = args;
694
936
  if (!Array.isArray(from) || !Array.isArray(to)) return { error: "from:[x,y], to:[x,y] required" };
695
937
  const a = ["swipe", String(from[0]), String(from[1]), String(to[0]), String(to[1])];
696
938
  if (ms) a.push("--ms", String(ms));
939
+ if (args.expect) a.push("--expect", args.expect);
697
940
  return imctl(...a);
698
941
  }
699
942
  // 镜像自带菜单 Home Screen ⌘1 / App Switcher ⌘2 可靠且不需前台(AXPress,非贴边手势)。
700
943
  // 菜单优先;标签不匹配(非英文 macOS)或镜像未连接时回退 imctl 手势,行为向后兼容。
701
- function mirrorMenu(command) {
702
- const m = macMenuCommand({ app: "iPhone Mirroring", command });
703
- return typeof m.text === "string" && m.text.startsWith("executed");
944
+ // F39: like imctl, the menu command runs asynchronously under a timer, so a stuck System Events
945
+ // cannot freeze the server either.
946
+ async function mirrorMenu(command, timeoutMs = 15000) {
947
+ const r = await runAsync("/usr/bin/osascript", ["-l", "JavaScript", "-e", MENU_COMMAND_SCRIPT, "--", "iPhone Mirroring", command], { timeoutMs });
948
+ return !r.timedOut && !r.error && r.code === 0 && r.stdout.trim().startsWith("executed");
704
949
  }
705
- function phoneHome() {
706
- if (mirrorMenu("Home Screen")) return { ok: true, out: "home (mirror menu)" };
950
+ async function phoneHome() {
951
+ if (await mirrorMenu("Home Screen")) return { ok: true, out: "home (mirror menu)" };
707
952
  return imctl("home");
708
953
  }
709
- function phoneAppSwitcher() {
710
- if (mirrorMenu("App Switcher")) return { ok: true, out: "app switcher (mirror menu)" };
954
+ async function phoneAppSwitcher() {
955
+ if (await mirrorMenu("App Switcher")) return { ok: true, out: "app switcher (mirror menu)" };
711
956
  return imctl("app-switcher");
712
957
  }
713
958
  function phoneScroll(args = {}) {
714
- return imctl("scroll", args.direction || "down", String(args.distance || 0.5));
959
+ const a = ["scroll", args.direction || "down", String(args.distance || 0.5)];
960
+ if (args.expect) a.push("--expect", args.expect);
961
+ return imctl(...a);
715
962
  }
716
963
  function phoneType(args) {
717
964
  if (!args.text) return { error: "text required" };
718
- return imctl("type", args.text);
965
+ // Options first, then `--`, then the free text: the text is a positional and
966
+ // may start with "-" (argparse would otherwise treat it as an option).
967
+ // Invariant: --expect and its value are two separate argv elements.
968
+ const a = ["type"];
969
+ if (args.replace) a.push("--replace");
970
+ if (args.expect) a.push("--expect", args.expect);
971
+ a.push("--", args.text);
972
+ return imctl(...a);
719
973
  }
720
974
  function phoneKey(args) {
721
975
  if (!args.key) return { error: "key required (return/delete/up/down/left/right)" };
722
- return imctl("key", args.key);
976
+ const a = ["key", args.key];
977
+ if (args.expect) a.push("--expect", args.expect);
978
+ return imctl(...a);
723
979
  }
724
980
  function phoneOcr() { return imctl("ocr"); }
725
981
  function phoneFind(args) {
@@ -730,17 +986,23 @@ function phoneOpen(args) {
730
986
  if (!args.app) return { error: "app required" };
731
987
  return imctl("open", args.app);
732
988
  }
733
- function phoneScreenshot() {
989
+ async function phoneScreenshot() {
734
990
  // Captured by imctl by CGWindow id, so it is the Mirroring window's own pixels even when another window covers it.
735
991
  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) };
738
992
  try {
739
- const data = readFileSync(file).toString("base64");
740
- unlinkSync(file);
741
- return { image: data, mime: "image/png" };
742
- } catch (e) {
743
- return { error: "screenshot file missing: " + String(e.message).slice(0, 150) };
993
+ const r = await imctl("screenshot", file);
994
+ if (!r.ok) return { error: r.out.slice(0, 300) };
995
+ try {
996
+ return { image: readFileSync(file).toString("base64"), mime: "image/png" };
997
+ } catch (e) {
998
+ return { error: "screenshot file missing: " + String(e.message).slice(0, 150) };
999
+ }
1000
+ } finally {
1001
+ // the phone's screen is private: remove the PNG on every path, timeouts and failures included —
1002
+ // and once more after any killed child is gone, in case it wrote the file on its way out
1003
+ const remove = () => { try { unlinkSync(file); } catch { /* never written, or already gone */ } };
1004
+ remove();
1005
+ if (lingering.size) Promise.all([...lingering]).then(remove);
744
1006
  }
745
1007
  }
746
1008
 
@@ -790,20 +1052,20 @@ const TOOLS = [
790
1052
  { name: "browser_evaluate", desc: "Evaluate JavaScript in the page and return the result.", args: { js: "string" }, fn: browserEvaluate },
791
1053
  { name: "browser_close", desc: "Close the browser.", args: {}, fn: browserClose },
792
1054
  // iPhone device-use(imctl)
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 },
1055
+ { 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, setup — true when a setup or welcome screen is showing that the user must finish).", args: {}, fn: phoneStatus },
1056
+ { 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. Never clicks through a setup or welcome screen: reports mirror_setup_required instead.", args: {}, fn: phoneLaunch },
1057
+ { 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). Fails with capture_failed instead of returning another window's pixels.", args: {}, fn: phoneScreenshot },
1058
+ { name: "phone_ocr", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates. Fails with capture_failed instead of returning another window's pixels.", args: {}, fn: phoneOcr },
1059
+ { name: "phone_find", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen. Fails with capture_failed instead of returning another window's pixels.", args: { text: "string" }, fn: phoneFind },
1060
+ { 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. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { x: "number", y: "number", expect: "string?" }, fn: phoneTap },
1061
+ { name: "phone_longpress", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { x: "number", y: "number", duration: "number?", expect: "string?" }, fn: phoneLongpress },
1062
+ { 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. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { from: "array", to: "array", ms: "number?", expect: "string?" }, fn: phoneSwipe },
801
1063
  { 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
1064
  { 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 },
1065
+ { name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by `distance` window heights (0 < distance <= 3, default 0.5) using trackpad-style scroll events. Reports scroll_no_effect when the screen did not change (list end, or the view does not scroll). Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { direction: "string?", distance: "number?", expect: "string?" }, fn: phoneScroll },
1066
+ { name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe). Restores the clipboard only after OCR sees the text appear (more often than before the paste) within its 2.5 s check; a paste that shows up a few seconds later is still reported as typed (do not type it again) but the clipboard keeps the typed text; otherwise type_not_confirmed, and the clipboard keeps the text. replace=true selects all and overwrites the field (over the same text nothing visibly changes, so that may report type_not_confirmed). Optional expect: on-screen text (OCR), else nothing is sent.", args: { text: "string", replace: "boolean?", expect: "string?" }, fn: phoneType },
1067
+ { name: "phone_key", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { key: "string", expect: "string?" }, fn: phoneKey },
1068
+ { name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app: Home Screen, Spotlight via the menu, clear, type the name (the clipboard keeps it), then tap only an exact label inside the Spotlight Top Hit card (suggestion, website and Settings rows of the same name are ignored, so a name the Top Hit card does not show is app not found; reads the English \"Top Hit\" label unless NORACU_TOPHIT_LABELS names the phone's own; a pasted name that never shows up in Spotlight, even after up to 15 s, is open_not_confirmed — retry); confirms the app opened (frame diff + OCR), taps the Top Hit icon when the label tap does nothing, else open_not_confirmed, back on the Home Screen.", args: { app: "string" }, fn: phoneOpen },
807
1069
  ];
808
1070
 
809
1071
  // ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──
@@ -868,12 +1130,28 @@ function validateArgs(name, a) {
868
1130
  return null;
869
1131
  case "phone_tap": case "phone_longpress":
870
1132
  if (!N(a.x) || !N(a.y) || a.x < 0 || a.x > 1 || a.y < 0 || a.y > 1) return `${name}: x,y normalized 0-1 required`;
1133
+ if (a.expect !== undefined && !S(a.expect, 200)) return `${name}: expect must be a string of 1-200 characters`;
871
1134
  return null;
872
1135
  case "phone_swipe":
873
1136
  if (!XY(a.from) || !XY(a.to)) return "phone_swipe: from/to [x,y] arrays required";
1137
+ if (a.expect !== undefined && !S(a.expect, 200)) return "phone_swipe: expect must be a string of 1-200 characters";
1138
+ return null;
1139
+ case "phone_scroll":
1140
+ if (a.direction !== undefined && a.direction !== "up" && a.direction !== "down")
1141
+ return "phone_scroll: direction must be up|down";
1142
+ if (a.distance !== undefined && (!N(a.distance) || a.distance <= 0 || a.distance > 3))
1143
+ return "phone_scroll: distance is in window heights, 0 < distance <= 3 (default 0.5)";
1144
+ if (a.expect !== undefined && !S(a.expect, 200)) return "phone_scroll: expect must be a string of 1-200 characters";
874
1145
  return null;
875
1146
  case "phone_type": case "phone_find":
876
1147
  if (!S(a.text, 5000)) return `${name}: text string (max 5000) required`;
1148
+ if (name === "phone_type" && a.replace !== undefined && typeof a.replace !== "boolean")
1149
+ return "phone_type: replace must be a boolean";
1150
+ if (name === "phone_type" && a.expect !== undefined && !S(a.expect, 200))
1151
+ return "phone_type: expect must be a string of 1-200 characters";
1152
+ return null;
1153
+ case "phone_key":
1154
+ if (a.expect !== undefined && !S(a.expect, 200)) return "phone_key: expect must be a string of 1-200 characters";
877
1155
  return null;
878
1156
  case "phone_open":
879
1157
  if (!S(a.app, 200)) return "phone_open: app string (max 200) required";
@@ -897,6 +1175,19 @@ function send(obj) {
897
1175
  process.stdout.write(JSON.stringify(obj) + "\n");
898
1176
  }
899
1177
 
1178
+ // tools/call 结果统一出口(F23):进程比磁盘旧时,把 staleServerNote() 的一行提示加在
1179
+ // 第一个 text 内容块的开头(单独一行);纯图片结果没有 text 块则补一个。只加提示 ——
1180
+ // 不改变工具执行、isError 返回码或其余内容块;tools/list / initialize 不加。
1181
+ function sendToolResult(id, content, isError) {
1182
+ const note = staleServerNote();
1183
+ if (note) {
1184
+ const firstText = content.find(b => b?.type === "text");
1185
+ if (firstText) firstText.text = `${note}\n${firstText.text}`;
1186
+ else content.unshift({ type: "text", text: note });
1187
+ }
1188
+ send({ jsonrpc: "2.0", id, result: { content, ...(isError ? { isError: true } : {}) } });
1189
+ }
1190
+
900
1191
  rl.on("line", async (line) => {
901
1192
  if (!line.trim()) return;
902
1193
  let msg;
@@ -904,9 +1195,14 @@ rl.on("line", async (line) => {
904
1195
  const { id, method, params } = msg;
905
1196
  try {
906
1197
  if (method === "initialize") {
907
- send({ jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "noracu", version: (() => { try { return JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf8")).version; } catch { return "0.0.0"; } })() } } });
1198
+ // F23:版本号用启动时快照的 LOADED.version,不在握手时现读 —— 进程旧了它也不会误报新版本
1199
+ send({ jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "noracu", version: LOADED.version } } });
908
1200
  } else if (method === "notifications/initialized") {
909
1201
  // no response
1202
+ } else if (method === "notifications/cancelled") {
1203
+ // F40: a queued phone/Mac call the client gave up on is skipped when its turn comes
1204
+ // (only a call still waiting in the queue can be skipped; ids are never kept beyond that)
1205
+ if (queuedRequests.has(params?.requestId)) cancelledRequests.add(params.requestId);
910
1206
  } else if (method === "tools/list") {
911
1207
  send({ jsonrpc: "2.0", id, result: { tools: TOOLS.map(t => ({
912
1208
  name: t.name, description: t.desc,
@@ -915,28 +1211,30 @@ rl.on("line", async (line) => {
915
1211
  } else if (method === "tools/call") {
916
1212
  const name = params?.name;
917
1213
  const tool = TOOLS.find(t => t.name === name);
918
- if (!tool) { send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `unknown tool: ${name}` }], isError: true } }); return; }
1214
+ if (!tool) { sendToolResult(id, [{ type: "text", text: `unknown tool: ${name}` }], true); return; }
919
1215
  let r;
920
1216
  if (process.env.NORACU_READ_ONLY === "1" && !READ_ONLY_TOOLS.has(name)) {
921
- send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `ERROR: ${name} blocked by NORACU_READ_ONLY=1 (observation-only mode)` }], isError: true } });
1217
+ sendToolResult(id, [{ type: "text", text: `ERROR: ${name} blocked by NORACU_READ_ONLY=1 (observation-only mode)` }], true);
922
1218
  return;
923
1219
  }
924
1220
  const verr = validateArgs(name, params?.arguments || {});
925
- if (verr) { send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `ERROR: ${verr}` }], isError: true } }); return; }
926
- try { r = await tool.fn(params?.arguments || {}); }
1221
+ if (verr) { sendToolResult(id, [{ type: "text", text: `ERROR: ${verr}` }], true); return; }
1222
+ const run = () => tool.fn(params?.arguments || {});
1223
+ try { r = await (/^(phone|mac)_/.test(name) ? serializedInput(run, id) : run()); }
927
1224
  catch (e) { r = { error: String(e?.message ?? e).slice(0, 400) }; }
1225
+ if (r === CANCELLED) return; // the client cancelled it while it waited: no response (MCP)
928
1226
  if (r?.error) {
929
- send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `ERROR: ${r.error}` }], isError: true } });
1227
+ sendToolResult(id, [{ type: "text", text: `ERROR: ${r.error}` }], true);
930
1228
  } else if (r?.ok === false) {
931
1229
  // imctl 子进程失败(imctl 缺失、Mirroring 窗口无法置前)返回 { ok:false, out },
932
1230
  // 此前被当作成功文本下发 —— 统一在此标记为工具错误(一处覆盖所有 phone_* 工具)
933
- send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `ERROR: ${r.out}` }], isError: true } });
1231
+ sendToolResult(id, [{ type: "text", text: `ERROR: ${r.out}` }], true);
934
1232
  } else if (r?.image) {
935
1233
  const content = [{ type: "image", data: r.image, mimeType: r.mime || "image/png" }];
936
1234
  if (r.meta) content.push({ type: "text", text: JSON.stringify(r.meta) });
937
- send({ jsonrpc: "2.0", id, result: { content } });
1235
+ sendToolResult(id, content);
938
1236
  } else {
939
- send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: typeof r?.text === "string" ? r.text : (r?.out ?? JSON.stringify(r)) }] } });
1237
+ sendToolResult(id, [{ type: "text", text: typeof r?.text === "string" ? r.text : (r?.out ?? JSON.stringify(r)) }]);
940
1238
  }
941
1239
  } else if (method === "ping") {
942
1240
  send({ jsonrpc: "2.0", id, result: {} });