noracu 0.3.0 → 0.3.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 +647 -3
- package/README.md +109 -188
- package/SECURITY.md +44 -1
- package/docs/README.zh-CN.md +143 -0
- package/docs/apps.md +38 -0
- package/docs/architecture.md +9 -9
- package/docs/ios-runner-protocol.md +20 -4
- package/docs/iphone.md +59 -0
- package/docs/known-issues.md +84 -0
- package/docs/tools.md +7 -7
- package/docs/troubleshooting.md +29 -0
- package/docs/usage.md +73 -11
- package/imctl/src/imctl/cli.py +116 -54
- package/imctl/src/imctl/gestures.py +96 -65
- package/imctl/src/imctl/input.py +104 -62
- package/imctl/src/imctl/screenrect.py +3 -1
- package/imctl/src/imctl/verify.py +72 -53
- package/imctl/src/imctl/vision.py +45 -24
- package/imctl/src/imctl/window.py +83 -37
- package/ios-runner/NoracuRunnerUITests/NoracuRunner.swift +114 -61
- package/ios-runner/NoracuRunnerUITests/RunnerCommands.swift +14 -4
- package/ios-runner/NoracuRunnerUITests/RunnerServer.swift +1 -2
- package/ios-runner/README.md +1 -1
- package/package.json +13 -6
- package/src/approval.js +66 -25
- package/src/bg-inject.js +9 -9
- package/src/doctor.js +156 -0
- package/src/ios-session.js +172 -40
- package/src/ios-setup.js +31 -14
- package/src/ios-xcuitest.js +71 -15
- package/src/mac-ax.js +535 -125
- package/src/server.mjs +928 -262
- package/README.zh-CN.md +0 -245
package/src/server.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// noracu MCP server — local computer-use across macOS apps, a Playwright browser, and iPhone Mirroring.
|
|
3
3
|
//
|
|
4
|
-
// Layers (
|
|
4
|
+
// Layers (47 tools across three surfaces, 33 by default, 42 with the XCUITest iPhone backend; observe -> act -> verify):
|
|
5
5
|
// Mac (20 mac_*): src/mac-ax.js (JXA over the macOS Accessibility C API: snapshots, search,
|
|
6
6
|
// element reads, semantic actions, menus, windows, apps, clipboard, notifications,
|
|
7
7
|
// waits) + cliclick (physical pointer/keyboard) + screencapture (screenshots)
|
|
8
|
-
// Browser (
|
|
8
|
+
// Browser (13 browser_*): Playwright persistent-profile browser (or opt-in loopback CDP attach via
|
|
9
9
|
// NORACU_ALLOW_CDP=1|any) with ARIA + element_index snapshots and real pointer input
|
|
10
10
|
// iPhone (14 phone_*): EXPERIMENTAL — bundled imctl (CGEvent input, Vision OCR, pixel/OCR verification)
|
|
11
|
-
// plus iPhone Mirroring menu commands over normalized 0-1 coordinates
|
|
11
|
+
// plus iPhone Mirroring menu commands over normalized 0-1 coordinates; with
|
|
12
|
+
// NORACU_PHONE_BACKEND=xcuitest, 9 ios_* tools (src/ios-session.js) take their place
|
|
12
13
|
//
|
|
13
14
|
// Transport: stdio JSON-RPC 2.0 (initialize / tools/list / tools/call / notifications/cancelled / ping)
|
|
14
15
|
|
|
@@ -27,9 +28,17 @@ import { bgCandidate, postKeyToPid, postClickToPid, BGPOST_DISABLED, BG_SCRIPT }
|
|
|
27
28
|
import { stopFileBlocked, evaluateApproval, denyList, gateActive } from "./approval.js";
|
|
28
29
|
import { createIosSession } from "./ios-session.js";
|
|
29
30
|
import { validBundleId } from "./ios-xcuitest.js";
|
|
31
|
+
import { defaultCliclick } from "./doctor.js";
|
|
30
32
|
|
|
31
|
-
// `noracu
|
|
32
|
-
//
|
|
33
|
+
// `noracu doctor`, `--help` and `--version` are for a person at a terminal (src/doctor.js); `noracu ios-setup …`
|
|
34
|
+
// builds the on-device runner of the XCUITest backend. Each exits when done; every other start is the MCP
|
|
35
|
+
// server on stdio.
|
|
36
|
+
if (["doctor", "--doctor", "--help", "--version"].includes(process.argv[2])) {
|
|
37
|
+
const { cli } = await import("./doctor.js");
|
|
38
|
+
const code = await cli(process.argv.slice(2));
|
|
39
|
+
await new Promise((done) => process.stdout.write("", done)); // a pipe is written asynchronously: let it drain before exiting
|
|
40
|
+
process.exit(code);
|
|
41
|
+
}
|
|
33
42
|
if (process.argv[2] === "ios-setup") {
|
|
34
43
|
const { main } = await import("./ios-setup.js");
|
|
35
44
|
process.exit(await main(process.argv.slice(3)));
|
|
@@ -39,10 +48,11 @@ if (process.argv[2] === "ios-setup") {
|
|
|
39
48
|
const __dirname = fileURLToPath(new URL(".", import.meta.url));
|
|
40
49
|
// imctl (the iPhone Mirroring driver, Python) ships inside the package at imctl/; NORACU_IMCTL_DIR overrides it (e.g. a dev checkout)
|
|
41
50
|
const IMCTL_DIR = process.env.NORACU_IMCTL_DIR || join(__dirname, "..", "imctl");
|
|
42
|
-
|
|
51
|
+
// cliclick: NORACU_CLICLICK, else the first of Homebrew's places that has it (Apple silicon, then Intel) — doctor.js
|
|
52
|
+
const CLICLICK = process.env.NORACU_CLICLICK || defaultCliclick();
|
|
43
53
|
// where the "time since the last keyboard or mouse event" is read (NORACU_IOREG is a test hook, like NORACU_CLICLICK)
|
|
44
54
|
const IOREG = process.env.NORACU_IOREG || "/usr/sbin/ioreg";
|
|
45
|
-
// 0.2.7
|
|
55
|
+
// 0.2.7: the Mac is shared with the person sitting at it. Mac and iPhone input goes
|
|
46
56
|
// second: when the keyboard or mouse was used in the last NORACU_USER_IDLE_S seconds (default 2) — and not
|
|
47
57
|
// by noracu's own last input — the call returns user_active and sends nothing; and after a pointer action
|
|
48
58
|
// the pointer goes back where it was. 0 turns both off (a Mac dedicated to the agent). A value that is not
|
|
@@ -71,7 +81,7 @@ const PHONE_BACKEND = (() => {
|
|
|
71
81
|
// 0.3.0: which layers this server offers. NORACU_LAYERS is a comma-separated list of mac, browser, iphone —
|
|
72
82
|
// a tool of a layer that is left out is neither listed nor callable (for instance NORACU_LAYERS=iphone for a
|
|
73
83
|
// client entry that should carry the iPhone tools only). Unset or blank: mac and browser — the experimental
|
|
74
|
-
// iPhone layer is opt-in (
|
|
84
|
+
// iPhone layer is opt-in (2026-11-12): NORACU_LAYERS=mac,browser,iphone adds it. A name that
|
|
75
85
|
// is not one of the three stops the server at start instead of falling back: a typo must not widen the list.
|
|
76
86
|
const LAYER_NAMES = ["mac", "browser", "iphone"];
|
|
77
87
|
const DEFAULT_LAYERS = ["mac", "browser"];
|
|
@@ -95,10 +105,10 @@ if (LAYERS.has("iphone") && !existsSync(IMCTL_DIR)) {
|
|
|
95
105
|
process.stderr.write(`[noracu] warning: imctl not found at ${IMCTL_DIR} — phone_* tools will fail. Set NORACU_IMCTL_DIR.\n`);
|
|
96
106
|
}
|
|
97
107
|
|
|
98
|
-
// ──
|
|
108
|
+
// ── 进程/磁盘漂移检测(server 进程比磁盘上的文件旧时提示调用方)──
|
|
99
109
|
// MCP 客户端(如 Claude Desktop)会把 server 进程常驻数小时;磁盘上的 package.json /
|
|
100
110
|
// src/server.mjs 升级后,进程里跑的仍是启动时加载的旧代码(旧版本号、旧工具描述),
|
|
101
|
-
// 实际形成"旧 server + 新 imctl 驱动"
|
|
111
|
+
// 实际形成"旧 server + 新 imctl 驱动"混跑,调用方照旧描述传参会踩坑。
|
|
102
112
|
// 注意:git 切分支同样会改写 src/server.mjs 的内容 —— 这时下面的提示同样成立,因为
|
|
103
113
|
// 进程里的代码确实与磁盘不同。启动时快照一次 LOADED,每次 tools/call 现读磁盘对比
|
|
104
114
|
// (两个文件都很小,不做缓存)。
|
|
@@ -150,7 +160,7 @@ function staleCheck() {
|
|
|
150
160
|
|
|
151
161
|
// ── 工具实现 ──────────────────────────────────────────────
|
|
152
162
|
|
|
153
|
-
// Every child process runs asynchronously under its own timer
|
|
163
|
+
// Every child process runs asynchronously under its own timer, so no tool call can block the
|
|
154
164
|
// event loop: tools/list, ping and other calls keep being answered while it runs.
|
|
155
165
|
async function sh(cmd, args, timeoutMs = 15000) {
|
|
156
166
|
const r = await runAsync(cmd, args, { timeoutMs });
|
|
@@ -166,10 +176,13 @@ async function sh(cmd, args, timeoutMs = 15000) {
|
|
|
166
176
|
// phone_* call, so the Mac and browser layers pay nothing. Apple's /usr/bin/python3 usually lacks pyobjc; Homebrew's
|
|
167
177
|
// python3 plus the three pyobjc-framework-* packages is the common working setup.
|
|
168
178
|
const PYTHON_CANDIDATES = ["/opt/homebrew/bin/python3", "/usr/local/bin/python3", "python3", "/usr/bin/python3"];
|
|
169
|
-
const
|
|
179
|
+
const PYOBJC_PKGS = "pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-Cocoa";
|
|
180
|
+
const PYOBJC_INSTALL = `python3 -m pip install ${PYOBJC_PKGS}`;
|
|
181
|
+
// the install command for one interpreter: its own path, quoted when it needs it — "python3" may be another one
|
|
182
|
+
const pyobjcInstallFor = (path) => `${/^[\w@%+=:,./-]+$/.test(path) ? path : `'${String(path).replace(/'/g, "'\\''")}'`} -m pip install ${PYOBJC_PKGS}`;
|
|
170
183
|
let pythonProbe = null; // { path, tried } once resolved; path === null when nothing qualified
|
|
171
184
|
function pythonArgv(path) { return path === "python3" ? ["/usr/bin/env", ["python3"]] : [path, []]; }
|
|
172
|
-
//
|
|
185
|
+
// 2026-11-05: execFileSync's timeout only sends a signal and then keeps waiting for the
|
|
173
186
|
// child to exit. On 2026-11-04 an imctl child stuck in an uninterruptible wait never exited, so
|
|
174
187
|
// the whole server stopped answering — tools/call, tools/list, even ping — for minutes. Every
|
|
175
188
|
// iPhone-layer subprocess now runs asynchronously under its own timer and in its own process
|
|
@@ -260,19 +273,22 @@ async function runAsync(cmd, argv, opts) {
|
|
|
260
273
|
// out, then its gesture fallback).
|
|
261
274
|
if (lingering.size) await Promise.all([...lingering]);
|
|
262
275
|
if (shuttingDown) return { code: null, error: new Error("server is shutting down"), stdout: "", stderr: "" };
|
|
276
|
+
// a call the client cancelled before its child was started: the child is not started
|
|
277
|
+
if (opts?.live?.cancelled) return { code: null, cancelled: true, stdout: "", stderr: "" };
|
|
263
278
|
return spawnTimed(cmd, argv, opts);
|
|
264
279
|
}
|
|
265
280
|
|
|
266
281
|
// `input` (optional) is written to the child's stdin, which is then closed; without it stdin is
|
|
267
282
|
// ignored as before. The Mac accessibility engine takes its whole request this way, so text to
|
|
268
283
|
// insert never appears in argv (a process list shows argv to every local user).
|
|
269
|
-
function spawnTimed(cmd, argv, { timeoutMs, cwd, env, input }) {
|
|
284
|
+
function spawnTimed(cmd, argv, { timeoutMs, cwd, env, input, live }) {
|
|
270
285
|
return new Promise((resolve) => {
|
|
271
|
-
let stdout = "", stderr = "", size = 0, done = false, exited = false, child = null, timer = null;
|
|
286
|
+
let stdout = "", stderr = "", size = 0, done = false, exited = false, child = null, timer = null, unhook = null;
|
|
272
287
|
const finish = (r) => {
|
|
273
288
|
if (done) return;
|
|
274
289
|
done = true;
|
|
275
290
|
clearTimeout(timer);
|
|
291
|
+
unhook?.();
|
|
276
292
|
resolve({ stdout, stderr, ...r });
|
|
277
293
|
};
|
|
278
294
|
const terminate = () => {
|
|
@@ -303,6 +319,15 @@ function spawnTimed(cmd, argv, { timeoutMs, cwd, env, input }) {
|
|
|
303
319
|
child.stdin.end(input);
|
|
304
320
|
}
|
|
305
321
|
timer = setTimeout(() => { terminate(); finish({ code: null, timedOut: true }); }, timeoutMs);
|
|
322
|
+
// the client cancelled the call (notifications/cancelled): the child is stopped as on a timeout — imctl puts the
|
|
323
|
+
// clipboard back when its paste had not gone out yet, and only then
|
|
324
|
+
if (live) {
|
|
325
|
+
const onCancel = () => { terminate(); finish({ code: null, cancelled: true }); };
|
|
326
|
+
if (!live.hooks) live.hooks = new Set();
|
|
327
|
+
live.hooks.add(onCancel);
|
|
328
|
+
unhook = () => live.hooks.delete(onCancel);
|
|
329
|
+
if (live.cancelled) onCancel();
|
|
330
|
+
}
|
|
306
331
|
const collect = (which) => (chunk) => {
|
|
307
332
|
if (done) return;
|
|
308
333
|
size += chunk.length;
|
|
@@ -313,7 +338,8 @@ function spawnTimed(cmd, argv, { timeoutMs, cwd, env, input }) {
|
|
|
313
338
|
child.stderr.setEncoding("utf8");
|
|
314
339
|
child.stdout.on("data", collect("out"));
|
|
315
340
|
child.stderr.on("data", collect("err"));
|
|
316
|
-
|
|
341
|
+
// spawned: the program did start (an error that comes later than that is not "it never ran")
|
|
342
|
+
child.on("error", (error) => { activeChildren.delete(child); finish({ code: null, error, spawned: child.pid !== undefined }); });
|
|
317
343
|
child.on("close", (code, signal) => { exited = true; activeChildren.delete(child); finish({ code, signal }); });
|
|
318
344
|
});
|
|
319
345
|
}
|
|
@@ -354,7 +380,7 @@ function resolvePython() {
|
|
|
354
380
|
// 原样透传匹配到的那一行,不归类为 imctl unavailable。后续任务会往列表里追加更多前缀。
|
|
355
381
|
// "app not found" (phone_open, printed on stdout) is taken from stdout or stderr as one whole line, so a
|
|
356
382
|
// warning on stderr or a long label list cannot hide the "could not go back" note retryOpenHome looks for.
|
|
357
|
-
const IMCTL_PASS_THROUGH = ["mirror_not_live", "mirror_state_unknown", "mirror_setup_required", "type_not_confirmed", "scroll_no_effect", "expect_not_found", "capture_failed", "open_not_confirmed", "focus_lost", "app not found", "keyboard_layout", "out_of_screen"];
|
|
383
|
+
const IMCTL_PASS_THROUGH = ["mirror_not_live", "mirror_state_unknown", "mirror_setup_required", "type_not_confirmed", "scroll_no_effect", "expect_not_found", "capture_failed", "open_not_confirmed", "focus_lost", "app not found", "keyboard_layout", "out_of_screen", "spotlight_unavailable"];
|
|
358
384
|
|
|
359
385
|
// What a timed-out command may have left behind, appended to imctl_timeout.
|
|
360
386
|
const IMCTL_TIMEOUT_HINT = new Map([
|
|
@@ -368,7 +394,7 @@ const BROWSER_STOPPABLE = new Set(["browser_click", "browser_type", "browser_fil
|
|
|
368
394
|
const IMCTL_LOOK = new Set(["status", "screenshot", "ocr", "find", "wait", "expect", "state", "rect"]);
|
|
369
395
|
// text that would otherwise sit in argv (visible in the process list) goes in on stdin: imctl reads "-"
|
|
370
396
|
function imctlIn(input, ...args) { return imctlRun(args, input); }
|
|
371
|
-
async function imctlRun(args, input) {
|
|
397
|
+
async function imctlRun(args, input, live) {
|
|
372
398
|
if (shuttingDown) return { ok: false, out: "server_shutting_down: nothing was done" };
|
|
373
399
|
const py = await resolvePython();
|
|
374
400
|
if (!py.path) {
|
|
@@ -376,23 +402,24 @@ async function imctlRun(args, input) {
|
|
|
376
402
|
}
|
|
377
403
|
const [cmd, pre] = pythonArgv(py.path);
|
|
378
404
|
const timeoutMs = PHONE_TIMEOUT_OVERRIDE ?? IMCTL_TIMEOUT_MS.get(args[0]) ?? IMCTL_DEFAULT_TIMEOUT_MS;
|
|
379
|
-
if (!IMCTL_LOOK.has(args[0])) { const stop = stopFileBlocked(); if (stop) return { ok: false, out: stop }; }
|
|
405
|
+
if (!IMCTL_LOOK.has(args[0])) { const stop = stopFileBlocked(); if (stop) return { ok: false, out: stop }; }
|
|
380
406
|
// wait for any lingering child first, so the deadline below is counted from the actual spawn
|
|
381
407
|
if (lingering.size) {
|
|
382
408
|
await Promise.all([...lingering]);
|
|
383
|
-
// a stop file made while that child was reaped still stops this input
|
|
409
|
+
// a stop file made while that child was reaped still stops this input
|
|
384
410
|
if (!IMCTL_LOOK.has(args[0])) { const stop = stopFileBlocked(); if (stop) return { ok: false, out: stop }; }
|
|
385
411
|
}
|
|
386
412
|
const marginMs = Math.min(OPEN_DEADLINE_MARGIN_MS, timeoutMs * 0.4);
|
|
387
413
|
const r = await runAsync(cmd, [...pre, "-m", "imctl.cli", ...args], {
|
|
388
|
-
timeoutMs, cwd: IMCTL_DIR, input,
|
|
414
|
+
timeoutMs, cwd: IMCTL_DIR, input, live,
|
|
389
415
|
env: { ...process.env, PYTHONPATH: join(IMCTL_DIR, "src"), PYTHONDONTWRITEBYTECODE: "1",
|
|
390
416
|
NORACU_OPEN_DEADLINE_EPOCH: String((Date.now() + timeoutMs - marginMs) / 1000) },
|
|
391
417
|
});
|
|
392
418
|
// phone input posts HID events into iPhone Mirroring — unless imctl refused before sending anything (it exits non-zero
|
|
393
419
|
// and says so): stamping a refusal would let the person's key or mouse move of that moment pass for noracu's on the
|
|
394
|
-
// next call
|
|
420
|
+
// next call
|
|
395
421
|
if (!r.error && !IMCTL_LOOK.has(args[0]) && !imctlSentNothing(r)) noteHid(r);
|
|
422
|
+
if (r.cancelled) return { ok: false, out: `cancelled: the client cancelled phone ${args[0]} and imctl was stopped — the action may have partly run; check phone_screenshot before retrying` };
|
|
396
423
|
if (r.timedOut) {
|
|
397
424
|
let hint = IMCTL_TIMEOUT_HINT.get(args[0]) ?? "";
|
|
398
425
|
if (args[0] === "open") {
|
|
@@ -403,11 +430,11 @@ async function imctlRun(args, input) {
|
|
|
403
430
|
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` };
|
|
404
431
|
}
|
|
405
432
|
if (r.overflow) {
|
|
406
|
-
return { ok: false, out: `imctl_output_overflow: phone ${args[0]} printed more than 10 MB and was stopped` };
|
|
433
|
+
return { ok: false, out: `imctl_output_overflow: phone ${args[0]} printed more than 10 MB and was stopped — the action may have partly run; check phone_status / phone_screenshot before retrying` };
|
|
407
434
|
}
|
|
408
435
|
if (!r.error && r.code === 0) return { ok: true, out: r.stdout.trim() };
|
|
409
436
|
const message = r.error ? String(r.error.message || r.error) : `imctl exited with code ${r.code}${r.signal ? ` (${r.signal})` : ""}`;
|
|
410
|
-
//
|
|
437
|
+
// 0.1.2:镜像不在线(mirror_not_live)或粘贴未上屏(type_not_confirmed)时
|
|
411
438
|
// imctl 拒绝输入并在 stderr 带前缀行 —— 原样透传那一行,不归类为 imctl unavailable
|
|
412
439
|
const combined = String(r.stderr || "") + "\n" + String(r.stdout || "");
|
|
413
440
|
for (const prefix of IMCTL_PASS_THROUGH) {
|
|
@@ -418,7 +445,7 @@ async function imctlRun(args, input) {
|
|
|
418
445
|
// Collapse Python import/spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
|
|
419
446
|
if (/No module named|ModuleNotFoundError|ImportError/.test(raw)) {
|
|
420
447
|
const mod = (raw.match(/No module named '([^']+)'/) || [])[1];
|
|
421
|
-
return { ok: false, out: `imctl unavailable: ${py.path} is missing ${mod ? `the ${mod} module` : "a module"} — run \`${
|
|
448
|
+
return { ok: false, out: `imctl unavailable: ${py.path} is missing ${mod ? `the ${mod} module` : "a module"} — run \`${pyobjcInstallFor(py.path)}\`, or set NORACU_PYTHON to another python3 (see README)` };
|
|
422
449
|
}
|
|
423
450
|
if (/Traceback \(most recent/.test(raw)) {
|
|
424
451
|
const last = raw.trim().split("\n").map((l) => l.trim()).filter(Boolean).pop() || message;
|
|
@@ -438,7 +465,7 @@ async function retryOpenHome(args, out) {
|
|
|
438
465
|
return out.replace(OPEN_HOME_FAILED, "noracu then sent the Home Screen command (the screen was not checked)");
|
|
439
466
|
}
|
|
440
467
|
|
|
441
|
-
//
|
|
468
|
+
// phone_* and mac_* drive the same real mouse, keyboard, clipboard and windows. At first
|
|
442
469
|
// every one of them ran synchronously, so tool calls were implicitly serialized; now that imctl
|
|
443
470
|
// runs asynchronously, two concurrent calls (MCP clients do issue parallel tool calls) could
|
|
444
471
|
// interleave taps and pastes and race on the clipboard. They go through one FIFO queue instead.
|
|
@@ -451,41 +478,81 @@ const QUEUE_WAIT_LIMIT_MS = Math.max(60000, (PHONE_TIMEOUT_OVERRIDE ?? 0) + 1500
|
|
|
451
478
|
const CANCELLED = Symbol("cancelled"); // a skipped job's result: the dispatcher sends nothing
|
|
452
479
|
const queuedRequests = new Set(); // ids of jobs waiting in the queue (not yet started)
|
|
453
480
|
const cancelledRequests = new Set(); // ids among them the client cancelled
|
|
481
|
+
// Every tools/call that is under way, waiting or running: id → { cancelled }. The client's notifications/cancelled
|
|
482
|
+
// (its Stop button, or its own timeout) sets the flag: the call is not answered any more (MCP), and a tool that
|
|
483
|
+
// works in steps looks at the flag between them — browser_type stops typing. A tool that waits on a child process
|
|
484
|
+
// hands it to spawnTimed, which puts a stop in `hooks`: mac_wait's engine and phone_type's imctl end at once.
|
|
485
|
+
const liveCalls = new Map();
|
|
454
486
|
let inputChain = Promise.resolve();
|
|
455
487
|
// The person at the Mac goes first (0.2.7, see USER_IDLE_S). macOS keeps one "time since the last keyboard
|
|
456
488
|
// or mouse event" (IOHIDSystem HIDIdleTime), and noracu's own events reset it too (cliclick, imctl and
|
|
457
489
|
// CGEventPost alike — measured 2026-11-08; a cursor warp does not). So an event counts as the person's only
|
|
458
490
|
// when it came after noracu's last input — and every child it left running — had ended.
|
|
459
491
|
let lastOwnInputEnd = 0;
|
|
460
|
-
// 0.3.0
|
|
492
|
+
// 0.3.0: only a child that posts keyboard or mouse events through
|
|
461
493
|
// the HID system moves lastOwnInputEnd — cliclick, the wheel script, the engine's key and paste, and imctl's
|
|
462
494
|
// phone input — and to the moment that child ended, not the end of the whole call: the 250 ms look after a
|
|
463
495
|
// click, an AXPress, a pid-targeted bgpost or a refusal post no such event, and stamping them would let the
|
|
464
496
|
// person's own key or mouse move of that moment pass for noracu's on the next call. A child that timed out may
|
|
465
497
|
// post until it is gone: then the stamp waits for it (the queue's drain).
|
|
466
498
|
let hidRuns = 0, hidEnd = 0, hidLate = false;
|
|
499
|
+
// hidRuns when the input call that is running left the queue: more than that means this call has sent events
|
|
500
|
+
let jobHidBase = 0;
|
|
467
501
|
// imctl refused before any event went out: a non-zero exit whose output says nothing was sent, or names a refusal
|
|
468
502
|
// that comes before any input (the mirror not live, its state unknown, a setup page)
|
|
469
503
|
function imctlSentNothing(r) {
|
|
470
504
|
if (r.timedOut || r.code === 0) return false;
|
|
471
505
|
const out = `${r.stderr || ""}\n${r.stdout || ""}`;
|
|
472
|
-
|
|
506
|
+
// a driver that could not import its modules (pyobjc missing) ended before it could post any event
|
|
507
|
+
return /\bnothing was sent\b/.test(out) || /^(mirror_not_live|mirror_state_unknown|mirror_setup_required):/m.test(out)
|
|
508
|
+
|| /No module named|ModuleNotFoundError|ImportError/.test(out);
|
|
473
509
|
}
|
|
474
510
|
function noteHid(r) { hidRuns++; hidEnd = Date.now(); if (r?.timedOut) hidLate = true; }
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
511
|
+
// ownEnd: when the events this same call already sent ended (they are noracu's own); partly: something of this
|
|
512
|
+
// call did go out before, so a refusal must not say "nothing was sent"
|
|
513
|
+
// One look at the time since the last keyboard or mouse event: { t0, idleMs }, or null when it cannot be read.
|
|
514
|
+
// The clock is read before ioreg runs: ioreg samples the idle time later than t0, so t0 - idle is never later than
|
|
515
|
+
// the event itself — ioreg's exit and the event loop cannot push noracu's own last event past lastOwnInputEnd.
|
|
516
|
+
async function idleSample() {
|
|
480
517
|
const t0 = Date.now();
|
|
481
518
|
const r = await runAsync(IOREG, ["-c", "IOHIDSystem", "-d", "4", "-r", "-k", "HIDIdleTime"], { timeoutMs: 3000 });
|
|
482
519
|
const m = /"HIDIdleTime" = (\d+)/.exec(String(r.stdout || ""));
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
if (!
|
|
487
|
-
|
|
488
|
-
|
|
520
|
+
return m ? { t0, idleMs: Number(m[1]) / 1e6 } : null;
|
|
521
|
+
}
|
|
522
|
+
async function userActive(ownEnd = 0, partly = false) {
|
|
523
|
+
if (!SHARED_INPUT) return null;
|
|
524
|
+
// the person's: an event less than USER_IDLE_S old that is not noracu's own. Unreadable: input is not held
|
|
525
|
+
// up — this is a courtesy to the person at the Mac, not a safety check
|
|
526
|
+
const persons = (s) => Boolean(s) && s.idleMs < USER_IDLE_S * 1000 && s.t0 - s.idleMs > Math.max(lastOwnInputEnd, ownEnd) + 50;
|
|
527
|
+
let s = await idleSample();
|
|
528
|
+
if (!persons(s)) return null;
|
|
529
|
+
// The person's last key or click is often the Return that sent this very request. It is
|
|
530
|
+
// waited out once — the rest of USER_IDLE_S, nothing is sent meanwhile — and the time read again: the input
|
|
531
|
+
// goes ahead when they did nothing more, and is refused as before when they did.
|
|
532
|
+
const waitMs = Math.max(0, USER_IDLE_S * 1000 - s.idleMs) + 100;
|
|
533
|
+
await new Promise((r) => setTimeout(r, waitMs));
|
|
534
|
+
const again = await idleSample();
|
|
535
|
+
if (!persons(again)) {
|
|
536
|
+
// a stop file made during the wait still stops the input
|
|
537
|
+
const stop = stopFileBlocked();
|
|
538
|
+
return stop || null;
|
|
539
|
+
}
|
|
540
|
+
s = again;
|
|
541
|
+
const idleMs = s.idleMs;
|
|
542
|
+
const used = `user_active: this Mac's keyboard or mouse was used ${(idleMs / 1000).toFixed(1)} s ago, not by noracu, and again after noracu had waited ${(waitMs / 1000).toFixed(1)} s for it — the person at the Mac goes first`;
|
|
543
|
+
const when = `(noracu acts once there has been no keyboard or mouse input for ${USER_IDLE_S} s; NORACU_USER_IDLE_S=0 turns this off)`;
|
|
544
|
+
return partly
|
|
545
|
+
? `${used}, so the rest of this call was not sent — an earlier part of it was: look before retrying ${when} (delivery=unknown, retry=unsafe)`
|
|
546
|
+
: `${used}, so nothing was sent; retry in a few seconds ${when} (delivery=not_delivered, retry=safe)`;
|
|
547
|
+
}
|
|
548
|
+
// The same check once more, right before keyboard or mouse events go out: the queue's check is older by then
|
|
549
|
+
// (the app rules, the engine's look at the element, a click of this same call). Events this call already
|
|
550
|
+
// sent ended at hidEnd and are noracu's own; when something did go out before, a refusal says so. While a
|
|
551
|
+
// child that timed out may still be posting, its events cannot be told from the person's: no check then.
|
|
552
|
+
async function lateUserCheck() {
|
|
553
|
+
if (!SHARED_INPUT || hidLate) return null;
|
|
554
|
+
const sent = hidRuns > jobHidBase;
|
|
555
|
+
return userActive(sent ? hidEnd : 0, sent);
|
|
489
556
|
}
|
|
490
557
|
function serializedInput(fn, requestId, yieldToUser = false) {
|
|
491
558
|
const queuedAt = Date.now();
|
|
@@ -494,7 +561,7 @@ function serializedInput(fn, requestId, yieldToUser = false) {
|
|
|
494
561
|
// setImmediate: after a synchronous mac_* job the event loop polls I/O once before the next job
|
|
495
562
|
// starts, so a notifications/cancelled line already sent for it is read first
|
|
496
563
|
const result = inputChain.then(() => new Promise((r) => setImmediate(r))).then(async () => {
|
|
497
|
-
// the job stays cancellable until it runs: the idle read below can take seconds
|
|
564
|
+
// the job stays cancellable until it runs: the idle read below can take seconds
|
|
498
565
|
const settle = () => { queuedRequests.delete(requestId); return requestId !== undefined && cancelledRequests.delete(requestId); };
|
|
499
566
|
if (settle()) return CANCELLED;
|
|
500
567
|
if (requestId !== undefined) queuedRequests.add(requestId);
|
|
@@ -506,14 +573,14 @@ function serializedInput(fn, requestId, yieldToUser = false) {
|
|
|
506
573
|
}
|
|
507
574
|
if (yieldToUser) {
|
|
508
575
|
// 0.3.0: the person's stop file first — it covers every phone_* and mac_* input, including the
|
|
509
|
-
// semantic (AXPress / AXSetValue) paths that send no event
|
|
576
|
+
// semantic (AXPress / AXSetValue) paths that send no event
|
|
510
577
|
const stop = stopFileBlocked();
|
|
511
578
|
if (stop) { settle(); return { error: stop }; }
|
|
512
579
|
// ios_* input ("stop") does not use this Mac's keyboard or mouse, so it does not wait for the person at it
|
|
513
580
|
const busy = yieldToUser === "stop" ? null : await userActive();
|
|
514
581
|
if (busy) { settle(); return { error: busy }; }
|
|
515
582
|
// what was checked before the idle read (ioreg, after any child still being reaped) is checked again: a cancel,
|
|
516
|
-
// a shutdown or a stop file that came meanwhile still wins
|
|
583
|
+
// a shutdown or a stop file that came meanwhile still wins
|
|
517
584
|
if (settle()) return CANCELLED;
|
|
518
585
|
if (shuttingDown) return { error: "server_shutting_down: nothing was done (delivery=not_delivered, retry=safe)" };
|
|
519
586
|
const stopNow = stopFileBlocked();
|
|
@@ -521,7 +588,7 @@ function serializedInput(fn, requestId, yieldToUser = false) {
|
|
|
521
588
|
}
|
|
522
589
|
settle();
|
|
523
590
|
ran = true;
|
|
524
|
-
hidBefore = hidRuns; hidLate = false;
|
|
591
|
+
hidBefore = hidRuns; jobHidBase = hidRuns; hidLate = false;
|
|
525
592
|
return fn();
|
|
526
593
|
});
|
|
527
594
|
const drain = () => Promise.all([...lingering]).then(() => {
|
|
@@ -546,11 +613,24 @@ function afterQueuedInput(fn, limitMs) {
|
|
|
546
613
|
});
|
|
547
614
|
}
|
|
548
615
|
// phone_* reads stay in the queue: imctl reads the mirroring window through System Events and
|
|
549
|
-
// captures it, and a read running alongside a phone gesture can catch it mid-transition
|
|
616
|
+
// captures it, and a read running alongside a phone gesture can catch it mid-transition
|
|
550
617
|
const OBSERVE_TOOLS = new Set(["mac_ax_state", "mac_find", "mac_get", "mac_windows", "mac_apps", "mac_screenshot", "mac_status", "mac_wait"]);
|
|
551
618
|
|
|
552
619
|
// ── Mac 层 ──
|
|
553
620
|
|
|
621
|
+
// Screen Recording as the engine's status sees it (no other app's window title can be read without it). Without it
|
|
622
|
+
// a capture holds the desktop picture and the host's own windows only — which reads as "nothing is open". Seen
|
|
623
|
+
// granted once, it is not asked again (a permission taken back makes macOS ask for the host to be reopened);
|
|
624
|
+
// anything else is asked again at the next screenshot.
|
|
625
|
+
let screenRecordingSeen = false;
|
|
626
|
+
const SCREEN_RECORDING_NOTE = "Screen Recording looks not granted to the app that runs noracu (no other app's window title can be read): the image then shows the desktop picture and that app's own windows, not other apps' windows — turn it on in System Settings → Privacy & Security → Screen & System Audio Recording (Screen Recording before macOS 15), then quit and reopen that app";
|
|
627
|
+
async function screenRecordingNote() {
|
|
628
|
+
if (screenRecordingSeen) return null;
|
|
629
|
+
const st = await axEngine({ op: "status" }, 10000);
|
|
630
|
+
if (st?.ok && st.screen_recording === true) { screenRecordingSeen = true; return null; }
|
|
631
|
+
return st?.ok && st.screen_recording === false ? SCREEN_RECORDING_NOTE : null;
|
|
632
|
+
}
|
|
633
|
+
|
|
554
634
|
// 主屏 DPR(backingScaleFactor)读取 — 结果缓存 60s,失败返回 null(截图主路径不依赖它)
|
|
555
635
|
let _mainScaleCache = null; // { value, ts }
|
|
556
636
|
async function mainScreenScale() {
|
|
@@ -563,7 +643,7 @@ async function mainScreenScale() {
|
|
|
563
643
|
}
|
|
564
644
|
|
|
565
645
|
// The frontmost app, by pid, from the accessibility engine (NSWorkspace): no System Events, no
|
|
566
|
-
// Automation permission, and asynchronous under a timer like every other child
|
|
646
|
+
// Automation permission, and asynchronous under a timer like every other child. spec: {} or
|
|
567
647
|
// { app } (name, bundle id or .app path, resolved like every other app argument) or { pid }.
|
|
568
648
|
async function frontmost(spec = {}) {
|
|
569
649
|
const r = await axEngine({ op: "frontmost", ...spec }, 8000);
|
|
@@ -578,14 +658,15 @@ async function frontmostApp() { return (await frontmost())?.front?.name ?? null;
|
|
|
578
658
|
// own app (by pid), the screenshot's window's app, the app named in the call, or — only when the input
|
|
579
659
|
// goes to whatever is in front — the frontmost app. An app that cannot be identified gets nothing (fail
|
|
580
660
|
// closed). The engine names an app's bundle id `bundle`; mac_apps and the gate call it bundle_id.
|
|
581
|
-
// (
|
|
661
|
+
// (device run 2026-11-09: the gate read bundle_id from the engine's `bundle`, so
|
|
582
662
|
// bundle-id patterns, the Terminal/iTerm2 defaults included, never matched)
|
|
583
663
|
const appInfo = (a) => (a && (a.name || a.bundle || a.bundle_id) ? { pid: a.pid, name: a.name ?? null, bundle_id: a.bundle_id ?? a.bundle ?? null } : null);
|
|
584
664
|
function approveKnown(a, what) {
|
|
585
665
|
if (!a) return { error: `input_denied: could not identify ${what} — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
|
|
586
|
-
//
|
|
666
|
+
// bundle-id rules cannot rule out an app whose bundle id is unknown
|
|
587
667
|
if (!a.bundle_id && gateActive()) return { error: `input_denied: "${a.name}" has no readable bundle id, so the deny list / approval file cannot rule it out — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
|
|
588
|
-
|
|
668
|
+
// a Mac app has a name to read: without it, a rule that names apps cannot rule the app out
|
|
669
|
+
const ap = evaluateApproval({ bundleId: a.bundle_id, appName: a.name, needName: true });
|
|
589
670
|
if (ap.error) return { error: ap.error };
|
|
590
671
|
if (ap.verdict === "deny") return { error: `input_denied: "${a.name || a.bundle_id}" — ${ap.reason} (delivery=not_delivered, retry=safe)` };
|
|
591
672
|
if (ap.verdict === "ask") return { error: ap.reason };
|
|
@@ -598,12 +679,14 @@ async function approveTarget(...specs) {
|
|
|
598
679
|
const seen = new Set();
|
|
599
680
|
for (const spec of specs.length ? specs : [{}]) {
|
|
600
681
|
// a pid that was asked for but not read (an AX answer without one) is an app that cannot be identified —
|
|
601
|
-
// never the frontmost app in its place
|
|
682
|
+
// never the frontmost app in its place
|
|
602
683
|
if (Object.hasOwn(spec, "pid") && (spec.pid === undefined || spec.pid === null)) return { error: "input_denied: could not identify the app that would receive the input (no pid) — nothing was sent (fail closed; delivery=not_delivered, retry=safe)" };
|
|
603
684
|
const key = spec.pid !== undefined ? `pid:${spec.pid}` : spec.app !== undefined ? `app:${spec.app}` : "front";
|
|
604
685
|
if (seen.has(key)) continue;
|
|
605
686
|
seen.add(key);
|
|
606
687
|
const r = await frontmost(spec.pid !== undefined ? { pid: spec.pid } : spec.app !== undefined ? { app: spec.app } : {});
|
|
688
|
+
// a name several running apps share: none of them is picked — the engine's refusal lists them
|
|
689
|
+
if (r?.ambiguous) return { error: axErrorText(r.ambiguous) };
|
|
607
690
|
// a named app that is not running gets nothing anyway: say so plainly (an unreadable answer is not this)
|
|
608
691
|
if (r && spec.app !== undefined && spec.pid === undefined && !r.target) return { error: `app_not_found: "${spec.app}" is not running — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
609
692
|
const a = appInfo(spec.pid !== undefined || spec.app !== undefined ? r?.target : r?.front);
|
|
@@ -621,6 +704,7 @@ async function focusGuard(app) {
|
|
|
621
704
|
const r = await frontmost(app === undefined ? {} : { app });
|
|
622
705
|
const fm = r?.front?.name ?? null;
|
|
623
706
|
if (app !== undefined) {
|
|
707
|
+
if (r?.ambiguous) return { error: axErrorText(r.ambiguous) };
|
|
624
708
|
if (!r || !r.front) return { error: "focus_unknown: could not read the frontmost app — no input was sent (delivery=not_delivered, retry=safe)" };
|
|
625
709
|
if (!r.target) return { error: `focus_lost: "${app}" is not running (frontmost is "${fm}") — no input was sent (delivery=not_delivered, retry=safe)` };
|
|
626
710
|
if (!r.match) return { error: `focus_lost: expected "${r.target.name}", frontmost is "${fm}" — no input was sent (delivery=not_delivered, retry=safe)` };
|
|
@@ -630,7 +714,7 @@ async function focusGuard(app) {
|
|
|
630
714
|
return { fm, front: g.app };
|
|
631
715
|
}
|
|
632
716
|
|
|
633
|
-
// cliclick runs asynchronously under a timer like every other child
|
|
717
|
+
// cliclick runs asynchronously under a timer like every other child. A spawn error means nothing
|
|
634
718
|
// was sent; a timeout or a failing exit may come after some of the events went out.
|
|
635
719
|
// pointer: the commands move the pointer (click, drag). With a shared Mac (USER_IDLE_S) the pointer goes back
|
|
636
720
|
// where it was: 0.1 s after cliclick is done, and only while it is still at the last point the commands sent it
|
|
@@ -650,8 +734,11 @@ const POINTER_SCRIPT = `
|
|
|
650
734
|
$.CGAssociateMouseAndMouseCursorPosition(true);
|
|
651
735
|
return 'back';
|
|
652
736
|
}`;
|
|
737
|
+
// test hook (with NORACU_AX_ENGINE only): a stand-in for osascript running POINTER_SCRIPT
|
|
738
|
+
const POINTER_RUNNER = process.env.NORACU_AX_ENGINE && process.env.NORACU_TEST_POINTER ? process.env.NORACU_TEST_POINTER : "/usr/bin/osascript";
|
|
739
|
+
const POINTER_NOT_BACK = "the pointer's position could not be read before the click, so it was not put back";
|
|
653
740
|
const pointerAt = async () => {
|
|
654
|
-
const r = await sh(
|
|
741
|
+
const r = await sh(POINTER_RUNNER, ["-l", "JavaScript", "-e", POINTER_SCRIPT, "--", "get"], 5000);
|
|
655
742
|
const v = r.ok ? r.out.trim().split(",").map(Number) : [];
|
|
656
743
|
return v.length === 2 && v.every(Number.isFinite) ? v : null;
|
|
657
744
|
};
|
|
@@ -661,33 +748,37 @@ const lastPointOf = (cmds) => {
|
|
|
661
748
|
return m ? [Number(m[1].replace("=", "")), Number(m[2].replace("=", ""))] : null;
|
|
662
749
|
};
|
|
663
750
|
async function cliclick(cmds, timeoutMs = 15000, { pointer = false, recovery = false } = {}) {
|
|
664
|
-
//
|
|
751
|
+
// the person's stop file once more, right before events go out — the queue's check can be a
|
|
665
752
|
// second old by now (re-identification, hit test). A recovery mouse-up is never held back: it lets go of a
|
|
666
753
|
// button an earlier event pressed.
|
|
667
754
|
if (!recovery) { const stop = stopFileBlocked(); if (stop) return { ok: false, sent: false, refused: true, out: stop }; }
|
|
668
755
|
const home = pointer && SHARED_INPUT ? await pointerAt() : null;
|
|
669
|
-
if (
|
|
670
|
-
// 0.3.0
|
|
756
|
+
if (!recovery) {
|
|
757
|
+
// 0.3.0: the person-goes-first check once more, as late as it can be made. By now the
|
|
671
758
|
// queue's check is older than the re-identification and the hit test that ran since, and `home` was read a
|
|
672
759
|
// moment ago: someone who took the keyboard or mouse in between keeps it — nothing is sent and the pointer
|
|
673
760
|
// is not touched. What remains is the time from this read to cliclick's first event (two process starts).
|
|
674
|
-
|
|
761
|
+
// Keystrokes are checked like the pointer (they used to go out unchecked, up to seconds after the queue's
|
|
762
|
+
// check when a click came first).
|
|
763
|
+
const busy = await lateUserCheck();
|
|
675
764
|
if (busy) return { ok: false, sent: false, refused: true, out: busy };
|
|
676
765
|
}
|
|
677
766
|
const r = await runAsync(CLICLICK, cmds, { timeoutMs });
|
|
678
767
|
if (!r.error) noteHid(r); // it started, so it may have posted events
|
|
679
768
|
const last = home ? lastPointOf(cmds) : null;
|
|
680
769
|
if (home && last && !r.error) {
|
|
681
|
-
await sh(
|
|
770
|
+
await sh(POINTER_RUNNER, ["-l", "JavaScript", "-e", POINTER_SCRIPT, "--", "back", ...[...home, ...last].map(String)], 5000);
|
|
682
771
|
}
|
|
772
|
+
// the pointer was to go back and its position was not known: the click went out all the same — the result says so
|
|
773
|
+
const pointerNote = pointer && SHARED_INPUT && !home && !r.error ? POINTER_NOT_BACK : null;
|
|
683
774
|
if (r.error) return { ok: false, sent: false, out: r.error.code === "ENOENT" ? "cliclick not found — brew install cliclick (or set NORACU_CLICLICK)" : `cliclick could not start: ${String(r.error.message || r.error).slice(0, 160)}` };
|
|
684
775
|
if (r.timedOut) return { ok: false, sent: "unknown", out: `cliclick did not finish within ${Math.round(timeoutMs / 1000)} s` };
|
|
685
776
|
if (r.code !== 0) return { ok: false, sent: "unknown", out: String(r.stderr || r.stdout || `cliclick exited with ${r.code}`).trim().slice(0, 300) };
|
|
686
|
-
return { ok: true, out: String(r.stdout || "").trim() };
|
|
777
|
+
return { ok: true, out: String(r.stdout || "").trim(), ...(pointerNote ? { pointerNote } : {}) };
|
|
687
778
|
}
|
|
688
779
|
function cliFail(r) { return r.refused ? r.out : r.sent === false ? `${r.out} (delivery=not_delivered, retry=safe)` : `action_failed: ${r.out} (delivery=unknown, retry=unsafe)`; }
|
|
689
780
|
|
|
690
|
-
// 0.3.0
|
|
781
|
+
// 0.3.0: screenshot_id — every mac_screenshot gets one; a window capture also records a geometry
|
|
691
782
|
// fingerprint {pid, bounds} so a later mac_click screenshot_id+x/y (screenshot pixels) can refuse a
|
|
692
783
|
// window that moved, resized or was rebuilt (stale) instead of clicking whatever is there now.
|
|
693
784
|
const SCREENSHOTS = new Map(); // screenshot_id → { window_id?, pid?, bounds?, scale, px, ts } (insertion order = age)
|
|
@@ -701,6 +792,22 @@ function screenshotEntry(id) {
|
|
|
701
792
|
// Test hook (never set in normal use, honoured only with NORACU_AX_ENGINE, like NORACU_AX_TIMEOUT_MS): a
|
|
702
793
|
// program that takes screencapture's argv and writes the PNG to the last argument.
|
|
703
794
|
const SCREENCAPTURE = process.env.NORACU_AX_ENGINE && process.env.NORACU_SCREENCAPTURE ? process.env.NORACU_SCREENCAPTURE : "/usr/sbin/screencapture";
|
|
795
|
+
// Test hook (never set in normal use, honoured only with NORACU_AX_ENGINE, like NORACU_SCREENCAPTURE): the
|
|
796
|
+
// program the wheel script is handed to, so a test sends no wheel event to this Mac
|
|
797
|
+
const WHEEL_RUNNER = process.env.NORACU_AX_ENGINE && process.env.NORACU_TEST_WHEEL ? process.env.NORACU_TEST_WHEEL : "/usr/bin/osascript";
|
|
798
|
+
// One wheel event at a point. Whether the script ran is taken from how it ended, not from what it printed:
|
|
799
|
+
// one that could not be started sent nothing and stamps nothing; one that did start sent its event or may
|
|
800
|
+
// have, so that event is noracu's own (the next input is not refused as the person's), whatever it printed.
|
|
801
|
+
async function wheelAt(dy, dx, px, py) {
|
|
802
|
+
const w = await runAsync(WHEEL_RUNNER, ["-l", "JavaScript", "-e", WHEEL_SCRIPT, "--", String(dy), String(dx), String(px), String(py), SHARED_INPUT ? "1" : "0"], { timeoutMs: 8000 });
|
|
803
|
+
if (w.error && !w.spawned) return { error: `scroll failed: the wheel script could not be started (${String(w.error.code || w.error.message || w.error).slice(0, 80)}) (delivery=not_delivered, retry=safe)` };
|
|
804
|
+
noteHid(w);
|
|
805
|
+
if (w.error || w.timedOut || w.overflow || w.code !== 0) {
|
|
806
|
+
const why = w.timedOut ? "the wheel script did not finish within 8 s" : String(w.stderr || w.stdout || w.error?.message || `exit ${w.code}`).trim().slice(0, 200);
|
|
807
|
+
return { error: `scroll failed: ${why} (delivery=unknown, retry=unsafe)` };
|
|
808
|
+
}
|
|
809
|
+
return {};
|
|
810
|
+
}
|
|
704
811
|
const windowById = async (id) => {
|
|
705
812
|
const wl = await axEngine({ op: "windows" }, 15000);
|
|
706
813
|
return (wl?.ok ? wl.windows || [] : []).find((w) => w.id === id && Array.isArray(w.bounds) && w.bounds[2] > 0 && w.bounds[3] > 0) || null;
|
|
@@ -737,7 +844,7 @@ async function macScreenshot(args = {}) {
|
|
|
737
844
|
// DPR 元数据 — logical_size 单位 = 显示点(mac_click 坐标系)
|
|
738
845
|
// 全屏:像素尺寸读 PNG IHDR(bytes 16-23,big-endian)÷ 主屏 scale
|
|
739
846
|
// region:-R rect 本身是点坐标 → logical_size 直接取 region 的 w,h(实测 2x 屏 100pt rect 出 200px PNG)
|
|
740
|
-
// window(0.3.0
|
|
847
|
+
// window(0.3.0):按窗口所在显示器的 scale = PNG 宽 ÷ 窗口宽(点),不再一律取主屏的
|
|
741
848
|
let scale = await mainScreenScale();
|
|
742
849
|
if (args.display !== undefined && args.window_id === undefined) {
|
|
743
850
|
// a display other than the main one may have another backing scale (a 1x screen next to a 2x laptop panel)
|
|
@@ -763,18 +870,20 @@ async function macScreenshot(args = {}) {
|
|
|
763
870
|
const entry = { scale, px: pngW && pngH ? [pngW, pngH] : null, ts: Date.now() };
|
|
764
871
|
if (win && !args.region) Object.assign(entry, { window_id: args.window_id, pid: win.pid, bounds: win.bounds });
|
|
765
872
|
else if (args.window_id !== undefined) meta.screenshot_note = "the window moved or could not be measured during the capture: this screenshot_id has no window fingerprint, so mac_click cannot take its pixels — capture again";
|
|
766
|
-
// bounded: expired ids go first, then the oldest one (
|
|
873
|
+
// bounded: expired ids go first, then the oldest one (clear() dropped ids still in their 30 s)
|
|
767
874
|
for (const [k, v] of SCREENSHOTS) if (Date.now() - v.ts > SCREENSHOT_TTL_MS) SCREENSHOTS.delete(k);
|
|
768
875
|
while (SCREENSHOTS.size >= SCREENSHOT_MAX) SCREENSHOTS.delete(SCREENSHOTS.keys().next().value);
|
|
769
876
|
SCREENSHOTS.set(screenshot_id, entry);
|
|
770
877
|
meta.screenshot_id = screenshot_id;
|
|
878
|
+
const sr = await screenRecordingNote();
|
|
879
|
+
if (sr) meta.screen_recording_note = sr;
|
|
771
880
|
return { image: png.toString("base64"), mime: "image/png", meta };
|
|
772
881
|
}
|
|
773
882
|
|
|
774
883
|
// ── Mac 层:无障碍引擎(src/mac-ax.js)──
|
|
775
884
|
// Every accessibility read and every semantic action runs in one short-lived osascript process that
|
|
776
885
|
// executes the static engine file with the request as JSON on stdin (identity model: see mac-ax.js).
|
|
777
|
-
// It runs asynchronously under a timer like imctl
|
|
886
|
+
// It runs asynchronously under a timer like imctl, so a hung app cannot freeze the server.
|
|
778
887
|
// NORACU_AX_ENGINE=<executable> replaces the engine with a program that speaks the same protocol (one
|
|
779
888
|
// JSON request on stdin, one JSON reply on stdout) — the test suite uses it to exercise the server's Mac
|
|
780
889
|
// logic without macOS permissions. Like NORACU_PYTHON / NORACU_CLICLICK it names a program to run.
|
|
@@ -788,20 +897,21 @@ const AX_TIMEOUT_MS = (() => {
|
|
|
788
897
|
return 30000;
|
|
789
898
|
})();
|
|
790
899
|
const MUTATING_OPS = new Set(["act", "set_value", "insert_text", "menu", "window_op", "app_ctl", "scroll_prep", "paste", "key"]);
|
|
791
|
-
async function axEngine(req, timeoutMs = AX_TIMEOUT_MS) {
|
|
900
|
+
async function axEngine(req, timeoutMs = AX_TIMEOUT_MS, live) {
|
|
792
901
|
const budgetMs = Number.isFinite(req?.timeout_ms) ? Math.max(timeoutMs, Number(req.timeout_ms) + 12000) : timeoutMs;
|
|
793
902
|
const mutating = MUTATING_OPS.has(req?.op) || (req?.op === "notifications" && req.action !== undefined && req.action !== "list");
|
|
794
903
|
if (mutating) {
|
|
795
|
-
// the stop file right before an action goes out
|
|
904
|
+
// the stop file right before an action goes out, as in cliclick
|
|
796
905
|
const stop = stopFileBlocked();
|
|
797
906
|
const m = stop && /^([a-z_]+): ([\s\S]*)$/.exec(stop);
|
|
798
907
|
if (m) return { ok: false, code: m[1].toUpperCase(), message: m[2] };
|
|
799
908
|
}
|
|
800
|
-
const r = await runAsync(AX_ENGINE_CMD[0], AX_ENGINE_CMD[1], { timeoutMs: budgetMs, input: JSON.stringify(req) });
|
|
909
|
+
const r = await runAsync(AX_ENGINE_CMD[0], AX_ENGINE_CMD[1], { timeoutMs: budgetMs, input: JSON.stringify(req), live });
|
|
801
910
|
if (!r.error && (req?.op === "key" || req?.op === "paste")) noteHid(r); // the engine's two ops that post HID events
|
|
802
911
|
if (r.timedOut) return { ok: false, code: "TIMEOUT", message: `the accessibility engine did not answer within ${Math.round(budgetMs / 1000)}s — the target app may be busy or hung${req?.op === "paste" ? " (clipboard restored: unknown — it may still hold the pasted text)" : ""}`, ...(mutating ? { delivery: "unknown", retry: "unsafe" } : {}) };
|
|
803
912
|
// a mutating op whose engine was stopped or answered garbage may have acted; one that never started did not
|
|
804
913
|
const maybe = mutating ? { delivery: "unknown", retry: "unsafe" } : {};
|
|
914
|
+
if (r.cancelled) return { ok: false, code: "CANCELLED", message: "the client cancelled the call — the accessibility engine was stopped", ...maybe };
|
|
805
915
|
if (r.overflow) return { ok: false, code: "INTERNAL", message: "the accessibility engine printed more than 10 MB and was stopped", ...maybe };
|
|
806
916
|
if (r.error) return { ok: false, code: "INTERNAL", message: `osascript could not run: ${String(r.error.message || r.error).slice(0, 200)}`, ...(mutating ? { delivery: "not_delivered", retry: "safe" } : {}) };
|
|
807
917
|
const out = String(r.stdout || "").trim();
|
|
@@ -818,7 +928,7 @@ const AX_ERROR_PREFIX = {
|
|
|
818
928
|
ACTION_NOT_SUPPORTED: "action_not_supported", ACTION_FAILED: "action_failed", OCCLUDED: "occluded",
|
|
819
929
|
APP_UNRESPONSIVE: "app_unresponsive", NOT_CONFIRMED: "not_confirmed", POLICY_DENIED: "policy_denied", INTERNAL: "ax_error",
|
|
820
930
|
FOCUS_LOST: "focus_lost", FOCUS_UNKNOWN: "focus_unknown", CLIPBOARD_REMOTE: "clipboard_remote", CLIPBOARD_TOO_LARGE: "clipboard_too_large",
|
|
821
|
-
NOTIFICATION_NOT_FOUND: "notification_not_found",
|
|
931
|
+
NOTIFICATION_NOT_FOUND: "notification_not_found", CANCELLED: "cancelled",
|
|
822
932
|
};
|
|
823
933
|
function axErrorText(e) {
|
|
824
934
|
const prefix = AX_ERROR_PREFIX[e.code] || String(e.code || "ax_error").toLowerCase();
|
|
@@ -904,11 +1014,11 @@ async function macAxState(args = {}) {
|
|
|
904
1014
|
}
|
|
905
1015
|
const o = { app: res.app, pid: res.pid, snapshot_id: snap.id, surface: res.surface };
|
|
906
1016
|
if (drill) o.root = args.root;
|
|
907
|
-
if (res.window) o.window = { title: res.window.title, frame: res.window.frame, window_id: res.window.window_id };
|
|
1017
|
+
if (res.window) o.window = { title: res.window.title, frame: res.window.frame, window_id: res.window.window_id, ...(res.window.title_match ? { title_match: res.window.title_match } : {}) };
|
|
908
1018
|
o.complete = res.complete;
|
|
909
1019
|
o.truncated = !res.complete;
|
|
910
1020
|
if (res.web_accessibility) o.web_accessibility = res.web_accessibility;
|
|
911
|
-
if (res.web_accessibility === "unsupported") o.web_accessibility_hint = WEB_AX_HINT;
|
|
1021
|
+
if (res.web_accessibility === "unsupported" || res.web_accessibility === "unknown") o.web_accessibility_hint = WEB_AX_HINT;
|
|
912
1022
|
if (res.window_identity) { o.window_identity = res.window_identity; o.window_identity_hint = WINDOW_ID_HINT; }
|
|
913
1023
|
o.elements = elements;
|
|
914
1024
|
if (!res.complete) o.hint = "partial tree: raise depth or max_nodes, use interactive:true, or drill into one element with root";
|
|
@@ -916,7 +1026,8 @@ async function macAxState(args = {}) {
|
|
|
916
1026
|
}
|
|
917
1027
|
|
|
918
1028
|
// web_accessibility "unsupported": the app refused AXManualAccessibility and no web content was found in
|
|
919
|
-
// the window (Google Chrome does this); "exposed": it refused, but its pages are in the tree anyway
|
|
1029
|
+
// the window (Google Chrome does this); "exposed": it refused, but its pages are in the tree anyway; "unknown": it
|
|
1030
|
+
// refused, and the window was too large to look through for web content in time (the hint goes with it too).
|
|
920
1031
|
// window_identity "unverifiable": the window has no CGWindowID (seen only on Finder's desktop, which is
|
|
921
1032
|
// exempt), so element_index actions in it are refused with policy_denied.
|
|
922
1033
|
const WINDOW_ID_HINT = "this window has no window ID, so a closed and reopened window with the same title could not be told apart from it: element_index actions here are refused (policy_denied). Use mac_menu_command, or mac_click x,y (checked against the window on top)";
|
|
@@ -933,7 +1044,7 @@ async function macFind(args = {}) {
|
|
|
933
1044
|
const matches = addItems(snap, res, res.nodes, true);
|
|
934
1045
|
const o = { app: res.app, pid: res.pid, snapshot_id: snap.id, count: matches.length, complete: res.complete };
|
|
935
1046
|
if (res.web_accessibility) o.web_accessibility = res.web_accessibility;
|
|
936
|
-
if (res.web_accessibility === "unsupported") o.web_accessibility_hint = WEB_AX_HINT;
|
|
1047
|
+
if (res.web_accessibility === "unsupported" || res.web_accessibility === "unknown") o.web_accessibility_hint = WEB_AX_HINT;
|
|
937
1048
|
if (res.window_identity) { o.window_identity = res.window_identity; o.window_identity_hint = WINDOW_ID_HINT; }
|
|
938
1049
|
o.matches = matches;
|
|
939
1050
|
return { text: JSON.stringify(o) };
|
|
@@ -956,7 +1067,7 @@ async function macStatus() {
|
|
|
956
1067
|
out.noracu = LOADED.version;
|
|
957
1068
|
out.node = process.versions.node;
|
|
958
1069
|
out.read_only = process.env.NORACU_READ_ONLY === "1";
|
|
959
|
-
//
|
|
1070
|
+
// browser_evaluate is opt-in
|
|
960
1071
|
out.browser_evaluate = process.env.NORACU_DISABLE_EVAL === "1" ? "off (NORACU_DISABLE_EVAL=1)" : process.env.NORACU_ENABLE_EVAL === "1" ? "on (NORACU_ENABLE_EVAL=1)" : "off (default; NORACU_ENABLE_EVAL=1 turns it on)";
|
|
961
1072
|
out.chrome = process.env.NORACU_ALLOW_CHROME === "1" ? `allowed (NORACU_ALLOW_CHROME=1): browser_launch chrome:true works in your own Chrome — ${process.env.NORACU_CHROME_TABS === "all" ? "all your tabs (NORACU_CHROME_TABS=all)" : "only the tabs noracu opens"}` : "off (default; NORACU_ALLOW_CHROME=1 lets browser_launch chrome:true work in your own Chrome)";
|
|
962
1073
|
out.user_idle_s = USER_IDLE_S; // 0.2.7: Mac/iPhone input waits this long after the person's last keyboard or mouse input (0: off)
|
|
@@ -1024,7 +1135,7 @@ const CLICK_VERB = { left: "c:", right: "rc:", middle: "mc:" };
|
|
|
1024
1135
|
const cc = (v) => { const n = Math.round(Number(v)); return n < 0 ? `=${n}` : String(n); };
|
|
1025
1136
|
const ccPoint = (x, y) => `${cc(x)},${cc(y)}`;
|
|
1026
1137
|
// a left double or triple click is one cliclick verb (dc: / tc:): repeated c: posts single clicks with a click count of 1
|
|
1027
|
-
// each, which apps do not take for a double click
|
|
1138
|
+
// each, which apps do not take for a double click
|
|
1028
1139
|
const clickCmds = (button, count, x, y) => (button === "left" && (count === 2 || count === 3)
|
|
1029
1140
|
? [`${count === 2 ? "dc:" : "tc:"}${ccPoint(x, y)}`]
|
|
1030
1141
|
: Array(count).fill(`${CLICK_VERB[button] || "c:"}${ccPoint(x, y)}`));
|
|
@@ -1033,10 +1144,18 @@ const clickCmds = (button, count, x, y) => (button === "left" && (count === 2 ||
|
|
|
1033
1144
|
// element's window (by CGWindowID; by app when the element's window has none, e.g. Finder's desktop).
|
|
1034
1145
|
// Something that came on top in between refuses the input, nothing sent (Reddit r/mcp review 2026-11-06).
|
|
1035
1146
|
async function lateTopCheck(points) {
|
|
1036
|
-
for (const { point: [x, y], pid, wid } of points) {
|
|
1147
|
+
for (const { point: [x, y], pid, wid, topWid } of points) {
|
|
1037
1148
|
const r = await frontmost({ at: [x, y] });
|
|
1038
1149
|
if (!r || r.top === undefined) return { error: `focus_unknown: could not re-check the window on top at ${x},${y} right before the input — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1039
1150
|
const top = r.top;
|
|
1151
|
+
// An element with no window id of its own (a menu item, a menu bar item, Finder's desktop): the engine noted
|
|
1152
|
+
// which window was on top at its point when it hit-tested it, and it must still be that one. A menu that
|
|
1153
|
+
// closed leaves the app's own window or the desktop there; and the menu bar is the window server's window,
|
|
1154
|
+
// so whose window is on top says nothing for these.
|
|
1155
|
+
if (!wid && topWid !== undefined) {
|
|
1156
|
+
if ((top ? top.wid : null) !== topWid) return { error: `occluded: what is on top at ${x},${y} changed between the hit test and the input (a menu that closed, a window that came up) — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1040
1159
|
if (!top) { if (wid) return { error: `occluded: the element's window is no longer on screen at ${x},${y} (it moved or closed after the hit test) — nothing was sent (delivery=not_delivered, retry=safe)` }; continue; }
|
|
1041
1160
|
if (top.pid !== pid || (wid && top.wid !== wid)) return { error: `occluded: a window of "${top.owner}" came on top at ${x},${y} between the hit test and the input — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1042
1161
|
}
|
|
@@ -1053,8 +1172,8 @@ async function testGap(what) {
|
|
|
1053
1172
|
}
|
|
1054
1173
|
|
|
1055
1174
|
// bgpost children run like every other child: timed, killed on shutdown, waited for by the input queue
|
|
1056
|
-
// (
|
|
1057
|
-
// a stop file that appeared since the queue's check: nothing is posted, and the fallback path refuses on its own
|
|
1175
|
+
// (they ran outside activeChildren / lingering)
|
|
1176
|
+
// a stop file that appeared since the queue's check: nothing is posted, and the fallback path refuses on its own
|
|
1058
1177
|
const bgRun = (argv) => {
|
|
1059
1178
|
const stop = stopFileBlocked();
|
|
1060
1179
|
if (stop) return Promise.resolve({ error: Object.assign(new Error(stop), { code: "STOPPED" }) });
|
|
@@ -1070,10 +1189,10 @@ async function physicalClickAt(target, label, button, count, timeoutMs, { real =
|
|
|
1070
1189
|
if (!prep.ok) return { error: axErrorText(prep) };
|
|
1071
1190
|
const [x, y] = prep.point;
|
|
1072
1191
|
// the approval check judges the element's own app (the hit test proved the point reaches it) —
|
|
1073
|
-
// whether or not bgpost is on
|
|
1192
|
+
// whether or not bgpost is on
|
|
1074
1193
|
const gate = await approveTarget({ pid: prep.pid });
|
|
1075
1194
|
if (gate.error) return { error: gate.error };
|
|
1076
|
-
const late = await lateTopCheck([{ point: prep.point, pid: prep.pid, wid: prep.wid }]);
|
|
1195
|
+
const late = await lateTopCheck([{ point: prep.point, pid: prep.pid, wid: prep.wid, topWid: prep.top_wid }]);
|
|
1077
1196
|
if (late.error) return { error: late.error };
|
|
1078
1197
|
await testGap(`physical click at ${x},${y}`);
|
|
1079
1198
|
// 0.3.0 bgpost route (src/bg-inject.js): a native app gets the click posted straight to its pid —
|
|
@@ -1087,22 +1206,24 @@ async function physicalClickAt(target, label, button, count, timeoutMs, { real =
|
|
|
1087
1206
|
// a timeout or an odd exit may have posted some events: never send the click again another way
|
|
1088
1207
|
else if (b.sent !== false) return { error: `action_failed: ${b.error} — the click may or may not have been posted (delivery=unknown, retry=unsafe)` };
|
|
1089
1208
|
// proven not posted (bad pid, events not created): the real pointer below, after the window on top is
|
|
1090
|
-
// checked again — the bgpost attempt took time
|
|
1209
|
+
// checked again — the bgpost attempt took time
|
|
1091
1210
|
else {
|
|
1092
1211
|
route = "cliclick (bgpost not posted)";
|
|
1093
|
-
const again = await lateTopCheck([{ point: prep.point, pid: prep.pid, wid: prep.wid }]);
|
|
1212
|
+
const again = await lateTopCheck([{ point: prep.point, pid: prep.pid, wid: prep.wid, topWid: prep.top_wid }]);
|
|
1094
1213
|
if (again.error) return { error: again.error };
|
|
1095
1214
|
}
|
|
1096
1215
|
}
|
|
1216
|
+
let pointerNote = null;
|
|
1097
1217
|
if (route !== "bgpost") {
|
|
1098
1218
|
const r = await cliclick(clickCmds(button, count, x, y), undefined, { pointer: true });
|
|
1099
1219
|
if (!r.ok) return { error: cliFail(r) };
|
|
1220
|
+
pointerNote = r.pointerNote || null;
|
|
1100
1221
|
}
|
|
1101
1222
|
await sleep(250);
|
|
1102
1223
|
const after = await axEngine({ op: "observe_after", target, before: prep.before, physical: true, point: prep.point, wid: prep.wid || null });
|
|
1103
1224
|
const res = after.ok ? { ...after } : { delivery: "delivered_unverified", retry: "unsafe" };
|
|
1104
1225
|
if (route === "bgpost" && res.delivery !== "delivered_verified") res.note = res.note ? `${res.note}; ${BG_UNVERIFIED_NOTE}` : BG_UNVERIFIED_NOTE;
|
|
1105
|
-
return { text: actText(`clicked ${button} x${count} on ${label} @ ${x},${y}`, { ...res, mechanism: "physical", hit: prep.hit, reason: prep.reason }) + ` (route: ${route})` + await frontmostNote() };
|
|
1226
|
+
return { text: actText(`clicked ${button} x${count} on ${label} @ ${x},${y}`, { ...res, mechanism: "physical", hit: prep.hit, reason: prep.reason }) + ` (route: ${route})` + (pointerNote ? ` — ${pointerNote}` : "") + await frontmostNote() };
|
|
1106
1227
|
}
|
|
1107
1228
|
|
|
1108
1229
|
// A raw x,y click has no element to re-identify, so before anything is sent the window server is asked
|
|
@@ -1111,12 +1232,13 @@ async function physicalClickAt(target, label, button, count, timeoutMs, { real =
|
|
|
1111
1232
|
// between this check and the click; force:true skips it.
|
|
1112
1233
|
const MENU_BAR_LAYER = 24;
|
|
1113
1234
|
// scroll: mac_scroll's wording — it takes no force and no app, so its refusals point at element_index instead
|
|
1114
|
-
// (
|
|
1235
|
+
// (device run 2026-11-07, the click advice "pass force:true" leaked into mac_scroll's occluded message)
|
|
1115
1236
|
// pid (0.3.0): the target is the app of that pid (a screenshot's window) instead of app or the frontmost app;
|
|
1116
|
-
// wid: and that very window must be the one on top at the point (
|
|
1117
|
-
//
|
|
1237
|
+
// wid: and that very window must be the one on top at the point (another window of the same app, or its menu
|
|
1238
|
+
// bar, would pass an app-only check)
|
|
1118
1239
|
async function rawPointGuard(x, y, app, { scroll = false, pid, wid } = {}) {
|
|
1119
1240
|
const r = await frontmost(pid !== undefined ? { pid, at: [x, y] } : app === undefined ? { at: [x, y] } : { app, at: [x, y] });
|
|
1241
|
+
if (r?.ambiguous) return { error: axErrorText(r.ambiguous) };
|
|
1120
1242
|
const named = pid !== undefined ? `pid ${pid}` : app;
|
|
1121
1243
|
const v = scroll
|
|
1122
1244
|
? rawPointVerdict(r, x, y, named, "pass element_index to scroll a specific element", "scroll", false)
|
|
@@ -1159,7 +1281,7 @@ async function macClick(args) {
|
|
|
1159
1281
|
if (typeof x !== "number" || typeof y !== "number") return { error: "invalid_args: x,y numbers or element_index required (delivery=not_delivered, retry=safe)" };
|
|
1160
1282
|
if (mechanism === "semantic") return { error: "invalid_args: x,y clicks are physical; mechanism \"semantic\" needs an element_index (delivery=not_delivered, retry=safe)" };
|
|
1161
1283
|
let px = x, py = y, viaShot = "", shot = null;
|
|
1162
|
-
// 0.3.0
|
|
1284
|
+
// 0.3.0: screenshot_id + x,y names screenshot pixels (mac_screenshot meta). The window's
|
|
1163
1285
|
// geometry fingerprint is re-checked first — pid and bounds must match exactly (0 px): a window
|
|
1164
1286
|
// that moved, resized or was rebuilt since the capture is stale, nothing is sent.
|
|
1165
1287
|
if (args.screenshot_id !== undefined) {
|
|
@@ -1176,17 +1298,18 @@ async function macClick(args) {
|
|
|
1176
1298
|
if (!w) return { error: `stale: window ${e.window_id} of the screenshot is gone — take a new mac_screenshot (delivery=not_delivered, retry=safe)` };
|
|
1177
1299
|
if (w.pid !== e.pid || String(w.bounds) !== String(e.bounds)) return { error: `stale: window ${e.window_id} moved or resized since the screenshot (was ${e.bounds}, now ${w.bounds}) — take a new mac_screenshot (delivery=not_delivered, retry=safe)` };
|
|
1178
1300
|
// screenshot pixels are relative to the window's own top-left corner, at the scale of its display
|
|
1179
|
-
// (
|
|
1301
|
+
// (the window origin was left out, so the click landed off by bounds.x,bounds.y)
|
|
1180
1302
|
if (Array.isArray(e.px) && !(x >= 0 && y >= 0 && x < e.px[0] && y < e.px[1])) return { error: `invalid_args: ${x},${y} is outside the screenshot (${e.px[0]}×${e.px[1]} pixels) — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1181
1303
|
const sc = e.scale && e.scale > 0 ? e.scale : 1;
|
|
1182
1304
|
// floor, then clamp inside the window: the last pixel column/row must not round onto the next point
|
|
1183
1305
|
px = Math.min(Math.floor(e.bounds[0] + x / sc), e.bounds[0] + e.bounds[2] - 1);
|
|
1184
1306
|
py = Math.min(Math.floor(e.bounds[1] + y / sc), e.bounds[1] + e.bounds[3] - 1);
|
|
1185
1307
|
viaShot = `screenshot pixels ${x},${y} at scale ${sc} of window ${e.window_id} (fingerprint verified); `;
|
|
1186
|
-
// app with screenshot_id: the screenshot's window must belong to that very app (
|
|
1308
|
+
// app with screenshot_id: the screenshot's window must belong to that very app (
|
|
1187
1309
|
// the app was ignored once the screenshot named a pid, so the click went to another app's window)
|
|
1188
1310
|
if (args.app !== undefined) {
|
|
1189
1311
|
const fa = await frontmost({ app: args.app });
|
|
1312
|
+
if (fa?.ambiguous) return { error: axErrorText(fa.ambiguous) };
|
|
1190
1313
|
if (!fa || !fa.target) return { error: `focus_lost: "${args.app}" is not running — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1191
1314
|
if (fa.target.pid !== e.pid) return { error: `focus_lost: window ${e.window_id} of the screenshot belongs to pid ${e.pid}, not to "${fa.target.name ?? args.app}" — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1192
1315
|
}
|
|
@@ -1202,7 +1325,7 @@ async function macClick(args) {
|
|
|
1202
1325
|
// the app the click will reach — and, for a screenshot click, the screenshot's app too
|
|
1203
1326
|
const at = await frontmost({ at: [px, py] });
|
|
1204
1327
|
ownerPid = pointOwnerPid(at);
|
|
1205
|
-
// no window there: the bare desktop, which Finder draws and which gets the click
|
|
1328
|
+
// no window there: the bare desktop, which Finder draws and which gets the click
|
|
1206
1329
|
if (ownerPid === undefined && at && at.top === null) ownerPid = "finder";
|
|
1207
1330
|
if (ownerPid === undefined) return { error: `input_denied: could not identify the app on top at ${px},${py}, which would receive the click — nothing was sent (fail closed; delivery=not_delivered, retry=safe)` };
|
|
1208
1331
|
}
|
|
@@ -1213,14 +1336,14 @@ async function macClick(args) {
|
|
|
1213
1336
|
const late = await lateTopCheck([{ point: [px, py], pid: shot.pid, wid: shot.window_id }]);
|
|
1214
1337
|
if (late.error) return { error: late.error };
|
|
1215
1338
|
// ... and has not moved since its fingerprint was checked: a window dragged a little can stay on top at
|
|
1216
|
-
// the old point while the control under it changed
|
|
1339
|
+
// the old point while the control under it changed
|
|
1217
1340
|
const wl = await axEngine({ op: "windows" }, 15000);
|
|
1218
1341
|
const w = (wl?.ok ? wl.windows || [] : []).find((w) => w.id === shot.window_id);
|
|
1219
1342
|
if (!w || w.pid !== shot.pid || String(w.bounds) !== String(shot.bounds)) return { error: `stale: window ${shot.window_id} moved, resized or closed just before the click — nothing was sent; take a new mac_screenshot (delivery=not_delivered, retry=safe)` };
|
|
1220
1343
|
}
|
|
1221
1344
|
const r = await cliclick(clickCmds(button, count, px, py), undefined, { pointer: true });
|
|
1222
1345
|
if (!r.ok) return { error: cliFail(r) };
|
|
1223
|
-
return { text: `clicked ${button} x${count} @ ${px},${py} (xy; ${viaShot}physical, ${checked}; no element to verify — delivery=delivered_unverified, retry=unsafe)${await frontmostNote()}` };
|
|
1346
|
+
return { text: `clicked ${button} x${count} @ ${px},${py} (xy; ${viaShot}physical, ${checked}; no element to verify — delivery=delivered_unverified, retry=unsafe)${r.pointerNote ? ` — ${r.pointerNote}` : ""}${await frontmostNote()}` };
|
|
1224
1347
|
}
|
|
1225
1348
|
const l = lookupIndex(args.element_index, args.snapshot_id);
|
|
1226
1349
|
if (l.error) return { error: l.error };
|
|
@@ -1261,7 +1384,7 @@ async function macDrag(args) {
|
|
|
1261
1384
|
// both ends' apps are judged (a drop into another app is input to that app too)
|
|
1262
1385
|
const gate = await approveTarget({ pid: prep.pid }, { pid: prepTo.pid });
|
|
1263
1386
|
if (gate.error) return { error: gate.error };
|
|
1264
|
-
const late = await lateTopCheck([{ point: from, pid: prep.pid, wid: prep.wid }, { point: to, pid: prepTo.pid, wid: prepTo.wid }]);
|
|
1387
|
+
const late = await lateTopCheck([{ point: from, pid: prep.pid, wid: prep.wid, topWid: prep.top_wid }, { point: to, pid: prepTo.pid, wid: prepTo.wid, topWid: prepTo.top_wid }]);
|
|
1265
1388
|
if (late.error) return { error: late.error };
|
|
1266
1389
|
await testGap(`drag ${from} → ${to}`);
|
|
1267
1390
|
}
|
|
@@ -1279,11 +1402,11 @@ async function macDrag(args) {
|
|
|
1279
1402
|
const up = await cliclick([`du:${ccPoint(to[0], to[1])}`], 5000, { recovery: true });
|
|
1280
1403
|
return { error: `${cliFail(r)} — a mouse-up was sent at ${to} ${up.ok ? "to release the button" : `but failed too (${up.out.slice(0, 80)}): the button may still be held`}` };
|
|
1281
1404
|
}
|
|
1282
|
-
return r.ok ? { text: `dragged ${from} → ${to} (${note}; physical${holdMs ? `, hold ${holdMs}ms` : ""}${stepMs ? `, ${stepMs}ms steps` : ""} — check the drop target: delivery=delivered_unverified, retry=unsafe)` } : { error: cliFail(r) };
|
|
1405
|
+
return r.ok ? { text: `dragged ${from} → ${to} (${note}; physical${holdMs ? `, hold ${holdMs}ms` : ""}${stepMs ? `, ${stepMs}ms steps` : ""} — check the drop target: delivery=delivered_unverified, retry=unsafe)${r.pointerNote ? ` — ${r.pointerNote.replace("the click", "the drag")}` : ""}` } : { error: cliFail(r) };
|
|
1283
1406
|
}
|
|
1284
1407
|
// 0.3.0 hold_ms / step_ms (physical path only): hold_ms presses and holds after mouse-down before the move
|
|
1285
1408
|
// starts (timeline editors use it to tell clip-move from marquee selection); step_ms moves in steps of about
|
|
1286
|
-
// 20 points with that many ms between them.
|
|
1409
|
+
// 20 points with that many ms between them. the whole gesture must fit well inside
|
|
1287
1410
|
// cliclick's timer — a cliclick killed mid-drag would leave the mouse button down — so over DRAG_MAX_MS of
|
|
1288
1411
|
// waits nothing is sent, and the timer allows the waits plus 15 s.
|
|
1289
1412
|
const DRAG_MAX_MS = 10000;
|
|
@@ -1354,14 +1477,13 @@ async function macScroll(args) {
|
|
|
1354
1477
|
if (g.error) return { error: g.error };
|
|
1355
1478
|
const gate = await approveTarget({ pid: g.pid }); // 0.3.0: the app on top at that point (the frontmost app)
|
|
1356
1479
|
if (gate.error) return { error: gate.error };
|
|
1357
|
-
// the stop file right before the wheel event goes out, as in cliclick
|
|
1480
|
+
// the stop file right before the wheel event goes out, as in cliclick
|
|
1358
1481
|
const stop = stopFileBlocked();
|
|
1359
1482
|
if (stop) return { error: stop };
|
|
1360
|
-
const
|
|
1361
|
-
|
|
1362
|
-
return r.ok
|
|
1483
|
+
const w = await wheelAt(dy, dx, px, py);
|
|
1484
|
+
return !w.error
|
|
1363
1485
|
? { text: `scrolled ${direction} ${pages} page(s) at the center of ${win.title ? JSON.stringify(win.title) : "the front window"} of "${front.name}" (top window: ${g.owner}; physical — delivery=delivered_unverified, retry=unsafe)` }
|
|
1364
|
-
: { error:
|
|
1486
|
+
: { error: w.error };
|
|
1365
1487
|
}
|
|
1366
1488
|
const l = lookupIndex(args.element_index, args.snapshot_id);
|
|
1367
1489
|
if (l.error) return { error: l.error };
|
|
@@ -1371,9 +1493,21 @@ async function macScroll(args) {
|
|
|
1371
1493
|
if (gate.error) return { error: gate.error };
|
|
1372
1494
|
const prep = await axEngine({ op: "scroll_prep", target });
|
|
1373
1495
|
if (!prep.ok) return { error: axErrorText(prep) };
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1496
|
+
// an element that is not a scroll area was asked to scroll itself into view; the engine says whether it is there now
|
|
1497
|
+
if (prep.scrolled_into_view !== undefined) return { text: actText(prep.scrolled_into_view ? `scrolled ${label} into view` : `asked ${label} to scroll into view`, prep) };
|
|
1498
|
+
// what is on top at the point, once more right before the wheel event, as for a click: a window that came up since
|
|
1499
|
+
// the hit test would be scrolled instead
|
|
1500
|
+
const late = await lateTopCheck([{ point: prep.point, pid: prep.pid, wid: prep.wid, topWid: prep.top_wid }]);
|
|
1501
|
+
if (late.error) return { error: late.error };
|
|
1502
|
+
// the stop file right before the wheel event goes out, as for a scroll that names no element
|
|
1503
|
+
const stop = stopFileBlocked();
|
|
1504
|
+
if (stop) return { error: stop };
|
|
1505
|
+
// the person-goes-first check once more, as late as it can be made: the queue's check is older than the
|
|
1506
|
+
// approval and the engine's look at the element by now, and nothing of this call has gone out yet
|
|
1507
|
+
const busy = await lateUserCheck();
|
|
1508
|
+
if (busy) return { error: busy };
|
|
1509
|
+
const w = await wheelAt(dy, dx, prep.point[0], prep.point[1]);
|
|
1510
|
+
if (w.error) return { error: w.error };
|
|
1377
1511
|
await sleep(300);
|
|
1378
1512
|
const after = await axEngine({ op: "observe_after", target, before: prep.before, keys: ["vscroll", "hscroll"] });
|
|
1379
1513
|
const res = after.ok ? after : { delivery: "delivered_unverified", retry: "unsafe" };
|
|
@@ -1384,7 +1518,7 @@ async function macScroll(args) {
|
|
|
1384
1518
|
async function macSetValue(args) {
|
|
1385
1519
|
const l = lookupIndex(args.element_index, args.snapshot_id);
|
|
1386
1520
|
if (l.error) return { error: l.error };
|
|
1387
|
-
// 0.3.0: the element's own app, not the frontmost one (
|
|
1521
|
+
// 0.3.0: the element's own app, not the frontmost one (a background denied app's field was writable)
|
|
1388
1522
|
const gate = await approveTarget({ pid: l.item.pid });
|
|
1389
1523
|
if (gate.error) return { error: gate.error };
|
|
1390
1524
|
const res = await axEngine({ op: "set_value", target: targetOf(l.item), value: String(args.value), timeout_ms: args.timeout_ms });
|
|
@@ -1512,6 +1646,9 @@ async function macKey(args) {
|
|
|
1512
1646
|
if (b.sent !== false) return { error: `action_failed: ${b.error} — the key may or may not have been posted (delivery=unknown, retry=unsafe)` };
|
|
1513
1647
|
// proven not posted: the engine path below
|
|
1514
1648
|
}
|
|
1649
|
+
// the key goes out through the HID system like cliclick's: the person-goes-first check once more
|
|
1650
|
+
const busy = await lateUserCheck();
|
|
1651
|
+
if (busy) return { error: busy };
|
|
1515
1652
|
const r = await axEngine({ op: "key", ...ek }, 8000);
|
|
1516
1653
|
const how = ek.char !== undefined && Number.isInteger(r.code) ? `HID key event, key code ${r.code} in this layout` : "HID key event";
|
|
1517
1654
|
return r.ok ? { text: `pressed ${key} (${how}) — delivery=delivered_unverified, retry=unsafe (frontmost: ${g.fm ?? "unknown"})${r.note ? ` — ${r.note}` : ""}` } : { error: axErrorText(r) };
|
|
@@ -1535,6 +1672,14 @@ async function macType(args) {
|
|
|
1535
1672
|
if (l.error) return { error: l.error };
|
|
1536
1673
|
item = l.item; target = targetOf(item); label = itemLabel(args.element_index, item);
|
|
1537
1674
|
}
|
|
1675
|
+
// app given with an element_index: the element must belong to that app, else nothing at all is sent — checked
|
|
1676
|
+
// before either path (the accessibility path wrote into the element whatever app was named)
|
|
1677
|
+
if (target && args.app) {
|
|
1678
|
+
const a = await frontmost({ app: args.app });
|
|
1679
|
+
// a name several running apps share: the index already names the process, which must be one of them
|
|
1680
|
+
const pids = a?.ambiguous ? (a.ambiguous.details?.apps || []).map((x) => x.pid) : a?.target ? [a.target.pid] : [];
|
|
1681
|
+
if (!pids.includes(target.pid)) return { error: `focus_lost: element_index ${args.element_index} belongs to another app than "${args.app}" — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1682
|
+
}
|
|
1538
1683
|
let noFocus = false;
|
|
1539
1684
|
if (mechanism !== "physical") {
|
|
1540
1685
|
// 0.3.0: the app that gets the text — the element's, the named one, or the frontmost one — is judged
|
|
@@ -1552,7 +1697,7 @@ async function macType(args) {
|
|
|
1552
1697
|
const fallback = mechanism === "auto" && target === null && !args.replace && res.code === "ACTION_NOT_SUPPORTED" && (res.details?.kind === "no_focus" || res.details?.textlike === true);
|
|
1553
1698
|
if (!fallback) return { error: axErrorText(res) };
|
|
1554
1699
|
noFocus = res.details?.kind === "no_focus";
|
|
1555
|
-
// 0.2.6
|
|
1700
|
+
// 0.2.6: no focused element and no app named — the keystrokes would go wherever macOS
|
|
1556
1701
|
// routes them in whatever app is in front; refuse
|
|
1557
1702
|
if (noFocus && args.app === undefined) {
|
|
1558
1703
|
const who = engineApp ? `"${engineApp}" (the frontmost app)` : "the frontmost app";
|
|
@@ -1562,11 +1707,6 @@ async function macType(args) {
|
|
|
1562
1707
|
if (args.replace) return { error: "invalid_args: replace needs the accessibility path (mechanism auto or semantic) (delivery=not_delivered, retry=safe)" };
|
|
1563
1708
|
let g;
|
|
1564
1709
|
if (target) {
|
|
1565
|
-
// app given with an element_index: the element must belong to that app (else nothing at all is sent)
|
|
1566
|
-
if (args.app) {
|
|
1567
|
-
const a = await frontmost({ app: args.app });
|
|
1568
|
-
if (!a?.target || a.target.pid !== target.pid) return { error: `focus_lost: element_index ${args.element_index} belongs to another app than "${args.app}" — nothing was sent (delivery=not_delivered, retry=safe)` };
|
|
1569
|
-
}
|
|
1570
1710
|
// physical into an element: click it first (hit-tested), then type only if the click left the
|
|
1571
1711
|
// element's own app in front — otherwise the keystrokes would land in whatever app is
|
|
1572
1712
|
const c = await physicalClickAt(target, label, "left", 1, args.timeout_ms, { real: true });
|
|
@@ -1595,6 +1735,9 @@ async function macPasteImpl(args) {
|
|
|
1595
1735
|
// 0.3.0: ⌘V goes to the frontmost app (with app given, the engine refuses unless that app is in front)
|
|
1596
1736
|
const gate = await approveTarget(args.app !== undefined ? { app: args.app } : {});
|
|
1597
1737
|
if (gate.error) return { error: gate.error };
|
|
1738
|
+
// ⌘V goes out through the HID system: the person-goes-first check once more, before the clipboard is touched
|
|
1739
|
+
const busy = await lateUserCheck();
|
|
1740
|
+
if (busy) return { error: busy };
|
|
1598
1741
|
const res = await axEngine({ op: "paste", text, app: args.app, force: args.force === true }, 25000);
|
|
1599
1742
|
if (!res.ok) return { error: axErrorText(res) };
|
|
1600
1743
|
return { text: `pasted ${text.length} chars — delivery=${res.delivery}, retry=unsafe${res.reason ? ` (${res.reason})` : ""} (clipboard restored: ${res.restored}) (frontmost: ${res.front ?? "unknown"})` };
|
|
@@ -1615,7 +1758,7 @@ async function macMenuCommand(args) {
|
|
|
1615
1758
|
// ── Mac 层:等待 / 应用 / 窗口 / 剪贴板 / 通知 ──
|
|
1616
1759
|
const WAIT_CONDITIONS = ["window", "window_gone", "text", "text_gone", "element", "menu", "menu_closed", "sheet", "sheet_gone", "app_running", "app_gone", "notification"];
|
|
1617
1760
|
const WAIT_PREDICATES = ["exists", "gone", "enabled", "focused", "value_equals", "value_contains"];
|
|
1618
|
-
async function macWait(args) {
|
|
1761
|
+
async function macWait(args, live) {
|
|
1619
1762
|
if (args.condition === "notification" && process.env.NORACU_READ_ONLY === "1") {
|
|
1620
1763
|
return { error: 'mac_wait: condition "notification" blocked by NORACU_READ_ONLY=1 (observation-only mode)' };
|
|
1621
1764
|
}
|
|
@@ -1626,7 +1769,7 @@ async function macWait(args) {
|
|
|
1626
1769
|
if (l.error) return { error: l.error };
|
|
1627
1770
|
req.target = targetOf(l.item);
|
|
1628
1771
|
}
|
|
1629
|
-
const res = await axEngine(req, timeoutMs + 15000);
|
|
1772
|
+
const res = await axEngine(req, timeoutMs + 15000, live);
|
|
1630
1773
|
if (!res.ok) return { error: `${axErrorText(res)}${res.details?.last_observed ? ` — last observed: ${JSON.stringify(res.details.last_observed)}` : ""}` };
|
|
1631
1774
|
return { text: `${res.condition} met after ${res.elapsed_ms} ms — ${JSON.stringify(res.observed)}` };
|
|
1632
1775
|
}
|
|
@@ -1685,6 +1828,8 @@ async function cdpVersionOnce(port, timeoutMs = 2500) {
|
|
|
1685
1828
|
} catch { /* not up yet or unreachable */ }
|
|
1686
1829
|
return null;
|
|
1687
1830
|
}
|
|
1831
|
+
// test hook (with NORACU_AX_ENGINE only): a stand-in for /usr/bin/open in the DevTools-port launch
|
|
1832
|
+
const CDP_OPEN = process.env.NORACU_AX_ENGINE && process.env.NORACU_TEST_OPEN ? process.env.NORACU_TEST_OPEN : "/usr/bin/open";
|
|
1688
1833
|
async function cdpVersion(port, timeoutMs) {
|
|
1689
1834
|
const end = Date.now() + timeoutMs;
|
|
1690
1835
|
while (Date.now() < end) {
|
|
@@ -1694,6 +1839,21 @@ async function cdpVersion(port, timeoutMs) {
|
|
|
1694
1839
|
}
|
|
1695
1840
|
return null;
|
|
1696
1841
|
}
|
|
1842
|
+
// true when a process listening on the loopback port is the app (pid) or one of its own child processes: another
|
|
1843
|
+
// local process could take the port between the free-port check and the app's start (lsof lists the listeners)
|
|
1844
|
+
async function portHeldBy(port, pid) {
|
|
1845
|
+
const r = await sh("/usr/sbin/lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], 5000);
|
|
1846
|
+
if (!r.ok) return false;
|
|
1847
|
+
for (const line of r.out.split("\n")) {
|
|
1848
|
+
let p = Number(line.trim());
|
|
1849
|
+
for (let i = 0; i < 4 && Number.isInteger(p) && p > 1; i++) {
|
|
1850
|
+
if (p === pid) return true;
|
|
1851
|
+
const up = await sh("/bin/ps", ["-o", "ppid=", "-p", String(p)], 3000);
|
|
1852
|
+
p = up.ok ? Number(up.out.trim()) : NaN;
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
return false;
|
|
1856
|
+
}
|
|
1697
1857
|
|
|
1698
1858
|
// name (the bundle's file name, as Finder shows it) and bundle id of an installed app that is not running
|
|
1699
1859
|
async function installedBundle(path) {
|
|
@@ -1702,10 +1862,20 @@ async function installedBundle(path) {
|
|
|
1702
1862
|
return { name: String(path).replace(/\/+$/, "").split("/").pop().replace(/\.app$/i, ""), bundle_id: /^[\w.-]+$/.test(id) ? id : null };
|
|
1703
1863
|
}
|
|
1704
1864
|
|
|
1865
|
+
// Bring a running app forward. "pid:<number>" names one process of several that share a name or a bundle: the
|
|
1866
|
+
// engine activates that process — `open -a` would bring forward whichever copy macOS picks. Anything else goes
|
|
1867
|
+
// through `open -a`, as before.
|
|
1868
|
+
async function bringForward(app, target) {
|
|
1869
|
+
if (/^pid:\d{1,7}$/.test(String(app))) {
|
|
1870
|
+
const r = await axEngine({ op: "app_ctl", action: "activate", app }, 10000);
|
|
1871
|
+
return r.ok ? { ok: true, out: "" } : { ok: false, out: axErrorText(r) };
|
|
1872
|
+
}
|
|
1873
|
+
return sh("/usr/bin/open", ["-a", target], 15000);
|
|
1874
|
+
}
|
|
1705
1875
|
async function macApp(args) {
|
|
1706
1876
|
const { action, app } = args;
|
|
1707
1877
|
if (action === "launch") {
|
|
1708
|
-
// ~/ and symlinked .app paths resolve to the real bundle path for every launch
|
|
1878
|
+
// ~/ and symlinked .app paths resolve to the real bundle path for every launch
|
|
1709
1879
|
const spec = canonicalAppSpec(app);
|
|
1710
1880
|
const info = await axEngine({ op: "app_info", app: spec }, 10000);
|
|
1711
1881
|
if (!info.ok) return { error: axErrorText(info) };
|
|
@@ -1720,7 +1890,7 @@ async function macApp(args) {
|
|
|
1720
1890
|
}
|
|
1721
1891
|
if (!info.chromium) return { error: `invalid_args: "${app}" is not a Chromium or Electron app, so it has no DevTools port (delivery=not_delivered, retry=safe)` };
|
|
1722
1892
|
// a DevTools port hands the app to the browser tools, which app rules do not judge: an app the deny list or the
|
|
1723
|
-
// approval file rules out is not launched with one (
|
|
1893
|
+
// approval file rules out is not launched with one (an IDE with a terminal, driven over CDP)
|
|
1724
1894
|
// an app that is not running has no name or bundle id from the engine: read them from the bundle on disk
|
|
1725
1895
|
const who = info.running ? { name: info.name, bundle_id: info.bundle_id } : await installedBundle(info.path);
|
|
1726
1896
|
const ruled = approveKnown(appInfo(who), `the app "${app}" that would be launched with a DevTools port`);
|
|
@@ -1734,19 +1904,23 @@ async function macApp(args) {
|
|
|
1734
1904
|
// Chrome-family browsers (Chrome 136+) refuse remote debugging on the default profile, so they get a
|
|
1735
1905
|
// profile of their own under ~/.noracu; an Electron app keeps its own data (no --user-data-dir)
|
|
1736
1906
|
const extra = info.electron ? [] : [`--user-data-dir=${ensurePrivateDir(join(cdpProfilesDir, String(info.bundle_id || target).replace(/[^\w.-]+/g, "_")))}`];
|
|
1737
|
-
const r = await sh(
|
|
1907
|
+
const r = await sh(CDP_OPEN, [...(args.activate ? [] : ["-g"]), "-n", "-a", target, "--args", `--remote-debugging-port=${port}`, "--remote-debugging-address=127.0.0.1", ...extra], 15000);
|
|
1738
1908
|
if (!r.ok) return { error: `launch_failed: ${r.out.slice(0, 200)} (delivery=unknown, retry=unsafe)` };
|
|
1739
1909
|
const w = await axEngine({ op: "app_wait", app: info.bundle_id || target, timeout_ms: args.timeout_ms ?? 20000 }, (args.timeout_ms ?? 20000) + 10000);
|
|
1740
1910
|
const v = await cdpVersion(port, args.timeout_ms ?? 20000);
|
|
1741
|
-
|
|
1742
|
-
|
|
1911
|
+
// the endpoint is recorded as the app's only when it is: its websocket is on this port on 127.0.0.1, and the
|
|
1912
|
+
// process listening on the port is the app (or one of its child processes)
|
|
1913
|
+
const seen = Boolean(v) && w.ok && Number.isInteger(w.pid);
|
|
1914
|
+
const own = seen && String(v.webSocketDebuggerUrl || "").startsWith(`ws://127.0.0.1:${port}/`) && await portHeldBy(port, w.pid);
|
|
1915
|
+
if (!own) {
|
|
1916
|
+
return { text: JSON.stringify({ launched: w.ok ? w.name : app, pid: w.pid ?? null, cdp: null, note: !v ? (w.ok ? "the app started but its DevTools endpoint did not answer — use the accessibility tools instead" : "the app did not show up in time and its DevTools endpoint did not answer — check mac_apps before launching again") : !seen ? "the DevTools endpoint answered, but the launched app process could not be verified — check mac_apps" : `the DevTools endpoint on 127.0.0.1:${port} is not the launched app's own (another process may hold the port), so it was not recorded — use the accessibility tools, or quit the app and launch again`, delivery: "delivered_unverified", retry: "unsafe" }) };
|
|
1743
1917
|
}
|
|
1744
1918
|
cdpPorts.set(port, { pid: w.pid, wsUrl: v.webSocketDebuggerUrl });
|
|
1745
1919
|
return { text: JSON.stringify({ launched: w.name || app, pid: w.pid, cdp: { port, http_endpoint: `http://127.0.0.1:${port}`, websocket_url: v.webSocketDebuggerUrl, product: v.Browser }, next: `browser_launch with cdp_port ${port} drives its web contents through Playwright; menus, dialogs and windows stay on mac_* tools`, warning: "the DevTools port stays open until the app quits; any local process can control the app meanwhile", delivery: "delivered_verified", retry: "unsafe" }) };
|
|
1746
1920
|
}
|
|
1747
1921
|
if (info.running) {
|
|
1748
1922
|
// attaching sends nothing; activate:true brings it forward, verified by the frontmost app
|
|
1749
|
-
if (args.activate) await
|
|
1923
|
+
if (args.activate) await bringForward(app, target);
|
|
1750
1924
|
await sleep(args.activate ? 500 : 0);
|
|
1751
1925
|
const front = (await frontmost({ pid: info.pid }))?.match === true;
|
|
1752
1926
|
return { text: JSON.stringify({ app: info.name, pid: info.pid, already_running: true, frontmost: front, delivery: args.activate ? (front ? "delivered_verified" : "delivered_unverified") : "not_delivered", retry: "safe" }) };
|
|
@@ -1761,8 +1935,9 @@ async function macApp(args) {
|
|
|
1761
1935
|
}
|
|
1762
1936
|
if (action === "activate") {
|
|
1763
1937
|
const info = await axEngine({ op: "app_info", app }, 10000);
|
|
1938
|
+
if (info?.code === "AMBIGUOUS_APP") return { error: axErrorText(info) };
|
|
1764
1939
|
if (!info.ok || !info.running) return { error: `app_not_found: no running app named "${app}" (delivery=not_delivered, retry=safe)` };
|
|
1765
|
-
const o = await
|
|
1940
|
+
const o = await bringForward(app, info.path || app);
|
|
1766
1941
|
if (!o.ok) return { error: `activate_failed: ${o.out.slice(0, 160)} (delivery=unknown, retry=safe)` };
|
|
1767
1942
|
await sleep(500);
|
|
1768
1943
|
const f = await frontmost({ pid: info.pid });
|
|
@@ -1823,6 +1998,13 @@ async function macNotifications(args = {}) {
|
|
|
1823
1998
|
const browsers = new Map(); // browser_id → { browser, cdpBrowser?, cdp_port?, headless, activePage, pages: Map }
|
|
1824
1999
|
const browserElCache = new Map(); // browser_id → { elements: [{i,tag,role,name,href,x,y}], ts, page, url }
|
|
1825
2000
|
let chromiumInstalling = null; // the in-flight `playwright install chromium`, shared by concurrent launches
|
|
2001
|
+
// The download can take minutes — longer than a client waits for an answer. A browser_launch waits for it up to
|
|
2002
|
+
// CHROMIUM_WAIT_MS, then answers browser_installing while it goes on; browser_launch again takes the browser once it
|
|
2003
|
+
// is there. A download that failed after its call had answered is reported by the next browser_launch, once.
|
|
2004
|
+
const CHROMIUM_WAIT_MS = process.env.NORACU_CI === "1" && Number(process.env.NORACU_TEST_CHROMIUM_WAIT_MS) > 0 ? Number(process.env.NORACU_TEST_CHROMIUM_WAIT_MS) : 20000;
|
|
2005
|
+
let chromiumInstallFailed = null;
|
|
2006
|
+
const chromiumFailed = (r) => Boolean(r.error || r.timedOut || r.code !== 0);
|
|
2007
|
+
const chromiumFailedText = (r) => "Playwright chromium missing and auto-install failed. Run manually: npx playwright install chromium. Detail: " + String(r.stderr || r.stdout || r.error?.message || (r.timedOut ? "timed out after 10 min" : "")).slice(0, 200) + " (delivery=not_delivered, retry=safe)";
|
|
1826
2008
|
let browserLaunching = null; // the in-flight persistent-profile launch (one at a time)
|
|
1827
2009
|
|
|
1828
2010
|
// shutdown: close every browser (a CDP attachment only disconnects; the app keeps running)
|
|
@@ -1838,7 +2020,25 @@ async function closeAllBrowsers() {
|
|
|
1838
2020
|
|
|
1839
2021
|
const SNAPSHOT_EL_LIMIT = 100;
|
|
1840
2022
|
const INTERACTIVE_SELECTOR = 'a, button, input, select, textarea, summary, [role="button"], [role="link"], [role="tab"], [role="checkbox"], [role="radio"], [role="menuitem"], [role="option"], [role="switch"], [onclick], [tabindex]:not([tabindex="-1"])';
|
|
1841
|
-
|
|
2023
|
+
// A DevTools front end, however it is reached: what is typed into its console runs as script, which
|
|
2024
|
+
// browser_evaluate needs NORACU_ENABLE_EVAL for. By scheme (devtools://, the older chrome-devtools://); over
|
|
2025
|
+
// http, everything served by a DevTools port this server knows of (one it opened through mac_app, one a session
|
|
2026
|
+
// is attached to — the front end, and the /json endpoints that list, open and close the app's pages); and on
|
|
2027
|
+
// any other local port, the front end's own pages (/devtools/*.html).
|
|
2028
|
+
const LOOPBACK_HOST = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\]|0\.0\.0\.0|.+\.localhost)$/i;
|
|
2029
|
+
const DEVTOOLS_REFUSED = "that address is a DevTools port or its front end — noracu does not open, read or act on one: what is typed into a DevTools console runs as script (browser_evaluate, with NORACU_ENABLE_EVAL=1, is the way to run one)";
|
|
2030
|
+
function isDevtoolsUrl(url) {
|
|
2031
|
+
const s = String(url || "");
|
|
2032
|
+
if (/^(?:chrome-)?devtools:/i.test(s)) return true;
|
|
2033
|
+
if (!/^https?:\/\//i.test(s)) return false;
|
|
2034
|
+
let u;
|
|
2035
|
+
try { u = new URL(s); } catch { return false; }
|
|
2036
|
+
if (!LOOPBACK_HOST.test(u.hostname)) return false;
|
|
2037
|
+
const port = Number(u.port || (u.protocol === "https:" ? 443 : 80));
|
|
2038
|
+
if (cdpPorts.has(port) || [...browsers.values()].some((b) => b.cdp_port === port)) return true;
|
|
2039
|
+
return /^\/devtools\/[^/]+\.html$/i.test(u.pathname);
|
|
2040
|
+
}
|
|
2041
|
+
const isNonDevtoolsPage = (p) => !isDevtoolsUrl(p.url());
|
|
1842
2042
|
|
|
1843
2043
|
function withTimeout(promise, ms, label = "browser operation") {
|
|
1844
2044
|
let timer;
|
|
@@ -1872,7 +2072,7 @@ function pruneDeadBrowsers() {
|
|
|
1872
2072
|
if (b.cdpBrowser && !b.cdpBrowser.isConnected()) {
|
|
1873
2073
|
browsers.delete(id);
|
|
1874
2074
|
browserElCache.delete(id);
|
|
1875
|
-
// every one of noracu's tabs was seen closed before the connection went: that close is not "lost"
|
|
2075
|
+
// every one of noracu's tabs was seen closed before the connection went: that close is not "lost"
|
|
1876
2076
|
if (b.chrome && !endedChrome.has(id)) endedChrome.set(id, b.allClosed ? "closed" : "lost");
|
|
1877
2077
|
}
|
|
1878
2078
|
}
|
|
@@ -1882,8 +2082,11 @@ function pruneDeadBrowsers() {
|
|
|
1882
2082
|
// 索引仅对最近一次同 Page、同 URL 的 browser_snapshot 有效(TTL 30s);点击时重遍历 + tag/name/href/位置校验,
|
|
1883
2083
|
// 真实 Playwright 点击(含 actionability 检查,绝不回退合成 JS .click())。
|
|
1884
2084
|
|
|
2085
|
+
// How deep under <body> the element walks go. Pages built from nested components put controls 30-50
|
|
2086
|
+
// elements deep; a control past the limit is not listed, and the snapshot says its list may be incomplete.
|
|
2087
|
+
const DOM_WALK_DEPTH = 64;
|
|
1885
2088
|
async function listClickable(page) {
|
|
1886
|
-
return withTimeout(page.evaluate(({ limit, sel }) => {
|
|
2089
|
+
return withTimeout(page.evaluate(({ limit, sel, maxDepth }) => {
|
|
1887
2090
|
const elemName = (el) => {
|
|
1888
2091
|
const pick = (...vals) => {
|
|
1889
2092
|
for (const v of vals) {
|
|
@@ -1931,8 +2134,11 @@ async function listClickable(page) {
|
|
|
1931
2134
|
const shown = [];
|
|
1932
2135
|
let total = 0;
|
|
1933
2136
|
let visited = 0;
|
|
2137
|
+
let deep = false;
|
|
2138
|
+
let shadowRoots = 0, frames = 0;
|
|
1934
2139
|
const walk = (el, depth) => {
|
|
1935
|
-
if (!el ||
|
|
2140
|
+
if (!el || visited > 10000) return;
|
|
2141
|
+
if (depth > maxDepth) { deep = true; return; }
|
|
1936
2142
|
visited++;
|
|
1937
2143
|
let visible = false;
|
|
1938
2144
|
try {
|
|
@@ -1944,6 +2150,10 @@ async function listClickable(page) {
|
|
|
1944
2150
|
if (shown.length < limit) shown.push(el);
|
|
1945
2151
|
total++;
|
|
1946
2152
|
}
|
|
2153
|
+
// what is inside a shadow root or a frame is another tree: this walk does not go in — it is counted, so
|
|
2154
|
+
// that the list can say what it leaves out
|
|
2155
|
+
if (visible && el.shadowRoot) shadowRoots++;
|
|
2156
|
+
if (visible && (el.tagName === "IFRAME" || el.tagName === "FRAME")) frames++;
|
|
1947
2157
|
for (const c of el.children) walk(c, depth + 1);
|
|
1948
2158
|
};
|
|
1949
2159
|
if (document.body) walk(document.body, 0);
|
|
@@ -1961,19 +2171,20 @@ async function listClickable(page) {
|
|
|
1961
2171
|
};
|
|
1962
2172
|
}),
|
|
1963
2173
|
total,
|
|
1964
|
-
capped: visited > 10000,
|
|
2174
|
+
capped: visited > 10000 || deep,
|
|
2175
|
+
shadowRoots, frames,
|
|
1965
2176
|
};
|
|
1966
|
-
}, { limit: SNAPSHOT_EL_LIMIT, sel: INTERACTIVE_SELECTOR }), 5000, "snapshot DOM walk");
|
|
2177
|
+
}, { limit: SNAPSHOT_EL_LIMIT, sel: INTERACTIVE_SELECTOR, maxDepth: DOM_WALK_DEPTH }), 5000, "snapshot DOM walk");
|
|
1967
2178
|
}
|
|
1968
2179
|
|
|
1969
2180
|
async function clickByIndex(page, idx, expect, button = "left") {
|
|
1970
2181
|
let handle;
|
|
1971
2182
|
try {
|
|
1972
|
-
handle = await withTimeout(page.evaluateHandle(({ idx, sel }) => {
|
|
2183
|
+
handle = await withTimeout(page.evaluateHandle(({ idx, sel, maxDepth }) => {
|
|
1973
2184
|
const out = [];
|
|
1974
2185
|
let visited = 0;
|
|
1975
2186
|
const walk = (el, depth) => {
|
|
1976
|
-
if (!el || depth >
|
|
2187
|
+
if (!el || depth > maxDepth || visited > 10000 || out.length > idx) return;
|
|
1977
2188
|
visited++;
|
|
1978
2189
|
let visible = false;
|
|
1979
2190
|
try {
|
|
@@ -1989,7 +2200,7 @@ async function clickByIndex(page, idx, expect, button = "left") {
|
|
|
1989
2200
|
};
|
|
1990
2201
|
if (document.body) walk(document.body, 0);
|
|
1991
2202
|
return out[idx] || null;
|
|
1992
|
-
}, { idx, sel: INTERACTIVE_SELECTOR }), 5000, "element lookup");
|
|
2203
|
+
}, { idx, sel: INTERACTIVE_SELECTOR, maxDepth: DOM_WALK_DEPTH }), 5000, "element lookup");
|
|
1993
2204
|
} catch (e) {
|
|
1994
2205
|
const msg = String(e?.message || e);
|
|
1995
2206
|
if (/Execution context was destroyed|Target page, context or browser has been closed|detached/i.test(msg)) {
|
|
@@ -2096,13 +2307,13 @@ async function pw() {
|
|
|
2096
2307
|
return chromium;
|
|
2097
2308
|
}
|
|
2098
2309
|
|
|
2099
|
-
// browser_launch chrome:true
|
|
2310
|
+
// browser_launch chrome:true: work inside the person's own Chrome, with its sign-ins, through
|
|
2100
2311
|
// Chrome's own remote-debugging switch (chrome://inspect/#remote-debugging, Chrome 144+). Chrome asks the person to
|
|
2101
2312
|
// allow each connection and shows a banner while one is open. Since Chrome 136 --remote-debugging-port is ignored
|
|
2102
2313
|
// for the default profile, so this switch is the way in. Opt-in: NORACU_ALLOW_CHROME=1. noracu opens a window of
|
|
2103
2314
|
// its own there and works only in the tabs it opened (and tabs those open); the person's other tabs are never
|
|
2104
2315
|
// listed, read or acted on, and the usual address rules still apply in noracu's tabs. NORACU_CHROME_TABS=all
|
|
2105
|
-
// (opt-in
|
|
2316
|
+
// (opt-in) adds the person's own tabs: listed, selectable, read and acted on like noracu's, the
|
|
2106
2317
|
// address rules still applying; only noracu's own tabs are ever closed.
|
|
2107
2318
|
const chromeAllowed = () => process.env.NORACU_ALLOW_CHROME === "1";
|
|
2108
2319
|
const chromeAllTabs = () => process.env.NORACU_CHROME_TABS === "all";
|
|
@@ -2131,7 +2342,7 @@ async function chromeOwnWindow(b) {
|
|
|
2131
2342
|
while (Date.now() < deadline) {
|
|
2132
2343
|
for (const p of fresh) {
|
|
2133
2344
|
if (!p.isClosed() && (await targetIdOf(b, p).catch(() => null)) === targetId) {
|
|
2134
|
-
b.owned.add(p); // noracu's; browser_tabs new marks the tabs it opens itself
|
|
2345
|
+
b.owned.add(p); // noracu's; browser_tabs new marks the tabs it opens itself
|
|
2135
2346
|
watchFreshBlank(p); // a blank page the browser made, not one a page opened
|
|
2136
2347
|
return p;
|
|
2137
2348
|
}
|
|
@@ -2152,7 +2363,7 @@ async function chromeOwnWindow(b) {
|
|
|
2152
2363
|
// Measured on Chromium (2026-11-13 probe): a noopener tab still reports its opener over CDP (openerId).
|
|
2153
2364
|
async function chromeNewTab(b) {
|
|
2154
2365
|
// the host is one of noracu's tabs on a page it may act on, never a file:// page or an error page: the blank tab
|
|
2155
|
-
// takes its opener's origin
|
|
2366
|
+
// takes its opener's origin
|
|
2156
2367
|
const hostOk = (p) => p && !p.isClosed() && b.owned.has(p) && isNonDevtoolsPage(p) && tabAllowed(b, p) && !/^file:/i.test(p.url());
|
|
2157
2368
|
const host = hostOk(b.activePage) ? b.activePage : b.browser.pages().find(hostOk);
|
|
2158
2369
|
if (!host) return chromeOwnWindow(b);
|
|
@@ -2185,7 +2396,7 @@ async function chromeNewTab(b) {
|
|
|
2185
2396
|
await s?.detach().catch(() => {});
|
|
2186
2397
|
}
|
|
2187
2398
|
// a tab window.open may have made but that could not be matched is not closed — closing by guess could reach a
|
|
2188
|
-
// tab that is not noracu's — the result says it may be there
|
|
2399
|
+
// tab that is not noracu's — the result says it may be there
|
|
2189
2400
|
if (opened) b.strayTabs = (b.strayTabs || 0) + 1;
|
|
2190
2401
|
try { return await chromeOwnWindow(b); }
|
|
2191
2402
|
catch (e) { throw new Error(opened ? `${shortErr(e)}; a first try may also have left a blank tab in your Chrome that noracu could not tell apart (not closed)` : shortErr(e)); }
|
|
@@ -2243,7 +2454,7 @@ async function attachChrome() {
|
|
|
2243
2454
|
}
|
|
2244
2455
|
|
|
2245
2456
|
// one launch or attach at a time, the wait for Chrome's dialog included: a second call waits, then finds the
|
|
2246
|
-
// session
|
|
2457
|
+
// session; a loop, because another waiter can have started its own in between
|
|
2247
2458
|
async function oneLaunchAtATime(fn) {
|
|
2248
2459
|
while (browserLaunching) await browserLaunching.catch(() => {});
|
|
2249
2460
|
const p = fn();
|
|
@@ -2289,12 +2500,12 @@ async function attachCdp(args) {
|
|
|
2289
2500
|
const context = contexts.find((ctx) => ctx.pages().some(isNonDevtoolsPage)) || contexts[0];
|
|
2290
2501
|
if (!context) { await cdpBrowser.close().catch(() => {}); return { error: "cdp_connect_failed: the app exposes no browser context (delivery=not_delivered, retry=safe)" }; }
|
|
2291
2502
|
const nonDevPages = context.pages().filter(isNonDevtoolsPage);
|
|
2292
|
-
const activePage = nonDevPages[0] ||
|
|
2503
|
+
const activePage = nonDevPages[0] || null; // never a DevTools window, also when nothing else is open
|
|
2293
2504
|
const browserId = `b-${randomUUID().slice(0, 8)}`;
|
|
2294
2505
|
const entry = { browser: context, cdpBrowser, cdp_port: args.cdp_port, headless: false, activePage, pages: new Map() };
|
|
2295
2506
|
browsers.set(browserId, entry);
|
|
2296
2507
|
registerBrowserCleanup(browserId, entry);
|
|
2297
|
-
return { text: JSON.stringify({ browser_id: browserId, cdp_port: args.cdp_port, tabs: nonDevPages.length
|
|
2508
|
+
return { text: JSON.stringify({ browser_id: browserId, cdp_port: args.cdp_port, tabs: nonDevPages.length, attached: true, note: "browser_close disconnects; the app keeps running" }) };
|
|
2298
2509
|
}
|
|
2299
2510
|
async function browserLaunch(args = {}) {
|
|
2300
2511
|
if (args.chrome === true) return oneLaunchAtATime(attachChrome);
|
|
@@ -2337,15 +2548,23 @@ async function launchPersistent(args) {
|
|
|
2337
2548
|
if (process.env.NORACU_DISABLE_AUTO_INSTALL === "1") {
|
|
2338
2549
|
return { error: "Playwright chromium missing and auto-install disabled (NORACU_DISABLE_AUTO_INSTALL=1). Run manually: npx playwright install chromium (delivery=not_delivered, retry=safe)" };
|
|
2339
2550
|
}
|
|
2551
|
+
// a download that failed after its browser_launch had answered: this call says so (the next one tries again)
|
|
2552
|
+
if (chromiumInstallFailed && !chromiumInstalling) { const f = chromiumInstallFailed; chromiumInstallFailed = null; return { error: chromiumFailedText(f) }; }
|
|
2340
2553
|
const req = createRequire(import.meta.url);
|
|
2341
|
-
|
|
2554
|
+
// test hook (under NORACU_CI=1 only): a stand-in for Playwright's installer
|
|
2555
|
+
const cliJs = process.env.NORACU_CI === "1" && process.env.NORACU_TEST_PLAYWRIGHT_CLI ? process.env.NORACU_TEST_PLAYWRIGHT_CLI : join(dirname(req.resolve("playwright/package.json")), "cli.js");
|
|
2342
2556
|
const t0 = Date.now();
|
|
2343
2557
|
// one install at a time: a second browser_launch during the download waits for the same install
|
|
2344
|
-
if (!chromiumInstalling)
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2558
|
+
if (!chromiumInstalling) {
|
|
2559
|
+
chromiumInstallFailed = null;
|
|
2560
|
+
chromiumInstalling = runAsync(process.execPath, [cliJs, "install", "chromium"], { timeoutMs: 600000 })
|
|
2561
|
+
.then((r) => { if (chromiumFailed(r)) chromiumInstallFailed = r; return r; })
|
|
2562
|
+
.finally(() => { chromiumInstalling = null; });
|
|
2348
2563
|
}
|
|
2564
|
+
const r = await Promise.race([chromiumInstalling, new Promise((res) => setTimeout(res, CHROMIUM_WAIT_MS, null).unref())]);
|
|
2565
|
+
if (r === null) return { error: "browser_installing: Playwright's Chromium is not on this Mac yet and is being downloaded (the first time only; it can take a few minutes) — call browser_launch again in a minute (delivery=not_delivered, retry=safe)" };
|
|
2566
|
+
chromiumInstallFailed = null; // reported here
|
|
2567
|
+
if (chromiumFailed(r)) return { error: chromiumFailedText(r) };
|
|
2349
2568
|
installed = ((Date.now() - t0) / 1000).toFixed(0);
|
|
2350
2569
|
browser = await chromium.launchPersistentContext(profileDir, launchOpts);
|
|
2351
2570
|
}
|
|
@@ -2354,14 +2573,14 @@ async function launchPersistent(args) {
|
|
|
2354
2573
|
try { page = browser.pages()[0] || await withTimeout(browser.newPage(), 10000, "newPage"); }
|
|
2355
2574
|
catch (e) { await withTimeout(browser.close(), 10000, "close").catch(() => {}); throw e; }
|
|
2356
2575
|
// The first tab is Chromium's, not one newPage made, and what a blank page can reach depends on how the tab got
|
|
2357
|
-
// there: a blank page that a local file went to still loads local files into frames (measured
|
|
2358
|
-
// cannot be told from a fresh one from inside
|
|
2576
|
+
// there: a blank page that a local file went to still loads local files into frames (measured) and
|
|
2577
|
+
// cannot be told from a fresh one from inside. So the tab is not judged. When it is on a blank page noracu
|
|
2359
2578
|
// navigates it to about:blank itself (page.goto: a navigation the browser side starts) and counts it from then
|
|
2360
|
-
// on. Measured
|
|
2579
|
+
// on. Measured: a tab that had reached the blank page from a local file — by location.href, and by
|
|
2361
2580
|
// location.replace — loaded another local file into a frame before this navigation and did not after it; and
|
|
2362
2581
|
// every time, for those tabs, the first tab and a newPage tab, the navigation put a new document there (a
|
|
2363
2582
|
// property set on the window before it was gone after it). That is checked on each launch, not assumed: a mark
|
|
2364
|
-
// is set before the navigation and must be gone after it. window.name survives the navigation (measured
|
|
2583
|
+
// is set before the navigation and must be gone after it. window.name survives the navigation (measured);
|
|
2365
2584
|
// it is emptied and read back. Any navigation the tab reports later, back to an earlier entry of its history
|
|
2366
2585
|
// included, ends its standing (watchFreshBlank). If a step does not succeed, or the tab shows anything else (a
|
|
2367
2586
|
// restored tab), it does not count as a fresh blank page: it is held to the rule like any other tab.
|
|
@@ -2374,14 +2593,14 @@ async function launchPersistent(args) {
|
|
|
2374
2593
|
if (clean !== true) freshBlank.delete(page); // the old document is still there, the name is not empty, or neither is known
|
|
2375
2594
|
}
|
|
2376
2595
|
}
|
|
2377
|
-
// test switch
|
|
2596
|
+
// test switch: makes the first tab not count, so that the first_tab note below can be tested;
|
|
2378
2597
|
// honoured only together with NORACU_CI=1, and it only takes standing away
|
|
2379
2598
|
if (process.env.NORACU_CI === "1" && process.env.NORACU_TEST_FIRST_TAB_UNCOUNTED === "1") freshBlank.delete(page);
|
|
2380
2599
|
const entry = { browser, headless: Boolean(args.headless), activePage: page, pages: new Map([[page.url(), page]]) };
|
|
2381
2600
|
browsers.set(browserId, entry);
|
|
2382
2601
|
registerBrowserCleanup(browserId, entry);
|
|
2383
2602
|
// a first tab that may not be the active page (the check above did not pass, or Chromium started on something
|
|
2384
|
-
// else): the page tools will refuse it, and the caller is told now rather than at the first call
|
|
2603
|
+
// else): the page tools will refuse it, and the caller is told now rather than at the first call
|
|
2385
2604
|
const firstTab = tabAllowed(entry, page) ? {} : { first_tab: "not counted as a fresh blank page — use browser_navigate, or browser_tabs to open a tab" };
|
|
2386
2605
|
return { text: JSON.stringify({ browser_id: browserId, tabs: 1, headless: Boolean(args.headless), ...(installed ? { chromium_installed_sec: installed } : {}), ...firstTab }) };
|
|
2387
2606
|
}
|
|
@@ -2398,11 +2617,11 @@ function getActiveSession(browserId, { pageless = false, anyPage = false } = {})
|
|
|
2398
2617
|
const b = id ? browsers.get(id) : null;
|
|
2399
2618
|
if (!b) return null;
|
|
2400
2619
|
// the active tab may have gone by itself (the page closed it, a person did): the next one takes over and what
|
|
2401
|
-
// was read on the one that is gone is dropped — here as after browser_tabs close
|
|
2620
|
+
// was read on the one that is gone is dropped — here as after browser_tabs close
|
|
2402
2621
|
settleActiveTab(id, b);
|
|
2403
2622
|
// the person's own tab (NORACU_CHROME_TABS=all) that left http(s) — a settings page, a local file — is not the
|
|
2404
2623
|
// active page any more, not even for browser_navigate, which would replace what it shows: noracu's own tab takes
|
|
2405
|
-
// over, and a call that would have acted is refused
|
|
2624
|
+
// over, and a call that would have acted is refused
|
|
2406
2625
|
if (!pageless && b.chrome && b.activePage && !b.owned.has(b.activePage) && !tabAllowed(b, b.activePage)) {
|
|
2407
2626
|
const scheme = (String(b.activePage.url() || "").match(/^[a-z][a-z0-9+.-]*:/i) || ["another"])[0];
|
|
2408
2627
|
const was = tabId(b.activePage);
|
|
@@ -2414,14 +2633,14 @@ function getActiveSession(browserId, { pageless = false, anyPage = false } = {})
|
|
|
2414
2633
|
if (pageless) return { id, b, page: null };
|
|
2415
2634
|
// tabs are open and none may be the active page: say that, not "no browser" (the dispatcher reports it)
|
|
2416
2635
|
if (openTabs(b).length) throw new Refusal(NO_ACTIVE_PAGE);
|
|
2417
|
-
// a session with no tab left to act on is still a session: "call browser_launch" would be refused
|
|
2418
|
-
//
|
|
2636
|
+
// a session with no tab left to act on is still a session: "call browser_launch" would be refused,
|
|
2637
|
+
// so say how to go on
|
|
2419
2638
|
throw new Refusal(`no_active_page: browser session ${id} has no open tab noracu may act on — open one with browser_tabs (action new) or end the session with browser_close (delivery=not_delivered, retry=safe)`);
|
|
2420
2639
|
}
|
|
2421
2640
|
// What a tab must show to become the active page it must show to be read or acted on, and that is looked at
|
|
2422
2641
|
// on every call: a page can take itself to a blob it made, a load can fail (chrome-error://), a person can
|
|
2423
2642
|
// open a file in the tab. The tab stays the active page — no other tab takes over while it is open, so no
|
|
2424
|
-
// input goes to a tab nobody chose — and only browser_navigate and browser_tabs act
|
|
2643
|
+
// input goes to a tab nobody chose — and only browser_navigate and browser_tabs act
|
|
2425
2644
|
const nav = watchNavs(b, b.activePage);
|
|
2426
2645
|
if (!tabAllowed(b, b.activePage)) {
|
|
2427
2646
|
browserElCache.delete(id); // what was read before the page went there is dropped, whichever tool sees it
|
|
@@ -2444,7 +2663,10 @@ async function browserNavigate(args) {
|
|
|
2444
2663
|
return { error: `navigate_failed: ${shortErr(e)} (delivery=unknown, retry=unsafe)` };
|
|
2445
2664
|
}
|
|
2446
2665
|
const title = await withTimeout(page.title(), 5000, "page.title").catch(() => "");
|
|
2447
|
-
|
|
2666
|
+
// The navigation itself went through; what loaded can still be the server's error page (404, 500). That is said in
|
|
2667
|
+
// so many words, so the status code is not read past next to "delivered_verified".
|
|
2668
|
+
const st = resp ? resp.status() : 0;
|
|
2669
|
+
const statusInfo = st >= 400 ? `HTTP ${st} — an error page: the server did not find or could not serve this address` : st > 0 ? `HTTP ${st}` : "no response";
|
|
2448
2670
|
return { text: `navigated: ${page.url()} (${statusInfo}, title: ${title}) — delivery=delivered_verified, retry=unsafe` };
|
|
2449
2671
|
}
|
|
2450
2672
|
|
|
@@ -2455,8 +2677,8 @@ async function browserSnapshot(args = {}) {
|
|
|
2455
2677
|
if (!s) return { error: "no browser — call browser_launch first" };
|
|
2456
2678
|
const { id, page } = s;
|
|
2457
2679
|
// The tree, the element list and the address are read one after the other. When the page navigated in between
|
|
2458
|
-
// the parts can be of two pages: nothing is returned, and the list that was read is dropped
|
|
2459
|
-
// e: the error a part ended with because the page went to another document
|
|
2680
|
+
// the parts can be of two pages: nothing is returned, and the list that was read is dropped.
|
|
2681
|
+
// e: the error a part ended with because the page went to another document
|
|
2460
2682
|
const changed = (e) => {
|
|
2461
2683
|
const c = pageChanged(s, "the snapshot was being taken", e ? "it was not finished" : "its parts may be of two pages and none is returned", "browser_snapshot", e);
|
|
2462
2684
|
if (c) browserElCache.delete(id);
|
|
@@ -2466,6 +2688,7 @@ async function browserSnapshot(args = {}) {
|
|
|
2466
2688
|
let elements = [];
|
|
2467
2689
|
let total = 0;
|
|
2468
2690
|
let capped = false;
|
|
2691
|
+
let inner = "";
|
|
2469
2692
|
let walkErr = null;
|
|
2470
2693
|
let gone = null;
|
|
2471
2694
|
try {
|
|
@@ -2473,12 +2696,15 @@ async function browserSnapshot(args = {}) {
|
|
|
2473
2696
|
elements = r.elements;
|
|
2474
2697
|
total = r.total;
|
|
2475
2698
|
capped = r.capped;
|
|
2699
|
+
// open shadow roots only: a closed one cannot be seen from the page, so it is not counted (and not listed)
|
|
2700
|
+
const parts = [r.shadowRoots ? `${r.shadowRoots} open shadow root(s)` : "", r.frames ? `${r.frames} frame(s)` : ""].filter(Boolean);
|
|
2701
|
+
if (parts.length) inner = ` — not listed: what is inside ${parts.join(" and ")} of this page (browser_click with xy reaches those; a selector reaches into an open shadow root)`;
|
|
2476
2702
|
browserElCache.set(id, { elements, ts: Date.now(), page, url: page.url(), commits: navs.get(page).commits });
|
|
2477
2703
|
} catch (e) {
|
|
2478
|
-
// 遍历失败不影响 ARIA
|
|
2704
|
+
// 遍历失败不影响 ARIA 快照,但要说出来:an empty list would read as "nothing clickable"
|
|
2479
2705
|
walkErr = shortErr(e);
|
|
2480
2706
|
if (ctxGone(e)) gone = e;
|
|
2481
|
-
browserElCache.delete(id); // a list an earlier snapshot left does not stand in for this one
|
|
2707
|
+
browserElCache.delete(id); // a list an earlier snapshot left does not stand in for this one
|
|
2482
2708
|
}
|
|
2483
2709
|
const omitted = Math.max(0, total - elements.length);
|
|
2484
2710
|
const truncNote = omitted > 0
|
|
@@ -2486,12 +2712,12 @@ async function browserSnapshot(args = {}) {
|
|
|
2486
2712
|
: "";
|
|
2487
2713
|
const elHeader = walkErr
|
|
2488
2714
|
? `[clickable elements unavailable: ${walkErr} — retry browser_snapshot before using element_index]`
|
|
2489
|
-
: `[clickable elements${omitted > 0 ? ` — truncated (${omitted}${capped ? "+" : ""} left out)` : ""} — browser_click accepts element_index]`;
|
|
2715
|
+
: `[clickable elements${omitted > 0 ? ` — truncated (${omitted}${capped ? "+" : ""} left out)` : capped ? " — the page is larger or more deeply nested than the walk covers, so some may be missing" : ""}${inner} — browser_click accepts element_index]`;
|
|
2490
2716
|
const elList = elements.map((e) => `[${e.i}] ${e.role || e.tag} "${e.name}"${e.href ? ` (${e.href.slice(0, 40)})` : ""} @${e.x},${e.y}`).join("\n") + truncNote;
|
|
2491
2717
|
const elBlock = `\n\n${elHeader}\n${elList}`;
|
|
2492
2718
|
const headPrefix = `URL: ${page.url()}\n`;
|
|
2493
2719
|
const snapBudget = Math.max(1500, 14000 - headPrefix.length - elBlock.length);
|
|
2494
|
-
//
|
|
2720
|
+
// a cut snapshot says so — the page goes on below what is shown
|
|
2495
2721
|
const snapCut = snap.length > snapBudget ? `\n[aria snapshot truncated: showing ${snapBudget} of ${snap.length} chars — browser_read or browser_scroll for the rest]` : "";
|
|
2496
2722
|
const left = refusedSince(s, "the page was being read");
|
|
2497
2723
|
if (left) return left;
|
|
@@ -2516,7 +2742,7 @@ async function browserScreenshot(args = {}) {
|
|
|
2516
2742
|
opts.fullPage = false; // clip 与 fullPage 互斥
|
|
2517
2743
|
}
|
|
2518
2744
|
const buf = await withTimeout(page.screenshot(opts), 17000, "screenshot").catch((e) => readFailed(s, e));
|
|
2519
|
-
// looked at here as well as at the end: nothing more is asked of a page that stopped passing
|
|
2745
|
+
// looked at here as well as at the end: nothing more is asked of a page that stopped passing
|
|
2520
2746
|
const gone = refusedSince(s, "the page was being read");
|
|
2521
2747
|
if (gone) return gone;
|
|
2522
2748
|
const metrics = await withTimeout(
|
|
@@ -2536,17 +2762,23 @@ async function browserClick(args) {
|
|
|
2536
2762
|
if (!s) return { error: "no browser — call browser_launch first (delivery=not_delivered, retry=safe)" };
|
|
2537
2763
|
const { id, page } = s;
|
|
2538
2764
|
const button = args.button || "left";
|
|
2765
|
+
// A click that made the page navigate says so, as browser_fill and browser_scroll do: the elements of the
|
|
2766
|
+
// snapshot went with the page. A navigation the click started is given a moment to show.
|
|
2767
|
+
const moved = async () => {
|
|
2768
|
+
for (let i = 0; i < 3 && !navigated(s); i++) await sleep(50);
|
|
2769
|
+
return navigated(s) ? ` — the page navigated after the click (it shows ${showsNow(s)} now); take a new browser_snapshot before using element_index` : "";
|
|
2770
|
+
};
|
|
2539
2771
|
if (args.element_index !== undefined) {
|
|
2540
2772
|
const c = browserElCache.get(id);
|
|
2541
2773
|
if (!c || Date.now() - c.ts > 30000) return { error: "element_no_longer_valid: no fresh snapshot (TTL 30s) — re-run browser_snapshot (delivery=not_delivered, retry=safe)" };
|
|
2542
2774
|
if (c.page !== page) return { error: "element_no_longer_valid: active page changed since snapshot — re-run browser_snapshot (delivery=not_delivered, retry=safe)" };
|
|
2543
|
-
// the address is compared, and the count of navigations: a reload of the same address is one
|
|
2775
|
+
// the address is compared, and the count of navigations: a reload of the same address is one
|
|
2544
2776
|
if (c.url !== page.url() || c.commits !== navs.get(page).commits) return { error: "element_no_longer_valid: page navigated since snapshot — re-run browser_snapshot (delivery=not_delivered, retry=safe)" };
|
|
2545
2777
|
const want = c.elements[args.element_index];
|
|
2546
2778
|
if (!want) return { error: `invalid_element_index: ${args.element_index} (snapshot has ${c.elements.length} elements) (delivery=not_delivered, retry=safe)` };
|
|
2547
2779
|
const r = await clickByIndex(page, args.element_index, want, button);
|
|
2548
2780
|
if (r.error) return { error: r.error };
|
|
2549
|
-
return { text: `clicked element_index ${args.element_index} (${want.tag} "${want.name}") — delivery=delivered_unverified, retry=unsafe` };
|
|
2781
|
+
return { text: `clicked element_index ${args.element_index} (${want.tag} "${want.name}")${await moved()} — delivery=delivered_unverified, retry=unsafe` };
|
|
2550
2782
|
}
|
|
2551
2783
|
if (args.selector) {
|
|
2552
2784
|
try {
|
|
@@ -2554,7 +2786,7 @@ async function browserClick(args) {
|
|
|
2554
2786
|
} catch (e) {
|
|
2555
2787
|
return { error: `action_failed: click selector "${args.selector}" failed: ${shortErr(e)} (delivery=unknown, retry=unsafe)` };
|
|
2556
2788
|
}
|
|
2557
|
-
return { text: `clicked selector: ${args.selector} — delivery=delivered_unverified, retry=unsafe` };
|
|
2789
|
+
return { text: `clicked selector: ${args.selector}${await moved()} — delivery=delivered_unverified, retry=unsafe` };
|
|
2558
2790
|
}
|
|
2559
2791
|
if (Array.isArray(args.xy)) {
|
|
2560
2792
|
try {
|
|
@@ -2562,7 +2794,7 @@ async function browserClick(args) {
|
|
|
2562
2794
|
} catch (e) {
|
|
2563
2795
|
return { error: `action_failed: click @ ${args.xy} failed: ${shortErr(e)} (delivery=unknown, retry=unsafe)` };
|
|
2564
2796
|
}
|
|
2565
|
-
return { text: `clicked @ ${args.xy} — delivery=delivered_unverified, retry=unsafe` };
|
|
2797
|
+
return { text: `clicked @ ${args.xy}${await moved()} — delivery=delivered_unverified, retry=unsafe` };
|
|
2566
2798
|
}
|
|
2567
2799
|
return { error: "selector, xy:[x,y], or element_index required (delivery=not_delivered, retry=safe)" };
|
|
2568
2800
|
}
|
|
@@ -2571,13 +2803,16 @@ async function browserFill(args) {
|
|
|
2571
2803
|
const s = getActiveSession(args.browser_id);
|
|
2572
2804
|
if (!s || !args.selector) return { error: "no browser or selector (delivery=not_delivered, retry=safe)" };
|
|
2573
2805
|
const { page } = s;
|
|
2574
|
-
const val = String(args.value
|
|
2806
|
+
const val = String(args.value);
|
|
2575
2807
|
try {
|
|
2576
2808
|
await withTimeout(page.fill(args.selector, val, { timeout: 10000 }), 12000, "fill");
|
|
2577
2809
|
} catch (e) {
|
|
2578
2810
|
return { error: `action_failed: fill "${args.selector}" failed: ${shortErr(e)} (delivery=unknown, retry=unsafe)` };
|
|
2579
2811
|
}
|
|
2580
2812
|
const actual = await withTimeout(page.locator(args.selector).first().inputValue({ timeout: 2000 }), 2500, "inputValue").catch(() => null);
|
|
2813
|
+
// a fill can make the page navigate (a search box that reloads as it is typed in): what is read back then
|
|
2814
|
+
// may be a field of the next page, which says nothing about this fill
|
|
2815
|
+
if (navigated(s)) return { text: `filled ${args.selector} — the page navigated after the fill (it shows ${showsNow(s)} now), so the field was not read back — delivery=delivered_unverified, retry=unsafe` };
|
|
2581
2816
|
const delivery = actual === val ? "delivered_verified" : "delivered_unverified";
|
|
2582
2817
|
return { text: `filled ${args.selector} — delivery=${delivery}, retry=unsafe` };
|
|
2583
2818
|
}
|
|
@@ -2594,65 +2829,362 @@ async function browserPressKey(args) {
|
|
|
2594
2829
|
return { text: `pressed ${args.key} — delivery=delivered_unverified, retry=unsafe` };
|
|
2595
2830
|
}
|
|
2596
2831
|
|
|
2597
|
-
async function browserType(args) {
|
|
2832
|
+
async function browserType(args, live) {
|
|
2598
2833
|
const s = getActiveSession(args.browser_id);
|
|
2599
2834
|
if (!s || !args.text) return { error: "no browser or text (delivery=not_delivered, retry=safe)" };
|
|
2600
2835
|
const { page } = s;
|
|
2601
2836
|
// the budget covers the 20 ms/key typing time with margin (validateArgs caps text at 2000 chars), so an
|
|
2602
2837
|
// ordinary type is never cut off with keystrokes still going out
|
|
2603
2838
|
const budget = Math.max(10000, args.text.length * 30 + 5000);
|
|
2839
|
+
// One character at a time, as keyboard.type does itself — so that typing can be stopped: a timeout here does
|
|
2840
|
+
// not stop a keyboard.type that is under way, and the rest of the text would keep arriving after the error,
|
|
2841
|
+
// into whatever has the focus by then.
|
|
2842
|
+
const chars = [...args.text];
|
|
2843
|
+
let sent = 0, stop = false, under = false, left = false, halted = null;
|
|
2844
|
+
const typing = (async () => {
|
|
2845
|
+
for (const ch of chars) {
|
|
2846
|
+
if (stop) return;
|
|
2847
|
+
// the client gave the call up (its Stop button): the rest of the text is not typed
|
|
2848
|
+
if (live?.cancelled) return;
|
|
2849
|
+
// a long text outlasts a navigation: once the tab shows a page noracu does not act on, the rest of the
|
|
2850
|
+
// text is not typed into it
|
|
2851
|
+
if (!tabAllowed(s.b, page)) { left = true; return; }
|
|
2852
|
+
// the stop file is the person's switch: a long text does not go on being typed once the file is there
|
|
2853
|
+
halted = stopFileBlocked();
|
|
2854
|
+
if (halted) return;
|
|
2855
|
+
under = true;
|
|
2856
|
+
try {
|
|
2857
|
+
if (ch.codePointAt(0) > 0x7f) {
|
|
2858
|
+
// keyboard.type waits its delay and then inserts such a character; the wait is made here instead, so
|
|
2859
|
+
// that a stop during it keeps the character from going out
|
|
2860
|
+
await sleep(20);
|
|
2861
|
+
if (stop || live?.cancelled) return;
|
|
2862
|
+
halted = stopFileBlocked(); // the file may have come during the wait
|
|
2863
|
+
if (halted) return;
|
|
2864
|
+
await page.keyboard.insertText(ch);
|
|
2865
|
+
} else await page.keyboard.type(ch, { delay: 20 });
|
|
2866
|
+
} finally { under = false; }
|
|
2867
|
+
sent++;
|
|
2868
|
+
}
|
|
2869
|
+
})();
|
|
2604
2870
|
try {
|
|
2605
|
-
await withTimeout(
|
|
2871
|
+
await withTimeout(typing, budget, "keyboard.type");
|
|
2606
2872
|
} catch (e) {
|
|
2607
|
-
|
|
2873
|
+
const going = under; // read before the loop is told to stop: a character was on its way when the time ran out
|
|
2874
|
+
stop = true;
|
|
2875
|
+
typing.catch(() => {});
|
|
2876
|
+
const rest = chars.length - sent - (going ? 1 : 0);
|
|
2877
|
+
return { error: `action_failed: type failed: ${shortErr(e)} — ${sent} of ${chars.length} character(s) had gone out${going ? "; one more was under way and may still arrive" : ""}${rest > 0 ? `; the other ${rest} are not sent` : ""} (delivery=unknown, retry=unsafe)` };
|
|
2878
|
+
}
|
|
2879
|
+
if (left) return { error: `active_page_not_allowed: the tab went to a page noracu does not act on while the text was being typed (it shows ${showsNow(s)} now) — ${sent} of ${chars.length} character(s) had gone out before that and the rest are not sent ${sent ? "(delivery=unknown, retry=unsafe)" : "(delivery=not_delivered, retry=safe)"}` };
|
|
2880
|
+
if (halted) {
|
|
2881
|
+
if (!sent) return { error: halted };
|
|
2882
|
+
// the reason as it is given (the file is there, or it could not be checked), without its "nothing was sent":
|
|
2883
|
+
// part of the text did go out
|
|
2884
|
+
const why = halted.split(/\s*[;—]?\s*nothing was sent/)[0].trim();
|
|
2885
|
+
return { error: `${why} — this came up while the text was being typed: ${sent} of ${chars.length} character(s) had gone out before that and the rest are not sent (delivery=unknown, retry=unsafe)${/^user_stopped/.test(halted) ? "; remove the file to resume" : ""}` };
|
|
2608
2886
|
}
|
|
2609
|
-
return { text: `typed ${
|
|
2887
|
+
return { text: `typed ${chars.length} chars — delivery=delivered_unverified, retry=unsafe` };
|
|
2610
2888
|
}
|
|
2611
2889
|
|
|
2612
|
-
|
|
2890
|
+
// browser_scroll judges the wheel by what the page did with it, read once the page has had it — not at a fixed time
|
|
2891
|
+
// after mouse.wheel returns. Measured 2026-11-19 (headless, a 125-button page): the page got the wheel and moved
|
|
2892
|
+
// 36–58 ms after mouse.wheel returned in a normal process, 200–660 ms when the server (and with it Chromium) ran at
|
|
2893
|
+
// background priority, as a launchd job without ProcessType does — there it moved up to 224 ms after it reported
|
|
2894
|
+
// the wheel; a navigation the wheel started committed after 36–60 ms and 236–455 ms. A fixed 80 ms then said "did
|
|
2895
|
+
// not move" for a scroll that went through, took the late scroll of the call before for its own, and missed the
|
|
2896
|
+
// navigation. So: the position is to be still before the wheel; listeners under a name of this call's own count the
|
|
2897
|
+
// trusted wheel events that reach the page (one mouse.wheel makes one, with this call's deltas) and say that a
|
|
2898
|
+
// navigation began (the Navigation API's navigate event, or pagehide where there is none); after the wheel the
|
|
2899
|
+
// position is read until it has moved and stopped, until SCROLL_STILL_MS have passed since the page had the wheel
|
|
2900
|
+
// without it moving, or until SCROLL_SEEN_MS have passed. A movement is verified only when exactly one wheel reached
|
|
2901
|
+
// the page and it was this one. A wheel over a frame goes to the frame's document, which these listeners do not
|
|
2902
|
+
// hear: there the page around it is watched for SCROLL_FRAME_MS after the wheel is sent, and nothing is verified
|
|
2903
|
+
// (also when the page reports a wheel then: it can tell neither that it was this one nor that the frame was not
|
|
2904
|
+
// there). Calls on one page take turns, so one call's wheel is not read as another's. A wheel whose effect a call
|
|
2905
|
+
// did not verify may still have one, at any time and either way — a page can act on a wheel later, or make room to
|
|
2906
|
+
// scroll first — so in a document a movement is verified only while every wheel that may have reached it was
|
|
2907
|
+
// verified. That doubt is kept here, out of the page's reach, by the identity Chromium gives a document (scrollDocId):
|
|
2908
|
+
// a document is in doubt from right before a wheel goes out to it until a call verifies. A wheel can also reach a
|
|
2909
|
+
// document that comes later — a navigation that commits before the page has handled it — so while a wheel may still
|
|
2910
|
+
// be on its way (pending), every document the tab commits is in doubt as well. A wheel is on its way from right
|
|
2911
|
+
// before it goes out until the page reports it, or until the page, in one and the same document, has drawn twice
|
|
2912
|
+
// since Chromium acknowledged it (mouse.wheel returns once the page's renderer has the wheel): Chromium hands queued
|
|
2913
|
+
// wheel events to the page at the start of a frame, before its requestAnimationFrame callbacks (scrollFlushed). A
|
|
2914
|
+
// document the server cannot name gets no wheel, and a tab whose documents the server lost sight of no longer
|
|
2915
|
+
// verifies (blind).
|
|
2916
|
+
const SCROLL_POLL_MS = 25, SCROLL_STABLE_MS = 75, SCROLL_STILL_MS = 1000, SCROLL_FRAME_MS = 1500, SCROLL_SEEN_MS = 3000, SCROLL_SETTLE_MS = 1000, SCROLL_FLUSH_MS = 1000;
|
|
2917
|
+
const scrollTurns = new WeakMap(); // page → the end of the last browser_scroll queued on it
|
|
2918
|
+
// the gap between a float32 and the next one above it, at |x| (Chromium carries a wheel's distance as a float32)
|
|
2919
|
+
const f32Cell = new Float32Array(1), f32Bits = new Int32Array(f32Cell.buffer);
|
|
2920
|
+
const ulp32 = (x) => { f32Cell[0] = Math.abs(x); const a = f32Cell[0]; f32Bits[0] += 1; return f32Cell[0] - a; };
|
|
2921
|
+
const scrollPages = new WeakMap(); // page → { cdp: the server's own CDP session, doubted: Set of documents, pending, blind, world, tag }
|
|
2922
|
+
const scrollPage = (page) => {
|
|
2923
|
+
let st = scrollPages.get(page);
|
|
2924
|
+
if (!st) scrollPages.set(page, (st = { cdp: null, doubted: new Set(), pending: false, blind: false, world: null, tag: 0 }));
|
|
2925
|
+
return st;
|
|
2926
|
+
};
|
|
2927
|
+
// The document the page shows, as Chromium names it: the main frame's id and the id of the loader of its document,
|
|
2928
|
+
// read through a CDP session of the server's own. history.pushState and fragments keep it; a document loaded again
|
|
2929
|
+
// has a new one; a document brought back from the back-forward cache keeps its own (with its doubt). null when it
|
|
2930
|
+
// cannot be read — the call then does not verify.
|
|
2931
|
+
async function scrollDocId(page) {
|
|
2932
|
+
const st = scrollPage(page);
|
|
2933
|
+
try {
|
|
2934
|
+
if (!st.cdp) {
|
|
2935
|
+
const making = page.context().newCDPSession(page);
|
|
2936
|
+
let cdp;
|
|
2937
|
+
try {
|
|
2938
|
+
cdp = await withTimeout(making, 5000, "scroll document");
|
|
2939
|
+
} catch (e) {
|
|
2940
|
+
making.then((late) => late.detach().catch(() => {}), () => {});
|
|
2941
|
+
throw e;
|
|
2942
|
+
}
|
|
2943
|
+
cdp.on("Page.frameNavigated", (e) => {
|
|
2944
|
+
// the tab shows another document while a wheel may still be on its way: it may go there
|
|
2945
|
+
if (st.pending && e?.frame && !e.frame.parentId) st.doubted.add(`${e.frame.id}:${e.frame.loaderId}`);
|
|
2946
|
+
});
|
|
2947
|
+
try {
|
|
2948
|
+
await withTimeout(cdp.send("Page.enable"), 5000, "scroll document");
|
|
2949
|
+
} catch (e) {
|
|
2950
|
+
cdp.detach().catch(() => {});
|
|
2951
|
+
throw e;
|
|
2952
|
+
}
|
|
2953
|
+
st.cdp = cdp;
|
|
2954
|
+
}
|
|
2955
|
+
const { frameTree } = await withTimeout(st.cdp.send("Page.getFrameTree"), 5000, "scroll document");
|
|
2956
|
+
return frameTree?.frame?.id && frameTree.frame.loaderId ? `${frameTree.frame.id}:${frameTree.frame.loaderId}` : null;
|
|
2957
|
+
} catch (e) {
|
|
2958
|
+
// the server's view of the tab ended (not a slow answer): documents committed from then on went unseen, so the
|
|
2959
|
+
// tab no longer verifies; the next call opens a new view, to name documents again
|
|
2960
|
+
if (st.cdp && /closed|detached|not attached|No target|not found/i.test(String(e?.message ?? e))) {
|
|
2961
|
+
st.blind = true;
|
|
2962
|
+
st.cdp.detach().catch(() => {});
|
|
2963
|
+
st.cdp = null;
|
|
2964
|
+
}
|
|
2965
|
+
return null;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
// evaluated in a world of the server's own in that document (made once per document), out of the page scripts' reach
|
|
2969
|
+
async function scrollWorldEval(page, docId, expression, ms) {
|
|
2970
|
+
const st = scrollPage(page);
|
|
2971
|
+
if (docId === null || !st.cdp) throw new Error("no document");
|
|
2972
|
+
if (st.world?.doc !== docId) {
|
|
2973
|
+
const w = await withTimeout(st.cdp.send("Page.createIsolatedWorld", { frameId: docId.split(":")[0], worldName: "noracu-scroll" }), 5000, "scroll world");
|
|
2974
|
+
st.world = { doc: docId, ctx: w.executionContextId };
|
|
2975
|
+
}
|
|
2976
|
+
const r = await withTimeout(st.cdp.send("Runtime.evaluate", { expression, contextId: st.world.ctx, awaitPromise: true, returnByValue: true }), ms, "scroll world");
|
|
2977
|
+
if (r?.exceptionDetails) throw new Error(`scroll world: ${r.exceptionDetails.text || "exception"}`);
|
|
2978
|
+
return r?.result?.value;
|
|
2979
|
+
}
|
|
2980
|
+
// true once the page, in one and the same document, has drawn twice: every wheel Chromium acknowledged before was
|
|
2981
|
+
// handed to that document's renderer by then
|
|
2982
|
+
async function scrollFlushed(page) {
|
|
2983
|
+
const docId = await scrollDocId(page);
|
|
2984
|
+
try {
|
|
2985
|
+
const v = await scrollWorldEval(page, docId, "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(1))))", SCROLL_FLUSH_MS);
|
|
2986
|
+
return v === 1 && (await scrollDocId(page)) === docId;
|
|
2987
|
+
} catch {
|
|
2988
|
+
return false;
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
async function browserScroll(args = {}, live) {
|
|
2992
|
+
const first = getActiveSession(args.browser_id);
|
|
2993
|
+
if (!first) return { error: "no browser — call browser_launch first (delivery=not_delivered, retry=safe)" };
|
|
2994
|
+
const turn = (scrollTurns.get(first.page) || Promise.resolve()).then(() => scrollOnce(args, live, first.page));
|
|
2995
|
+
scrollTurns.set(first.page, turn.then(() => {}, () => {}));
|
|
2996
|
+
return turn;
|
|
2997
|
+
}
|
|
2998
|
+
async function scrollOnce(args, live, page0) {
|
|
2999
|
+
// the call may have waited for the one before it: what was checked when it came in is checked again
|
|
3000
|
+
if (live?.cancelled) return { error: "cancelled: the client cancelled the call while it waited for its turn; nothing was sent (delivery=not_delivered, retry=safe)" };
|
|
3001
|
+
const stop = stopFileBlocked();
|
|
3002
|
+
if (stop) return { error: stop };
|
|
2613
3003
|
const s = getActiveSession(args.browser_id);
|
|
2614
3004
|
if (!s) return { error: "no browser — call browser_launch first (delivery=not_delivered, retry=safe)" };
|
|
3005
|
+
if (s.page !== page0) return { error: "not_actionable: the active page changed while this call waited for the browser_scroll before it; nothing was sent (delivery=not_delivered, retry=safe)" };
|
|
2615
3006
|
const { page } = s;
|
|
2616
3007
|
const direction = args.direction || "down";
|
|
2617
3008
|
const pages = args.pages !== undefined ? Number(args.pages) : 1;
|
|
2618
|
-
|
|
3009
|
+
const key = `__noracu_wheel_${randomUUID().replace(/-/g, "")}`;
|
|
3010
|
+
const read = (k) => withTimeout(page.evaluate((k2) => {
|
|
3011
|
+
const f = k2 ? window[k2] : null;
|
|
3012
|
+
return { x: Math.round(window.scrollX), y: Math.round(window.scrollY), ours: !k2 || Boolean(f), n: f ? f.n : 0, wx: f ? f.dx : 0, wy: f ? f.dy : 0, leaving: f?.leaving === true };
|
|
3013
|
+
}, k), 5000, "scroll read");
|
|
3014
|
+
// the listeners go when the call is done (nothing waits for that; on another page there is nothing to remove)
|
|
3015
|
+
const unhook = () => page.evaluate((k) => {
|
|
3016
|
+
const f = window[k];
|
|
3017
|
+
if (!f) return;
|
|
3018
|
+
try { f.off(); } catch {}
|
|
3019
|
+
try { delete window[k]; } catch {}
|
|
3020
|
+
}, key).catch(() => {});
|
|
3021
|
+
let before, cx, cy, still = true, framed = false, doubt = false, docId = null, dpr = null;
|
|
2619
3022
|
try {
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
3023
|
+
// still before the wheel: a page that is still moving (a scroll of its own, or one that has not landed yet)
|
|
3024
|
+
// would have that movement counted as this wheel's
|
|
3025
|
+
let a = await read(null);
|
|
3026
|
+
for (const t0 = Date.now(); ;) {
|
|
3027
|
+
await sleep(2 * SCROLL_POLL_MS);
|
|
3028
|
+
const b = await read(null);
|
|
3029
|
+
if (b.x === a.x && b.y === a.y) break;
|
|
3030
|
+
a = b;
|
|
3031
|
+
if (Date.now() - t0 > SCROLL_SETTLE_MS) { still = false; break; }
|
|
3032
|
+
}
|
|
3033
|
+
const vp = page.viewportSize();
|
|
3034
|
+
// a document the server cannot name gets no wheel
|
|
3035
|
+
docId = await scrollDocId(page);
|
|
3036
|
+
if (docId === null) {
|
|
3037
|
+
unhook();
|
|
3038
|
+
return { error: "not_actionable: noracu could not tell which document the page shows (its DevTools view of the tab did not answer); no wheel was sent (delivery=not_delivered, retry=safe)" };
|
|
3039
|
+
}
|
|
3040
|
+
// an earlier wheel that may have reached this document was not verified, or may still be on its way
|
|
3041
|
+
doubt = scrollPage(page).blind || scrollPage(page).pending || scrollPage(page).doubted.has(docId);
|
|
3042
|
+
// the ratio the page reports wheel distances by, read where the page cannot change it; not known → not verified
|
|
3043
|
+
dpr = await scrollWorldEval(page, docId, "devicePixelRatio", 5000).then((v) => (typeof v === "number" && v > 0 ? v : null), () => null);
|
|
3044
|
+
const info = await withTimeout(page.evaluate(([k, vw, vh]) => {
|
|
3045
|
+
const f = { n: 0, dx: 0, dy: 0, leaving: false };
|
|
3046
|
+
const ac = new AbortController();
|
|
3047
|
+
f.off = () => ac.abort();
|
|
3048
|
+
Object.defineProperty(window, k, { value: f, configurable: true, enumerable: false, writable: false });
|
|
3049
|
+
// trusted only: a wheel event the page makes itself is no sign of this one
|
|
3050
|
+
addEventListener("wheel", (e) => { if (!e.isTrusted) return; if (++f.n === 1) { f.dx = e.deltaX; f.dy = e.deltaY; } }, { capture: true, passive: true, signal: ac.signal });
|
|
3051
|
+
const nav = globalThis.navigation;
|
|
3052
|
+
if (nav && typeof nav.addEventListener === "function") nav.addEventListener("navigate", () => { f.leaving = true; }, { once: true, signal: ac.signal });
|
|
3053
|
+
else addEventListener("pagehide", () => { f.leaving = true; }, { once: true, signal: ac.signal });
|
|
3054
|
+
// the point the wheel is sent at, and whether a frame is there (inside a shadow root too)
|
|
3055
|
+
const px = Math.round((vw || window.innerWidth || 800) / 2), py = Math.round((vh || window.innerHeight || 600) / 2);
|
|
3056
|
+
let el = document.elementFromPoint(px, py);
|
|
3057
|
+
for (let i = 0; el && el.shadowRoot && i < 32; i++) {
|
|
3058
|
+
const inner = el.shadowRoot.elementFromPoint(px, py);
|
|
3059
|
+
if (!inner || inner === el) break;
|
|
3060
|
+
el = inner;
|
|
3061
|
+
}
|
|
3062
|
+
return { x: Math.round(window.scrollX), y: Math.round(window.scrollY), px, py, framed: Boolean(el) && /^(IFRAME|FRAME|OBJECT|EMBED)$/.test(el.tagName) };
|
|
3063
|
+
}, [key, vp?.width || 0, vp?.height || 0]), 5000, "scroll read");
|
|
3064
|
+
cx = info.px;
|
|
3065
|
+
cy = info.py;
|
|
2628
3066
|
before = { x: info.x, y: info.y };
|
|
3067
|
+
framed = info.framed;
|
|
2629
3068
|
} catch (e) {
|
|
3069
|
+
unhook();
|
|
2630
3070
|
return { error: `not_actionable: could not read scroll position: ${shortErr(e)} (delivery=not_delivered, retry=safe)` };
|
|
2631
3071
|
}
|
|
2632
|
-
const
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
3072
|
+
const st = scrollPage(page);
|
|
3073
|
+
// the wheel carries a tag in its distance: 1 to 15 units of 16 float32 steps of that distance (a 1024th of a pixel
|
|
3074
|
+
// for one page; for a request under a 1200th of a page, which rounds to no pixel, the steps of 1 px), another one
|
|
3075
|
+
// on each call on the page; it moves the page by under a quarter pixel more, which the positions, in whole pixels,
|
|
3076
|
+
// do not show
|
|
3077
|
+
st.tag = (st.tag % 15) + 1;
|
|
3078
|
+
const base = Math.round(pages * 600);
|
|
3079
|
+
const unit = 16 * ulp32(Math.max(1, base));
|
|
3080
|
+
const amount = base + st.tag * unit;
|
|
3081
|
+
const dx = direction === "left" ? -amount : direction === "right" ? amount : 0;
|
|
3082
|
+
const dy = direction === "up" ? -amount : direction === "down" ? amount : 0;
|
|
3083
|
+
let after, seenAt = null, sent = false;
|
|
3084
|
+
// the one wheel the page had was this call's: one mouse.wheel is one trusted event, and the page reports its
|
|
3085
|
+
// distance divided by the device pixel ratio, tag included (measured at ratios 1 to 3: as sent divided by the ratio;
|
|
3086
|
+
// were it rounded to a float32 on the way, it would still be within 2 float32 steps of that). So: within 2 such
|
|
3087
|
+
// steps, and a tag's step, as reported, over 4 of them — else this wheel cannot be told from the next tag's, and is
|
|
3088
|
+
// not taken for this call's. A wheel of another size, or another call's, is not this one.
|
|
3089
|
+
const near = (w, d) => {
|
|
3090
|
+
if (d === 0) return w === 0;
|
|
3091
|
+
if (dpr === null) return false;
|
|
3092
|
+
const want = d / dpr, step = ulp32(want);
|
|
3093
|
+
return unit / dpr > 4 * step && Math.abs(w - want) <= 2 * step;
|
|
3094
|
+
};
|
|
3095
|
+
const isMine = (a) => a.n === 1 && near(a.wx, dx) && near(a.wy, dy);
|
|
3096
|
+
let pendingBefore = st.pending;
|
|
3097
|
+
// the stop file and a cancellation, again before the input (the still-wait above can take a second or more), and
|
|
3098
|
+
// once more right before the wheel (moving the pointer waits for the page)
|
|
3099
|
+
const halted = () => (live?.cancelled ? "cancelled: the client cancelled the call; nothing was sent (delivery=not_delivered, retry=safe)" : stopFileBlocked());
|
|
3100
|
+
let halt = halted();
|
|
3101
|
+
if (halt) {
|
|
3102
|
+
unhook();
|
|
3103
|
+
return { error: halt };
|
|
3104
|
+
}
|
|
2636
3105
|
try {
|
|
2637
3106
|
await withTimeout(page.mouse.move(cx, cy), 5000, "mouse.move");
|
|
3107
|
+
// the document the wheel goes to: the one the call read the page in, or no wheel
|
|
3108
|
+
const wheelDoc = await scrollDocId(page);
|
|
3109
|
+
if (wheelDoc !== docId) {
|
|
3110
|
+
unhook();
|
|
3111
|
+
if (wheelDoc === null) return { error: `not_actionable: noracu could not tell which document the page showed by the time the pointer had moved to (${cx},${cy}) (its DevTools view of the tab did not answer); no wheel was sent (delivery=not_delivered, retry=safe)` };
|
|
3112
|
+
return { error: `not_actionable: the page showed another document by the time the pointer had moved to (${cx},${cy}) (it shows ${showsNow(s)} now); no wheel was sent (delivery=not_delivered, retry=safe)` };
|
|
3113
|
+
}
|
|
3114
|
+
// the stop file and a cancellation, last thing before the wheel: from this check to the wheel nothing waits
|
|
3115
|
+
halt = halted();
|
|
3116
|
+
if (halt) {
|
|
3117
|
+
unhook();
|
|
3118
|
+
// the reason as it is given, without its "nothing was sent": the pointer did move
|
|
3119
|
+
const why = halt.split(/\s*[;—]?\s*nothing was sent/)[0].trim();
|
|
3120
|
+
return { error: `${why} — this came up after the pointer had moved to (${cx},${cy}) in the page; no wheel was sent (delivery=not_delivered, retry=safe)${/^user_stopped/.test(halt) ? "; remove the file to resume" : ""}` };
|
|
3121
|
+
}
|
|
3122
|
+
// from here on a wheel may reach the document, or one that comes later: in doubt until a call verifies
|
|
3123
|
+
pendingBefore = st.pending;
|
|
3124
|
+
st.doubted.add(docId);
|
|
3125
|
+
st.pending = true;
|
|
2638
3126
|
await withTimeout(page.mouse.wheel(dx, dy), 5000, "mouse.wheel");
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
3127
|
+
sent = true;
|
|
3128
|
+
const t0 = Date.now();
|
|
3129
|
+
let last = null, lastAt = t0;
|
|
3130
|
+
for (;;) {
|
|
3131
|
+
await sleep(SCROLL_POLL_MS);
|
|
3132
|
+
after = await read(key);
|
|
3133
|
+
const now = Date.now();
|
|
3134
|
+
// the page has had this call's wheel, and none was on its way before: none can reach another document now
|
|
3135
|
+
if (after.ours && isMine(after) && !pendingBefore) st.pending = false;
|
|
3136
|
+
if (navigated(s) || !after.ours || after.leaving) break;
|
|
3137
|
+
if (after.n > 0 && seenAt === null) seenAt = now;
|
|
3138
|
+
const at = `${after.x},${after.y}`;
|
|
3139
|
+
if (at !== last) { last = at; lastAt = now; }
|
|
3140
|
+
const moved = after.x !== before.x || after.y !== before.y;
|
|
3141
|
+
if (moved && now - lastAt >= SCROLL_STABLE_MS) break;
|
|
3142
|
+
// still since the page had the wheel; over a frame, which does not say so, since the wheel was sent
|
|
3143
|
+
const from = framed ? t0 : seenAt;
|
|
3144
|
+
if (!moved && from !== null && now - from >= (framed ? SCROLL_FRAME_MS : SCROLL_STILL_MS)) break;
|
|
3145
|
+
if (now - t0 >= SCROLL_SEEN_MS) break;
|
|
3146
|
+
}
|
|
2645
3147
|
} catch (e) {
|
|
2646
|
-
|
|
3148
|
+
unhook();
|
|
3149
|
+
// whatever the call ends with: a wheel the page has drawn twice since is no longer on its way
|
|
3150
|
+
if (sent && (await scrollFlushed(page))) st.pending = false;
|
|
3151
|
+
const shows = navigated(s) ? ` (it shows ${showsNow(s)} now)` : "";
|
|
3152
|
+
// the wheel went out and the page navigated before it was read: as when a read below shows that
|
|
3153
|
+
if (sent && (navigated(s) || ctxGone(e))) return { text: `scrolled ${direction} ${pages} page(s) at (${cx},${cy}): scrollX ${before.x}, scrollY ${before.y} before the wheel — the page navigated meanwhile${shows}, so where the wheel left it was not read — delivery=delivered_unverified, retry=unsafe` };
|
|
3154
|
+
return { error: `action_failed: scroll ${direction} failed: ${shortErr(e)}${navigated(s) || ctxGone(e) ? " — the page navigated meanwhile" : ""} (delivery=unknown, retry=unsafe)` };
|
|
2647
3155
|
}
|
|
3156
|
+
unhook();
|
|
3157
|
+
if (await scrollFlushed(page)) st.pending = false;
|
|
3158
|
+
const where = `scrolled ${direction} ${pages} page(s) at (${cx},${cy}): scrollX ${before.x} → ${after.x}, scrollY ${before.y} → ${after.y}`;
|
|
3159
|
+
// the two positions are of two pages: a new page starts at the top, which says nothing about the wheel
|
|
3160
|
+
if (navigated(s) || !after.ours) return { text: `${where} — the page navigated meanwhile${navigated(s) ? ` (it shows ${showsNow(s)} now)` : ""}, so the positions are of two pages — delivery=delivered_unverified, retry=unsafe` };
|
|
3161
|
+
const unverified = (text) => ({ text });
|
|
3162
|
+
// a navigation that began may not finish (a download, a 204): the page stays, and the wheel's effect is not known
|
|
3163
|
+
if (after.leaving) return unverified(`${where} — the page navigated meanwhile (a navigation started while this call ran), so the position is not taken as the wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
2648
3164
|
const moved = after.x !== before.x || after.y !== before.y;
|
|
3165
|
+
const mine = isMine(after);
|
|
3166
|
+
const overFrame = framed;
|
|
3167
|
+
if (after.n > 0 && !mine) return unverified(`${where}${moved ? "" : " (did not move)"} — ${after.n > 1 ? `${after.n} wheel events` : "a wheel event that was not this one"} reached the page meanwhile, so what it did is not known to be this wheel's — delivery=unknown, retry=unsafe`);
|
|
2649
3168
|
if (!moved) {
|
|
2650
|
-
return {
|
|
3169
|
+
if (overFrame) return unverified(`${where} (did not move in the ${SCROLL_FRAME_MS / 1000} s after the wheel was sent; the wheel was over a frame, whose own scrolling is not read) — delivery=delivered_unverified, retry=unsafe`);
|
|
3170
|
+
// no sign that the page had the wheel: it may still arrive
|
|
3171
|
+
if (!mine) return unverified(`${where} (did not move) — the page did not report the wheel within ${SCROLL_SEEN_MS / 1000} s; it may still arrive — delivery=unknown, retry=unsafe`);
|
|
3172
|
+
return unverified(`${where} (did not move in the ${SCROLL_STILL_MS / 1000} s after the page had the wheel) — delivery=delivered_unverified, retry=unsafe`);
|
|
2651
3173
|
}
|
|
2652
|
-
|
|
3174
|
+
if (!still) return unverified(`${where} — the page was still moving before the wheel, so this movement is not known to be the wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
3175
|
+
if (overFrame) return unverified(`${where} — the page moved, but the wheel was over a frame, so the movement is not known to be the wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
3176
|
+
if (!mine) return unverified(`${where} — the page moved but did not report the wheel, so the movement is not known to be the wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
3177
|
+
// verified only when the page went the way that was asked: a page can move itself, also the other way
|
|
3178
|
+
const went = dy > 0 ? after.y > before.y : dy < 0 ? after.y < before.y : dx > 0 ? after.x > before.x : dx < 0 ? after.x < before.x : false;
|
|
3179
|
+
if (!went) return unverified(`${where} (the page moved, but not ${direction}) — delivery=delivered_unverified, retry=unsafe`);
|
|
3180
|
+
if (st.blind) return unverified(`${where} — noracu lost sight of this tab's documents earlier (its DevTools view ended), so no movement in it is taken as the wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
3181
|
+
if (doubt) return unverified(`${where} — an earlier wheel that may have reached this page was not verified, so this movement may be that wheel's — delivery=delivered_unverified, retry=unsafe`);
|
|
3182
|
+
// every wheel that may have reached this document was verified: the doubt comes off
|
|
3183
|
+
st.doubted.delete(docId);
|
|
3184
|
+
return { text: `${where} — delivery=delivered_verified, retry=unsafe` };
|
|
2653
3185
|
}
|
|
2654
3186
|
|
|
2655
|
-
//
|
|
3187
|
+
// cut text says where it was cut
|
|
2656
3188
|
function capText(t, max) {
|
|
2657
3189
|
return t.length > max ? `${t.slice(0, max)}\n[truncated: showing ${max} of ${t.length} chars]` : t;
|
|
2658
3190
|
}
|
|
@@ -2673,11 +3205,11 @@ async function browserRead(args = {}) {
|
|
|
2673
3205
|
async function browserEvaluate(args) {
|
|
2674
3206
|
// 安全:熔断开关——NORACU_DISABLE_EVAL=1 时禁用任意 JS 执行(优先于开启开关)
|
|
2675
3207
|
if (process.env.NORACU_DISABLE_EVAL === "1") return { error: "browser_evaluate disabled by NORACU_DISABLE_EVAL=1 (delivery=not_delivered, retry=safe)" };
|
|
2676
|
-
//
|
|
3208
|
+
// 2026-11-12: running any script in the page is opt-in — off unless NORACU_ENABLE_EVAL=1
|
|
2677
3209
|
if (process.env.NORACU_ENABLE_EVAL !== "1") return { error: "eval_disabled: browser_evaluate is off by default — it runs any script in the page; set NORACU_ENABLE_EVAL=1 in the server's environment to turn it on (delivery=not_delivered, retry=safe)" };
|
|
2678
3210
|
const s = getActiveSession(args.browser_id);
|
|
2679
3211
|
if (!s || !args.js) return { error: "no browser or js (delivery=not_delivered, retry=safe)" };
|
|
2680
|
-
//
|
|
3212
|
+
// in the person's own Chrome a script runs with every sign-in they have — never there
|
|
2681
3213
|
if (s.b.chrome) return { error: "eval_disabled: browser_evaluate does not run in your own Chrome (browser_launch chrome:true) — a script there runs with every sign-in you have; use browser_read or browser_snapshot (delivery=not_delivered, retry=safe)" };
|
|
2682
3214
|
const { page } = s;
|
|
2683
3215
|
let r, failed = null;
|
|
@@ -2706,7 +3238,7 @@ let tabSeq = 0;
|
|
|
2706
3238
|
const tabId = (p) => { if (!tabIds.has(p)) tabIds.set(p, `t${++tabSeq}`); return tabIds.get(p); };
|
|
2707
3239
|
// in the person's own Chrome (chrome:true) only noracu's tabs count: the others are not listed, read or acted on
|
|
2708
3240
|
// the person's tabs (NORACU_CHROME_TABS=all) count only while they show an http(s) page — never file://, whatever
|
|
2709
|
-
// NORACU_ALLOW_FILE_URL says, and never a browser page
|
|
3241
|
+
// NORACU_ALLOW_FILE_URL says, and never a browser page
|
|
2710
3242
|
const personTabOk = (b, p) => b.allTabs && /^https?:\/\//.test(String(p.url() || ""));
|
|
2711
3243
|
const openTabs = (b) => b.browser.pages().filter((p) => !p.isClosed() && isNonDevtoolsPage(p) && (!b.chrome || b.owned.has(p) || personTabOk(b, p)));
|
|
2712
3244
|
// Which tab may be the active page — picked with select, taking over when the active tab goes, or still being
|
|
@@ -2714,15 +3246,15 @@ const openTabs = (b) => b.browser.pages().filter((p) => !p.isClosed() && isNonDe
|
|
|
2714
3246
|
// on a local file, a browser page (chrome://) or a blob is listed only; the active page that comes to show one
|
|
2715
3247
|
// is not read or acted on while it does. about:blank counts only in a tab noracu opened itself (browser_launch,
|
|
2716
3248
|
// browser_tabs new), and only while that tab has loaded nothing else (freshBlank): a blank tab that a page
|
|
2717
|
-
// opened shares that page's origin and can read it — measured with a file:// page
|
|
3249
|
+
// opened shares that page's origin and can read it — measured with a file:// page. A session attached to an app (cdp_port) is that app's own pages, whatever
|
|
2718
3250
|
// they show: there the rule does not apply.
|
|
2719
3251
|
// Tabs still on the blank page noracu opened them on (browser_launch's first tab, browser_tabs new). Once a tab
|
|
2720
|
-
// has loaded anything, a blank page it shows later is whatever page sent it there: measured
|
|
3252
|
+
// has loaded anything, a blank page it shows later is whatever page sent it there: measured, a
|
|
2721
3253
|
// blank page reached from a local file still loads other local files into frames — a screenshot shows them —
|
|
2722
|
-
// and keeps that file's window.name. A new tab left alone reports no main-frame navigation (measured again
|
|
2723
|
-
//
|
|
3254
|
+
// and keeps that file's window.name. A new tab left alone reports no main-frame navigation (measured again).
|
|
3255
|
+
// Any navigation it does report ends its standing: a fragment put on the blank page, and also
|
|
2724
3256
|
// one whose address is about:blank again — history.back() to a blank page that a local file had reached is
|
|
2725
|
-
// reported that way, and that page loads local files again (measured
|
|
3257
|
+
// reported that way, and that page loads local files again (measured).
|
|
2726
3258
|
const freshBlank = new WeakSet();
|
|
2727
3259
|
function watchFreshBlank(page) {
|
|
2728
3260
|
if (String(page.url() || "") !== "about:blank") return;
|
|
@@ -2735,20 +3267,26 @@ function watchFreshBlank(page) {
|
|
|
2735
3267
|
page.on("framenavigated", onNav);
|
|
2736
3268
|
}
|
|
2737
3269
|
const urlPasses = (b, p, url) => {
|
|
2738
|
-
|
|
2739
|
-
|
|
3270
|
+
// a DevTools front end is not read or acted on in any session: keys typed into its console run as script
|
|
3271
|
+
if (isDevtoolsUrl(url)) return false;
|
|
3272
|
+
// an app attached over its DevTools port shows what it shows (file://, app://…); a page that has no address
|
|
3273
|
+
// yet is not known to be one of the app's
|
|
3274
|
+
if (b.cdpBrowser && !b.chrome) return url !== "";
|
|
3275
|
+
// the person's own tabs (NORACU_CHROME_TABS=all): http(s) only, whatever NORACU_ALLOW_FILE_URL says
|
|
2740
3276
|
if (b.chrome && !b.owned.has(p)) return Boolean(b.allTabs) && /^https?:\/\//.test(url);
|
|
2741
3277
|
if (url === "about:blank") return freshBlank.has(p);
|
|
2742
3278
|
return /^https?:\/\//.test(url) || (process.env.NORACU_ALLOW_FILE_URL === "1" && /^file:\/\//.test(url));
|
|
2743
3279
|
};
|
|
2744
3280
|
const tabAllowed = (b, p) => (!b.chrome || b.owned.has(p) || personTabOk(b, p)) && urlPasses(b, p, String(p.url() || ""));
|
|
3281
|
+
// a tab's address as a result names it: whole for a page the tools read, its first 60 characters otherwise
|
|
3282
|
+
const shownUrl = (b, p) => { const u = String(p.url() || ""); return tabAllowed(b, p) ? u : u.slice(0, 60); };
|
|
2745
3283
|
// How many times a tab's main frame has committed a page the tools do not read, counted from the first call the
|
|
2746
3284
|
// tab is the active page of. A content tool notes the count when it starts and compares when it is done: a tab
|
|
2747
3285
|
// that went to such a page and came back while the tool worked may have answered from there, and the address
|
|
2748
|
-
// at the end does not show it
|
|
3286
|
+
// at the end does not show it.
|
|
2749
3287
|
// commits: every navigation the main frame reported — another address, a fragment, a reload of the same address,
|
|
2750
3288
|
// history.pushState. A snapshot, whose parts are read one after the other, is not returned when one happened
|
|
2751
|
-
// while it was taken, and an element_index is not used after one
|
|
3289
|
+
// while it was taken, and an element_index is not used after one.
|
|
2752
3290
|
const navs = new WeakMap(); // page → { strays, commits }
|
|
2753
3291
|
function watchNavs(b, page) {
|
|
2754
3292
|
let n = navs.get(page);
|
|
@@ -2765,10 +3303,10 @@ function watchNavs(b, page) {
|
|
|
2765
3303
|
const NO_ACTIVE_PAGE = "no_active_page: none of the open tabs may be the active page — they show a local file, a browser page, a blob, or a blank page other than the one browser_launch or browser_tabs opened the tab on; open a tab with browser_tabs (action new) or select one on an http(s) page (delivery=not_delivered, retry=safe)";
|
|
2766
3304
|
// The active page is open and shows what no tab may show to be the active page. With the url held to 60
|
|
2767
3305
|
// characters the text stays under 400; it is thrown as a Refusal, which the dispatcher does not cut.
|
|
2768
|
-
const pageNote = (url) => (url.startsWith("chrome-error://") ? " (a load that failed)" : url === "about:blank" ? " (not the blank page noracu opened the tab on)" : "");
|
|
3306
|
+
const pageNote = (url) => (isDevtoolsUrl(url) ? " (DevTools — noracu does not read or act on it)" : url.startsWith("chrome-error://") ? " (a load that failed)" : url === "about:blank" ? " (not the blank page noracu opened the tab on)" : "");
|
|
2769
3307
|
// What a read or a script returned is handed over only if the active page still passes once it is done: a
|
|
2770
3308
|
// navigation can commit while a slow read runs, and a read that waits for a selector, or that starts while a
|
|
2771
|
-
// page is arriving, is answered by the new page
|
|
3309
|
+
// page is arriving, is answered by the new page. Input tools are checked when the call
|
|
2772
3310
|
// starts only. s: what getActiveSession returned.
|
|
2773
3311
|
function refusedSince(s, during, tail = " (delivery=not_delivered, retry=safe)") {
|
|
2774
3312
|
const passes = tabAllowed(s.b, s.page);
|
|
@@ -2789,9 +3327,9 @@ function readFailed(s, e, onNav = null) {
|
|
|
2789
3327
|
// what was read may be of the page before or of the one after. A snapshot, and a read of the whole page, are not
|
|
2790
3328
|
// returned. A read that waits for a selector is: going on across the page's own move to the next page is what
|
|
2791
3329
|
// "click, then read" relies on — its first line says that the page navigated, and gives both addresses
|
|
2792
|
-
|
|
2793
|
-
// A read that a move to another document cuts short is rejected before that navigation is reported (measured
|
|
2794
|
-
//
|
|
3330
|
+
//.
|
|
3331
|
+
// A read that a move to another document cuts short is rejected before that navigation is reported (measured:
|
|
3332
|
+
// 23 of 24 page.evaluate reads racing a reload or a move to another address), so the count does
|
|
2795
3333
|
// not show it yet; Playwright's own message does ("Execution context was destroyed, most likely because of a
|
|
2796
3334
|
// navigation"). e: the error a read ended with, when it did.
|
|
2797
3335
|
const navigated = (s) => navs.get(s.page).commits !== s.commits;
|
|
@@ -2802,12 +3340,12 @@ const pageChanged = (s, what, lost, again, e = null) => (navigated(s) || (e && c
|
|
|
2802
3340
|
const movedNote = (s) => {
|
|
2803
3341
|
const n = navs.get(s.page).commits - s.commits;
|
|
2804
3342
|
if (!n) return "";
|
|
2805
|
-
// more than one navigation: the text may also be of a page the tab only passed through
|
|
3343
|
+
// more than one navigation: the text may also be of a page the tab only passed through
|
|
2806
3344
|
return `[the page navigated ${n === 1 ? "" : `${n} times `}while this was read: it showed ${s.url.slice(0, 80)} when the read began and shows ${showsNow(s)} now — the text may be of either${n === 1 ? "" : ", or of a page in between"}]\n`;
|
|
2807
3345
|
};
|
|
2808
3346
|
// A script's result and a screenshot name no page and are handed over when the page navigated, between pages the
|
|
2809
3347
|
// tools read, while they were made: a script often navigates itself, and a refusal here would leave nothing to see
|
|
2810
|
-
// of a page that keeps changing its address. They say that it happened
|
|
3348
|
+
// of a page that keeps changing its address. They say that it happened.
|
|
2811
3349
|
const navNote = (s, during) => {
|
|
2812
3350
|
const n = navs.get(s.page).commits - s.commits;
|
|
2813
3351
|
return n ? `the page navigated ${n === 1 ? "" : `${n} times `}while ${during}: it showed ${s.url.slice(0, 80)} when the call began and shows ${showsNow(s)} now${n === 1 ? "" : ", by way of at least one page in between"}` : "";
|
|
@@ -2820,7 +3358,7 @@ const activePageRefused = (p) => {
|
|
|
2820
3358
|
// The tab that takes over when the active page is gone: the first open one that may be the active page, never
|
|
2821
3359
|
// one select would refuse — closing the active tab is not a way around select. None: there is no active page.
|
|
2822
3360
|
function nextActiveTab(b) {
|
|
2823
|
-
if (b.cdpBrowser && !b.chrome) { const open = b.browser.pages().filter((p) => !p.isClosed()); return open.find(isNonDevtoolsPage) ||
|
|
3361
|
+
if (b.cdpBrowser && !b.chrome) { const open = b.browser.pages().filter((p) => !p.isClosed()); return open.find(isNonDevtoolsPage) || null; }
|
|
2824
3362
|
// in the person's Chrome only one of noracu's tabs takes over: the person's become the active page by select alone
|
|
2825
3363
|
return openTabs(b).find((p) => (!b.chrome || b.owned.has(p)) && tabAllowed(b, p)) || null;
|
|
2826
3364
|
}
|
|
@@ -2828,14 +3366,20 @@ function nextActiveTab(b) {
|
|
|
2828
3366
|
// Returns how a result names it.
|
|
2829
3367
|
function settleActiveTab(id, b) {
|
|
2830
3368
|
if (!b.activePage || b.activePage.isClosed()) { b.activePage = nextActiveTab(b); browserElCache.delete(id); }
|
|
2831
|
-
return b.activePage ? `tab ${tabId(b.activePage)} (${b.activePage
|
|
3369
|
+
return b.activePage ? `tab ${tabId(b.activePage)} (${shownUrl(b, b.activePage)})` : "none";
|
|
2832
3370
|
}
|
|
2833
3371
|
async function describeTabs(b) {
|
|
2834
3372
|
const out = [];
|
|
2835
3373
|
for (const p of openTabs(b)) {
|
|
2836
3374
|
// null: the page did not answer in 3 s (busy or stuck) — not the same as a page that has no title
|
|
2837
|
-
|
|
2838
|
-
|
|
3375
|
+
// a tab on a page the tools do not read: its title is page content and is not asked for, and of its address
|
|
3376
|
+
// only the start is given, as in the refusals — enough to tell the tab apart, select another or close it
|
|
3377
|
+
let reads = tabAllowed(b, p);
|
|
3378
|
+
let title = reads ? await withTimeout(p.title(), 3000, "page.title").then((t) => String(t).slice(0, 120), () => null) : null;
|
|
3379
|
+
// the title is a round trip to the page: a tab that left for a page the tools do not read meanwhile may have
|
|
3380
|
+
// answered with that page's title
|
|
3381
|
+
if (reads && !tabAllowed(b, p)) { reads = false; title = null; }
|
|
3382
|
+
out.push({ tab_id: tabId(p), url: shownUrl(b, p), title, ...(reads ? {} : { not_read: true }), active: p === b.activePage, opened_by_browser_tabs: ownTabs.has(p), ...(b.chrome ? { noracu_tab: b.owned.has(p) } : {}) });
|
|
2839
3383
|
}
|
|
2840
3384
|
return out;
|
|
2841
3385
|
}
|
|
@@ -2856,7 +3400,7 @@ async function browserTabs(args = {}) {
|
|
|
2856
3400
|
b.activePage = page;
|
|
2857
3401
|
browserElCache.delete(id);
|
|
2858
3402
|
const stray = (b.strayTabs || 0) > strayBefore ? " (a first try may have left a blank tab in your Chrome that noracu could not tell apart; it was not closed)" : "";
|
|
2859
|
-
//
|
|
3403
|
+
// the tab's own address, read now; and with a stray tab about, which tab is noracu's is not certain
|
|
2860
3404
|
const how = stray ? "delivery=delivered_unverified, retry=unsafe" : "delivery=delivered_verified, retry=unsafe";
|
|
2861
3405
|
if (!args.url) return { text: `opened tab ${tabId(page)} (${String(page.url()).slice(0, 80) || "about:blank"})${stray} — it is the active page now; ${how}` };
|
|
2862
3406
|
try { await withTimeout(page.goto(args.url, { timeout: 30000, waitUntil: "domcontentloaded" }), 32000, "navigate"); }
|
|
@@ -2865,7 +3409,7 @@ async function browserTabs(args = {}) {
|
|
|
2865
3409
|
if (page.isClosed()) return { error: `navigate_failed: tab ${tabId(page)} was opened and closed again before the page loaded: ${shortErr(e)} — the active page is ${settleActiveTab(id, b)}${stray} (delivery=unknown, retry=unsafe)` };
|
|
2866
3410
|
return { error: `navigate_failed: tab ${tabId(page)} was opened and is the active page, but the page did not load: ${shortErr(e)}${stray} (delivery=unknown, retry=unsafe)` };
|
|
2867
3411
|
}
|
|
2868
|
-
//
|
|
3412
|
+
// the page can close itself or go somewhere the other tools refuse while it loads
|
|
2869
3413
|
if (page.isClosed()) return { error: `navigate_failed: tab ${tabId(page)} closed itself while loading ${String(args.url).slice(0, 80)} — the active page is ${settleActiveTab(id, b)}${stray} (delivery=unknown, retry=unsafe)` };
|
|
2870
3414
|
if (!tabAllowed(b, page)) return { error: `active_page_not_allowed: tab ${tabId(page)} was opened and asked for ${String(args.url).slice(0, 80)}, but it shows ${String(page.url()).slice(0, 80)} now — it is the active page and the other browser tools refuse it; use browser_navigate on it, or browser_tabs to select another${stray} (delivery=delivered_unverified, retry=unsafe)` };
|
|
2871
3415
|
return { text: `opened tab ${tabId(page)}: ${page.url()}${stray} — it is the active page now; ${how}` };
|
|
@@ -2890,7 +3434,7 @@ async function browserTabs(args = {}) {
|
|
|
2890
3434
|
const now = settleActiveTab(id, b);
|
|
2891
3435
|
if (!page.isClosed()) return { error: `action_failed: could not close tab ${args.tab_id}: ${shortErr(failed || "the tab is still open")} — the active page is ${now} (delivery=unknown, retry=unsafe)` };
|
|
2892
3436
|
// closed, but close() did not answer: the person or the page may have closed it — it is gone, noracu's close is not
|
|
2893
|
-
// confirmed as the cause
|
|
3437
|
+
// confirmed as the cause
|
|
2894
3438
|
if (failed) return { text: `tab ${args.tab_id} (${url}) is closed, but noracu's close did not answer (${shortErr(failed)}), so what closed it is not confirmed — the active page is ${now}; delivery=delivered_unverified, retry=safe` };
|
|
2895
3439
|
return { text: `closed tab ${args.tab_id} (${url}) — the active page is ${now}; delivery=delivered_verified, retry=unsafe` };
|
|
2896
3440
|
}
|
|
@@ -2900,7 +3444,7 @@ async function browserClose(args = {}) {
|
|
|
2900
3444
|
const lostMsg = (ids) => ({ error: `chrome_disconnected: ${ids.join(", ")} ${ids.length > 1 ? "are" : "is"} no longer connected to your Chrome (the connection ended) — noracu could not close its tabs there, they may still be open; noracu did not quit Chrome (delivery=not_delivered, retry=safe)` });
|
|
2901
3445
|
if (!args.browser_id && browsers.size === 0) {
|
|
2902
3446
|
// nothing open: a session in the person's Chrome whose connection was lost is named, never hidden behind a later
|
|
2903
|
-
// clean close
|
|
3447
|
+
// clean close
|
|
2904
3448
|
const lostIds = [...endedChrome].filter(([, v]) => v === "lost").map(([k]) => k);
|
|
2905
3449
|
if (lostIds.length) return lostMsg(lostIds);
|
|
2906
3450
|
const last = [...endedChrome.keys()].pop();
|
|
@@ -2916,7 +3460,7 @@ async function browserClose(args = {}) {
|
|
|
2916
3460
|
const port = b.cdp_port;
|
|
2917
3461
|
if (b.chrome) return closeChromeSession(id, b);
|
|
2918
3462
|
// the standalone browser, or a DevTools-port attach (the app keeps running): said done only once it is seen —
|
|
2919
|
-
// the context's close event, or the connection gone
|
|
3463
|
+
// the context's close event, or the connection gone
|
|
2920
3464
|
let seen = isCdp ? !b.cdpBrowser.isConnected() : false;
|
|
2921
3465
|
const ev = new Promise((r) => (isCdp ? b.cdpBrowser : b.browser).once(isCdp ? "disconnected" : "close", () => { seen = true; r(); }));
|
|
2922
3466
|
await withTimeout(isCdp ? b.cdpBrowser.close() : b.browser.close(), 10000, "close").catch(() => {});
|
|
@@ -2930,7 +3474,7 @@ async function browserClose(args = {}) {
|
|
|
2930
3474
|
|
|
2931
3475
|
// browser_close in the person's Chrome: noracu closes its own tabs and then disconnects; it never quits Chrome. The
|
|
2932
3476
|
// session stays listed until the disconnect is seen, so no second attach starts meanwhile; while one of noracu's
|
|
2933
|
-
// tabs is still open it does not disconnect, so a later browser_close can close it
|
|
3477
|
+
// tabs is still open it does not disconnect, so a later browser_close can close it
|
|
2934
3478
|
async function closeChromeSession(id, b) {
|
|
2935
3479
|
// the connection ended (Chrome quit, the switch turned off): which tabs closed is not known — say so
|
|
2936
3480
|
const lost = (when) => {
|
|
@@ -2944,7 +3488,7 @@ async function closeChromeSession(id, b) {
|
|
|
2944
3488
|
const tabs = () => b.browser.pages().filter((p) => !p.isClosed() && b.owned.has(p));
|
|
2945
3489
|
const mine = tabs();
|
|
2946
3490
|
// a tab counts as closed by noracu only when its close() answered; one that went while noracu was closing it
|
|
2947
|
-
// (the person, the page) is named apart
|
|
3491
|
+
// (the person, the page) is named apart
|
|
2948
3492
|
let closed = 0, gone = 0;
|
|
2949
3493
|
for (const p of mine) {
|
|
2950
3494
|
const ok = await withTimeout(p.close(), 5000, "page.close").then(() => true, () => false);
|
|
@@ -3005,7 +3549,7 @@ function phoneSwipe(args) {
|
|
|
3005
3549
|
// the imctl gesture; disabled / not-running return mirror_not_live, and unknown/timeout returns menu_unknown
|
|
3006
3550
|
// without retrying via imctl (which could send the gesture a second time).
|
|
3007
3551
|
async function mirrorMenu(command, timeoutMs = 15000) {
|
|
3008
|
-
// by bundle id: the app's display name is localized on non-English macOS
|
|
3552
|
+
// by bundle id: the app's display name is localized on non-English macOS
|
|
3009
3553
|
const r = await axEngine({ op: "menu", app: "com.apple.ScreenContinuity", command, require_enabled: true }, timeoutMs);
|
|
3010
3554
|
if (r.ok === true && r.delivery !== "unknown") {
|
|
3011
3555
|
return { ok: true, delivery: r.delivery || "delivered_unverified" };
|
|
@@ -3041,7 +3585,7 @@ function phoneScroll(args = {}) {
|
|
|
3041
3585
|
if (args.expect) a.push(`--expect=${args.expect}`);
|
|
3042
3586
|
return imctl(...a);
|
|
3043
3587
|
}
|
|
3044
|
-
function phoneType(args) {
|
|
3588
|
+
function phoneType(args, live) {
|
|
3045
3589
|
if (!args.text) return { error: "text required" };
|
|
3046
3590
|
// Options first, then `--`, then the free text: the text is a positional and
|
|
3047
3591
|
// may start with "-" (argparse would otherwise treat it as an option).
|
|
@@ -3051,7 +3595,7 @@ function phoneType(args) {
|
|
|
3051
3595
|
if (args.replace) a.push("--replace");
|
|
3052
3596
|
if (args.expect) a.push(`--expect=${args.expect}`);
|
|
3053
3597
|
a.push("--", "-");
|
|
3054
|
-
return
|
|
3598
|
+
return imctlRun(a, args.text, live); // the client's Stop ends imctl (see spawnTimed)
|
|
3055
3599
|
}
|
|
3056
3600
|
function phoneKey(args) {
|
|
3057
3601
|
if (!args.key) return { error: "key required (return/delete/up/down/left/right)" };
|
|
@@ -3096,9 +3640,9 @@ async function phoneScreenshot() {
|
|
|
3096
3640
|
// reads as "in front" under every app (measured: state 4 with Settings in front, simulator, iOS 26.5) — a rule
|
|
3097
3641
|
// that allows SpringBoard would let a tap reach an app the rules do not allow. So while an approval file or a
|
|
3098
3642
|
// NORACU_DENY_APPS of the user's own is in force, no input that names it is sent — not even one tap on a button
|
|
3099
|
-
// of a system prompt, which 0.3.0's first cut let through (
|
|
3643
|
+
// of a system prompt, which 0.3.0's first cut let through (2026-11-12). On the Home Screen a tap
|
|
3100
3644
|
// on an icon would open an app no rule was asked about, which is what ios_launch is for; text goes wherever the
|
|
3101
|
-
// keyboard focus is, which cannot be read
|
|
3645
|
+
// keyboard focus is, which cannot be read. With no rules, such input is
|
|
3102
3646
|
// sent as asked. The runner still understands springboard_only (docs/ios-runner-protocol.md); noracu no longer
|
|
3103
3647
|
// sends it.
|
|
3104
3648
|
const iosRulesInForce = () => process.env.NORACU_APPROVAL_FILE !== undefined || !/^(|none)$/i.test((process.env.NORACU_DENY_APPS || "").trim());
|
|
@@ -3113,6 +3657,7 @@ if (PHONE_BACKEND === "xcuitest") {
|
|
|
3113
3657
|
iosSession = createIosSession({
|
|
3114
3658
|
approve: iosApprove,
|
|
3115
3659
|
springboardDenied: iosRulesInForce,
|
|
3660
|
+
stopCheck: stopFileBlocked,
|
|
3116
3661
|
// a process group of its own, known to the exit hooks: a server that goes away takes xcodebuild with it
|
|
3117
3662
|
spawnImpl: (file, argv, opts) => { const c = spawn(file, argv, { ...opts, detached: true }); iosChild = c; c.once("close", () => { if (iosChild === c) iosChild = null; }); return c; },
|
|
3118
3663
|
});
|
|
@@ -3148,8 +3693,8 @@ function inputSchemaFromArgs(args, required) {
|
|
|
3148
3693
|
const TOOL_DEFS = [
|
|
3149
3694
|
// Mac computer-use
|
|
3150
3695
|
{ name: "mac_screenshot", desc: "Capture the Mac screen as PNG base64: the main display, display (index from mac_windows), or one window by window_id (CGWindowID from mac_windows; works when covered). A display capture can be cropped to region {x,y,w,h} in screen points as mac_windows reports them (the main display's top-left is 0,0; a display to its left has negative x), not relative to the display; with display given, a region not inside that display is refused. Returns {scale, logical_size, screen, screenshot_id}; click coordinates are in points (pixels / scale). screenshot_id (valid 30 s) lets mac_click take x,y in screenshot pixels: the window's geometry is re-checked first and a window that moved, resized or was rebuilt since the capture is refused as stale.", args: { region: "object?", window_id: "integer?", display: "integer?" }, fn: macScreenshot },
|
|
3151
|
-
{ name: "mac_ax_state", desc: "Read an app's accessibility tree
|
|
3152
|
-
{ name: "mac_click", desc: "Click a UI element by element_index (from mac_ax_state / mac_find; valid 30 s) or at raw {x,y}.
|
|
3696
|
+
{ name: "mac_ax_state", desc: "Read an app's accessibility tree (default: the frontmost app's focused window). app: a name, a bundle id, a .app path or pid:<n> — ambiguous_app when several running apps match; pick one by pid:<n> from its list. Returns {app, snapshot_id, window, complete, elements:[{i, d, role, title, value, states, actions, frame}]}; i is the element_index for mac_click, mac_get, mac_set_value, mac_type, mac_scroll and mac_drag — unique across snapshots, valid 30 s; an action re-identifies the element first (element_no_longer_valid if gone, moved or replaced). Options: interactive (actionable elements only), compact (default true: skip empty layout wrappers), skeleton (a shallow map with children_count), then root (an element_index to drill into, given alone: not with app, window, window_id or surface; adds indexes to the same snapshot), surface (window|menubar|menu|sheet|alert|dialog|popover|focused|app), window (index or title) or window_id (from mac_windows), depth (default 12, 1-40), max_nodes (default 400), web_accessibility (default true; false under NORACU_READ_ONLY=1): sets AXManualAccessibility on Electron/Chromium apps, never AXEnhancedUserInterface; the result says enabled, already_on, exposed (refused, but the pages are in the tree) or unsupported with a web_accessibility_hint (Google Chrome refuses it) — unknown, with the hint, when the window was too large to look through. window_identity unverifiable marks a window without a window ID: element_index actions in it are refused. ax_empty when the app has no readable window.", args: { app: "string?", interactive: "boolean?", compact: "boolean?", skeleton: "boolean?", root: "integer?", snapshot_id: "string?", surface: "string?", window: "string?", window_id: "integer?", depth: "integer?", max_nodes: "integer?", web_accessibility: "boolean?" }, fn: macAxState },
|
|
3697
|
+
{ name: "mac_click", desc: "Click a UI element by element_index (from mac_ax_state / mac_find; valid 30 s; snapshot_id only with it: the snapshot the index came from) or at raw {x,y}. The element is re-identified first (element_no_longer_valid if gone or changed). mechanism auto (default): the element's own accessibility action (press / show menu / select — no pointer, works in background windows) when it has one, else a physical click, sent only if a hit test shows the point reaches the element (occluded otherwise); semantic / physical force one path. count 2-3 and button middle are physical. Under auto a physical click on a native app is posted to its pid (route bgpost: no pointer move; never re-sent another way — no visible change is delivered_unverified with a note, a timeout delivery=unknown); web-engine apps (Chromium/Electron) and mechanism physical use the real pointer (route cliclick), re-checked right before it is sent. A physical click is delivered_verified only if the element is still there, changed, and its window is still on top at the point. A raw {x,y} click is sent only when the window on top at that point belongs to app (default: the frontmost app; the menu bar counts as its) — otherwise occluded names what covers it; force:true skips that check. screenshot_id + x,y: pixels of a mac_screenshot window capture, relative to its top-left corner; a window that moved, resized or was rebuilt since is refused as stale. Results state delivery (delivered_verified / delivered_unverified / not_delivered / unknown) and whether a retry is safe, plus newly opened sheets, dialogs or menus.", args: { element_index: "integer?", snapshot_id: "string?", x: "number?", y: "number?", screenshot_id: "string?", app: "string?", force: "boolean?", button: "string?", count: "number?", mechanism: "string?", timeout_ms: "integer?" }, fn: macClick },
|
|
3153
3698
|
{ name: "mac_drag", desc: "Drag from one UI element to another (sliders, selections, list items) with the physical pointer; from_index/to_index come from mac_ax_state or mac_find (valid 30 s). Both ends are re-identified and hit-tested first (either one gone or covered: nothing sent). hold_ms (0-2000) presses and holds after mouse-down before the move starts (timeline editors use it to tell clip-move from marquee selection); step_ms (1-500) moves in steps of about 20 points with that many ms between them. A drag whose holds and steps add up to more than 10 s is refused; a drag that fails midway gets a mouse-up so the button is not left held. Check the drop target afterwards.", args: { from_index: "integer", to_index: "integer", snapshot_id: "string?", hold_ms: "integer?", step_ms: "integer?" }, required: ["from_index", "to_index"], fn: macDrag },
|
|
3154
3699
|
{ name: "mac_scroll", desc: "Scroll up/down/left/right by a number of pages (default 1). Without element_index: the center of the frontmost app's front window (the pointer moves there), only when that app's window is on top at that point (else occluded, nothing scrolled). With element_index: a scroll area is scrolled at its own center (hit-tested; reports when the position did not change), any other element is scrolled into view (AXScrollToVisible).", args: { direction: "string?", pages: "number?", element_index: "integer?", snapshot_id: "string?" }, fn: macScroll },
|
|
3155
3700
|
{ name: "mac_key", desc: "Press a key or modifier chord, e.g. 'return', 'esc', 'cmd-c', 'cmd-shift-v', 'arrow-up'. Named keys (return, esc, tab, space, delete, arrows, home/end, page keys, F1-F16), with or without modifiers, go out as HID key events with each modifier pressed and released around the key; a chord with cmd or ctrl on a character key (cmd-c, cmd-shift-v) goes out the same way on the key that types that character in the current keyboard layout (no such key: not_delivered, keyboard_layout); a plain character or a shift/alt-only chord is typed through cliclick. Pass app to refuse input unless that app is frontmost (focus guard). A named key for a native frontmost app is posted straight to its pid (route: bgpost — no focus theft); web-engine apps and layout-dependent chords use the engine HID path. Chords that quit, log out, lock, force-quit, delete immediately or empty the Trash (cmd-q, alt-cmd-q, cmd-shift-q, cmd-alt-esc, ctrl-cmd-q, cmd-alt-delete, cmd-shift-delete…) are refused unless force:true.", args: { key: "string", app: "string?", force: "boolean?" }, fn: macKey },
|
|
@@ -3172,14 +3717,14 @@ const TOOL_DEFS = [
|
|
|
3172
3717
|
{ name: "browser_navigate", desc: "Navigate the active page to an http(s) URL (file:// is disabled unless NORACU_ALLOW_FILE_URL=1). Reports the final URL, HTTP status (or \"no response\" for same-document navigations), title, and delivery/retry.", args: { url: "string" }, fn: browserNavigate },
|
|
3173
3718
|
{ name: "browser_snapshot", desc: "Return the active page's ARIA accessibility snapshot (about 14000 characters with the list; a longer snapshot is cut and marked) plus up to 100 indexed interactive elements (reporting truncation and omitted count beyond 100, or that the list could not be read); indexes feed browser_click. When the page navigates while the snapshot is being taken it returns page_changed and nothing else (ask again); an element_index is not used after the page navigated. The active page stays the tab noracu is driving: a tab the page opens itself (window.open, target=_blank) is never switched to; another tab becomes active only after the active one closes.", args: { browser_id: "string?" }, fn: browserSnapshot },
|
|
3174
3719
|
{ name: "browser_screenshot", desc: "Screenshot the active page with optional fullPage, format png|jpeg, quality (1-100, jpeg) and clip {x,y,width,height} (uses scale:\"css\" when attached over CDP); returns the image plus DPR/viewport metadata (with a navigated note when the page navigated while the picture was taken).", args: { fullPage: "boolean?", format: "string?", quality: "number?", clip: "object?" }, fn: browserScreenshot },
|
|
3175
|
-
{ name: "browser_click", desc: "Click an element on the active page
|
|
3176
|
-
{ name: "browser_fill", desc: "Fill an input field matched by selector; fill replaces the whole value (browser_type appends keystrokes). Reports delivery and retry.", args: { selector: "string", value: "string
|
|
3720
|
+
{ name: "browser_click", desc: "Click an element on the active page. Give exactly one of element_index (from the latest browser_snapshot of that page; valid 30 s; page, URL, tag, name, href and position are re-checked, element_no_longer_valid when stale), selector (a fallback) or xy (pixel coordinates; not recommended). Real Playwright pointer input with actionability checks: occluded or not_actionable when covered or disabled — never a synthetic JS .click(). Reports delivery and retry.", args: { element_index: "integer?", selector: "string?", xy: "array?", button: "string?" }, fn: browserClick },
|
|
3721
|
+
{ name: "browser_fill", desc: "Fill an input field matched by selector with value; fill replaces the whole value — pass \"\" to clear the field (browser_type appends keystrokes). Reports delivery and retry.", args: { selector: "string", value: "string" }, fn: browserFill },
|
|
3177
3722
|
{ name: "browser_press_key", desc: "Press a key or chord, e.g. 'Enter' or 'Control+A'. Reports delivery and retry.", args: { key: "string" }, fn: browserPressKey },
|
|
3178
3723
|
{ name: "browser_type", desc: "Type up to 2000 characters via the keyboard into the focused element; type appends keystrokes (browser_fill replaces the whole value and suits longer text). Reports delivery and retry.", args: { text: "string" }, fn: browserType },
|
|
3179
3724
|
{ name: "browser_scroll", desc: "Scroll the active page up, down, left, or right by a number of pages (default: down, 1 page) via mouse wheel at the viewport center; reports the scrollX/scrollY change (or \"did not move\") plus delivery and retry.", args: { direction: "string?", pages: "number?" }, fn: browserScroll },
|
|
3180
3725
|
{ name: "browser_read", desc: "Read the active page's visible text (up to 12000 characters; 8000 with a selector; longer text is cut and marked), optionally scoped to a selector. When the page navigated while it was read: without a selector it returns page_changed (ask again); with one — a read that waits for a selector goes on across the page's own move to the next page — the first line of the result says so and gives both addresses.", args: { selector: "string?" }, fn: browserRead },
|
|
3181
3726
|
{ name: "browser_evaluate", desc: "Evaluate JavaScript in the active page and return the result plus delivery and retry. Off by default: runs only when the server was started with NORACU_ENABLE_EVAL=1 (eval_disabled otherwise), and never when NORACU_DISABLE_EVAL=1 or in your own Chrome (browser_launch chrome:true). When the page navigated while the script ran, a line after the result says so.", args: { js: "string" }, fn: browserEvaluate },
|
|
3182
|
-
{ name: "browser_tabs", desc: "List, open, select or close the tabs of the browser session.
|
|
3727
|
+
{ name: "browser_tabs", desc: "List, open, select or close the tabs of the browser session. list (the default): each tab's tab_id, url, title (null when the page did not answer in 3 s; a tab on a page the tools do not read has not_read:true, no title and the start of its address), whether it is the active page and whether browser_tabs opened it. new: opens a tab (url: http(s); file:// needs NORACU_ALLOW_FILE_URL=1) and makes it the active page. select: makes tab_id the active page — only a tab on an http(s) page (or file:// with NORACU_ALLOW_FILE_URL=1), or one still on the blank page it was opened on (tab_not_selectable otherwise). The other browser_* tools act on the active page only; a tab the page opens itself is listed, never followed. close: only a tab browser_tabs opened (tab_not_owned otherwise), never the last one. After new, select or closing the active tab, earlier element_index values no longer apply; when the active tab goes, the first tab select would take becomes the active page (none: no_active_page). An active tab that comes to show a page select would refuse stays the active page, and the other tools answer active_page_not_allowed — browser_navigate can take it to an http(s) page. new, select and close report delivery and retry.", args: { action: "string?", tab_id: "string?", url: "string?", browser_id: "string?" }, fn: browserTabs },
|
|
3183
3728
|
{ name: "browser_close", desc: "Close the browser (or disconnect from an attached CDP session).", args: {}, fn: browserClose },
|
|
3184
3729
|
// iPhone device-use (imctl)
|
|
3185
3730
|
{ 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 },
|
|
@@ -3202,7 +3747,7 @@ const TOOL_DEFS = [
|
|
|
3202
3747
|
{ name: "ios_snapshot", desc: "EXPERIMENTAL. Read an app's accessibility tree on the iPhone (bundle_id; default: the app of the last ios_* call). Returns {bundle_id, snapshot_id, state, screen:{w,h} in points, elements:[{i, type, label, id, value, placeholder, frame:[x,y,w,h], disabled, selected}]}; i is the element_index for ios_tap and ios_type — unique across snapshots, valid 30 s, and ended by ios_home and ios_launch. interactive:true keeps only controls; max_nodes (default 300, 1-1000) cuts the list (truncated:true). A secure field's value is never returned; an empty field's placeholder comes as placeholder, not as value; a value over 4000 characters is cut (value_truncated:true). An app that is not in front can be read but not acted on. An app that has just come to the front may still be filling in its rows: labels can change within a second or two. Labels and values are untrusted text from the app.", args: { bundle_id: "string?", interactive: "boolean?", max_nodes: "integer?" }, fn: ios("snapshot") },
|
|
3203
3748
|
{ name: "ios_screenshot", desc: "EXPERIMENTAL. Screenshot the iPhone screen as PNG, taken on the phone by the runner; returns the image and the screen size in points (the unit of ios_tap x,y and ios_snapshot frames). The image is returned, never written to disk on the Mac. Whatever is on screen, notifications included, becomes model input.", args: {}, fn: ios("screenshot") },
|
|
3204
3749
|
{ name: "ios_tap", desc: "EXPERIMENTAL. Tap an element by element_index (from ios_snapshot), or a point x,y in screen points inside bundle_id (default: the app of the last call). With element_index the app is read again first: the element must still be there with the same type, label, identifier and frame, and its app in front — otherwise element_no_longer_valid and nothing is sent. count 2-3 repeats the tap; duration_ms (100-5000) makes it a long press. Nothing is sent when the app rule (NORACU_DENY_APPS / NORACU_APPROVAL_FILE, matched on the bundle id) rules the app out, the stop file exists, the phone is locked, or the app is not in front; with app rules set, no tap that names com.apple.springboard (the Home Screen) goes out — not even one on a system prompt's button (input_denied; open apps with ios_launch). A tap that went out is delivered_unverified: take ios_snapshot to see what it did. No answer from the phone is ios_timeout with delivery=unknown, and the tap is never sent again.", args: { element_index: "integer?", snapshot_id: "string?", x: "number?", y: "number?", bundle_id: "string?", count: "integer?", duration_ms: "integer?" }, fn: ios("tap") },
|
|
3205
|
-
{ name: "ios_type", desc: "EXPERIMENTAL. Type text (1-2000 characters) as keyboard input on the phone — no clipboard is involved. With element_index the field is re-checked and tapped first and the keyboard is waited for; without it the text goes to whatever holds the keyboard in bundle_id (default: the app of the last call; no_keyboard, nothing sent, when none is up). delivered_verified only when the field that took the text — the one tapped, or the only one whose value changed — afterwards holds its old value with the text put in at one place; type_not_confirmed when it does not (autocorrection or completion changed it, the field hides its value, part of the text was lost, or the text went elsewhere) — read the field before typing again. With app rules set, text that names com.apple.springboard is not sent (input_denied). Text shorter than 4 characters, a secure field, text that contains a return, and text typed while the app's fields could not be read, are not read back (delivered_unverified). The result never repeats the text.", args: { text: "string", element_index: "integer?", snapshot_id: "string?", bundle_id: "string?" }, fn: ios("type") },
|
|
3750
|
+
{ name: "ios_type", desc: "EXPERIMENTAL. Type text (1-2000 characters) as keyboard input on the phone — no clipboard is involved. With element_index — of a text field, a secure field, a search field or a text view; anything else is refused (not_a_text_field) and nothing is tapped — the field is re-checked and tapped first and the keyboard is waited for; without it the text goes to whatever holds the keyboard in bundle_id (default: the app of the last call; no_keyboard, nothing sent, when none is up). delivered_verified only when the field that took the text — the one tapped, or the only one whose value changed — afterwards holds its old value with the text put in at one place; type_not_confirmed when it does not (autocorrection or completion changed it, the field hides its value, part of the text was lost, or the text went elsewhere) — read the field before typing again. With app rules set, text that names com.apple.springboard is not sent (input_denied). Text shorter than 4 characters, a secure field, text that contains a return, and text typed while the app's fields could not be read, are not read back (delivered_unverified). The result never repeats the text.", args: { text: "string", element_index: "integer?", snapshot_id: "string?", bundle_id: "string?" }, fn: ios("type") },
|
|
3206
3751
|
{ name: "ios_key", desc: "EXPERIMENTAL. Press return or delete (count 1-50) on the phone's keyboard in bundle_id (default: the app of the last call); no_keyboard, nothing sent, when no keyboard is up. With app rules set, keys that name com.apple.springboard are not sent (input_denied). Reports delivery and retry.", args: { key: "string", count: "integer?", bundle_id: "string?" }, fn: ios("key") },
|
|
3207
3752
|
{ name: "ios_swipe", desc: "EXPERIMENTAL. Drag from [x,y] to [x,y] in screen points inside bundle_id (default: the app of the last call), to scroll a list or move something: hold_ms (0-2000, default 50) is the press before the move — a long hold picks an item up; end_hold_ms (0-2000, default 300) is the pause before lifting; velocity slow (default), default or fast. A list usually moves a little less than the finger. With app rules set, a swipe that names com.apple.springboard is not sent (input_denied). Reports delivery and retry; take ios_snapshot to see the result.", args: { from: "array", to: "array", bundle_id: "string?", hold_ms: "integer?", end_hold_ms: "integer?", velocity: "string?" }, fn: ios("swipe") },
|
|
3208
3753
|
{ name: "ios_home", desc: "EXPERIMENTAL. Press the Home button (go to the Home Screen). Ends every earlier element_index; the Home Screen (com.apple.springboard) becomes the default app of later calls. delivered_verified when the app that was in front is seen to leave it. The app rule judges it as com.apple.springboard. Reports delivery and retry.", args: {}, fn: ios("home") },
|
|
@@ -3228,23 +3773,24 @@ function validateArgs(name, a) {
|
|
|
3228
3773
|
if (a.snapshot_id !== undefined && !S(a.snapshot_id, 20)) return "mac_click: snapshot_id string required";
|
|
3229
3774
|
if (a.app !== undefined && !S(a.app, 200)) return "mac_click: app string (max 200) required";
|
|
3230
3775
|
if (a.force !== undefined && typeof a.force !== "boolean") return "mac_click: force must be a boolean";
|
|
3231
|
-
// 0.3.0
|
|
3776
|
+
// 0.3.0: screenshot_id is an 8-character id from mac_screenshot
|
|
3232
3777
|
if (a.screenshot_id !== undefined && !S(a.screenshot_id, 16)) return "mac_click: screenshot_id must be the id string from mac_screenshot (max 16)";
|
|
3233
3778
|
if (a.element_index !== undefined) {
|
|
3234
3779
|
if (!Number.isInteger(a.element_index) || a.element_index < 0) return "mac_click: element_index must be non-negative int";
|
|
3235
3780
|
if (a.app !== undefined || a.force !== undefined) return "mac_click: app and force apply to x,y clicks only (an element_index already names its app and is hit-tested)";
|
|
3236
3781
|
if (a.screenshot_id !== undefined) return "mac_click: screenshot_id names screenshot pixels for x,y — it cannot be combined with element_index";
|
|
3237
|
-
|
|
3238
|
-
if (a.
|
|
3782
|
+
// two ways to name the target: the point would be dropped without a word
|
|
3783
|
+
if (a.x !== undefined || a.y !== undefined) return "mac_click: give element_index, or x and y — one of the two (with both, the point would be ignored)";
|
|
3239
3784
|
return null;
|
|
3240
3785
|
}
|
|
3241
3786
|
if (!N(a.x) || !N(a.y)) return "mac_click: x,y finite numbers or element_index required";
|
|
3787
|
+
if (a.snapshot_id !== undefined) return "mac_click: snapshot_id goes with element_index — a click at x,y is not checked against a snapshot";
|
|
3242
3788
|
if (a.screenshot_id !== undefined && a.app !== undefined) return "mac_click: screenshot_id already names the window and its app — leave app out";
|
|
3243
3789
|
return null;
|
|
3244
3790
|
case "mac_drag":
|
|
3245
3791
|
if (!(Number.isInteger(a.from_index) && a.from_index >= 0 && Number.isInteger(a.to_index) && a.to_index >= 0)) return "mac_drag: from_index/to_index (non-negative ints) required (delivery=not_delivered, retry=safe)";
|
|
3246
3792
|
if (a.snapshot_id !== undefined && !S(a.snapshot_id, 20)) return "mac_drag: snapshot_id string required";
|
|
3247
|
-
// 0.3.0
|
|
3793
|
+
// 0.3.0: integers within the ranges the description gives
|
|
3248
3794
|
if (a.hold_ms !== undefined && (!Number.isInteger(a.hold_ms) || a.hold_ms < 0 || a.hold_ms > 2000)) return "mac_drag: hold_ms must be an integer 0-2000";
|
|
3249
3795
|
if (a.step_ms !== undefined && (!Number.isInteger(a.step_ms) || a.step_ms < 1 || a.step_ms > 500)) return "mac_drag: step_ms must be an integer 1-500";
|
|
3250
3796
|
return null;
|
|
@@ -3253,6 +3799,7 @@ function validateArgs(name, a) {
|
|
|
3253
3799
|
if (a.pages !== undefined && (!N(a.pages) || a.pages < 0.1 || a.pages > 10)) return "mac_scroll: pages 0.1-10";
|
|
3254
3800
|
if (a.element_index !== undefined && (!Number.isInteger(a.element_index) || a.element_index < 0)) return "mac_scroll: element_index must be a non-negative integer";
|
|
3255
3801
|
if (a.snapshot_id !== undefined && !S(a.snapshot_id, 20)) return "mac_scroll: snapshot_id string required";
|
|
3802
|
+
if (a.snapshot_id !== undefined && a.element_index === undefined) return "mac_scroll: snapshot_id goes with element_index — without one there is nothing to check against the snapshot";
|
|
3256
3803
|
return null;
|
|
3257
3804
|
case "mac_set_value":
|
|
3258
3805
|
if (!Number.isInteger(a.element_index) || a.element_index < 0) return "mac_set_value: element_index must be a non-negative integer";
|
|
@@ -3277,6 +3824,7 @@ function validateArgs(name, a) {
|
|
|
3277
3824
|
if (name === "mac_type") {
|
|
3278
3825
|
if (a.element_index !== undefined && (!Number.isInteger(a.element_index) || a.element_index < 0)) return "mac_type: element_index must be a non-negative integer";
|
|
3279
3826
|
if (a.snapshot_id !== undefined && !S(a.snapshot_id, 20)) return "mac_type: snapshot_id string required";
|
|
3827
|
+
if (a.snapshot_id !== undefined && a.element_index === undefined) return "mac_type: snapshot_id goes with element_index — without one there is nothing to check against the snapshot";
|
|
3280
3828
|
if (a.mechanism !== undefined && !MECHANISMS.includes(a.mechanism)) return "mac_type: mechanism must be auto|semantic|physical";
|
|
3281
3829
|
if (a.replace !== undefined && typeof a.replace !== "boolean") return "mac_type: replace must be a boolean";
|
|
3282
3830
|
if (a.replace === true && a.mechanism === "physical") return "mac_type: replace needs mechanism auto or semantic";
|
|
@@ -3288,11 +3836,13 @@ function validateArgs(name, a) {
|
|
|
3288
3836
|
for (const k of ["interactive", "compact", "skeleton", "web_accessibility"]) if (a[k] !== undefined && typeof a[k] !== "boolean") return `mac_ax_state: ${k} must be a boolean`;
|
|
3289
3837
|
if (a.surface !== undefined && !AX_SURFACES.includes(a.surface)) return `mac_ax_state: surface must be one of ${AX_SURFACES.join("|")}`;
|
|
3290
3838
|
if (a.window !== undefined && !WIN(a.window)) return "mac_ax_state: window must be an index or a title (max 200)";
|
|
3291
|
-
if (a.depth !== undefined && (!
|
|
3839
|
+
if (a.depth !== undefined && (!Number.isInteger(a.depth) || a.depth < 1 || a.depth > 40)) return "mac_ax_state: depth integer 1-40";
|
|
3292
3840
|
if (a.max_nodes !== undefined && (!Number.isInteger(a.max_nodes) || a.max_nodes < 10 || a.max_nodes > 2000)) return "mac_ax_state: max_nodes integer 10-2000";
|
|
3293
3841
|
if (a.root !== undefined && (!Number.isInteger(a.root) || a.root < 0)) return "mac_ax_state: root must be a non-negative element_index";
|
|
3294
3842
|
if (a.window_id !== undefined && (!Number.isInteger(a.window_id) || a.window_id < 0)) return "mac_ax_state: window_id must be a non-negative integer (from mac_windows)";
|
|
3295
3843
|
if (a.snapshot_id !== undefined && !S(a.snapshot_id, 20)) return "mac_ax_state: snapshot_id string required";
|
|
3844
|
+
// a root is an element of an earlier snapshot: it names its app and window, and these were not looked at
|
|
3845
|
+
if (a.root !== undefined && ["app", "window", "window_id", "surface"].some((k) => a[k] !== undefined)) return "mac_ax_state: root drills into an element of an earlier snapshot, which names its app and window — pass root (with its snapshot_id) without app, window, window_id or surface";
|
|
3296
3846
|
return null;
|
|
3297
3847
|
case "mac_find":
|
|
3298
3848
|
for (const k of ["app", "role", "title", "value", "text", "id"]) if (a[k] !== undefined && !S(a[k], 200)) return `mac_find: ${k} must be a string of 1-200 characters`;
|
|
@@ -3406,6 +3956,7 @@ function validateArgs(name, a) {
|
|
|
3406
3956
|
if (!BID(a.browser_id)) return "browser_navigate: browser_id must be a string (1-64 chars)";
|
|
3407
3957
|
const schemeOk = process.env.NORACU_ALLOW_FILE_URL === "1" ? /^(https?|file):\/\//.test(a.url) : /^https?:\/\//.test(a.url);
|
|
3408
3958
|
if (!S(a.url, 20000) || !schemeOk) return "browser_navigate: url must start with http(s):// (file:// requires NORACU_ALLOW_FILE_URL=1)";
|
|
3959
|
+
if (isDevtoolsUrl(a.url)) return `browser_navigate: ${DEVTOOLS_REFUSED}`;
|
|
3409
3960
|
return null;
|
|
3410
3961
|
}
|
|
3411
3962
|
case "browser_snapshot":
|
|
@@ -3439,6 +3990,7 @@ function validateArgs(name, a) {
|
|
|
3439
3990
|
if (act !== "new") return "browser_tabs: url goes with action new only";
|
|
3440
3991
|
const schemeOk = process.env.NORACU_ALLOW_FILE_URL === "1" ? /^(https?|file):\/\//.test(a.url) : /^https?:\/\//.test(a.url);
|
|
3441
3992
|
if (!S(a.url, 20000) || !schemeOk) return "browser_tabs: url must start with http(s):// (file:// requires NORACU_ALLOW_FILE_URL=1)";
|
|
3993
|
+
if (isDevtoolsUrl(a.url)) return `browser_tabs: ${DEVTOOLS_REFUSED}`;
|
|
3442
3994
|
}
|
|
3443
3995
|
const needsTab = act === "select" || act === "close";
|
|
3444
3996
|
if (needsTab && !(typeof a.tab_id === "string" && /^t\d{1,9}$/.test(a.tab_id))) return "browser_tabs: tab_id (from action list, such as \"t2\") is required for select and close";
|
|
@@ -3451,6 +4003,8 @@ function validateArgs(name, a) {
|
|
|
3451
4003
|
case "browser_click":
|
|
3452
4004
|
if (!BID(a.browser_id)) return "browser_click: browser_id must be a string (1-64 chars)";
|
|
3453
4005
|
if (a.button !== undefined && !["left", "right", "middle"].includes(a.button)) return "browser_click: button must be left|right|middle";
|
|
4006
|
+
// more than one way to name the target: the first in this order would be used and the others dropped
|
|
4007
|
+
if ([a.element_index, a.selector, a.xy].filter((v) => v !== undefined).length > 1) return "browser_click: give element_index, selector or xy — one of the three (the others would be ignored)";
|
|
3454
4008
|
if (a.element_index !== undefined) {
|
|
3455
4009
|
if (!Number.isInteger(a.element_index) || a.element_index < 0) return "browser_click: element_index must be non-negative int";
|
|
3456
4010
|
return null;
|
|
@@ -3467,8 +4021,10 @@ function validateArgs(name, a) {
|
|
|
3467
4021
|
case "browser_fill":
|
|
3468
4022
|
if (!BID(a.browser_id)) return "browser_fill: browser_id must be a string (1-64 chars)";
|
|
3469
4023
|
if (!S(a.selector, 2000)) return "browser_fill: selector string (max 2000) required";
|
|
3470
|
-
|
|
3471
|
-
if (a.value
|
|
4024
|
+
// a fill without value would clear the field and read back as verified: the text has to be given
|
|
4025
|
+
if (a.value === undefined || a.value === null) return `browser_fill: value is required — the text to put in the field${a.text !== undefined ? " (it was passed as text; this tool's argument is value)" : ""}; pass "" to clear the field`;
|
|
4026
|
+
if (typeof a.value !== "string" && typeof a.value !== "number") return "browser_fill: value must be a string";
|
|
4027
|
+
if (String(a.value).length > 100000) return "browser_fill: value too long (max 100000)";
|
|
3472
4028
|
return null;
|
|
3473
4029
|
case "browser_type":
|
|
3474
4030
|
if (!BID(a.browser_id)) return "browser_type: browser_id must be a string (1-64 chars)";
|
|
@@ -3523,6 +4079,9 @@ function validateArgs(name, a) {
|
|
|
3523
4079
|
return null;
|
|
3524
4080
|
case "phone_open":
|
|
3525
4081
|
if (!S(a.app, 200)) return "phone_open: app string (max 200) required";
|
|
4082
|
+
// the name is pasted into Spotlight as it is: a line break or another control character is no part of an app's
|
|
4083
|
+
// name, and a pasted return could act on Spotlight's first result before the name is compared
|
|
4084
|
+
if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(a.app)) return "phone_open: app must not contain control characters (a line break, a tab)";
|
|
3526
4085
|
return null;
|
|
3527
4086
|
case "ios_status": case "ios_home": case "ios_screenshot":
|
|
3528
4087
|
return null;
|
|
@@ -3656,7 +4215,7 @@ const MCP_INSTRUCTIONS = (() => {
|
|
|
3656
4215
|
const readers = [mac && "mac_get", mac && "mac_ax_state", browser && "browser_snapshot", iphone && (xc ? "ios_snapshot" : "phone_ocr")].filter(Boolean).join(", ");
|
|
3657
4216
|
return [
|
|
3658
4217
|
`noracu operates${what}.${iphone && xc ? " iPhone: ios_launch an app by bundle id, ios_snapshot, then act by element_index (valid 30 s; ios_home and ios_launch end earlier indexes); coordinates are screen points." : ""}`,
|
|
3659
|
-
`Loop: observe, act, then observe again to verify.${mac ? " Mac: mac_ax_state (interactive:true for dense apps; skeleton then root to drill) or mac_find, then act by element_index; an index is unique across snapshots and lasts 30 s." : ""}`,
|
|
4218
|
+
`Loop: observe, act, then observe again to verify.${mac ? " Mac: mac_ax_state (interactive:true for dense apps; skeleton then root to drill) or mac_find, then act by element_index; an index is unique across snapshots and lasts 30 s. An app argument is a name, a bundle id, a .app path or pid:<n>; ambiguous_app lists the running apps that share a name — pick one by pid:<n>." : ""}`,
|
|
3660
4219
|
`${all ? "Mac, browser and iPhone input actions" : "Input actions"} report delivery (delivered_verified / delivered_unverified / not_delivered / unknown) and retry (safe / unsafe). Retry or substitute an action only when retry=safe; otherwise read the state first (${readers}).`,
|
|
3661
4220
|
mac || browser ? "element_no_longer_valid means take a new snapshot; occluded means bring the window forward or close what covers it; do not fall back to raw coordinates to get around either."
|
|
3662
4221
|
: xc ? "element_no_longer_valid means take a new snapshot; do not fall back to raw coordinates to get around it." : null,
|
|
@@ -3686,14 +4245,14 @@ function errorCodeOf(raw) {
|
|
|
3686
4245
|
if (/^Playwright chromium missing/i.test(s)) return "browser_unavailable";
|
|
3687
4246
|
return "error";
|
|
3688
4247
|
}
|
|
3689
|
-
function traceCall(name, args, ms, isError, errText) {
|
|
4248
|
+
function traceCall(name, args, ms, isError, errText, code) {
|
|
3690
4249
|
if (!TRACE_FILE) return;
|
|
3691
4250
|
let fd = null;
|
|
3692
4251
|
try {
|
|
3693
4252
|
const shape = {};
|
|
3694
|
-
for (const [k, v] of Object.entries(args
|
|
4253
|
+
for (const [k, v] of Object.entries(args && typeof args === "object" && !Array.isArray(args) ? args : {})) shape[k] = typeof v === "string" ? `string(${v.length})` : typeof v === "number" || typeof v === "boolean" ? v : Array.isArray(v) ? `array(${v.length})` : typeof v;
|
|
3695
4254
|
const err = Boolean(isError);
|
|
3696
|
-
const line = JSON.stringify({ ts: new Date().toISOString(), tool: name, args: shape, ms, error: err, code: err ? errorCodeOf(errText) : null }) + "\n";
|
|
4255
|
+
const line = JSON.stringify({ ts: new Date().toISOString(), tool: name, args: shape, ms, error: err, code: err ? (code ?? errorCodeOf(errText)) : null }) + "\n";
|
|
3697
4256
|
fd = openSync(TRACE_FILE, TRACE_FLAGS, 0o600);
|
|
3698
4257
|
writeSync(fd, line);
|
|
3699
4258
|
} catch { /* tracing never breaks a call */ }
|
|
@@ -3704,22 +4263,26 @@ function traceCall(name, args, ms, isError, errText) {
|
|
|
3704
4263
|
// the delivery wording is added here, once for every phone tool (read-only phone tools get none).
|
|
3705
4264
|
const PHONE_INPUTS = new Set(["phone_tap", "phone_longpress", "phone_swipe", "phone_scroll", "phone_type", "phone_key", "phone_open", "phone_home", "phone_app_switcher", "phone_launch"]);
|
|
3706
4265
|
// success that the phone screen confirmed (open: the app opened; type: the paste landed). phone_scroll is not here
|
|
3707
|
-
// (0.2.5
|
|
4266
|
+
// (0.2.5): "the screen changed" is all it sees, and a notification or an animation changes it too
|
|
3708
4267
|
const PHONE_CONFIRMED = new Set(["phone_open", "phone_type"]);
|
|
3709
4268
|
// "nothing was sent": refusals before the first event (expect_not_found, a capture that failed while checking --expect, invalid_args,
|
|
3710
4269
|
// out_of_screen: a tap or long press aimed at the mirror window's margin, 2026-11-10)
|
|
3711
4270
|
const PHONE_NOTHING_SENT = /^(mirror_not_live|mirror_state_unknown|mirror_setup_required|expect_not_found|imctl unavailable|server_shutting_down|keyboard_layout|out_of_screen)|server is shutting down|nothing was typed|nothing was sent/;
|
|
4271
|
+
// phone_open and phone_type are verified only on the driver's own line for a confirmed result: "opened '<app>'…",
|
|
4272
|
+
// and "typed <n> chars" with nothing after it. Any other line that comes with exit code 0 is a result the driver did
|
|
4273
|
+
// not confirm, whatever its words — a wording added to the driver later is not read as verified.
|
|
4274
|
+
const PHONE_VERIFIED_LINE = { phone_open: /^opened /, phone_type: /^typed \d+ chars$/ };
|
|
3712
4275
|
function phoneDelivery(name, text, ok) {
|
|
3713
4276
|
if (!PHONE_INPUTS.has(name) || /delivery=/.test(text)) return text;
|
|
3714
4277
|
if (name === "phone_launch") return `${text} (delivery=${ok ? "delivered_unverified" : PHONE_NOTHING_SENT.test(text) ? "not_delivered" : "unknown"}, retry=safe)`;
|
|
3715
4278
|
// a paste only the frame diff saw (OCR cannot read the text back) is not verified (device run 2026-11-06); neither is
|
|
3716
|
-
// one character OCR saw appear, nor a text seen late — OCR cannot tell the paste from a line repeating it
|
|
3717
|
-
//
|
|
4279
|
+
// one character OCR saw appear, nor a text seen late — OCR cannot tell the paste from a line repeating it
|
|
4280
|
+
// nor a text too short for OCR to confirm, nor one OCR saw only in the banner strip at the top
|
|
3718
4281
|
if (ok && /OCR cannot read this text back|no proof of where it landed|showed up late|never confirmed by OCR|cannot be told from a notification banner/.test(text)) return `${text} (delivery=delivered_unverified, retry=unsafe)`;
|
|
3719
|
-
if (ok) return `${text} (delivery=${PHONE_CONFIRMED.has(name) ? "delivered_verified" : "delivered_unverified"}, retry=unsafe)`;
|
|
4282
|
+
if (ok) return `${text} (delivery=${PHONE_CONFIRMED.has(name) && PHONE_VERIFIED_LINE[name].test(String(text).split("\n")[0].trim()) ? "delivered_verified" : "delivered_unverified"}, retry=unsafe)`;
|
|
3720
4283
|
if (PHONE_NOTHING_SENT.test(text)) return `${text} (delivery=not_delivered, retry=safe)`;
|
|
3721
4284
|
if (/^scroll_no_effect/.test(text)) return `${text} (delivery=delivered_unverified, retry=unsafe)`;
|
|
3722
|
-
// phone_open went Home and searched Spotlight before it knew the app was not there
|
|
4285
|
+
// phone_open went Home and searched Spotlight before it knew the app was not there
|
|
3723
4286
|
if (/^app not found/.test(text)) return `${text} (delivery=delivered_unverified, retry=safe)`;
|
|
3724
4287
|
// type_not_confirmed, open_not_confirmed, capture_failed, focus_lost, imctl_timeout, imctl_error, …
|
|
3725
4288
|
return `${text} (delivery=unknown, retry=unsafe)`;
|
|
@@ -3727,7 +4290,11 @@ function phoneDelivery(name, text, ok) {
|
|
|
3727
4290
|
|
|
3728
4291
|
// ── MCP stdio 协议 ──
|
|
3729
4292
|
|
|
3730
|
-
|
|
4293
|
+
// One JSON-RPC message per line, and a line ends at \n (MCP's stdio framing). Not node:readline: it also ends a line at
|
|
4294
|
+
// U+2028 and U+2029, which JSON leaves as they are inside a string — a tools/call whose text held one was cut in two,
|
|
4295
|
+
// answered with parse errors under id null, and never under its own id. The reading starts at the end of this file,
|
|
4296
|
+
// once the handlers below are attached.
|
|
4297
|
+
const rl = new (await import("node:events")).EventEmitter();
|
|
3731
4298
|
|
|
3732
4299
|
// a client that went away closes our stdout too: writing then must not crash the shutdown
|
|
3733
4300
|
process.stdout.on("error", () => {});
|
|
@@ -3736,16 +4303,16 @@ function send(obj) {
|
|
|
3736
4303
|
try { process.stdout.write(JSON.stringify(obj) + "\n"); } catch { /* the client is gone */ }
|
|
3737
4304
|
}
|
|
3738
4305
|
|
|
3739
|
-
// tools/call
|
|
4306
|
+
// tools/call 结果统一出口:进程比磁盘旧时,把 staleServerNote() 的一行提示加在
|
|
3740
4307
|
// 第一个 text 内容块的开头(单独一行);纯图片结果没有 text 块则补一个。第一个 text 块是 JSON 时(截图元数据、
|
|
3741
|
-
// 快照)提示改为结尾单独一个 text 块,JSON
|
|
4308
|
+
// 快照)提示改为结尾单独一个 text 块,JSON 照样能解析。只加提示 ——
|
|
3742
4309
|
// 不改变工具执行、isError 返回码或其余内容块;tools/list / initialize 不加。
|
|
3743
4310
|
function sendToolResult(id, content, isError) {
|
|
3744
4311
|
const note = staleServerNote();
|
|
3745
4312
|
if (note) {
|
|
3746
4313
|
const firstText = content.find(b => b?.type === "text");
|
|
3747
4314
|
const isJson = (t) => { try { JSON.parse(t); return true; } catch { return false; } };
|
|
3748
|
-
// JSON stays parseable: the note goes in a block of its own after it
|
|
4315
|
+
// JSON stays parseable: the note goes in a block of its own after it
|
|
3749
4316
|
if (firstText && isJson(firstText.text)) content.push({ type: "text", text: note });
|
|
3750
4317
|
else if (firstText) firstText.text = `${note}\n${firstText.text}`;
|
|
3751
4318
|
else content.unshift({ type: "text", text: note });
|
|
@@ -3753,25 +4320,41 @@ function sendToolResult(id, content, isError) {
|
|
|
3753
4320
|
send({ jsonrpc: "2.0", id, result: { content, ...(isError ? { isError: true } : {}) } });
|
|
3754
4321
|
}
|
|
3755
4322
|
|
|
4323
|
+
// The protocol revisions this server answers in. It offers tools over stdio only, and what it sends for
|
|
4324
|
+
// them — text and image content, isError, and annotations that a 2024-11-05 client ignores — is valid in
|
|
4325
|
+
// each. 2025-03-26 is left out:
|
|
4326
|
+
// that revision requires a server to accept JSON-RPC batches (added there, removed again in 2025-06-18), and
|
|
4327
|
+
// this server does not; a client that asks for it also speaks 2024-11-05 and gets that. Any other version
|
|
4328
|
+
// gets the latest one here, as the specification says, and the client decides whether it can go on.
|
|
4329
|
+
const PROTOCOL_VERSIONS = ["2024-11-05", "2025-06-18", "2025-11-25"];
|
|
4330
|
+
function negotiateProtocol(requested) {
|
|
4331
|
+
if (PROTOCOL_VERSIONS.includes(requested)) return requested;
|
|
4332
|
+
if (requested === "2025-03-26") return "2024-11-05";
|
|
4333
|
+
return PROTOCOL_VERSIONS[PROTOCOL_VERSIONS.length - 1];
|
|
4334
|
+
}
|
|
4335
|
+
|
|
3756
4336
|
rl.on("line", async (line) => {
|
|
3757
4337
|
if (!line.trim()) return;
|
|
3758
4338
|
let msg;
|
|
3759
4339
|
try { msg = JSON.parse(line); } catch { send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error: the line is not JSON" } }); return; }
|
|
3760
|
-
//
|
|
4340
|
+
// JSON-RPC batches are not accepted: only revision 2025-03-26 has them, and this server does not answer in it
|
|
3761
4341
|
if (Array.isArray(msg)) { send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "JSON-RPC batch is not supported" } }); return; }
|
|
3762
4342
|
if (!msg || typeof msg !== "object") { send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "invalid request" } }); return; }
|
|
3763
4343
|
const { id, method, params } = msg;
|
|
3764
4344
|
if (shuttingDown) { if (id !== undefined) send({ jsonrpc: "2.0", id, error: { code: -32603, message: "server is shutting down" } }); return; }
|
|
3765
4345
|
try {
|
|
3766
4346
|
if (method === "initialize") {
|
|
3767
|
-
//
|
|
3768
|
-
send({ jsonrpc: "2.0", id, result: { protocolVersion:
|
|
4347
|
+
// 版本号用启动时快照的 LOADED.version,不在握手时现读 —— 进程旧了它也不会误报新版本
|
|
4348
|
+
send({ jsonrpc: "2.0", id, result: { protocolVersion: negotiateProtocol(params?.protocolVersion), capabilities: { tools: {} }, serverInfo: { name: "noracu", version: LOADED.version }, instructions: MCP_INSTRUCTIONS } });
|
|
3769
4349
|
} else if (method === "notifications/initialized") {
|
|
3770
4350
|
// no response
|
|
3771
4351
|
} else if (method === "notifications/cancelled") {
|
|
3772
|
-
//
|
|
4352
|
+
// A queued phone/Mac call the client gave up on is skipped when its turn comes
|
|
3773
4353
|
// (only a call still waiting in the queue can be skipped; ids are never kept beyond that)
|
|
3774
4354
|
if (queuedRequests.has(params?.requestId)) cancelledRequests.add(params.requestId);
|
|
4355
|
+
// a call whose tool is already running is marked: no answer is sent for it, and browser_type stops typing
|
|
4356
|
+
const given = liveCalls.get(params?.requestId);
|
|
4357
|
+
if (given) { given.cancelled = true; for (const stop of [...(given.hooks || [])]) stop(); }
|
|
3775
4358
|
} else if (method === "tools/list") {
|
|
3776
4359
|
send({ jsonrpc: "2.0", id, result: { tools: TOOLS.map(t => ({
|
|
3777
4360
|
name: t.name, description: t.desc,
|
|
@@ -3781,40 +4364,66 @@ rl.on("line", async (line) => {
|
|
|
3781
4364
|
} else if (method === "tools/call") {
|
|
3782
4365
|
const name = params?.name;
|
|
3783
4366
|
const tool = TOOLS.find(t => t.name === name);
|
|
4367
|
+
// A request id is the client's handle on one call. A second call under an id that is still under way would
|
|
4368
|
+
// take over the first one's entry here and in the input queue, and a cancellation would then stop the wrong
|
|
4369
|
+
// call. It is refused before anything else is answered for it — an unknown tool, a refusal of its arguments,
|
|
4370
|
+
// of observation-only mode or of the stop file would be a result under that id, which the client takes for
|
|
4371
|
+
// the first call's. The first call goes on and is answered under the id as usual.
|
|
4372
|
+
if (id !== undefined && liveCalls.has(id)) {
|
|
4373
|
+
traceCall(tool ? name : `unknown(${String(name).length})`, params?.arguments, 0, true, "", "duplicate_id");
|
|
4374
|
+
send({ jsonrpc: "2.0", id, error: { code: -32600, message: `invalid request: id ${JSON.stringify(id)} is already in use by a call that has not been answered yet — this call was not run` } });
|
|
4375
|
+
return;
|
|
4376
|
+
}
|
|
3784
4377
|
if (!tool) {
|
|
3785
4378
|
// a tool of a layer that is off says how to turn the layer on; the other iPhone backend's tools do not,
|
|
3786
|
-
// whether the layer is on or off
|
|
4379
|
+
// whether the layer is on or off
|
|
3787
4380
|
const n = String(name);
|
|
3788
4381
|
const ofBackend = !n.startsWith(PHONE_BACKEND === "xcuitest" ? "phone_" : "ios_");
|
|
3789
4382
|
const off = TOOL_DEFS.some((t) => t.name === n) && ofBackend && !LAYERS.has(layerOf(n)) ? ` — ${layerOffNote(layerOf(n))}` : "";
|
|
4383
|
+
// the name of a tool this server does not have is the caller's own text: its length goes in the trace, not the name
|
|
4384
|
+
traceCall(`unknown(${n.length})`, params?.arguments, 0, true, "", "unknown_tool");
|
|
3790
4385
|
sendToolResult(id, [{ type: "text", text: `unknown tool: ${name}${off}` }], true);
|
|
3791
4386
|
return;
|
|
3792
4387
|
}
|
|
3793
4388
|
let r;
|
|
4389
|
+
// a call refused before the tool runs is a call all the same: each refusal below gets its line in the
|
|
4390
|
+
// trace (NORACU_TRACE), with the code and 0 ms
|
|
3794
4391
|
if (process.env.NORACU_READ_ONLY === "1" && !READ_ONLY_TOOLS.has(name)) {
|
|
4392
|
+
traceCall(name, params?.arguments, 0, true, "", "read_only");
|
|
3795
4393
|
sendToolResult(id, [{ type: "text", text: `ERROR: ${name} blocked by NORACU_READ_ONLY=1 (observation-only mode) (delivery=not_delivered, retry=safe)` }], true);
|
|
3796
4394
|
return;
|
|
3797
4395
|
}
|
|
3798
4396
|
// a refusal before the tool runs sent nothing: input tools say so
|
|
3799
4397
|
const nothingSent = (t) => (/^(phone|mac|browser|ios)_/.test(name) && (!READ_ONLY_TOOLS.has(name) || name === "browser_navigate" || name === "browser_launch") && !/delivery=/.test(t) ? `${t} (delivery=not_delivered, retry=safe)` : t);
|
|
3800
4398
|
const verr = validateArgs(name, params?.arguments || {});
|
|
3801
|
-
if (verr) { sendToolResult(id, [{ type: "text", text: `ERROR: ${nothingSent(verr)}` }], true); return; }
|
|
3802
|
-
// the stop file is the person's brake for the browser's input tools too (
|
|
4399
|
+
if (verr) { traceCall(name, params?.arguments, 0, true, "", "invalid_args"); sendToolResult(id, [{ type: "text", text: `ERROR: ${nothingSent(verr)}` }], true); return; }
|
|
4400
|
+
// the stop file is the person's brake for the browser's input tools too (it stopped
|
|
3803
4401
|
// Mac and iPhone input only, while chrome:true acts in the person's own Chrome)
|
|
3804
4402
|
if (BROWSER_STOPPABLE.has(name) || (name === "browser_tabs" && ["new", "close"].includes(params?.arguments?.action))) {
|
|
3805
4403
|
const stop = stopFileBlocked();
|
|
3806
|
-
if (stop) { sendToolResult(id, [{ type: "text", text: `ERROR: ${stop}` }], true); return; }
|
|
4404
|
+
if (stop) { traceCall(name, params?.arguments, 0, true, stop); sendToolResult(id, [{ type: "text", text: `ERROR: ${stop}` }], true); return; }
|
|
3807
4405
|
}
|
|
3808
|
-
const
|
|
4406
|
+
const live = { cancelled: false };
|
|
4407
|
+
if (id !== undefined) liveCalls.set(id, live);
|
|
4408
|
+
const run = () => tool.fn(params?.arguments || {}, live);
|
|
3809
4409
|
const t0 = Date.now();
|
|
3810
|
-
// ios_* calls share the queue (the runner takes one command at a time); ios_status asks devicectl only
|
|
4410
|
+
// ios_* calls share the queue (the runner takes one command at a time); ios_status asks devicectl / simctl only
|
|
3811
4411
|
const queued = /^(phone|mac|ios)_/.test(name) && !OBSERVE_TOOLS.has(name) && name !== "ios_status";
|
|
3812
4412
|
// every queued tool that is not read-only waits for the person at the Mac (0.2.7); ios_* input checks
|
|
3813
4413
|
// the stop file but does not wait: it does not use this Mac's keyboard or mouse
|
|
3814
4414
|
const yieldToUser = queued && TOOL_HINTS[name][0] !== 1 ? (name.startsWith("ios_") ? "stop" : true) : false;
|
|
3815
4415
|
try { r = await (queued ? serializedInput(run, id, yieldToUser) : OBSERVE_TOOLS.has(name) ? afterQueuedInput(run, QUEUE_WAIT_LIMIT_MS) : run()); }
|
|
3816
|
-
catch (e) {
|
|
3817
|
-
|
|
4416
|
+
catch (e) {
|
|
4417
|
+
// an exception nobody planned for, from an input tool: what it had sent by then is not known
|
|
4418
|
+
const msg = e instanceof Refusal ? e.message : String(e?.message ?? e).slice(0, 400);
|
|
4419
|
+
const input = /^(phone|mac|browser|ios)_/.test(name) && (!READ_ONLY_TOOLS.has(name) || name === "browser_navigate");
|
|
4420
|
+
r = { error: !(e instanceof Refusal) && input && !/delivery=/.test(msg) ? `internal_error: ${msg} (delivery=unknown, retry=unsafe)` : msg };
|
|
4421
|
+
}
|
|
4422
|
+
if (id !== undefined && liveCalls.get(id) === live) liveCalls.delete(id);
|
|
4423
|
+
// the client cancelled it while it waited: it did not run, and gets no response (MCP)
|
|
4424
|
+
if (r === CANCELLED) { traceCall(name, params?.arguments, Date.now() - t0, true, "", "cancelled_queued"); return; }
|
|
4425
|
+
// the client gave the call up while its tool ran: it gets no answer either
|
|
4426
|
+
if (live.cancelled) { traceCall(name, params?.arguments, Date.now() - t0, true, "", "cancelled"); return; }
|
|
3818
4427
|
traceCall(name, params?.arguments, Date.now() - t0, Boolean(r?.error || r?.ok === false), r?.error ?? (r?.ok === false ? r.out : ""));
|
|
3819
4428
|
if (r?.error) {
|
|
3820
4429
|
sendToolResult(id, [{ type: "text", text: `ERROR: ${r.error}` }], true);
|
|
@@ -3842,5 +4451,62 @@ rl.on("line", async (line) => {
|
|
|
3842
4451
|
|
|
3843
4452
|
// the client closed our stdin: it is gone, so stop (browsers closed, children ended) instead of lingering
|
|
3844
4453
|
rl.on("close", () => { shutdown(0); });
|
|
4454
|
+
{
|
|
4455
|
+
const decoder = new (await import("node:string_decoder")).StringDecoder("utf8"); // a chunk can end inside a character
|
|
4456
|
+
let pending = "", scanned = 0, over = false;
|
|
4457
|
+
// One message is one line. A line that grows past MAX_LINE without ending is not kept: no request this server
|
|
4458
|
+
// takes comes near it (its largest text argument is 100,000 characters), and a sender that never ends the line
|
|
4459
|
+
// would otherwise make the process hold whatever it sends. What arrived of it is dropped, the rest is skipped up
|
|
4460
|
+
// to the line end, and the sender gets an error — under the request's id when the id stands before "params" in
|
|
4461
|
+
// what was read (an "id" further in could be an argument's), under null otherwise. A line that is complete but
|
|
4462
|
+
// longer than the limit is dropped the same way.
|
|
4463
|
+
const MAX_LINE = 4 * 1024 * 1024; // characters as JavaScript counts them (UTF-16 units), not bytes
|
|
4464
|
+
let skipping = false;
|
|
4465
|
+
// head: the first 4096 characters of the line that is dropped. The id is taken only from before the "params"
|
|
4466
|
+
// field (the name followed by a colon — a string that merely reads "params" is not it).
|
|
4467
|
+
const tooLarge = (head) => {
|
|
4468
|
+
const at = head.search(/"params"\s*:/);
|
|
4469
|
+
const m = /"id"\s*:\s*(-?\d+|"(?:[^"\\]|\\.){0,128}")/.exec(at === -1 ? head : head.slice(0, at));
|
|
4470
|
+
let id = null;
|
|
4471
|
+
try { if (m) id = JSON.parse(m[1]); } catch { /* not an id */ }
|
|
4472
|
+
send({ jsonrpc: "2.0", id, error: { code: -32600, message: `request too large: a message of more than ${MAX_LINE} characters on one line was dropped, unread` } });
|
|
4473
|
+
};
|
|
4474
|
+
const end = () => {
|
|
4475
|
+
if (over) return;
|
|
4476
|
+
over = true;
|
|
4477
|
+
const rest = pending + decoder.end();
|
|
4478
|
+
pending = "";
|
|
4479
|
+
if (rest.trim()) rl.emit("line", rest);
|
|
4480
|
+
rl.emit("close");
|
|
4481
|
+
};
|
|
4482
|
+
process.stdin.on("data", (chunk) => {
|
|
4483
|
+
if (over) return;
|
|
4484
|
+
let text = decoder.write(chunk);
|
|
4485
|
+
if (skipping) {
|
|
4486
|
+
const nl = text.indexOf("\n");
|
|
4487
|
+
if (nl === -1) return;
|
|
4488
|
+
skipping = false;
|
|
4489
|
+
text = text.slice(nl + 1);
|
|
4490
|
+
}
|
|
4491
|
+
pending += text;
|
|
4492
|
+
for (let i = pending.indexOf("\n", scanned); i !== -1; i = pending.indexOf("\n")) {
|
|
4493
|
+
const line = pending.slice(0, i);
|
|
4494
|
+
pending = pending.slice(i + 1);
|
|
4495
|
+
// the limit holds for a line that ends in the very chunk that takes it past it, too
|
|
4496
|
+
if (line.length > MAX_LINE) { tooLarge(line.slice(0, 4096)); continue; }
|
|
4497
|
+
rl.emit("line", line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
4498
|
+
}
|
|
4499
|
+
scanned = pending.length; // what is left holds no line end: the next chunk is searched from here
|
|
4500
|
+
if (pending.length > MAX_LINE) {
|
|
4501
|
+
tooLarge(pending.slice(0, 4096));
|
|
4502
|
+
pending = ""; scanned = 0; skipping = true;
|
|
4503
|
+
}
|
|
4504
|
+
});
|
|
4505
|
+
process.stdin.on("end", end);
|
|
4506
|
+
process.stdin.on("close", end);
|
|
4507
|
+
process.stdin.on("error", end);
|
|
4508
|
+
}
|
|
3845
4509
|
|
|
3846
4510
|
process.stderr.write(`[noracu] ready — ${LAYERS.size === LAYER_NAMES.length ? "mac/browser/phone layers" : `layers: ${LAYER_NAMES.filter((l) => LAYERS.has(l)).join(", ")} (${LAYERS_RAW ? "NORACU_LAYERS" : "default; NORACU_LAYERS=mac,browser,iphone adds the iPhone layer"})`} (iPhone backend: ${PHONE_BACKEND})\n`);
|
|
4511
|
+
// started by hand in a terminal: say what this is (a client never gives the server a terminal for stdin)
|
|
4512
|
+
if (process.stdin.isTTY) process.stderr.write("[noracu] this is an MCP server: it waits for a client on stdin and answers in JSON-RPC, so typing here does nothing. `noracu doctor` checks this machine and prints the client configuration; `noracu --help` lists the commands. Ctrl-C to quit.\n");
|