noracu 0.1.3 → 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
@@ -85,56 +85,257 @@ const PYTHON_CANDIDATES = ["/opt/homebrew/bin/python3", "/usr/local/bin/python3"
85
85
  const PYOBJC_INSTALL = "python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit";
86
86
  let pythonProbe = null; // { path, tried } once resolved; path === null when nothing qualified
87
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
88
213
  function resolvePython() {
89
- if (pythonProbe) return pythonProbe;
90
- const tried = [];
91
- for (const cand of (process.env.NORACU_PYTHON ? [process.env.NORACU_PYTHON] : PYTHON_CANDIDATES)) {
92
- 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;
93
219
  try {
94
- execFileSync(cmd, [...pre, "-c", "import Quartz, Vision, AppKit"], { timeout: 20000, stdio: ["ignore", "ignore", "ignore"] });
95
- pythonProbe = { path: cand, tried };
96
- return pythonProbe;
97
- } catch { tried.push(cand); }
98
- }
99
- pythonProbe = { path: null, tried };
100
- 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;
101
238
  }
102
239
 
103
240
  // imctl 拒绝输入时在 stderr 打印 `前缀: 说明` 行。这些是可恢复的调用方错误(不是环境缺失),
104
241
  // 原样透传匹配到的那一行,不归类为 imctl unavailable。后续任务会往列表里追加更多前缀。
105
- const IMCTL_PASS_THROUGH = ["mirror_not_live", "type_not_confirmed", "scroll_no_effect", "expect_not_found", "capture_failed", "open_not_confirmed", "focus_lost"];
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
+ ]);
106
251
 
107
- function imctl(...args) {
108
- const py = resolvePython();
252
+ async function imctl(...args) {
253
+ const py = await resolvePython();
109
254
  if (!py.path) {
110
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)` };
111
256
  }
112
257
  const [cmd, pre] = pythonArgv(py.path);
113
- try {
114
- const out = execFileSync(cmd, [...pre, "-m", "imctl.cli", ...args], {
115
- timeout: 30000, encoding: "utf8", maxBuffer: 10 * 1024 * 1024,
116
- cwd: IMCTL_DIR, env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src"), PYTHONDONTWRITEBYTECODE: "1" },
117
- });
118
- return { ok: true, out: out.trim() };
119
- } catch (e) {
120
- // G23(0.1.2)/ G26:镜像不在线(mirror_not_live)或粘贴未上屏(type_not_confirmed)时
121
- // imctl 拒绝输入并在 stderr 带前缀行 —— 原样透传那一行,不归类为 imctl unavailable
122
- const combined = String(e.stderr || "") + "\n" + String(e.stdout || "");
123
- for (const prefix of IMCTL_PASS_THROUGH) {
124
- const line = combined.split("\n").find((l) => l.startsWith(prefix + ":"));
125
- if (line) return { ok: false, out: line.trim() };
126
- }
127
- const raw = String(e.stderr || e.stdout || e.message);
128
- // Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
129
- if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
130
- const mod = (raw.match(/No module named '([^']+)'/) || [])[1];
131
- 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)` };
132
- }
133
- if (/ENOENT|No such file or directory/.test(raw)) {
134
- 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;
135
273
  }
136
- 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()) };
137
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;
138
339
  }
139
340
 
140
341
  // ── Mac 层 ──
@@ -440,12 +641,9 @@ async function macPasteImpl(args) {
440
641
  return { text: `pasted ${text.length} chars (clipboard restored: ${restored}) (frontmost: ${g.fm ?? "unknown"})` };
441
642
  }
442
643
 
