noracu 0.1.1 → 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 +98 -0
- package/README.md +22 -13
- package/README.zh-CN.md +21 -12
- package/SECURITY.md +5 -1
- package/docs/architecture.md +3 -2
- package/docs/tools.md +13 -13
- package/docs/usage.md +37 -11
- package/imctl/README.md +5 -3
- package/imctl/src/imctl/cli.py +261 -18
- package/imctl/src/imctl/gestures.py +555 -28
- package/imctl/src/imctl/input.py +443 -45
- package/imctl/src/imctl/verify.py +250 -1
- package/imctl/src/imctl/vision.py +214 -29
- package/imctl/src/imctl/window.py +285 -27
- package/package.json +3 -2
- package/src/server.mjs +113 -26
|
@@ -64,7 +64,7 @@ end tell
|
|
|
64
64
|
'''
|
|
65
65
|
|
|
66
66
|
|
|
67
|
-
def _run_osascript(script: str) -> str:
|
|
67
|
+
def _run_osascript(script: str, *, strip: bool = True) -> str:
|
|
68
68
|
result = subprocess.run(
|
|
69
69
|
["osascript", "-e", script],
|
|
70
70
|
capture_output=True,
|
|
@@ -73,7 +73,7 @@ def _run_osascript(script: str) -> str:
|
|
|
73
73
|
)
|
|
74
74
|
if result.returncode != 0:
|
|
75
75
|
raise WindowError(f"osascript failed: {result.stderr.strip()}")
|
|
76
|
-
return result.stdout.strip()
|
|
76
|
+
return result.stdout.strip() if strip else result.stdout
|
|
77
77
|
|
|
78
78
|
|
|
79
79
|
def is_running() -> bool:
|
|
@@ -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:
|
|
@@ -152,25 +179,101 @@ def get_bounds() -> WindowBounds:
|
|
|
152
179
|
return WindowBounds(x=x, y=y, width=w, height=h)
|
|
153
180
|
|
|
154
181
|
|
|
155
|
-
|
|
182
|
+
# Language-independent mirror-state probe. When the mirroring session is live, window 1 contains a
|
|
183
|
+
# single group (the AXHostingView) with no children; when an overlay is shown (paused, connecting,
|
|
184
|
+
# "iPhone in use", …) that group gains child elements (image / static text / button). Overlay text
|
|
185
|
+
# is localized, so the decision never matches on text — only on structure (child count, classes).
|
|
186
|
+
# Labels can span multiple lines and nameless elements coerce to the literal "missing value";
|
|
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.
|
|
191
|
+
_OVERLAY_SCRIPT = '''
|
|
192
|
+
on collapseBreaks(s)
|
|
193
|
+
set tid to AppleScript's text item delimiters
|
|
194
|
+
set AppleScript's text item delimiters to linefeed
|
|
195
|
+
set parts to text items of s
|
|
196
|
+
set AppleScript's text item delimiters to " "
|
|
197
|
+
set s to parts as text
|
|
198
|
+
set AppleScript's text item delimiters to return
|
|
199
|
+
set parts to text items of s
|
|
200
|
+
set AppleScript's text item delimiters to " "
|
|
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
|
|
206
|
+
set AppleScript's text item delimiters to tid
|
|
207
|
+
return s
|
|
208
|
+
end collapseBreaks
|
|
209
|
+
|
|
156
210
|
tell application "System Events"
|
|
157
211
|
tell process "iPhone Mirroring"
|
|
212
|
+
set winCount to count of windows
|
|
213
|
+
if winCount is 0 then return "NO_WINDOW"
|
|
158
214
|
tell window 1
|
|
159
|
-
|
|
215
|
+
if not (exists group 1) then return "NO_GROUP"
|
|
216
|
+
set els to UI elements of group 1
|
|
217
|
+
if (count of els) is 0 then return ""
|
|
218
|
+
set out to ""
|
|
219
|
+
repeat with e in els
|
|
220
|
+
set c to (class of e) as text
|
|
221
|
+
set lbl to ""
|
|
222
|
+
try
|
|
223
|
+
set n to (name of e) as text
|
|
224
|
+
if n is not "missing value" then set lbl to n
|
|
225
|
+
end try
|
|
226
|
+
if lbl is "" then
|
|
227
|
+
try
|
|
228
|
+
set v to (value of e) as text
|
|
229
|
+
if v is not "missing value" then set lbl to v
|
|
230
|
+
end try
|
|
231
|
+
end if
|
|
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
|
|
246
|
+
end repeat
|
|
247
|
+
return out
|
|
160
248
|
end tell
|
|
161
249
|
end tell
|
|
162
250
|
end tell
|
|
163
251
|
'''
|
|
164
252
|
|
|
165
|
-
|
|
253
|
+
# Clicks the Resume control of the paused overlay. Only ever invoked after _OVERLAY_SCRIPT
|
|
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.
|
|
258
|
+
_CLICK_RESUME_SCRIPT = '''
|
|
166
259
|
tell application "System Events"
|
|
167
260
|
tell process "iPhone Mirroring"
|
|
168
261
|
tell window 1
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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"
|
|
174
277
|
end tell
|
|
175
278
|
end tell
|
|
176
279
|
end tell
|
|
@@ -212,37 +315,192 @@ def get_window_info() -> dict | None:
|
|
|
212
315
|
|
|
213
316
|
|
|
214
317
|
def is_frontmost() -> bool:
|
|
215
|
-
"""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
|
+
"""
|
|
216
327
|
try:
|
|
217
328
|
return _run_osascript(_FRONTMOST_SCRIPT) == "true"
|
|
218
|
-
except WindowError:
|
|
329
|
+
except (WindowError, subprocess.TimeoutExpired, OSError):
|
|
219
330
|
return False
|
|
220
331
|
|
|
221
332
|
|
|
222
|
-
|
|
223
|
-
|
|
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).
|
|
342
|
+
|
|
343
|
+
Rules (structure only, never localized text):
|
|
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.
|
|
356
|
+
"""
|
|
357
|
+
unknown = {"live": None, "overlay": None, "buttons": 0}
|
|
358
|
+
if raw is None:
|
|
359
|
+
return unknown, False
|
|
360
|
+
if raw.strip() in ("NO_WINDOW", "NO_GROUP"):
|
|
361
|
+
return unknown, False
|
|
362
|
+
# Keep lines as-is (a trailing tab is significant: "button\t" means a nameless button);
|
|
363
|
+
# only filter out blank lines.
|
|
364
|
+
lines = [ln for ln in raw.split("\n") if ln.strip()]
|
|
365
|
+
if not lines:
|
|
366
|
+
return {"live": True, "overlay": None, "buttons": 0}, False
|
|
367
|
+
elements = []
|
|
368
|
+
for ln in lines:
|
|
369
|
+
parts = ln.split("\t", 1)
|
|
370
|
+
if len(parts) != 2:
|
|
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]]
|
|
390
|
+
return {
|
|
391
|
+
"live": False,
|
|
392
|
+
"overlay": " / ".join(texts) if texts else None,
|
|
393
|
+
"buttons": buttons,
|
|
394
|
+
}, hover
|
|
395
|
+
|
|
396
|
+
|
|
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.
|
|
404
|
+
|
|
405
|
+
Fail-open: any osascript failure (app not running, AX hiccup, timeout) returns
|
|
406
|
+
live=None so callers can decide; this never raises.
|
|
407
|
+
"""
|
|
224
408
|
try:
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
409
|
+
# strip=False: a trailing "<class>\t" line (nameless button) must keep its tab —
|
|
410
|
+
# str.strip() would eat it and make the last line unparseable.
|
|
411
|
+
raw = _run_osascript(_OVERLAY_SCRIPT, strip=False)
|
|
412
|
+
except Exception:
|
|
413
|
+
return {"live": None, "overlay": None, "buttons": 0}, False
|
|
414
|
+
return parse_overlay_ex(raw)
|
|
228
415
|
|
|
229
416
|
|
|
230
|
-
def
|
|
231
|
-
"""
|
|
417
|
+
def get_overlay() -> dict:
|
|
418
|
+
"""Return the current overlay state: {"live", "overlay", "buttons"} (fail-open)."""
|
|
419
|
+
return overlay_snapshot()[0]
|
|
420
|
+
|
|
232
421
|
|
|
233
|
-
|
|
234
|
-
|
|
422
|
+
def is_paused(overlay: dict | None = None) -> bool | None:
|
|
423
|
+
"""True when the overlay shows a Resume control; False when live; None when unknown.
|
|
424
|
+
|
|
425
|
+
Language-independent: derived from the overlay structure (live flag + button count),
|
|
426
|
+
not from localized text such as "Connection Paused". Accepts a pre-fetched overlay
|
|
427
|
+
dict (as returned by get_overlay) so status can report one consistent snapshot.
|
|
235
428
|
"""
|
|
236
|
-
|
|
429
|
+
if overlay is None:
|
|
430
|
+
overlay = get_overlay()
|
|
431
|
+
if overlay["live"] is False and overlay["buttons"] >= 1:
|
|
432
|
+
return True
|
|
433
|
+
if overlay["live"] is True:
|
|
434
|
+
return False
|
|
435
|
+
return None
|
|
436
|
+
|
|
237
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
|
+
"""
|
|
238
446
|
try:
|
|
239
|
-
|
|
240
|
-
|
|
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:
|
|
241
470
|
return False
|
|
242
|
-
|
|
471
|
+
return False
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def resume() -> bool:
|
|
475
|
+
"""Click the Resume control when the session is paused (language-independent).
|
|
476
|
+
|
|
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.
|
|
484
|
+
"""
|
|
485
|
+
import time
|
|
486
|
+
|
|
487
|
+
overlay, hover = overlay_snapshot()
|
|
488
|
+
if hover:
|
|
489
|
+
_move_pointer_off_window()
|
|
490
|
+
time.sleep(0.6)
|
|
491
|
+
overlay, hover = overlay_snapshot()
|
|
492
|
+
if overlay["live"] is True:
|
|
243
493
|
return True
|
|
244
|
-
|
|
494
|
+
if overlay["live"] is not False or overlay["buttons"] != 1:
|
|
495
|
+
return False
|
|
496
|
+
try:
|
|
497
|
+
clicked = _run_osascript(_CLICK_RESUME_SCRIPT)
|
|
498
|
+
except (WindowError, subprocess.TimeoutExpired):
|
|
499
|
+
return False
|
|
500
|
+
if clicked != "CLICKED":
|
|
501
|
+
return False
|
|
502
|
+
for _ in range(12): # up to ~6 s for the stream to come back
|
|
245
503
|
time.sleep(0.5)
|
|
246
|
-
if
|
|
504
|
+
if get_overlay()["live"] is True:
|
|
247
505
|
return True
|
|
248
506
|
return False
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "noracu",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"mcpName": "io.github.sgInnora/noracu",
|
|
5
|
+
"description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"main": "src/server.mjs",
|
|
7
8
|
"bin": {
|
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,6 +117,13 @@ function imctl(...args) {
|
|
|
83
117
|
});
|
|
84
118
|
return { ok: true, out: out.trim() };
|
|
85
119
|
} catch (e) {
|
|
120
|
+
// G23(0.1.2)/ G26:镜像不在线(mirror_not_live)或粘贴未上屏(type_not_confirmed)时
|
|
121
|
+
// imctl 拒绝输入并在 stderr 带前缀行 —— 原样透传那一行,不归类为 imctl unavailable
|
|
122
|
+
const combined = String(e.stderr || "") + "\n" + String(e.stdout || "");
|
|
123
|
+
for (const prefix of IMCTL_PASS_THROUGH) {
|
|
124
|
+
const line = combined.split("\n").find((l) => l.startsWith(prefix + ":"));
|
|
125
|
+
if (line) return { ok: false, out: line.trim() };
|
|
126
|
+
}
|
|
86
127
|
const raw = String(e.stderr || e.stdout || e.message);
|
|
87
128
|
// Collapse Python tracebacks / spawn errors into one actionable line so phone_* fail cleanly and tests can skip (graceful degradation).
|
|
88
129
|
if (/No module named|ModuleNotFoundError|ImportError|Traceback \(most recent/.test(raw)) {
|
|
@@ -679,17 +720,22 @@ function phoneStatus() { return imctl("status"); }
|
|
|
679
720
|
function phoneLaunch() { return imctl("launch"); }
|
|
680
721
|
function phoneTap(args) {
|
|
681
722
|
if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y (0-1 normalized) required" };
|
|
682
|
-
|
|
723
|
+
const a = ["tap", String(args.x), String(args.y)];
|
|
724
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
725
|
+
return imctl(...a);
|
|
683
726
|
}
|
|
684
727
|
function phoneLongpress(args) {
|
|
685
728
|
if (typeof args.x !== "number" || typeof args.y !== "number") return { error: "x,y required" };
|
|
686
|
-
|
|
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);
|
|
687
732
|
}
|
|
688
733
|
function phoneSwipe(args) {
|
|
689
734
|
const { from, to, ms } = args;
|
|
690
735
|
if (!Array.isArray(from) || !Array.isArray(to)) return { error: "from:[x,y], to:[x,y] required" };
|
|
691
736
|
const a = ["swipe", String(from[0]), String(from[1]), String(to[0]), String(to[1])];
|
|
692
737
|
if (ms) a.push("--ms", String(ms));
|
|
738
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
693
739
|
return imctl(...a);
|
|
694
740
|
}
|
|
695
741
|
// 镜像自带菜单 Home Screen ⌘1 / App Switcher ⌘2 可靠且不需前台(AXPress,非贴边手势)。
|
|
@@ -707,15 +753,26 @@ function phoneAppSwitcher() {
|
|
|
707
753
|
return imctl("app-switcher");
|
|
708
754
|
}
|
|
709
755
|
function phoneScroll(args = {}) {
|
|
710
|
-
|
|
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);
|
|
711
759
|
}
|
|
712
760
|
function phoneType(args) {
|
|
713
761
|
if (!args.text) return { error: "text required" };
|
|
714
|
-
|
|
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);
|
|
715
770
|
}
|
|
716
771
|
function phoneKey(args) {
|
|
717
772
|
if (!args.key) return { error: "key required (return/delete/up/down/left/right)" };
|
|
718
|
-
|
|
773
|
+
const a = ["key", args.key];
|
|
774
|
+
if (args.expect) a.push("--expect", args.expect);
|
|
775
|
+
return imctl(...a);
|
|
719
776
|
}
|
|
720
777
|
function phoneOcr() { return imctl("ocr"); }
|
|
721
778
|
function phoneFind(args) {
|
|
@@ -786,20 +843,20 @@ const TOOLS = [
|
|
|
786
843
|
{ name: "browser_evaluate", desc: "Evaluate JavaScript in the page and return the result.", args: { js: "string" }, fn: browserEvaluate },
|
|
787
844
|
{ name: "browser_close", desc: "Close the browser.", args: {}, fn: browserClose },
|
|
788
845
|
// iPhone device-use(imctl)
|
|
789
|
-
{ 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, paused).", args: {}, fn: phoneStatus },
|
|
790
|
-
{ name: "phone_launch", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and
|
|
791
|
-
{ 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 },
|
|
792
|
-
{ name: "phone_ocr", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates.", args: {}, fn: phoneOcr },
|
|
793
|
-
{ name: "phone_find", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen.", args: { text: "string" }, fn: phoneFind },
|
|
794
|
-
{ name: "phone_tap", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates.", args: { x: "number", y: "number" }, fn: phoneTap },
|
|
795
|
-
{ 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 },
|
|
796
|
-
{ name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe from [x,y] to [x,y] over an optional duration in ms.", args: { from: "array", to: "array", ms: "number?" }, fn: phoneSwipe },
|
|
846
|
+
{ name: "phone_status", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, live, overlay, paused).", args: {}, fn: phoneStatus },
|
|
847
|
+
{ name: "phone_launch", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and clicks Resume when the connection is paused.", args: {}, fn: phoneLaunch },
|
|
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 },
|
|
797
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 },
|
|
798
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 },
|
|
799
|
-
{ name: "phone_scroll", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by
|
|
800
|
-
{ 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 },
|
|
801
|
-
{ 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 },
|
|
802
|
-
{ name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app
|
|
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 },
|
|
803
860
|
];
|
|
804
861
|
|
|
805
862
|
// ── 统一参数校验(全工具入口门禁,返回 null=通过 / string=错误)──
|
|
@@ -864,12 +921,28 @@ function validateArgs(name, a) {
|
|
|
864
921
|
return null;
|
|
865
922
|
case "phone_tap": case "phone_longpress":
|
|
866
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`;
|
|
867
925
|
return null;
|
|
868
926
|
case "phone_swipe":
|
|
869
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";
|
|
870
936
|
return null;
|
|
871
937
|
case "phone_type": case "phone_find":
|
|
872
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";
|
|
873
946
|
return null;
|
|
874
947
|
case "phone_open":
|
|
875
948
|
if (!S(a.app, 200)) return "phone_open: app string (max 200) required";
|
|
@@ -893,6 +966,19 @@ function send(obj) {
|
|
|
893
966
|
process.stdout.write(JSON.stringify(obj) + "\n");
|
|
894
967
|
}
|
|
895
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
|
+
|
|
896
982
|
rl.on("line", async (line) => {
|
|
897
983
|
if (!line.trim()) return;
|
|
898
984
|
let msg;
|
|
@@ -900,7 +986,8 @@ rl.on("line", async (line) => {
|
|
|
900
986
|
const { id, method, params } = msg;
|
|
901
987
|
try {
|
|
902
988
|
if (method === "initialize") {
|
|
903
|
-
|
|
989
|
+
// F23:版本号用启动时快照的 LOADED.version,不在握手时现读 —— 进程旧了它也不会误报新版本
|
|
990
|
+
send({ jsonrpc: "2.0", id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "noracu", version: LOADED.version } } });
|
|
904
991
|
} else if (method === "notifications/initialized") {
|
|
905
992
|
// no response
|
|
906
993
|
} else if (method === "tools/list") {
|
|
@@ -911,28 +998,28 @@ rl.on("line", async (line) => {
|
|
|
911
998
|
} else if (method === "tools/call") {
|
|
912
999
|
const name = params?.name;
|
|
913
1000
|
const tool = TOOLS.find(t => t.name === name);
|
|
914
|
-
if (!tool) {
|
|
1001
|
+
if (!tool) { sendToolResult(id, [{ type: "text", text: `unknown tool: ${name}` }], true); return; }
|
|
915
1002
|
let r;
|
|
916
1003
|
if (process.env.NORACU_READ_ONLY === "1" && !READ_ONLY_TOOLS.has(name)) {
|
|
917
|
-
|
|
1004
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${name} blocked by NORACU_READ_ONLY=1 (observation-only mode)` }], true);
|
|
918
1005
|
return;
|
|
919
1006
|
}
|
|
920
1007
|
const verr = validateArgs(name, params?.arguments || {});
|
|
921
|
-
if (verr) {
|
|
1008
|
+
if (verr) { sendToolResult(id, [{ type: "text", text: `ERROR: ${verr}` }], true); return; }
|
|
922
1009
|
try { r = await tool.fn(params?.arguments || {}); }
|
|
923
1010
|
catch (e) { r = { error: String(e?.message ?? e).slice(0, 400) }; }
|
|
924
1011
|
if (r?.error) {
|
|
925
|
-
|
|
1012
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${r.error}` }], true);
|
|
926
1013
|
} else if (r?.ok === false) {
|
|
927
1014
|
// imctl 子进程失败(imctl 缺失、Mirroring 窗口无法置前)返回 { ok:false, out },
|
|
928
1015
|
// 此前被当作成功文本下发 —— 统一在此标记为工具错误(一处覆盖所有 phone_* 工具)
|
|
929
|
-
|
|
1016
|
+
sendToolResult(id, [{ type: "text", text: `ERROR: ${r.out}` }], true);
|
|
930
1017
|
} else if (r?.image) {
|
|
931
1018
|
const content = [{ type: "image", data: r.image, mimeType: r.mime || "image/png" }];
|
|
932
1019
|
if (r.meta) content.push({ type: "text", text: JSON.stringify(r.meta) });
|
|
933
|
-
|
|
1020
|
+
sendToolResult(id, content);
|
|
934
1021
|
} else {
|
|
935
|
-
|
|
1022
|
+
sendToolResult(id, [{ type: "text", text: typeof r?.text === "string" ? r.text : (r?.out ?? JSON.stringify(r)) }]);
|
|
936
1023
|
}
|
|
937
1024
|
} else if (method === "ping") {
|
|
938
1025
|
send({ jsonrpc: "2.0", id, result: {} });
|