nini-computer-use 0.4.4__py3-none-any.whl
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.
- nini_computer_use/__init__.py +21 -0
- nini_computer_use/__main__.py +131 -0
- nini_computer_use/audit.py +131 -0
- nini_computer_use/errors.py +92 -0
- nini_computer_use/helper.py +271 -0
- nini_computer_use/native/main.swift +618 -0
- nini_computer_use/paths.py +112 -0
- nini_computer_use/permissions.py +225 -0
- nini_computer_use/safety.py +157 -0
- nini_computer_use/server.py +213 -0
- nini_computer_use/tools.py +542 -0
- nini_computer_use/validate.py +306 -0
- nini_computer_use-0.4.4.dist-info/METADATA +38 -0
- nini_computer_use-0.4.4.dist-info/RECORD +17 -0
- nini_computer_use-0.4.4.dist-info/WHEEL +4 -0
- nini_computer_use-0.4.4.dist-info/entry_points.txt +2 -0
- nini_computer_use-0.4.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Nini computer-use MCP server (macOS).
|
|
2
|
+
|
|
3
|
+
Exposed as an MCP server rather than a desktop-only API so that the CLI, the web
|
|
4
|
+
console, remote sessions and the desktop app all drive the same tools (ADR-0003).
|
|
5
|
+
|
|
6
|
+
Layers
|
|
7
|
+
------
|
|
8
|
+
``server`` MCP stdio transport (JSON-RPC framing, error codes)
|
|
9
|
+
``tools`` tool catalog + policy chain (validate → permission → safety → helper)
|
|
10
|
+
``validate`` argument bounds (coordinates, regions, text, key combos)
|
|
11
|
+
``permissions`` macOS TCC probes with typed ``permission_denied`` errors
|
|
12
|
+
``safety`` protected-app and denied-shortcut lists
|
|
13
|
+
``audit`` append-only ``audit.jsonl`` (0600)
|
|
14
|
+
``helper`` build/invoke the Swift ``nini-cu`` binary (CGEvent + screencapture)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
__version__ = "0.4.4"
|
|
20
|
+
|
|
21
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""``python -m nini_computer_use`` — entrypoint for the MCP server.
|
|
2
|
+
|
|
3
|
+
No arguments: speak MCP over stdio (what ``~/.nini/mcp.json`` starts).
|
|
4
|
+
``--info``: print one JSON object describing helper, permissions, tools and the
|
|
5
|
+
last audit entries (what a human runs when something does not work).
|
|
6
|
+
``--doctor``: same probe with human-readable sentences and a non-zero exit when
|
|
7
|
+
a permission is missing.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .audit import AuditLog
|
|
20
|
+
from .server import McpServer
|
|
21
|
+
from .tools import SERVER_NAME, TOOL_NAMES, ComputerUseService
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
prog="nini-computer-use",
|
|
27
|
+
description="Nini computer-use MCP server (macOS screenshot + input injection)",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument("--version", action="store_true", help="print the version and exit")
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--info", action="store_true", help="print helper/permissions/tools as JSON and exit"
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--doctor", action="store_true", help="human-readable permission check (exit 1 if missing)"
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--no-precompile",
|
|
38
|
+
action="store_true",
|
|
39
|
+
help="do not compile the Swift helper in the background at startup",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument("--verbose", action="store_true", help="extra diagnostics on stderr")
|
|
42
|
+
return parser
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _precompile(service: ComputerUseService) -> None:
|
|
46
|
+
"""Compile the helper eagerly so the first tools/call is not a 15s build."""
|
|
47
|
+
if service.helper.is_mock or service.helper.binary.exists():
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
def work() -> None:
|
|
51
|
+
try:
|
|
52
|
+
service.helper.ensure()
|
|
53
|
+
except Exception as exc: # noqa: BLE001 - reported on first call instead
|
|
54
|
+
print(f"nini-computer-use: helper precompile failed: {exc}", file=sys.stderr)
|
|
55
|
+
|
|
56
|
+
threading.Thread(target=work, name="nini-cu-build", daemon=True).start()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _print_json(payload: Any) -> None:
|
|
60
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _doctor(service: ComputerUseService) -> int:
|
|
64
|
+
info = service.info()
|
|
65
|
+
permissions = info["permissions"]
|
|
66
|
+
print(f"{SERVER_NAME} {__version__}")
|
|
67
|
+
print(f" helper : {info['helper']['path']} (mock={info['helper']['mock']})")
|
|
68
|
+
print(f" audit : {info['audit_path']}")
|
|
69
|
+
print(f" screenshot : {info['screenshot_path']}")
|
|
70
|
+
print(f" tools : {len(TOOL_NAMES)} ({', '.join(TOOL_NAMES)})")
|
|
71
|
+
if not permissions.get("available", True):
|
|
72
|
+
print(f" probe : unavailable ({permissions.get('error')})")
|
|
73
|
+
return 1
|
|
74
|
+
missing = 0
|
|
75
|
+
for key, label in (
|
|
76
|
+
("accessibility", "Accessibility (mouse / keyboard injection)"),
|
|
77
|
+
("screen_recording", "Screen Recording (screenshot, window titles)"),
|
|
78
|
+
):
|
|
79
|
+
granted = bool(permissions.get(key))
|
|
80
|
+
print(f" {label:46s} {'granted' if granted else 'MISSING'}")
|
|
81
|
+
if not granted:
|
|
82
|
+
missing += 1
|
|
83
|
+
|
|
84
|
+
snapshot = service.probe.snapshot()
|
|
85
|
+
host = permissions.get("host") or {}
|
|
86
|
+
host_label = snapshot.host_label()
|
|
87
|
+
if snapshot.has_gui_host():
|
|
88
|
+
print(f" host : TCC attributes to: {host_label} (pid {host.get('pid')})")
|
|
89
|
+
print(" → 在系统设置里给这个 app 授权,不是 nini-cu")
|
|
90
|
+
elif host_label:
|
|
91
|
+
print(f" host : {host_label} (pid {host.get('pid')}) — no GUI identity")
|
|
92
|
+
else:
|
|
93
|
+
print(" host : no GUI app detected in the parent chain")
|
|
94
|
+
|
|
95
|
+
if missing:
|
|
96
|
+
for link in permissions.get("deeplinks", []):
|
|
97
|
+
print(f" grant via : {link}")
|
|
98
|
+
if snapshot.has_gui_host():
|
|
99
|
+
print(f" note : enable it for {host_label}, then restart that app.")
|
|
100
|
+
else:
|
|
101
|
+
print(
|
|
102
|
+
" note : no GUI app to enable — start the service from an "
|
|
103
|
+
"authorized Terminal or Nini app instead."
|
|
104
|
+
)
|
|
105
|
+
return 1
|
|
106
|
+
print(" status : all permissions granted")
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def main(argv: list[str] | None = None) -> int:
|
|
111
|
+
args = _build_parser().parse_args(argv)
|
|
112
|
+
if args.version:
|
|
113
|
+
print(__version__)
|
|
114
|
+
return 0
|
|
115
|
+
|
|
116
|
+
service = ComputerUseService(audit=AuditLog())
|
|
117
|
+
if args.info:
|
|
118
|
+
_print_json(service.info())
|
|
119
|
+
return 0
|
|
120
|
+
if args.doctor:
|
|
121
|
+
return _doctor(service)
|
|
122
|
+
|
|
123
|
+
if not args.no_precompile:
|
|
124
|
+
_precompile(service)
|
|
125
|
+
if args.verbose:
|
|
126
|
+
print(f"{SERVER_NAME} {__version__}: serving MCP over stdio", file=sys.stderr)
|
|
127
|
+
return McpServer(service).serve_forever()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
if __name__ == "__main__": # pragma: no cover
|
|
131
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Append-only audit log for every computer-use call.
|
|
2
|
+
|
|
3
|
+
The log is the only durable trace of an agent touching the user's machine, so
|
|
4
|
+
it is written on *every* outcome (success, validation error, permission denial,
|
|
5
|
+
dangerous-target refusal) and it must never be able to break a call: a failing
|
|
6
|
+
audit write degrades to stderr, never to an exception.
|
|
7
|
+
|
|
8
|
+
Record shape::
|
|
9
|
+
|
|
10
|
+
{"ts": "2026-12-02T18:04:11.412Z", "tool": "type_text",
|
|
11
|
+
"args": {"text": "hello…", "chars": 1200, "truncated": true},
|
|
12
|
+
"ok": false, "code": "dangerous_target", "duration_ms": 41}
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import datetime as dt
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .paths import audit_path, ensure_private_dir
|
|
26
|
+
|
|
27
|
+
SUMMARY_LIMIT = 200
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _now() -> str:
|
|
31
|
+
return dt.datetime.now(dt.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _summarize_value(value: Any) -> Any:
|
|
35
|
+
if isinstance(value, str):
|
|
36
|
+
return value if len(value) <= SUMMARY_LIMIT else value[:SUMMARY_LIMIT] + "…"
|
|
37
|
+
if isinstance(value, dict):
|
|
38
|
+
return {key: _summarize_value(item) for key, item in list(value.items())[:8]}
|
|
39
|
+
if isinstance(value, (list, tuple)):
|
|
40
|
+
return [_summarize_value(item) for item in list(value)[:8]]
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def summarize_arguments(arguments: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
45
|
+
"""Short, secret-free view of the arguments for the log.
|
|
46
|
+
|
|
47
|
+
``text`` is kept as a truncated preview plus its real length, so a reviewer
|
|
48
|
+
can see "a 4 000-character paste" without copying the payload around.
|
|
49
|
+
"""
|
|
50
|
+
if not arguments:
|
|
51
|
+
return {}
|
|
52
|
+
summary: dict[str, Any] = {}
|
|
53
|
+
for key, value in arguments.items():
|
|
54
|
+
if key == "text" and isinstance(value, str):
|
|
55
|
+
entry: dict[str, Any] = {"text": value[:SUMMARY_LIMIT], "chars": len(value)}
|
|
56
|
+
if len(value) > SUMMARY_LIMIT:
|
|
57
|
+
entry["truncated"] = True
|
|
58
|
+
summary[key] = entry
|
|
59
|
+
else:
|
|
60
|
+
summary[key] = _summarize_value(value)
|
|
61
|
+
return summary
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class AuditLog:
|
|
65
|
+
"""Writes NDJSON to ``<state>/audit.jsonl`` with 0600 permissions."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, path: str | Path | None = None) -> None:
|
|
68
|
+
self.path = Path(path) if path is not None else audit_path()
|
|
69
|
+
|
|
70
|
+
def record(
|
|
71
|
+
self,
|
|
72
|
+
tool: str,
|
|
73
|
+
arguments: Mapping[str, Any] | None,
|
|
74
|
+
*,
|
|
75
|
+
ok: bool,
|
|
76
|
+
code: str | None = None,
|
|
77
|
+
duration_ms: int = 0,
|
|
78
|
+
extra: Mapping[str, Any] | None = None,
|
|
79
|
+
) -> dict[str, Any]:
|
|
80
|
+
entry: dict[str, Any] = {
|
|
81
|
+
"ts": _now(),
|
|
82
|
+
"tool": tool,
|
|
83
|
+
"args": summarize_arguments(arguments),
|
|
84
|
+
"ok": bool(ok),
|
|
85
|
+
"duration_ms": int(duration_ms),
|
|
86
|
+
}
|
|
87
|
+
if not ok:
|
|
88
|
+
entry["code"] = code or "error"
|
|
89
|
+
if extra:
|
|
90
|
+
entry["extra"] = dict(extra)
|
|
91
|
+
self._append(entry)
|
|
92
|
+
return entry
|
|
93
|
+
|
|
94
|
+
def _append(self, entry: dict[str, Any]) -> None:
|
|
95
|
+
try:
|
|
96
|
+
ensure_private_dir(self.path.parent)
|
|
97
|
+
line = json.dumps(entry, ensure_ascii=False, separators=(",", ":")) + "\n"
|
|
98
|
+
fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
99
|
+
try:
|
|
100
|
+
# A pre-existing file created by an older build (or by hand) may
|
|
101
|
+
# be group/world readable; tighten it on every append.
|
|
102
|
+
os.fchmod(fd, 0o600)
|
|
103
|
+
os.write(fd, line.encode("utf-8"))
|
|
104
|
+
finally:
|
|
105
|
+
os.close(fd)
|
|
106
|
+
except OSError as exc: # pragma: no cover - disk full / permissions
|
|
107
|
+
print(f"nini-computer-use: audit write failed: {exc}", file=sys.stderr)
|
|
108
|
+
|
|
109
|
+
def tail(self, limit: int = 20) -> list[dict[str, Any]]:
|
|
110
|
+
"""Read back the last ``limit`` entries (used by ``--info`` and tests)."""
|
|
111
|
+
if not self.path.exists():
|
|
112
|
+
return []
|
|
113
|
+
rows: list[dict[str, Any]] = []
|
|
114
|
+
try:
|
|
115
|
+
with self.path.open("r", encoding="utf-8") as handle:
|
|
116
|
+
for line in handle:
|
|
117
|
+
line = line.strip()
|
|
118
|
+
if not line:
|
|
119
|
+
continue
|
|
120
|
+
try:
|
|
121
|
+
payload = json.loads(line)
|
|
122
|
+
except json.JSONDecodeError:
|
|
123
|
+
continue
|
|
124
|
+
if isinstance(payload, dict):
|
|
125
|
+
rows.append(payload)
|
|
126
|
+
except OSError:
|
|
127
|
+
return []
|
|
128
|
+
return rows[-limit:] if limit > 0 else rows
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
__all__ = ["SUMMARY_LIMIT", "AuditLog", "summarize_arguments"]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Structured errors shared by the MCP layer, validators and the helper client.
|
|
2
|
+
|
|
3
|
+
Every error carries a stable machine ``code`` because the caller is a model: it
|
|
4
|
+
needs to distinguish "you passed a bad coordinate" (retry with a better value)
|
|
5
|
+
from "the user has not granted Screen Recording" (stop and ask the human).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
ACCESSIBILITY_DEEPLINK = (
|
|
13
|
+
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
|
|
14
|
+
)
|
|
15
|
+
SCREEN_RECORDING_DEEPLINK = (
|
|
16
|
+
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CuError(Exception):
|
|
21
|
+
"""Base class; ``code`` is stable across releases."""
|
|
22
|
+
|
|
23
|
+
code = "computer_use_error"
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str,
|
|
28
|
+
*,
|
|
29
|
+
code: str | None = None,
|
|
30
|
+
data: dict[str, Any] | None = None,
|
|
31
|
+
deeplinks: list[str] | None = None,
|
|
32
|
+
hint: str | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.message = message
|
|
36
|
+
if code:
|
|
37
|
+
self.code = code
|
|
38
|
+
self.data = dict(data or {})
|
|
39
|
+
self.deeplinks = list(deeplinks or [])
|
|
40
|
+
self.hint = hint
|
|
41
|
+
|
|
42
|
+
def payload(self) -> dict[str, Any]:
|
|
43
|
+
body: dict[str, Any] = {"code": self.code, "message": self.message}
|
|
44
|
+
if self.hint:
|
|
45
|
+
body["hint"] = self.hint
|
|
46
|
+
if self.deeplinks:
|
|
47
|
+
body["deeplinks"] = self.deeplinks
|
|
48
|
+
if self.data:
|
|
49
|
+
body["data"] = self.data
|
|
50
|
+
return body
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class BadArguments(CuError):
|
|
54
|
+
"""The tool arguments are malformed; the model can retry."""
|
|
55
|
+
|
|
56
|
+
code = "bad_arguments"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PermissionDenied(CuError):
|
|
60
|
+
"""macOS TCC has not granted the permission this tool needs."""
|
|
61
|
+
|
|
62
|
+
code = "permission_denied"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class DangerousTarget(CuError):
|
|
66
|
+
"""The action targets an app or shortcut on the deny list."""
|
|
67
|
+
|
|
68
|
+
code = "dangerous_target"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class HelperUnavailable(CuError):
|
|
72
|
+
"""The Swift helper is missing and could not be compiled."""
|
|
73
|
+
|
|
74
|
+
code = "helper_unavailable"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class HelperFailed(CuError):
|
|
78
|
+
"""The helper ran but reported a failure."""
|
|
79
|
+
|
|
80
|
+
code = "helper_failed"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
__all__ = [
|
|
84
|
+
"ACCESSIBILITY_DEEPLINK",
|
|
85
|
+
"SCREEN_RECORDING_DEEPLINK",
|
|
86
|
+
"BadArguments",
|
|
87
|
+
"CuError",
|
|
88
|
+
"DangerousTarget",
|
|
89
|
+
"HelperFailed",
|
|
90
|
+
"HelperUnavailable",
|
|
91
|
+
"PermissionDenied",
|
|
92
|
+
]
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Lifecycle for the compiled Swift helper (``nini-cu``).
|
|
2
|
+
|
|
3
|
+
The helper binary lives in ``~/.nini/computer-use/bin/nini-cu``. It is built
|
|
4
|
+
once from ``native/main.swift`` with ``swiftc`` (Xcode is a hard prerequisite on
|
|
5
|
+
macOS) and rebuilt automatically when the source is newer than the binary.
|
|
6
|
+
|
|
7
|
+
Everything user-facing goes through :meth:`HelperClient.call`, which returns the
|
|
8
|
+
parsed JSON object or raises a typed :class:`~.errors.CuError`. The helper is a
|
|
9
|
+
trusted local binary, but its output is still parsed defensively: a crash or a
|
|
10
|
+
stray ``print`` must not desynchronise the MCP stream.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from collections.abc import Mapping, Sequence
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from . import paths
|
|
27
|
+
from .errors import (
|
|
28
|
+
ACCESSIBILITY_DEEPLINK,
|
|
29
|
+
SCREEN_RECORDING_DEEPLINK,
|
|
30
|
+
BadArguments,
|
|
31
|
+
CuError,
|
|
32
|
+
HelperFailed,
|
|
33
|
+
HelperUnavailable,
|
|
34
|
+
PermissionDenied,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
DEFAULT_TIMEOUT = 30.0
|
|
38
|
+
BUILD_TIMEOUT = 240.0
|
|
39
|
+
_SWIFT_FLAGS = ("-O",)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class HelperClient:
|
|
43
|
+
"""Build, locate and invoke ``nini-cu``."""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
*,
|
|
48
|
+
environ: Mapping[str, str] | None = None,
|
|
49
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
50
|
+
build_timeout: float = BUILD_TIMEOUT,
|
|
51
|
+
) -> None:
|
|
52
|
+
self._explicit_env = environ is not None
|
|
53
|
+
self.environ = paths.environ_of(environ)
|
|
54
|
+
self.timeout = float(timeout)
|
|
55
|
+
self.build_timeout = float(build_timeout)
|
|
56
|
+
self._lock = threading.Lock()
|
|
57
|
+
self._ensured: Path | None = None
|
|
58
|
+
self.build_count = 0
|
|
59
|
+
|
|
60
|
+
def live_env(self) -> dict[str, str]:
|
|
61
|
+
"""Current child environment (live ``os.environ`` + explicit overrides)."""
|
|
62
|
+
env = {} if self._explicit_env else dict(os.environ)
|
|
63
|
+
env.update(self.environ)
|
|
64
|
+
return env
|
|
65
|
+
|
|
66
|
+
# -- discovery ---------------------------------------------------------
|
|
67
|
+
@property
|
|
68
|
+
def binary(self) -> Path:
|
|
69
|
+
return paths.helper_path(self.environ)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def is_mock(self) -> bool:
|
|
73
|
+
"""An explicit ``NINI_CU_HELPER`` bypasses the Swift build entirely."""
|
|
74
|
+
return bool(self.environ.get(paths.HELPER_ENV))
|
|
75
|
+
|
|
76
|
+
def ensure(self) -> Path:
|
|
77
|
+
"""Return a usable helper path, compiling it if needed."""
|
|
78
|
+
target = self.binary
|
|
79
|
+
with self._lock:
|
|
80
|
+
if (
|
|
81
|
+
self._ensured is not None
|
|
82
|
+
and self._ensured == target
|
|
83
|
+
and self._usable(target)
|
|
84
|
+
and not self._stale(target)
|
|
85
|
+
):
|
|
86
|
+
return target
|
|
87
|
+
if self.is_mock:
|
|
88
|
+
if not self._usable(target):
|
|
89
|
+
raise HelperUnavailable(
|
|
90
|
+
f"NINI_CU_HELPER points at {target}, which is missing or not executable",
|
|
91
|
+
hint="unset NINI_CU_HELPER to let the server compile the bundled helper",
|
|
92
|
+
)
|
|
93
|
+
self._ensured = target
|
|
94
|
+
return target
|
|
95
|
+
if self._usable(target) and not self._stale(target):
|
|
96
|
+
self._ensured = target
|
|
97
|
+
return target
|
|
98
|
+
self._build(target)
|
|
99
|
+
self._ensured = target
|
|
100
|
+
return target
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def _usable(path: Path) -> bool:
|
|
104
|
+
return path.is_file() and os.access(path, os.X_OK)
|
|
105
|
+
|
|
106
|
+
def _stale(self, binary: Path) -> bool:
|
|
107
|
+
try:
|
|
108
|
+
source = paths.swift_source(self.environ)
|
|
109
|
+
if not source.is_file():
|
|
110
|
+
return False
|
|
111
|
+
return source.stat().st_mtime > binary.stat().st_mtime
|
|
112
|
+
except OSError: # pragma: no cover - race with a concurrent build
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
def _swiftc(self) -> str:
|
|
116
|
+
configured = self.environ.get(paths.SWIFTC_ENV)
|
|
117
|
+
if configured:
|
|
118
|
+
return configured
|
|
119
|
+
found = shutil.which("swiftc", path=self.environ.get("PATH"))
|
|
120
|
+
if not found:
|
|
121
|
+
raise HelperUnavailable(
|
|
122
|
+
"swiftc not found: building nini-cu needs the Xcode Command Line Tools",
|
|
123
|
+
hint="run `xcode-select --install`, then call again",
|
|
124
|
+
)
|
|
125
|
+
return found
|
|
126
|
+
|
|
127
|
+
def _build(self, target: Path) -> None:
|
|
128
|
+
source = paths.swift_source(self.environ)
|
|
129
|
+
if not source.is_file():
|
|
130
|
+
raise HelperUnavailable(
|
|
131
|
+
f"helper source not found: {source}",
|
|
132
|
+
hint="reinstall nini-computer-use (native/main.swift is missing)",
|
|
133
|
+
)
|
|
134
|
+
compiler = self._swiftc()
|
|
135
|
+
if not self._compiler_usable(compiler):
|
|
136
|
+
raise HelperUnavailable(
|
|
137
|
+
f"swiftc is not runnable: {compiler}",
|
|
138
|
+
hint="run `xcode-select --install`",
|
|
139
|
+
)
|
|
140
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
141
|
+
tmp = target.with_name(target.name + ".tmp")
|
|
142
|
+
started = time.monotonic()
|
|
143
|
+
try:
|
|
144
|
+
proc = subprocess.run( # noqa: S603 - fixed argv, no shell
|
|
145
|
+
[compiler, *_SWIFT_FLAGS, str(source), "-o", str(tmp)],
|
|
146
|
+
capture_output=True,
|
|
147
|
+
text=True,
|
|
148
|
+
timeout=self.build_timeout,
|
|
149
|
+
env=self.environ,
|
|
150
|
+
)
|
|
151
|
+
except subprocess.TimeoutExpired as exc:
|
|
152
|
+
tmp.unlink(missing_ok=True)
|
|
153
|
+
raise HelperUnavailable(
|
|
154
|
+
f"swiftc timed out after {self.build_timeout:.0f}s", code=None
|
|
155
|
+
) from exc
|
|
156
|
+
except OSError as exc:
|
|
157
|
+
raise HelperUnavailable(f"could not run swiftc: {exc}") from exc
|
|
158
|
+
if proc.returncode != 0 or not tmp.is_file():
|
|
159
|
+
tmp.unlink(missing_ok=True)
|
|
160
|
+
tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-6:]
|
|
161
|
+
raise HelperUnavailable(
|
|
162
|
+
"swiftc failed to build the helper",
|
|
163
|
+
data={"returncode": proc.returncode, "stderr": "\n".join(tail)},
|
|
164
|
+
)
|
|
165
|
+
os.chmod(tmp, 0o755)
|
|
166
|
+
os.replace(tmp, target)
|
|
167
|
+
self.build_count += 1
|
|
168
|
+
elapsed = time.monotonic() - started
|
|
169
|
+
print(
|
|
170
|
+
f"nini-computer-use: built {target} in {elapsed:.1f}s",
|
|
171
|
+
file=sys.stderr,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _compiler_usable(self, compiler: str) -> bool:
|
|
175
|
+
if os.path.sep in compiler:
|
|
176
|
+
return os.access(compiler, os.X_OK)
|
|
177
|
+
return True
|
|
178
|
+
|
|
179
|
+
# -- invocation --------------------------------------------------------
|
|
180
|
+
def call(
|
|
181
|
+
self,
|
|
182
|
+
command: str,
|
|
183
|
+
*args: str | int | float,
|
|
184
|
+
timeout: float | None = None,
|
|
185
|
+
env: Mapping[str, str] | None = None,
|
|
186
|
+
) -> dict[str, Any]:
|
|
187
|
+
binary = self.ensure()
|
|
188
|
+
argv = [str(binary), command, *(str(item) for item in args)]
|
|
189
|
+
# Inherit the *live* environment so late changes (NINI_* exported by a
|
|
190
|
+
# host, FAKE_HELPER_* in tests) reach the child; explicit overrides win.
|
|
191
|
+
child_env = self.live_env()
|
|
192
|
+
if env:
|
|
193
|
+
child_env.update({str(key): str(value) for key, value in env.items()})
|
|
194
|
+
try:
|
|
195
|
+
proc = subprocess.run( # noqa: S603 - fixed argv, no shell
|
|
196
|
+
argv,
|
|
197
|
+
capture_output=True,
|
|
198
|
+
text=True,
|
|
199
|
+
timeout=self.timeout if timeout is None else float(timeout),
|
|
200
|
+
env=child_env,
|
|
201
|
+
)
|
|
202
|
+
except FileNotFoundError as exc:
|
|
203
|
+
raise HelperUnavailable(f"helper disappeared: {binary}") from exc
|
|
204
|
+
except subprocess.TimeoutExpired as exc:
|
|
205
|
+
raise HelperFailed(
|
|
206
|
+
f"{command} timed out after {self.timeout:.0f}s", code="helper_timeout"
|
|
207
|
+
) from exc
|
|
208
|
+
except OSError as exc:
|
|
209
|
+
raise HelperUnavailable(f"could not run {binary}: {exc}") from exc
|
|
210
|
+
|
|
211
|
+
payload = parse_payload(proc.stdout)
|
|
212
|
+
if payload is None:
|
|
213
|
+
stderr = (proc.stderr or "").strip().splitlines()[-4:]
|
|
214
|
+
raise HelperFailed(
|
|
215
|
+
f"{command} produced no JSON (exit {proc.returncode})",
|
|
216
|
+
data={"returncode": proc.returncode, "stderr": "\n".join(stderr)},
|
|
217
|
+
)
|
|
218
|
+
if payload.get("ok") is False:
|
|
219
|
+
raise translate_error(payload, exit_code=proc.returncode)
|
|
220
|
+
if proc.returncode != 0:
|
|
221
|
+
raise HelperFailed(
|
|
222
|
+
f"{command} exited {proc.returncode} after reporting success",
|
|
223
|
+
data={"returncode": proc.returncode},
|
|
224
|
+
)
|
|
225
|
+
return payload
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def parse_payload(stdout: str | None) -> dict[str, Any] | None:
|
|
229
|
+
"""Return the last JSON object printed on stdout (helper diagnostics may precede)."""
|
|
230
|
+
if not stdout:
|
|
231
|
+
return None
|
|
232
|
+
for line in reversed(stdout.splitlines()):
|
|
233
|
+
line = line.strip()
|
|
234
|
+
if not line or line[0] != "{":
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
payload = json.loads(line)
|
|
238
|
+
except json.JSONDecodeError:
|
|
239
|
+
continue
|
|
240
|
+
if isinstance(payload, dict):
|
|
241
|
+
return payload
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def translate_error(payload: Mapping[str, Any], *, exit_code: int | None = None) -> CuError:
|
|
246
|
+
"""Map the helper's ``{"ok": false, "error": {...}}`` to a typed error."""
|
|
247
|
+
raw = payload.get("error")
|
|
248
|
+
error = dict(raw) if isinstance(raw, Mapping) else {}
|
|
249
|
+
code = str(error.get("code") or "helper_failed")
|
|
250
|
+
message = str(error.get("message") or "helper reported an error")
|
|
251
|
+
if code == "permission_denied":
|
|
252
|
+
return PermissionDenied(
|
|
253
|
+
message,
|
|
254
|
+
data={"exit_code": exit_code} if exit_code is not None else None,
|
|
255
|
+
deeplinks=[ACCESSIBILITY_DEEPLINK, SCREEN_RECORDING_DEEPLINK],
|
|
256
|
+
hint="grant the permission in System Settings, then restart the MCP host",
|
|
257
|
+
)
|
|
258
|
+
if code == "bad_arguments":
|
|
259
|
+
return BadArguments(message)
|
|
260
|
+
return HelperFailed(message, code=code, data={"exit_code": exit_code})
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def run_sequence(
|
|
264
|
+
helper: HelperClient, calls: Sequence[tuple[str, Sequence[str | int | float]]]
|
|
265
|
+
) -> None:
|
|
266
|
+
"""Small helper used by ``--smoke``; kept here so tests can exercise it."""
|
|
267
|
+
for command, args in calls:
|
|
268
|
+
helper.call(command, *args)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
__all__ = ["BUILD_TIMEOUT", "DEFAULT_TIMEOUT", "HelperClient", "parse_payload", "translate_error"]
|