noracu 0.1.2 → 0.1.3
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 +57 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/docs/tools.md +11 -11
- package/imctl/src/imctl/cli.py +201 -19
- package/imctl/src/imctl/gestures.py +390 -29
- package/imctl/src/imctl/input.py +360 -41
- package/imctl/src/imctl/verify.py +250 -1
- package/imctl/src/imctl/vision.py +214 -29
- package/imctl/src/imctl/window.py +189 -35
- package/package.json +1 -1
- package/src/server.mjs +111 -28
|
@@ -106,6 +106,9 @@ def ensure_frontmost() -> None:
|
|
|
106
106
|
|
|
107
107
|
CGEvents are delivered to the frontmost app; if another window
|
|
108
108
|
covers the mirroring window, taps would land on the wrong target.
|
|
109
|
+
F31: when the app had to be activated (possibly switching Spaces), wait
|
|
110
|
+
until the window yields a real frame before returning, so the caller's
|
|
111
|
+
next capture is not a transition frame refused as capture_failed.
|
|
109
112
|
"""
|
|
110
113
|
if _run_osascript(_FRONTMOST_SCRIPT) == "true":
|
|
111
114
|
return
|
|
@@ -119,6 +122,30 @@ def ensure_frontmost() -> None:
|
|
|
119
122
|
time.sleep(0.4) # let the window server settle
|
|
120
123
|
if _run_osascript(_FRONTMOST_SCRIPT) != "true":
|
|
121
124
|
raise WindowError("could not bring iPhone Mirroring to front")
|
|
125
|
+
_wait_capturable()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _wait_capturable(timeout_s: float = 2.0, poll_s: float = 0.2) -> bool:
|
|
129
|
+
"""Poll until the mirror window gives a valid frame (F31); best effort.
|
|
130
|
+
|
|
131
|
+
Uses verify.window_luma(), which refuses off-screen windows and blank
|
|
132
|
+
transition frames (F25). Returns True once a frame passes, False after
|
|
133
|
+
``timeout_s`` — it never raises: a caller whose own capture still fails
|
|
134
|
+
reports capture_failed as before.
|
|
135
|
+
"""
|
|
136
|
+
import time
|
|
137
|
+
|
|
138
|
+
from . import verify # runtime import: verify imports this module
|
|
139
|
+
|
|
140
|
+
deadline = time.monotonic() + timeout_s
|
|
141
|
+
while True:
|
|
142
|
+
try:
|
|
143
|
+
verify.window_luma()
|
|
144
|
+
return True
|
|
145
|
+
except Exception:
|
|
146
|
+
if time.monotonic() >= deadline:
|
|
147
|
+
return False
|
|
148
|
+
time.sleep(poll_s)
|
|
122
149
|
|
|
123
150
|
|
|
124
151
|
def get_bounds() -> WindowBounds:
|
|
@@ -157,7 +184,10 @@ def get_bounds() -> WindowBounds:
|
|
|
157
184
|
# "iPhone in use", …) that group gains child elements (image / static text / button). Overlay text
|
|
158
185
|
# is localized, so the decision never matches on text — only on structure (child count, classes).
|
|
159
186
|
# Labels can span multiple lines and nameless elements coerce to the literal "missing value";
|
|
160
|
-
# both are normalized so one element = exactly one `<class>\t<label>`
|
|
187
|
+
# both are normalized so one element = exactly one `<class>\t<label>\t<subrole>\t<child classes>`
|
|
188
|
+
# line (tabs inside labels are collapsed too). F28: the subrole and, for groups, the classes of
|
|
189
|
+
# their children let parse_overlay_ex tell the window's own hover controls (close / minimize /
|
|
190
|
+
# zoom buttons and the small toolbar group) apart from a real overlay.
|
|
161
191
|
_OVERLAY_SCRIPT = '''
|
|
162
192
|
on collapseBreaks(s)
|
|
163
193
|
set tid to AppleScript's text item delimiters
|
|
@@ -169,6 +199,10 @@ on collapseBreaks(s)
|
|
|
169
199
|
set parts to text items of s
|
|
170
200
|
set AppleScript's text item delimiters to " "
|
|
171
201
|
set s to parts as text
|
|
202
|
+
set AppleScript's text item delimiters to tab
|
|
203
|
+
set parts to text items of s
|
|
204
|
+
set AppleScript's text item delimiters to " "
|
|
205
|
+
set s to parts as text
|
|
172
206
|
set AppleScript's text item delimiters to tid
|
|
173
207
|
return s
|
|
174
208
|
end collapseBreaks
|
|
@@ -195,7 +229,20 @@ tell application "System Events"
|
|
|
195
229
|
if v is not "missing value" then set lbl to v
|
|
196
230
|
end try
|
|
197
231
|
end if
|
|
198
|
-
set
|
|
232
|
+
set sr to ""
|
|
233
|
+
try
|
|
234
|
+
set sr to (subrole of e) as text
|
|
235
|
+
if sr is "missing value" then set sr to ""
|
|
236
|
+
end try
|
|
237
|
+
set kids to ""
|
|
238
|
+
if c is "group" then
|
|
239
|
+
try
|
|
240
|
+
repeat with k in (UI elements of e)
|
|
241
|
+
set kids to kids & ((class of k) as text) & ","
|
|
242
|
+
end repeat
|
|
243
|
+
end try
|
|
244
|
+
end if
|
|
245
|
+
set out to out & c & tab & (my collapseBreaks(lbl)) & tab & sr & tab & kids & linefeed
|
|
199
246
|
end repeat
|
|
200
247
|
return out
|
|
201
248
|
end tell
|
|
@@ -204,12 +251,29 @@ end tell
|
|
|
204
251
|
'''
|
|
205
252
|
|
|
206
253
|
# Clicks the Resume control of the paused overlay. Only ever invoked after _OVERLAY_SCRIPT
|
|
207
|
-
# reported exactly one button under group 1 (static script, no interpolated
|
|
254
|
+
# reported exactly one overlay button under group 1 (static script, no interpolated
|
|
255
|
+
# parameters). F29: "button 1 of group 1" was the window's Close button whenever the
|
|
256
|
+
# pointer rested on the window, so window controls are skipped by AX subrole and the
|
|
257
|
+
# click happens only when exactly one other button remains; prints CLICKED or SKIP.
|
|
208
258
|
_CLICK_RESUME_SCRIPT = '''
|
|
209
259
|
tell application "System Events"
|
|
210
260
|
tell process "iPhone Mirroring"
|
|
211
261
|
tell window 1
|
|
212
|
-
|
|
262
|
+
set target to missing value
|
|
263
|
+
set n to 0
|
|
264
|
+
repeat with b in (buttons of group 1)
|
|
265
|
+
set sr to ""
|
|
266
|
+
try
|
|
267
|
+
set sr to (subrole of b) as text
|
|
268
|
+
end try
|
|
269
|
+
if sr is not "AXCloseButton" and sr is not "AXMinimizeButton" and sr is not "AXZoomButton" and sr is not "AXFullScreenButton" then
|
|
270
|
+
set n to n + 1
|
|
271
|
+
set target to contents of b
|
|
272
|
+
end if
|
|
273
|
+
end repeat
|
|
274
|
+
if n is not 1 then return "SKIP"
|
|
275
|
+
click target
|
|
276
|
+
return "CLICKED"
|
|
213
277
|
end tell
|
|
214
278
|
end tell
|
|
215
279
|
end tell
|
|
@@ -251,52 +315,92 @@ def get_window_info() -> dict | None:
|
|
|
251
315
|
|
|
252
316
|
|
|
253
317
|
def is_frontmost() -> bool:
|
|
254
|
-
"""True when iPhone Mirroring is the frontmost application.
|
|
318
|
+
"""True when iPhone Mirroring is the frontmost application, asked fresh on every call.
|
|
319
|
+
|
|
320
|
+
F26 runs this right before synthesized input events. F30: the in-process
|
|
321
|
+
NSWorkspace.frontmostApplication() query used before is a snapshot in a process
|
|
322
|
+
without a run loop (imctl's case) — after Finder came to the front it still answered
|
|
323
|
+
"iPhone Mirroring", so the re-checks inside one operation could never fire. System
|
|
324
|
+
Events reads the live process list (about 0.1 s per osascript call). Any failure
|
|
325
|
+
counts as not frontmost, so input is refused rather than sent blind.
|
|
326
|
+
"""
|
|
255
327
|
try:
|
|
256
328
|
return _run_osascript(_FRONTMOST_SCRIPT) == "true"
|
|
257
|
-
except WindowError:
|
|
329
|
+
except (WindowError, subprocess.TimeoutExpired, OSError):
|
|
258
330
|
return False
|
|
259
331
|
|
|
260
332
|
|
|
261
|
-
|
|
262
|
-
|
|
333
|
+
# F28: controls iPhone Mirroring adds to group 1 while the pointer rests on its window
|
|
334
|
+
# (the title-bar buttons), identified by AX subrole — never by localized text.
|
|
335
|
+
_CHROME_SUBROLES = frozenset(
|
|
336
|
+
{"AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton"}
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def parse_overlay_ex(raw: str) -> tuple[dict, bool]:
|
|
341
|
+
"""Parse _OVERLAY_SCRIPT output into ({"live", "overlay", "buttons"}, hover).
|
|
263
342
|
|
|
264
343
|
Rules (structure only, never localized text):
|
|
265
|
-
- "" (group 1 has no children)
|
|
266
|
-
- child lines "<class
|
|
267
|
-
|
|
268
|
-
|
|
344
|
+
- "" (group 1 has no children) -> live=True, overlay=None, buttons=0
|
|
345
|
+
- child lines "<class>\\t<label>[\\t<subrole>\\t<child classes>]"
|
|
346
|
+
-> live=False, overlay=static texts joined
|
|
347
|
+
with " / " (None when no text),
|
|
348
|
+
buttons=button count
|
|
349
|
+
- "NO_WINDOW" / "NO_GROUP" / unparseable -> live=None, overlay=None, buttons=0
|
|
350
|
+
|
|
351
|
+
F28: while the pointer rests on the mirror window, group 1 also holds the window's own
|
|
352
|
+
title-bar buttons (subroles AXCloseButton / AXMinimizeButton / AXZoomButton) and a small
|
|
353
|
+
toolbar (a group whose children are only buttons). hover is True when those buttons are
|
|
354
|
+
present; they and the toolbar group are not an overlay and are never counted. Without
|
|
355
|
+
them the rules above apply unchanged: any other child still means not live.
|
|
269
356
|
"""
|
|
270
357
|
unknown = {"live": None, "overlay": None, "buttons": 0}
|
|
271
358
|
if raw is None:
|
|
272
|
-
return unknown
|
|
359
|
+
return unknown, False
|
|
273
360
|
if raw.strip() in ("NO_WINDOW", "NO_GROUP"):
|
|
274
|
-
return unknown
|
|
361
|
+
return unknown, False
|
|
275
362
|
# Keep lines as-is (a trailing tab is significant: "button\t" means a nameless button);
|
|
276
363
|
# only filter out blank lines.
|
|
277
364
|
lines = [ln for ln in raw.split("\n") if ln.strip()]
|
|
278
365
|
if not lines:
|
|
279
|
-
return {"live": True, "overlay": None, "buttons": 0}
|
|
280
|
-
|
|
281
|
-
texts: list[str] = []
|
|
366
|
+
return {"live": True, "overlay": None, "buttons": 0}, False
|
|
367
|
+
elements = []
|
|
282
368
|
for ln in lines:
|
|
283
369
|
parts = ln.split("\t", 1)
|
|
284
370
|
if len(parts) != 2:
|
|
285
|
-
return unknown # unexpected format -> unknown, never guess
|
|
286
|
-
cls,
|
|
287
|
-
if
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
371
|
+
return unknown, False # unexpected format -> unknown, never guess
|
|
372
|
+
cls, rest = parts[0].strip(), parts[1]
|
|
373
|
+
if rest.count("\t") >= 2: # current script: label, subrole, child classes
|
|
374
|
+
label, subrole, kids = rest.rsplit("\t", 2)
|
|
375
|
+
else: # two-field form (label only)
|
|
376
|
+
label, subrole, kids = rest, "", ""
|
|
377
|
+
child_classes = [k.strip() for k in kids.split(",") if k.strip()]
|
|
378
|
+
elements.append((cls, label.strip(), subrole.strip(), child_classes))
|
|
379
|
+
hover = any(c == "button" and s in _CHROME_SUBROLES for c, _, s, _ in elements)
|
|
380
|
+
rest_els = [e for e in elements if not (e[0] == "button" and e[2] in _CHROME_SUBROLES)]
|
|
381
|
+
if hover:
|
|
382
|
+
# The hover toolbar: a group holding only buttons (or nothing yet, mid-animation).
|
|
383
|
+
rest_els = [
|
|
384
|
+
e for e in rest_els if not (e[0] == "group" and all(k == "button" for k in e[3]))
|
|
385
|
+
]
|
|
386
|
+
if not rest_els:
|
|
387
|
+
return {"live": True, "overlay": None, "buttons": 0}, hover
|
|
388
|
+
buttons = sum(1 for e in rest_els if e[0] == "button")
|
|
389
|
+
texts = [e[1] for e in rest_els if e[0] == "static text" and e[1]]
|
|
291
390
|
return {
|
|
292
391
|
"live": False,
|
|
293
392
|
"overlay": " / ".join(texts) if texts else None,
|
|
294
393
|
"buttons": buttons,
|
|
295
|
-
}
|
|
394
|
+
}, hover
|
|
296
395
|
|
|
297
396
|
|
|
298
|
-
def
|
|
299
|
-
"""
|
|
397
|
+
def parse_overlay(raw: str) -> dict:
|
|
398
|
+
"""Parse _OVERLAY_SCRIPT output into {"live", "overlay", "buttons"} (see parse_overlay_ex)."""
|
|
399
|
+
return parse_overlay_ex(raw)[0]
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def overlay_snapshot() -> tuple[dict, bool]:
|
|
403
|
+
"""(overlay state, hover) from one probe; the state is what get_overlay() returns.
|
|
300
404
|
|
|
301
405
|
Fail-open: any osascript failure (app not running, AX hiccup, timeout) returns
|
|
302
406
|
live=None so callers can decide; this never raises.
|
|
@@ -306,8 +410,13 @@ def get_overlay() -> dict:
|
|
|
306
410
|
# str.strip() would eat it and make the last line unparseable.
|
|
307
411
|
raw = _run_osascript(_OVERLAY_SCRIPT, strip=False)
|
|
308
412
|
except Exception:
|
|
309
|
-
return {"live": None, "overlay": None, "buttons": 0}
|
|
310
|
-
return
|
|
413
|
+
return {"live": None, "overlay": None, "buttons": 0}, False
|
|
414
|
+
return parse_overlay_ex(raw)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def get_overlay() -> dict:
|
|
418
|
+
"""Return the current overlay state: {"live", "overlay", "buttons"} (fail-open)."""
|
|
419
|
+
return overlay_snapshot()[0]
|
|
311
420
|
|
|
312
421
|
|
|
313
422
|
def is_paused(overlay: dict | None = None) -> bool | None:
|
|
@@ -326,24 +435,69 @@ def is_paused(overlay: dict | None = None) -> bool | None:
|
|
|
326
435
|
return None
|
|
327
436
|
|
|
328
437
|
|
|
438
|
+
def _move_pointer_off_window() -> bool:
|
|
439
|
+
"""Move the pointer just outside the mirror window (a move, never a click).
|
|
440
|
+
|
|
441
|
+
F28/F29: with the pointer on the window its title-bar buttons share group 1 with
|
|
442
|
+
the overlay; moving off hides them before resume() reads and clicks. Picks the
|
|
443
|
+
first point beside the window that lies on an active display. Best effort:
|
|
444
|
+
returns False when Quartz is unavailable or nothing qualifies.
|
|
445
|
+
"""
|
|
446
|
+
try:
|
|
447
|
+
import Quartz # type: ignore
|
|
448
|
+
|
|
449
|
+
b = get_bounds()
|
|
450
|
+
err, ids, count = Quartz.CGGetActiveDisplayList(16, None, None)
|
|
451
|
+
if err:
|
|
452
|
+
return False
|
|
453
|
+
rects = [Quartz.CGDisplayBounds(d) for d in list(ids)[:count]]
|
|
454
|
+
candidates = [
|
|
455
|
+
(b.x - 24, b.y + b.height / 2),
|
|
456
|
+
(b.x + b.width + 24, b.y + b.height / 2),
|
|
457
|
+
(b.x + b.width / 2, b.y + b.height + 24),
|
|
458
|
+
(b.x + b.width / 2, b.y - 24),
|
|
459
|
+
]
|
|
460
|
+
for x, y in candidates:
|
|
461
|
+
for r in rects:
|
|
462
|
+
if (r.origin.x <= x < r.origin.x + r.size.width
|
|
463
|
+
and r.origin.y <= y < r.origin.y + r.size.height):
|
|
464
|
+
ev = Quartz.CGEventCreateMouseEvent(
|
|
465
|
+
None, Quartz.kCGEventMouseMoved, (x, y), Quartz.kCGMouseButtonLeft
|
|
466
|
+
)
|
|
467
|
+
Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)
|
|
468
|
+
return True
|
|
469
|
+
except Exception:
|
|
470
|
+
return False
|
|
471
|
+
return False
|
|
472
|
+
|
|
473
|
+
|
|
329
474
|
def resume() -> bool:
|
|
330
475
|
"""Click the Resume control when the session is paused (language-independent).
|
|
331
476
|
|
|
332
|
-
Live already -> True.
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
477
|
+
Live already -> True. F28/F29: when the pointer rests on the window its title-bar
|
|
478
|
+
buttons appear in the same AX group, so the pointer is first moved off the window
|
|
479
|
+
and the state read again; window controls are never counted or clicked. Paused
|
|
480
|
+
overlay with exactly one other button -> click it, then poll up to ~6 s (0.5 s
|
|
481
|
+
interval) until the stream is live again. Anything else (several buttons, none,
|
|
482
|
+
unknown state) -> do not click, return False. The iPhone must be locked and near
|
|
483
|
+
the Mac for the stream to come back.
|
|
336
484
|
"""
|
|
337
485
|
import time
|
|
338
486
|
|
|
339
|
-
overlay =
|
|
487
|
+
overlay, hover = overlay_snapshot()
|
|
488
|
+
if hover:
|
|
489
|
+
_move_pointer_off_window()
|
|
490
|
+
time.sleep(0.6)
|
|
491
|
+
overlay, hover = overlay_snapshot()
|
|
340
492
|
if overlay["live"] is True:
|
|
341
493
|
return True
|
|
342
494
|
if overlay["live"] is not False or overlay["buttons"] != 1:
|
|
343
495
|
return False
|
|
344
496
|
try:
|
|
345
|
-
_run_osascript(_CLICK_RESUME_SCRIPT)
|
|
346
|
-
except WindowError:
|
|
497
|
+
clicked = _run_osascript(_CLICK_RESUME_SCRIPT)
|
|
498
|
+
except (WindowError, subprocess.TimeoutExpired):
|
|
499
|
+
return False
|
|
500
|
+
if clicked != "CLICKED":
|
|
347
501
|
return False
|
|
348
502
|
for _ in range(12): # up to ~6 s for the stream to come back
|
|
349
503
|
time.sleep(0.5)
|
package/package.json
CHANGED
package/src/server.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import { spawn, execFileSync, spawnSync } from "node:child_process";
|
|
|
21
21
|
import { readFileSync, writeFileSync, unlinkSync, existsSync } from "node:fs";
|
|
22
22
|
import { homedir, tmpdir } from "node:os";
|
|
23
23
|
import { join, dirname } from "node:path";
|
|
24
|
-
import { randomUUID } from "node:crypto";
|
|
24
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
25
25
|
import { fileURLToPath } from "node:url";
|
|
26
26
|
import { createRequire } from "node:module";
|
|
27
27
|
|
|
@@ -34,6 +34,36 @@ if (!existsSync(IMCTL_DIR)) {
|
|
|
34
34
|
process.stderr.write(`[noracu] warning: imctl not found at ${IMCTL_DIR} — phone_* tools will fail. Set NORACU_IMCTL_DIR.\n`);
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
// ── F23:进程/磁盘漂移检测(server 进程比磁盘上的文件旧时提示调用方)──
|
|
38
|
+
// MCP 客户端(如 Claude Desktop)会把 server 进程常驻数小时;磁盘上的 package.json /
|
|
39
|
+
// src/server.mjs 升级后,进程里跑的仍是启动时加载的旧代码(旧版本号、旧工具描述),
|
|
40
|
+
// 实际形成"旧 server + 新 imctl 驱动"混跑,调用方照旧描述传参会踩坑(F20 的根因之一)。
|
|
41
|
+
// 注意:git 切分支同样会改写 src/server.mjs 的内容 —— 这时下面的提示同样成立,因为
|
|
42
|
+
// 进程里的代码确实与磁盘不同。启动时快照一次 LOADED,每次 tools/call 现读磁盘对比
|
|
43
|
+
// (两个文件都很小,不做缓存)。
|
|
44
|
+
const PKG_JSON = join(__dirname, "..", "package.json");
|
|
45
|
+
const SERVER_MJS = join(__dirname, "server.mjs"); // 本文件
|
|
46
|
+
const sha256OfFile = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
|
|
47
|
+
const LOADED = (() => {
|
|
48
|
+
try {
|
|
49
|
+
return { version: JSON.parse(readFileSync(PKG_JSON, "utf8")).version, sha256: sha256OfFile(SERVER_MJS), at: new Date().toISOString() };
|
|
50
|
+
} catch {
|
|
51
|
+
return { version: "0.0.0", sha256: null, at: new Date().toISOString() };
|
|
52
|
+
}
|
|
53
|
+
})();
|
|
54
|
+
|
|
55
|
+
// 版本或哈希任一与磁盘不同 → 一行英文提示;读磁盘失败或一致 → null(不报错、不影响工具执行)
|
|
56
|
+
function staleServerNote() {
|
|
57
|
+
try {
|
|
58
|
+
const diskVersion = JSON.parse(readFileSync(PKG_JSON, "utf8")).version;
|
|
59
|
+
const hashChanged = LOADED.sha256 !== null && LOADED.sha256 !== sha256OfFile(SERVER_MJS);
|
|
60
|
+
if (LOADED.version === diskVersion && !hashChanged) return null;
|
|
61
|
+
return `noracu: this server process is stale: it loaded ${LOADED.version} at ${LOADED.at}, but the files on disk are ${diskVersion}${hashChanged ? " (src/server.mjs changed)" : ""}. Restart the MCP client to load them.`;
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
37
67
|
// ── 工具实现 ──────────────────────────────────────────────
|
|
38
68
|
|
|
39
69
|
function sh(cmd, args, timeoutMs = 15000) {
|
|
@@ -70,6 +100,10 @@ function resolvePython() {
|
|
|
70
100
|
return pythonProbe;
|
|
71
101
|
}
|
|
72
102
|
|
|
103
|
+
// imctl 拒绝输入时在 stderr 打印 `前缀: 说明` 行。这些是可恢复的调用方错误(不是环境缺失),
|
|
104
|
+
// 原样透传匹配到的那一行,不归类为 imctl unavailable。后续任务会往列表里追加更多前缀。
|
|
105
|
+
const IMCTL_PASS_THROUGH = ["mirror_not_live", "type_not_confirmed", "scroll_no_effect", "expect_not_found", "capture_failed", "open_not_confirmed", "focus_lost"];
|
|
106
|
+
|
|
73
107
|
function imctl(...args) {
|
|
74
108
|
const py = resolvePython();
|
|
75
109
|
if (!py.path) {
|
|
@@ -83,10 +117,13 @@ function imctl(...args) {
|
|
|
83
117
|
});
|
|
84
118
|
return { ok: true, out: out.trim() };
|
|
85
119
|
} catch (e) {
|
|
86
|
-
// G23(0.1.2
|
|
87
|
-
// 原样透传那一行,不归类为 imctl unavailable
|
|
88
|
-
const
|
|
89
|
-
|
|
120
|
+
// G23(0.1.2)/ G26:镜像不在线(mirror_not_live)或粘贴未上屏(type_not_confirmed)时
|
|
121
|
+
// imctl 拒绝输入并在 stderr 带前缀行 —— 原样透传那一行,不归类为 imctl unavailable
|
|
122
|
+
const combined = String(e.stderr || "") + "\n" + String(e.stdout || "");
|
|
123
|
+
for (const prefix of IMCTL_PASS_THROUGH) {
|
|
124
|
+
const line = combined.split("\n").find((l) => l.startsWith(prefix + ":"));
|
|
125
|
+
if (line) return { ok: false, out: line.trim() };
|
|
126
|
+
}
|
|
90
127
|
const raw = String(e.stderr || e.stdout || e.message);
|
|
91
128
|
// Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
|
|
92
129
|
if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
|
|
@@ -683,17 +720,22 @@ function phoneStatus() { return imctl("status"); }
|
|
|
683
720
|
function phoneLaunch() { return imctl("launch"); }
|
|
684
721
|
function phoneTap(args) {
|
|
685
722
|
if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y (0-1 normalized) required" };
|
|
686
|
-
|
|
723
|
+
const a = ["tap", String(args.x), String(args.y)];
|
|
724
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
725
|
+
return imctl(...a);
|
|
687
726
|
}
|
|
688
727
|
function phoneLongpress(args) {
|
|
689
728
|
if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y required" };
|
|
690
|
-
|
|
729
|
+
const a = ["longpress", String(args.x), String(args.y), String(args.duration || 0.8)];
|
|
730
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
731
|
+
return imctl(...a);
|
|
691
732
|
}
|
|
692
733
|
function phoneSwipe(args) {
|
|
693
734
|
const { from, to, ms } = args;
|
|
694
735
|
if (!Array.isArray(from) || !Array.isArray(to)) return { error: "from:[x,y], to:[x,y] required" };
|
|
695
736
|
const a = ["swipe", String(from[0]), String(from[1]), String(to[0]), String(to[1])];
|
|
696
737
|
if (ms) a.push("--ms", String(ms));
|
|
738
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
697
739
|
return imctl(...a);
|
|
698
740
|
}
|
|
699
741
|
// 镜像自带菜单 Home Screen ⌘1 / App Switcher ⌘2 可靠且不需前台(AXPress,非贴边手势)。
|
|
@@ -711,15 +753,26 @@ function phoneAppSwitcher() {
|
|
|
711
753
|
return imctl("app-switcher");
|
|
712
754
|
}
|
|
713
755
|
function phoneScroll(args = {}) {
|
|
714
|
-
|
|
756
|
+
const a = ["scroll", args.direction || "down", String(args.distance || 0.5)];
|
|
757
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
758
|
+
return imctl(...a);
|
|
715
759
|
}
|
|
716
760
|
function phoneType(args) {
|
|
717
761
|
if (!args.text) return { error: "text required" };
|
|
718
|
-
|
|
762
|
+
// Options first, then `--`, then the free text: the text is a positional and
|
|
763
|
+
// may start with "-" (argparse would otherwise treat it as an option).
|
|
764
|
+
// Invariant: --expect and its value are two separate argv elements.
|
|
765
|
+
const a = ["type"];
|
|
766
|
+
if (args.replace) a.push("--replace");
|
|
767
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
768
|
+
a.push("--", args.text);
|
|
769
|
+
return imctl(...a);
|
|
719
770
|
}
|
|
720
771
|
function phoneKey(args) {
|
|
721
772
|
if (!args.key) return { error: "key required (return/delete/up/down/left/right)" };
|
|
722
|
-
|
|
773
|
+
const a = ["key", args.key];
|
|
774
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
775
|
+
return imctl(...a);
|
|
723
776
|
}
|
|
724
777
|
function phoneOcr() { return imctl("ocr"); }
|
|
725
778
|
function phoneFind(args) {
|
|
@@ -792,18 +845,18 @@ const TOOLS = [
|
|
|
792
845
|
// iPhone device-use(imctl)
|
|
793
846
|
{ name: "phone_status", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, live, overlay, paused).", args: {}, fn: phoneStatus },
|
|
794
847
|
{ name: "phone_launch", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and clicks Resume when the connection is paused.", args: {}, fn: phoneLaunch },
|
|
795
|
-
{ name: "phone_screenshot", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered).", args: {}, fn: phoneScreenshot },
|
|
796
|
-
{ name: "phone_ocr", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates.", args: {}, fn: phoneOcr },
|
|
797
|
-
{ name: "phone_find", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen.", args: { text: "string" }, fn: phoneFind },
|
|
798
|
-
{ name: "phone_tap", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused.", args: { x: "number", y: "number" }, fn: phoneTap },
|
|
799
|
-
{ name: "phone_longpress", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds.", args: { x: "number", y: "number", duration: "number?" }, fn: phoneLongpress },
|
|
800
|
-
{ name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll.", args: { from: "array", to: "array", ms: "number?" }, fn: phoneSwipe },
|
|
848
|
+
{ name: "phone_screenshot", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered). Fails with capture_failed instead of returning another window's pixels.", args: {}, fn: phoneScreenshot },
|
|
849
|
+
{ name: "phone_ocr", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates. Fails with capture_failed instead of returning another window's pixels.", args: {}, fn: phoneOcr },
|
|
850
|
+
{ name: "phone_find", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen. Fails with capture_failed instead of returning another window's pixels.", args: { text: "string" }, fn: phoneFind },
|
|
851
|
+
{ name: "phone_tap", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { x: "number", y: "number", expect: "string?" }, fn: phoneTap },
|
|
852
|
+
{ name: "phone_longpress", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { x: "number", y: "number", duration: "number?", expect: "string?" }, fn: phoneLongpress },
|
|
853
|
+
{ name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { from: "array", to: "array", ms: "number?", expect: "string?" }, fn: phoneSwipe },
|
|
801
854
|
{ name: "phone_home", desc: "EXPERIMENTAL. Go to the iPhone Home Screen via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl swipe.", args: {}, fn: phoneHome },
|
|
802
855
|
{ name: "phone_app_switcher", desc: "EXPERIMENTAL. Open the iPhone App Switcher via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl gesture.", args: {}, fn: phoneAppSwitcher },
|
|
803
|
-
{ name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll
|
|
804
|
-
{ name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe).", args: { text: "string" }, fn: phoneType },
|
|
805
|
-
{ name: "phone_key", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right.", args: { key: "string" }, fn: phoneKey },
|
|
806
|
-
{ name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via the
|
|
856
|
+
{ name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by `distance` window heights (0 < distance <= 3, default 0.5) using trackpad-style scroll events. Reports scroll_no_effect when the screen did not change (list end, or the view does not scroll). Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { direction: "string?", distance: "number?", expect: "string?" }, fn: phoneScroll },
|
|
857
|
+
{ name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe). Restores the clipboard only after OCR sees the text, else reports type_not_confirmed and keeps the text. replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent.", args: { text: "string", replace: "boolean?", expect: "string?" }, fn: phoneType },
|
|
858
|
+
{ name: "phone_key", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. Optional expect: text that must be on screen (OCR) first, else nothing is sent.", args: { key: "string", expect: "string?" }, fn: phoneKey },
|
|
859
|
+
{ name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app: Home Screen, Spotlight via the menu, clear, type the name, OCR-pick the exact row and tap it; confirms the app opened (frame diff + OCR), taps the Top Hit icon when the label tap does nothing, else open_not_confirmed, back on the Home Screen.", args: { app: "string" }, fn: phoneOpen },
|
|
807
860
|
];
|
|
808
861
|
|
|
809
862
|
// ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──
|
|
@@ -868,12 +921,28 @@ function validateArgs(name, a) {
|
|
|
868
921
|
return null;
|
|
869
922
|
case "phone_tap": case "phone_longpress":
|
|
870
923
|
if (!N(a.x) || !N(a.y) || a.x < 0 || a.x > 1 || a.y < 0 || a.y > 1) return `${name}: x,y normalized 0-1 required`;
|
|
924
|
+
if (a.expect !== undefined && !S(a.expect, 200)) return `${name}: expect must be a string of 1-200 characters`;
|
|
871
925
|
return null;
|
|
872
926
|
case "phone_swipe":
|
|
873
927
|
if (!XY(a.from) || !XY(a.to)) return "phone_swipe: from/to [x,y] arrays required";
|
|
928
|
+
if (a.expect !== undefined && !S(a.expect, 200)) return "phone_swipe: expect must be a string of 1-200 characters";
|
|
929
|
+
return null;
|
|
930
|
+
case "phone_scroll":
|
|
931
|
+
if (a.direction !== undefined && a.direction !== "up" && a.direction !== "down")
|
|
932
|
+
return "phone_scroll: direction must be up|down";
|
|
933
|
+
if (a.distance !== undefined && (!N(a.distance) || a.distance <= 0 || a.distance > 3))
|
|
934
|
+
return "phone_scroll: distance is in window heights, 0 < distance <= 3 (default 0.5)";
|
|
935
|
+
if (a.expect !== undefined && !S(a.expect, 200)) return "phone_scroll: expect must be a string of 1-200 characters";
|
|
874
936
|
return null;
|
|
875
937
|
case "phone_type": case "phone_find":
|
|
876
938
|
if (!S(a.text, 5000)) return `${name}: text string (max 5000) required`;
|
|
939
|
+
if (name === "phone_type" && a.replace !== undefined && typeof a.replace !== "boolean")
|
|
940
|
+
return "phone_type: replace must be a boolean";
|
|
941
|
+
if (name === "phone_type" && a.expect !== undefined && !S(a.expect, 200))
|
|
942
|
+
return "phone_type: expect must be a string of 1-200 characters";
|
|
943
|
+
return null;
|
|
944
|
+
case "phone_key":
|
|
945
|
+
if (a.expect !== undefined && !S(a.expect, 200)) return "phone_key: expect must be a string of 1-200 characters";
|
|
877
946
|
return null;
|
|
878
947
|
case "phone_open":
|
|
879
948
|
if (!S(a.app, 200)) return "phone_open: app string (max 200) required";
|
|
@@ -897,6 +966,19 @@ function send(obj) {
|
|
|
897
966
|
process.stdout.write(JSON.stringify(obj) + "\n");
|
|
898
967
|
}
|
|
899
968
|
|
|
969
|
+
// tools/call 结果统一出口(F23):进程比磁盘旧时,把 staleServerNote() 的一行提示加在
|
|
970
|
+
// 第一个 text 内容块的开头(单独一行);纯图片结果没有 text 块则补一个。只加提示 ——
|
|
971
|
+
// 不改变工具执行、isError 返回码或其余内容块;tools/list / initialize 不加。
|
|
972
|
+
function sendToolResult(id, content, isError) {
|
|
973
|
+
const note = staleServerNote();
|
|
974
|
+
if (note) {
|
|
975
|
+
const firstText = content.find(b => b?.type === "text");
|
|
976
|
+
if (firstText) firstText.text = `${note}\n${firstText.text}`;
|
|
977
|
+
else content.unshift({ type: "text", text: note });
|
|
978
|
+
}
|
|
979
|
+
send({ jsonrpc: "2.0", id, result: { content, ...(isError ? { isError: true } : {}) } });
|
|
980
|
+
}
|
|
981
|
+
|
|
900
982
|
rl.on("line", async (line) => {
|
|
901
983
|
if (!line.trim()) return;
|
|
902
984
|
let msg;
|
|
@@ -904,7 +986,8 @@ rl.on("line", async (line) => {
|
|
|
904
986
|
const { id, method, params } = msg;
|
|
905
987
|
try {
|
|
906
988
|
if (method === "initialize") {
|
|
907
|
-
|
|
989
|
+
// F23:版本号用启动时快照的 LOADED.version,不在握手时现读 —— 进程旧了它也不会误报新版本
|
|
990
|
+
send({ jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "noracu", version: LOADED.version } } });
|
|
908
991
|
} else if (method === "notifications/initialized") {
|
|
909
992
|
// no response
|
|
910
993
|
} else if (method === "tools/list") {
|
|
@@ -915,28 +998,28 @@ rl.on("line", async (line) => {
|
|
|
915
998
|
} else if (method === "tools/call") {
|
|
916
999
|
const name = params?.name;
|
|
917
1000
|
const tool = TOOLS.find(t => t.name === name);
|
|
918
|
-
if (!tool) {
|
|
1001
|
+
if (!tool) { sendToolResult(id, [{ type: "text", text: `unknown tool: ${name}` }], true); return; }
|
|
919
1002
|
let r;
|
|
920
1003
|
if (process.env.NORACU_READ_ONLY === "1" && !READ_ONLY_TOOLS.has(name)) {
|
|
921
|
-
|
|
1004
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${name} blocked by NORACU_READ_ONLY=1 (observation-only mode)` }], true);
|
|
922
1005
|
return;
|
|
923
1006
|
}
|
|
924
1007
|
const verr = validateArgs(name, params?.arguments || {});
|
|
925
|
-
if (verr) {
|
|
1008
|
+
if (verr) { sendToolResult(id, [{ type: "text", text: `ERROR: ${verr}` }], true); return; }
|
|
926
1009
|
try { r = await tool.fn(params?.arguments || {}); }
|
|
927
1010
|
catch (e) { r = { error: String(e?.message ?? e).slice(0, 400) }; }
|
|
928
1011
|
if (r?.error) {
|
|
929
|
-
|
|
1012
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${r.error}` }], true);
|
|
930
1013
|
} else if (r?.ok === false) {
|
|
931
1014
|
// imctl 子进程失败(imctl 缺失、Mirroring 窗口无法置前)返回 { ok:false, out },
|
|
932
1015
|
// 此前被当作成功文本下发 —— 统一在此标记为工具错误(一处覆盖所有 phone_* 工具)
|
|
933
|
-
|
|
1016
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${r.out}` }], true);
|
|
934
1017
|
} else if (r?.image) {
|
|
935
1018
|
const content = [{ type: "image", data: r.image, mimeType: r.mime || "image/png" }];
|
|
936
1019
|
if (r.meta) content.push({ type: "text", text: JSON.stringify(r.meta) });
|
|
937
|
-
|
|
1020
|
+
sendToolResult(id, content);
|
|
938
1021
|
} else {
|
|
939
|
-
|
|
1022
|
+
sendToolResult(id, [{ type: "text", text: typeof r?.text === "string" ? r.text : (r?.out ?? JSON.stringify(r)) }]);
|
|
940
1023
|
}
|
|
941
1024
|
} else if (method === "ping") {
|
|
942
1025
|
send({ jsonrpc: "2.0", id, result: {} });
|