443
- function macMenuCommand(args) {
444
- // AX 菜单栏遍历找命令并 AXPress(本地化安全)
445
- // 安全:静态脚本 + argv 传参(结构性消除 JXA 注入)
446
- const { app, command } = args;
447
- if (!app || !command) return { error: "app + command required" };
448
- const script = `
644
+ // AX 菜单栏遍历找命令并 AXPress(本地化安全)
645
+ // 安全:静态脚本 + argv 传参(结构性消除 JXA 注入)
646
+ const MENU_COMMAND_SCRIPT = `
449
647
  function run(argv) {
450
648
  const se = Application("System Events");
451
649
  const proc = se.processes.byName(argv[0]);
@@ -460,7 +658,10 @@ function macMenuCommand(args) {
460
658
  }
461
659
  return "not-found";
462
660
  }`;
463
- 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);
464
665
  return { text: r.ok ? r.out : "menu command failed: " + r.out.slice(0, 150) };
465
666
  }
466
667
 
@@ -740,16 +941,18 @@ function phoneSwipe(args) {
740
941
  }
741
942
  // 镜像自带菜单 Home Screen ⌘1 / App Switcher ⌘2 可靠且不需前台(AXPress,非贴边手势)。
742
943
  // 菜单优先;标签不匹配(非英文 macOS)或镜像未连接时回退 imctl 手势,行为向后兼容。
743
- function mirrorMenu(command) {
744
- const m = macMenuCommand({ app: "iPhone Mirroring", command });
745
- 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");
746
949
  }
747
- function phoneHome() {
748
- 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)" };
749
952
  return imctl("home");
750
953
  }
751
- function phoneAppSwitcher() {
752
- 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)" };
753
956
  return imctl("app-switcher");
754
957
  }
755
958
  function phoneScroll(args = {}) {
@@ -783,17 +986,23 @@ function phoneOpen(args) {
783
986
  if (!args.app) return { error: "app required" };
784
987
  return imctl("open", args.app);
785
988
  }
786
- function phoneScreenshot() {
989
+ async function phoneScreenshot() {
787
990
  // Captured by imctl by CGWindow id, so it is the Mirroring window's own pixels even when another window covers it.
788
991
  const file = join(tmpdir(), `noracu-phone-${randomUUID().slice(0, 8)}.png`);
789
- const r = imctl("screenshot", file);
790
- if (!r.ok) return { error: r.out.slice(0, 300) };
791
992
  try {
792
- const data = readFileSync(file).toString("base64");
793
- unlinkSync(file);
794
- return { image: data, mime: "image/png" };
795
- } catch (e) {
796
- 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);
797
1006
  }
798
1007
  }
799
1008
 
@@ -843,8 +1052,8 @@ const TOOLS = [
843
1052
  { name: "browser_evaluate", desc: "Evaluate JavaScript in the page and return the result.", args: { js: "string" }, fn: browserEvaluate },
844
1053
  { name: "browser_close", desc: "Close the browser.", args: {}, fn: browserClose },
845
1054
  // iPhone device-use(imctl)
846
- { 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 },
847
- { 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 },
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 },
848
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 },
849
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 },
850
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 },
@@ -854,9 +1063,9 @@ const TOOLS = [
854
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 },
855
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 },
856
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 },
857
- { 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, else reports type_not_confirmed and keeps the text. replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent.", args: { text: "string", replace: "boolean?", expect: "string?" }, fn: phoneType },
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 },
858
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 },
859
- { 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, OCR-pick the exact row and tap it; 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 },
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 },
860
1069
  ];
861
1070
 
862
1071
  // ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──
@@ -990,6 +1199,10 @@ rl.on("line", async (line) => {
990
1199
  send({ jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "noracu", version: LOADED.version } } });
991
1200
  } else if (method === "notifications/initialized") {
992
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);
993
1206
  } else if (method === "tools/list") {
994
1207
  send({ jsonrpc: "2.0", id, result: { tools: TOOLS.map(t => ({
995
1208
  name: t.name, description: t.desc,
@@ -1006,8 +1219,10 @@ rl.on("line", async (line) => {
1006
1219
  }
1007
1220
  const verr = validateArgs(name, params?.arguments || {});
1008
1221
  if (verr) { sendToolResult(id, [{ type: "text", text: `ERROR: ${verr}` }], true); return; }
1009
- try { r = await tool.fn(params?.arguments || {}); }
1222
+ const run = () => tool.fn(params?.arguments || {});
1223
+ try { r = await (/^(phone|mac)_/.test(name) ? serializedInput(run, id) : run()); }
1010
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)
1011
1226
  if (r?.error) {
1012
1227
  sendToolResult(id, [{ type: "text", text: `ERROR: ${r.error}` }], true);
1013
1228
  } else if (r?.ok === false) {