dsh-plugin-linux-computer-use 0.0.0-stage → 0.1.0
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 +28 -0
- package/LICENSE +21 -0
- package/README.md +124 -2
- package/cordis.patch.yml +35 -0
- package/docs/DETAIL.md +118 -0
- package/docs/preview.svg +27 -0
- package/icon.svg +9 -0
- package/index.js +332 -0
- package/linux-computer-use-prep.sh +281 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +61 -4
- package/server/cu_a11y.py +452 -0
- package/server/cu_display.py +523 -0
- package/server/cu_input.py +528 -0
- package/server/cu_sys.py +232 -0
- package/server/cu_unlock.py +280 -0
- package/server/linux_desktop_mcp.py +1362 -0
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""linux-desktop-mcp: a stdio MCP server that drives a Wayland GNOME desktop.
|
|
3
|
+
|
|
4
|
+
The server speaks newline-delimited JSON-RPC 2.0 on stdin/stdout (the MCP stdio
|
|
5
|
+
transport) and exposes the tools DSH publishes as ``mcp__linux__*``:
|
|
6
|
+
|
|
7
|
+
vision screenshot portal Screenshot -> PNG
|
|
8
|
+
tree ui_apps, ui_tree, ui_find, ui_describe, ui_text
|
|
9
|
+
action ui_action, ui_focus, ui_set_text
|
|
10
|
+
pointer click, move, drag, scroll, pointer_button
|
|
11
|
+
keyboard key, type_text
|
|
12
|
+
system clipboard_get, clipboard_set, process_list, process_kill,
|
|
13
|
+
launch_app, settings_get, settings_set, settings_list_keys,
|
|
14
|
+
notify, window_list, display_info, desktop_status
|
|
15
|
+
|
|
16
|
+
Design notes that matter when editing this file:
|
|
17
|
+
|
|
18
|
+
* stdout is protocol-only. Every diagnostic goes to stderr or the log file.
|
|
19
|
+
* Input injection goes through /dev/uinput (see cu_input.py): it needs the udev
|
|
20
|
+
rule from the prep script and a re-login. When it is unavailable the tools
|
|
21
|
+
fail with an actionable message instead of silently doing nothing.
|
|
22
|
+
* Screenshots go through the portal Screenshot interface: GNOME asks once and
|
|
23
|
+
then remembers the answer, so repeated captures are silent (~0.5s each). The
|
|
24
|
+
ScreenCast session in cu_display.py is only a fallback behind
|
|
25
|
+
DSH_LINUX_CU_SCREENCAST=1.
|
|
26
|
+
* Coordinates are logical desktop pixels. ``space="screenshot"`` converts from
|
|
27
|
+
the pixels of the most recent screenshot, which differ on HiDPI setups.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import base64
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import sys
|
|
36
|
+
import time
|
|
37
|
+
import traceback
|
|
38
|
+
|
|
39
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
40
|
+
|
|
41
|
+
import cu_a11y # noqa: E402
|
|
42
|
+
import cu_display # noqa: E402
|
|
43
|
+
import cu_input # noqa: E402
|
|
44
|
+
import cu_sys # noqa: E402
|
|
45
|
+
import cu_unlock # noqa: E402
|
|
46
|
+
|
|
47
|
+
SERVER_NAME = "linux-desktop-mcp"
|
|
48
|
+
SERVER_VERSION = "1.0.0"
|
|
49
|
+
PROTOCOL_VERSION = "2025-06-18"
|
|
50
|
+
SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
|
|
51
|
+
LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
|
|
52
|
+
MAX_IMAGE_BYTES = 3_500_000
|
|
53
|
+
SHOT_MAX_WIDTH = 1600
|
|
54
|
+
|
|
55
|
+
A11Y = cu_a11y.A11y()
|
|
56
|
+
INPUT: cu_input.InputController | None = None
|
|
57
|
+
LAST_SHOT: dict = {"path": None, "width": 0, "height": 0, "logical": None, "at": 0.0}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
BUTTON_NAMES = {1: "left", 2: "middle", 3: "right"}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _button_name(value) -> str:
|
|
64
|
+
try:
|
|
65
|
+
number = int(value)
|
|
66
|
+
except (TypeError, ValueError):
|
|
67
|
+
raise ToolError("button must be 1 (left), 2 (middle) or 3 (right)") from None
|
|
68
|
+
name = BUTTON_NAMES.get(number)
|
|
69
|
+
if name is None:
|
|
70
|
+
raise ToolError("button must be 1 (left), 2 (middle) or 3 (right)")
|
|
71
|
+
return name
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ToolError(RuntimeError):
|
|
75
|
+
"""A tool-level failure with a message meant for the model."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def log(message: str) -> None:
|
|
79
|
+
line = f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {message}\n"
|
|
80
|
+
try:
|
|
81
|
+
os.makedirs(cu_display.CACHE_DIR, exist_ok=True)
|
|
82
|
+
with open(LOG_PATH, "a", encoding="utf-8") as handle:
|
|
83
|
+
handle.write(line)
|
|
84
|
+
if os.path.getsize(LOG_PATH) > 1_000_000:
|
|
85
|
+
os.replace(LOG_PATH, LOG_PATH + ".1")
|
|
86
|
+
except OSError:
|
|
87
|
+
pass
|
|
88
|
+
sys.stderr.write(line)
|
|
89
|
+
sys.stderr.flush()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# --------------------------------------------------------------------------- #
|
|
93
|
+
# shared helpers
|
|
94
|
+
# --------------------------------------------------------------------------- #
|
|
95
|
+
def layout() -> cu_display.Layout:
|
|
96
|
+
return cu_display.read_layout()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def controller(reload_layout: bool = False) -> cu_input.InputController:
|
|
100
|
+
global INPUT
|
|
101
|
+
current = layout()
|
|
102
|
+
if INPUT is None or reload_layout or INPUT.layout.serial != current.serial:
|
|
103
|
+
if INPUT is not None:
|
|
104
|
+
INPUT.close()
|
|
105
|
+
INPUT = cu_input.InputController(current)
|
|
106
|
+
return INPUT
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _guard_input(what: str) -> None:
|
|
110
|
+
"""Refuse to inject input while the session is locked.
|
|
111
|
+
|
|
112
|
+
A locked GNOME session keeps the password field focused, so a stray click
|
|
113
|
+
or keystroke lands inside it. Screenshots stay allowed; only input is
|
|
114
|
+
blocked. ``DSH_LINUX_CU_ALLOW_LOCKED_INPUT=1`` is the escape hatch for
|
|
115
|
+
someone who really knows what they are doing.
|
|
116
|
+
"""
|
|
117
|
+
if os.environ.get("DSH_LINUX_CU_ALLOW_LOCKED_INPUT") == "1":
|
|
118
|
+
return
|
|
119
|
+
if cu_sys.screen_locked() is True:
|
|
120
|
+
if cu_unlock.unlock_enabled():
|
|
121
|
+
hint = "unlock_screen is available because the user turned AI unlocking on."
|
|
122
|
+
else:
|
|
123
|
+
hint = (
|
|
124
|
+
"Unlock the desktop and retry; the user can also switch AI unlocking "
|
|
125
|
+
"on (unlock policy) to let this be handled here."
|
|
126
|
+
)
|
|
127
|
+
raise ToolError(
|
|
128
|
+
f"refusing to {what}: the session is locked. The lock screen's focused "
|
|
129
|
+
f"widget is the password field, so injected input would type into it. "
|
|
130
|
+
f"{hint} mcp__linux__screenshot still works."
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _to_logical(x: float, y: float, space: str) -> tuple[float, float]:
|
|
135
|
+
if space == "screenshot":
|
|
136
|
+
shot_w = LAST_SHOT.get("width") or 0
|
|
137
|
+
logical = LAST_SHOT.get("logical") or None
|
|
138
|
+
if not shot_w or not logical:
|
|
139
|
+
raise ToolError("no screenshot yet: take one first, or pass space='logical'")
|
|
140
|
+
ratio = (logical[0] / shot_w) if shot_w else 1.0
|
|
141
|
+
return (x * ratio, y * ratio)
|
|
142
|
+
return (x, y)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
|
|
146
|
+
"""Grab the desktop, preferring the screenshot portal over a pipewire stream.
|
|
147
|
+
|
|
148
|
+
The portal Screenshot interface is a single round trip (~0.5s) and needs no
|
|
149
|
+
long-lived session, so it is the default. The ScreenCast + GStreamer path
|
|
150
|
+
stays as a fallback because it is the only one that can stream frames when
|
|
151
|
+
capture permission exists but the screenshot interface is missing.
|
|
152
|
+
"""
|
|
153
|
+
name = f"shot-{time.strftime('%Y%m%d-%H%M%S')}-{int(time.time() * 1000) % 1000:03d}.png"
|
|
154
|
+
path = os.path.join(cu_display.SHOT_DIR, name)
|
|
155
|
+
method = ""
|
|
156
|
+
screenshot_error: Exception | None = None
|
|
157
|
+
|
|
158
|
+
if os.environ.get("DSH_LINUX_CU_SCREENCAST") != "1":
|
|
159
|
+
try:
|
|
160
|
+
cu_display.portal_screenshot(path)
|
|
161
|
+
method = "portal-screenshot"
|
|
162
|
+
except cu_display.PortalError as error:
|
|
163
|
+
screenshot_error = error
|
|
164
|
+
|
|
165
|
+
if not method:
|
|
166
|
+
session = cu_display.ScreencastSession.shared()
|
|
167
|
+
try:
|
|
168
|
+
session.ensure()
|
|
169
|
+
cu_display.capture_frame(session, path)
|
|
170
|
+
method = "portal-screencast"
|
|
171
|
+
except cu_display.PortalError as error:
|
|
172
|
+
session.close()
|
|
173
|
+
detail = f" (the screenshot portal said: {screenshot_error})" if screenshot_error else ""
|
|
174
|
+
raise ToolError(
|
|
175
|
+
f"screen capture is unavailable: {error}{detail}. "
|
|
176
|
+
"Grant screen sharing once when the desktop asks, then retry; "
|
|
177
|
+
"run linux_mcp_doctor to see the current state."
|
|
178
|
+
) from error
|
|
179
|
+
|
|
180
|
+
width, height = cu_display.downscale(path, max_width)
|
|
181
|
+
current = layout()
|
|
182
|
+
LAST_SHOT.update({
|
|
183
|
+
"path": path,
|
|
184
|
+
"width": width,
|
|
185
|
+
"height": height,
|
|
186
|
+
"logical": (current.width, current.height),
|
|
187
|
+
"at": time.time(),
|
|
188
|
+
})
|
|
189
|
+
return {
|
|
190
|
+
"path": path,
|
|
191
|
+
"width": width,
|
|
192
|
+
"height": height,
|
|
193
|
+
"logical_width": current.width,
|
|
194
|
+
"logical_height": current.height,
|
|
195
|
+
"coordinate_scale": round(current.width / width, 6) if width else 1.0,
|
|
196
|
+
"captured_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
197
|
+
"method": method,
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# --------------------------------------------------------------------------- #
|
|
202
|
+
# tool implementations
|
|
203
|
+
# --------------------------------------------------------------------------- #
|
|
204
|
+
def tool_screenshot(args: dict) -> dict:
|
|
205
|
+
max_width = int(args.get("max_width", SHOT_MAX_WIDTH))
|
|
206
|
+
info = capture_shot(max_width)
|
|
207
|
+
try:
|
|
208
|
+
with open(info["path"], "rb") as handle:
|
|
209
|
+
payload = handle.read()
|
|
210
|
+
except OSError as error:
|
|
211
|
+
raise ToolError(f"captured frame is not readable: {error}") from error
|
|
212
|
+
if len(payload) > MAX_IMAGE_BYTES:
|
|
213
|
+
cu_display.downscale(info["path"], max(640, int(info["width"] * 0.6)))
|
|
214
|
+
with open(info["path"], "rb") as handle:
|
|
215
|
+
payload = handle.read()
|
|
216
|
+
width, height = cu_display.png_size(info["path"])
|
|
217
|
+
info["width"], info["height"] = width, height
|
|
218
|
+
info["coordinate_scale"] = round(info["logical_width"] / width, 6) if width else 1.0
|
|
219
|
+
encoded = base64.b64encode(payload).decode("ascii")
|
|
220
|
+
note = (
|
|
221
|
+
f"screenshot {info['width']}x{info['height']} px saved at {info['path']}; "
|
|
222
|
+
f"logical desktop is {info['logical_width']}x{info['logical_height']}. "
|
|
223
|
+
f"To click at a pixel of this image pass space='screenshot'; "
|
|
224
|
+
f"otherwise multiply by {info['coordinate_scale']}."
|
|
225
|
+
)
|
|
226
|
+
return {
|
|
227
|
+
"content": [
|
|
228
|
+
{"type": "image", "data": encoded, "mimeType": "image/png"},
|
|
229
|
+
{"type": "text", "text": json.dumps({**info, "note": note}, ensure_ascii=False)},
|
|
230
|
+
]
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def tool_ui_apps(args: dict) -> dict:
|
|
235
|
+
apps = A11Y.apps()
|
|
236
|
+
return {"applications": apps, "count": len(apps)}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def tool_ui_tree(args: dict) -> dict:
|
|
240
|
+
app = args.get("app")
|
|
241
|
+
depth = max(1, min(int(args.get("max_depth", 3)), 8))
|
|
242
|
+
nodes = max(10, min(int(args.get("max_nodes", 220)), 1200))
|
|
243
|
+
snapshot = A11Y.snapshot(app=app, max_depth=depth, max_nodes=nodes)
|
|
244
|
+
if snapshot["nodes_used"] <= 3 and snapshot["applications"]:
|
|
245
|
+
snapshot["hint"] = (
|
|
246
|
+
"the application exposes (almost) no accessibility nodes: Chromium, "
|
|
247
|
+
"Electron and Qt apps stay dark unless started with accessibility on. "
|
|
248
|
+
"Use screenshot + coordinate clicks for that app instead."
|
|
249
|
+
)
|
|
250
|
+
return snapshot
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def tool_ui_find(args: dict) -> dict:
|
|
254
|
+
hits = A11Y.find(
|
|
255
|
+
query=args.get("query"),
|
|
256
|
+
role=args.get("role"),
|
|
257
|
+
app=args.get("app"),
|
|
258
|
+
limit=max(1, min(int(args.get("limit", 20)), 100)),
|
|
259
|
+
)
|
|
260
|
+
return {"matches": hits, "count": len(hits)}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def tool_ui_describe(args: dict) -> dict:
|
|
264
|
+
ref = _require(args, "ref")
|
|
265
|
+
return A11Y.describe(ref)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def tool_ui_text(args: dict) -> dict:
|
|
269
|
+
ref = _require(args, "ref")
|
|
270
|
+
return A11Y.text(ref)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def tool_ui_action(args: dict) -> dict:
|
|
274
|
+
_guard_input("tool_ui_action")
|
|
275
|
+
ref = _require(args, "ref")
|
|
276
|
+
action = args.get("action")
|
|
277
|
+
return A11Y.action(ref, action)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def tool_ui_focus(args: dict) -> dict:
|
|
281
|
+
_guard_input("tool_ui_focus")
|
|
282
|
+
ref = _require(args, "ref")
|
|
283
|
+
return A11Y.focus(ref)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def tool_ui_set_text(args: dict) -> dict:
|
|
287
|
+
_guard_input("tool_ui_set_text")
|
|
288
|
+
ref = _require(args, "ref")
|
|
289
|
+
text = args.get("text")
|
|
290
|
+
if not isinstance(text, str):
|
|
291
|
+
raise ToolError("'text' must be a string")
|
|
292
|
+
return A11Y.set_text(ref, text)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def tool_click(args: dict) -> dict:
|
|
296
|
+
_guard_input("click")
|
|
297
|
+
x, y = _point(args)
|
|
298
|
+
x, y = _to_logical(x, y, str(args.get("space", "logical")))
|
|
299
|
+
button = _button_name(args.get("button", 1))
|
|
300
|
+
count = max(1, min(int(args.get("count", 1)), 3))
|
|
301
|
+
controller().click(x, y, button=button, count=count)
|
|
302
|
+
return {"clicked": {"x": round(x), "y": round(y), "button": button, "count": count}}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def tool_move(args: dict) -> dict:
|
|
306
|
+
_guard_input("move the pointer")
|
|
307
|
+
x, y = _point(args)
|
|
308
|
+
x, y = _to_logical(x, y, str(args.get("space", "logical")))
|
|
309
|
+
controller().move(x, y)
|
|
310
|
+
return {"moved_to": {"x": round(x), "y": round(y)}}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def tool_drag(args: dict) -> dict:
|
|
314
|
+
_guard_input("drag")
|
|
315
|
+
start = (float(args.get("x1", 0)), float(args.get("y1", 0)))
|
|
316
|
+
end = (float(args.get("x2", 0)), float(args.get("y2", 0)))
|
|
317
|
+
space = str(args.get("space", "logical"))
|
|
318
|
+
start = _to_logical(*start, space)
|
|
319
|
+
end = _to_logical(*end, space)
|
|
320
|
+
duration = max(100, min(int(args.get("duration_ms", 450)), 5000))
|
|
321
|
+
controller().drag(start[0], start[1], end[0], end[1], duration_ms=duration)
|
|
322
|
+
return {"dragged": {"from": [round(v) for v in start], "to": [round(v) for v in end]}}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def tool_scroll(args: dict) -> dict:
|
|
326
|
+
_guard_input("scroll")
|
|
327
|
+
dx = int(args.get("dx", 0))
|
|
328
|
+
dy = int(args.get("dy", 0))
|
|
329
|
+
if not dx and not dy:
|
|
330
|
+
raise ToolError("pass a non-zero dx and/or dy (positive dy scrolls down)")
|
|
331
|
+
controller().scroll(dx=dx, dy=dy)
|
|
332
|
+
return {"scrolled": {"dx": dx, "dy": dy}}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def tool_pointer_button(args: dict) -> dict:
|
|
336
|
+
_guard_input("press a mouse button")
|
|
337
|
+
action = str(args.get("action", "press")).lower()
|
|
338
|
+
button = _button_name(args.get("button", 1))
|
|
339
|
+
if args.get("x") is not None and args.get("y") is not None:
|
|
340
|
+
x, y = _to_logical(float(args["x"]), float(args["y"]), str(args.get("space", "logical")))
|
|
341
|
+
controller().move(x, y)
|
|
342
|
+
if action == "press":
|
|
343
|
+
controller().press_hold(button)
|
|
344
|
+
elif action == "release":
|
|
345
|
+
controller().release_hold(button)
|
|
346
|
+
else:
|
|
347
|
+
raise ToolError("action must be 'press' or 'release'")
|
|
348
|
+
return {"button": button, "action": action}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def tool_key(args: dict) -> dict:
|
|
352
|
+
_guard_input("press a key")
|
|
353
|
+
combo = _require(args, "combo")
|
|
354
|
+
controller().key(str(combo))
|
|
355
|
+
return {"pressed": combo}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def tool_type_text(args: dict) -> dict:
|
|
359
|
+
_guard_input("type text")
|
|
360
|
+
text = _require(args, "text")
|
|
361
|
+
controller().type_text(str(text))
|
|
362
|
+
return {"typed": len(str(text))}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def tool_clipboard_get(args: dict) -> dict:
|
|
366
|
+
return cu_sys.clipboard_get()
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def tool_clipboard_set(args: dict) -> dict:
|
|
370
|
+
text = _require(args, "text")
|
|
371
|
+
return cu_sys.clipboard_set(str(text))
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def tool_process_list(args: dict) -> dict:
|
|
375
|
+
rows = cu_sys.process_list(
|
|
376
|
+
limit=max(1, min(int(args.get("limit", 25)), 200)),
|
|
377
|
+
sort=str(args.get("sort", "cpu")),
|
|
378
|
+
name_filter=args.get("name"),
|
|
379
|
+
)
|
|
380
|
+
return {"processes": rows, "count": len(rows)}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def tool_process_kill(args: dict) -> dict:
|
|
384
|
+
pid = int(args.get("pid", 0))
|
|
385
|
+
return cu_sys.process_kill(pid, str(args.get("signal", "TERM")))
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def tool_launch_app(args: dict) -> dict:
|
|
389
|
+
command = args.get("command")
|
|
390
|
+
if isinstance(command, list):
|
|
391
|
+
result = cu_sys.launch([str(part) for part in command])
|
|
392
|
+
elif isinstance(command, str) and command.strip():
|
|
393
|
+
result = cu_sys.launch(command)
|
|
394
|
+
else:
|
|
395
|
+
raise ToolError("'command' must be a string or a list of arguments")
|
|
396
|
+
time.sleep(0.4)
|
|
397
|
+
return result
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def tool_settings_get(args: dict) -> dict:
|
|
401
|
+
return cu_sys.settings_get(_require(args, "schema"), _require(args, "key"))
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def tool_settings_set(args: dict) -> dict:
|
|
405
|
+
return cu_sys.settings_set(
|
|
406
|
+
_require(args, "schema"), _require(args, "key"), _require(args, "value")
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def tool_settings_list_keys(args: dict) -> dict:
|
|
411
|
+
keys = cu_sys.settings_list_keys(_require(args, "schema"))
|
|
412
|
+
return {"schema": args["schema"], "keys": keys, "count": len(keys)}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def tool_notify(args: dict) -> dict:
|
|
416
|
+
return cu_sys.notify(
|
|
417
|
+
_require(args, "summary"),
|
|
418
|
+
str(args.get("body", "")),
|
|
419
|
+
int(args.get("timeout_ms", 8000)),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def tool_window_list(args: dict) -> dict:
|
|
424
|
+
windows = []
|
|
425
|
+
for app in A11Y.apps(max_age=2.0):
|
|
426
|
+
try:
|
|
427
|
+
node = A11Y.describe(app["ref"])
|
|
428
|
+
except cu_a11y.A11yError:
|
|
429
|
+
continue
|
|
430
|
+
target = _first_frame(A11Y.resolve(app["ref"]))
|
|
431
|
+
if target is None:
|
|
432
|
+
windows.append({"app": app["name"], "title": "", "ref": app["ref"], "pid": app["pid"]})
|
|
433
|
+
continue
|
|
434
|
+
title, states = target
|
|
435
|
+
windows.append({
|
|
436
|
+
"app": app["name"],
|
|
437
|
+
"title": title,
|
|
438
|
+
"ref": app["ref"],
|
|
439
|
+
"pid": app["pid"],
|
|
440
|
+
"active": "active" in states or "focused" in states,
|
|
441
|
+
})
|
|
442
|
+
del node
|
|
443
|
+
return {"windows": windows, "count": len(windows)}
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _first_frame(app):
|
|
447
|
+
try:
|
|
448
|
+
count = app.get_child_count()
|
|
449
|
+
except Exception: # noqa: BLE001
|
|
450
|
+
return None
|
|
451
|
+
for index in range(min(count, 4)):
|
|
452
|
+
try:
|
|
453
|
+
child = app.get_child_at_index(index)
|
|
454
|
+
if child is None:
|
|
455
|
+
continue
|
|
456
|
+
if (child.get_role_name() or "") == "frame":
|
|
457
|
+
return (child.get_name() or "", cu_a11y._state_names(child))
|
|
458
|
+
except Exception: # noqa: BLE001
|
|
459
|
+
continue
|
|
460
|
+
return None
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def tool_display_info(args: dict) -> dict:
|
|
464
|
+
current = layout()
|
|
465
|
+
info = current.describe()
|
|
466
|
+
info["session"] = {
|
|
467
|
+
"type": os.environ.get("XDG_SESSION_TYPE", ""),
|
|
468
|
+
"desktop": os.environ.get("XDG_CURRENT_DESKTOP", ""),
|
|
469
|
+
"wayland_display": os.environ.get("WAYLAND_DISPLAY", ""),
|
|
470
|
+
"display": os.environ.get("DISPLAY", ""),
|
|
471
|
+
}
|
|
472
|
+
info["last_screenshot"] = {key: LAST_SHOT[key] for key in ("path", "width", "height", "at")}
|
|
473
|
+
return info
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def tool_desktop_status(args: dict) -> dict:
|
|
477
|
+
status: dict = {"server": {"name": SERVER_NAME, "version": SERVER_VERSION, "log": LOG_PATH}}
|
|
478
|
+
status["session"] = {
|
|
479
|
+
"type": os.environ.get("XDG_SESSION_TYPE", ""),
|
|
480
|
+
"desktop": os.environ.get("XDG_CURRENT_DESKTOP", ""),
|
|
481
|
+
"locked": cu_sys.screen_locked(),
|
|
482
|
+
"unlock": cu_unlock.status(),
|
|
483
|
+
}
|
|
484
|
+
try:
|
|
485
|
+
current = layout()
|
|
486
|
+
status["display"] = current.describe()
|
|
487
|
+
except cu_display.PortalError as error:
|
|
488
|
+
status["display"] = {"error": str(error)}
|
|
489
|
+
try:
|
|
490
|
+
backend = controller().backend_name
|
|
491
|
+
status["input"] = {"backend": backend, "ready": True}
|
|
492
|
+
except Exception as error: # noqa: BLE001
|
|
493
|
+
status["input"] = {"ready": False, "error": str(error)}
|
|
494
|
+
token = cu_display.ScreencastSession.load_token()
|
|
495
|
+
status["capture"] = {
|
|
496
|
+
"preferred": "portal-screenshot",
|
|
497
|
+
"shots_dir": cu_display.SHOT_DIR,
|
|
498
|
+
"portal_screenshot": True,
|
|
499
|
+
"portal_screencast": True,
|
|
500
|
+
"screencast_restore_token": bool(token),
|
|
501
|
+
"screencast_session_open": cu_display.ScreencastSession.shared().fd is not None,
|
|
502
|
+
"gstreamer_pipewiresrc": _have_gst("pipewiresrc"),
|
|
503
|
+
}
|
|
504
|
+
try:
|
|
505
|
+
apps = A11Y.apps(max_age=10.0)
|
|
506
|
+
status["a11y"] = {"apps_visible": len(apps)}
|
|
507
|
+
except cu_a11y.A11yError as error:
|
|
508
|
+
status["a11y"] = {"error": str(error)}
|
|
509
|
+
status["system"] = {
|
|
510
|
+
"wl_clipboard": cu_sys.clipboard_available(),
|
|
511
|
+
"notify_send": cu_sys.have("notify-send"),
|
|
512
|
+
"gsettings": cu_sys.have("gsettings"),
|
|
513
|
+
"uinput_writable": os.access("/dev/uinput", os.W_OK),
|
|
514
|
+
}
|
|
515
|
+
return status
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _have_gst(element_name: str) -> bool:
|
|
519
|
+
try:
|
|
520
|
+
gi = __import__("gi")
|
|
521
|
+
gi.require_version("Gst", "1.0")
|
|
522
|
+
from gi.repository import Gst
|
|
523
|
+
|
|
524
|
+
if not Gst.is_initialized():
|
|
525
|
+
Gst.init(None)
|
|
526
|
+
return Gst.ElementFactory.find(element_name) is not None
|
|
527
|
+
except Exception: # noqa: BLE001
|
|
528
|
+
return False
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _require(args: dict, key: str) -> object:
|
|
532
|
+
value = args.get(key)
|
|
533
|
+
if value is None or value == "":
|
|
534
|
+
raise ToolError(f"missing required argument {key!r}")
|
|
535
|
+
return value
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _point(args: dict) -> tuple[float, float]:
|
|
539
|
+
if args.get("x") is None or args.get("y") is None:
|
|
540
|
+
raise ToolError("both 'x' and 'y' are required")
|
|
541
|
+
return (float(args["x"]), float(args["y"]))
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
# --------------------------------------------------------------------------- #
|
|
545
|
+
# tool registry
|
|
546
|
+
# --------------------------------------------------------------------------- #
|
|
547
|
+
SPACE_PROP = {
|
|
548
|
+
"type": "string",
|
|
549
|
+
"enum": ["logical", "screenshot"],
|
|
550
|
+
"default": "logical",
|
|
551
|
+
"description": "Coordinate space: 'logical' desktop pixels, or 'screenshot' pixels of the last screenshot.",
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
def tool_unlock_screen(args: dict) -> dict:
|
|
555
|
+
confirm = str(args.get("confirm") or "").strip().lower()
|
|
556
|
+
if confirm != "unlock":
|
|
557
|
+
raise ToolError(
|
|
558
|
+
"unlock_screen requires confirm='unlock'. It types your stored password into the "
|
|
559
|
+
"lock screen, so only call it when the user explicitly asked you to unlock now."
|
|
560
|
+
)
|
|
561
|
+
result = cu_unlock.unlock(controller())
|
|
562
|
+
log(
|
|
563
|
+
"unlock_screen: unlocked={} attempts={}".format(
|
|
564
|
+
result.get("unlocked"), result.get("attempts")
|
|
565
|
+
)
|
|
566
|
+
)
|
|
567
|
+
return result
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
TOOLS: list[dict] = [
|
|
571
|
+
{
|
|
572
|
+
"name": "screenshot",
|
|
573
|
+
"description": (
|
|
574
|
+
"Capture the whole desktop and return it as a PNG image plus its size and path. "
|
|
575
|
+
"Use it to see the screen before deciding where to click. The desktop asks for a "
|
|
576
|
+
"one-time screen-capture approval; after that every capture is silent and takes "
|
|
577
|
+
"about half a second."
|
|
578
|
+
),
|
|
579
|
+
"inputSchema": {
|
|
580
|
+
"type": "object",
|
|
581
|
+
"properties": {
|
|
582
|
+
"max_width": {
|
|
583
|
+
"type": "integer",
|
|
584
|
+
"default": SHOT_MAX_WIDTH,
|
|
585
|
+
"description": "Downscale the image to this pixel width (0 keeps native resolution).",
|
|
586
|
+
}
|
|
587
|
+
},
|
|
588
|
+
},
|
|
589
|
+
"handler": tool_screenshot,
|
|
590
|
+
},
|
|
591
|
+
{
|
|
592
|
+
"name": "ui_apps",
|
|
593
|
+
"description": (
|
|
594
|
+
"List the applications currently exposed through the AT-SPI accessibility bus, with "
|
|
595
|
+
"element references usable by ui_tree/ui_find/ui_action."
|
|
596
|
+
),
|
|
597
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
598
|
+
"handler": tool_ui_apps,
|
|
599
|
+
},
|
|
600
|
+
{
|
|
601
|
+
"name": "ui_tree",
|
|
602
|
+
"description": (
|
|
603
|
+
"Read the accessibility tree of one application (or a few) as nested role/name/rect/"
|
|
604
|
+
"action nodes. Bounded by max_depth and max_nodes. Chromium/Electron/Qt apps usually "
|
|
605
|
+
"expose almost nothing; use screenshot for those."
|
|
606
|
+
),
|
|
607
|
+
"inputSchema": {
|
|
608
|
+
"type": "object",
|
|
609
|
+
"properties": {
|
|
610
|
+
"app": {"type": "string", "description": "Application name as shown by ui_apps (substring match)."},
|
|
611
|
+
"max_depth": {"type": "integer", "default": 3, "minimum": 1, "maximum": 8},
|
|
612
|
+
"max_nodes": {"type": "integer", "default": 220, "minimum": 10, "maximum": 1200},
|
|
613
|
+
},
|
|
614
|
+
},
|
|
615
|
+
"handler": tool_ui_tree,
|
|
616
|
+
},
|
|
617
|
+
{
|
|
618
|
+
"name": "ui_find",
|
|
619
|
+
"description": (
|
|
620
|
+
"Search every reachable accessibility node for a name/text substring and/or a role, "
|
|
621
|
+
"returning refs with screen rectangles. Much cheaper than reading a whole tree."
|
|
622
|
+
),
|
|
623
|
+
"inputSchema": {
|
|
624
|
+
"type": "object",
|
|
625
|
+
"properties": {
|
|
626
|
+
"query": {"type": "string", "description": "Case-insensitive substring of the node name or text."},
|
|
627
|
+
"role": {"type": "string", "description": "Role filter, e.g. 'push button', 'text', 'entry'."},
|
|
628
|
+
"app": {"type": "string", "description": "Restrict to one application (substring match)."},
|
|
629
|
+
"limit": {"type": "integer", "default": 20, "minimum": 1, "maximum": 100},
|
|
630
|
+
},
|
|
631
|
+
},
|
|
632
|
+
"handler": tool_ui_find,
|
|
633
|
+
},
|
|
634
|
+
{
|
|
635
|
+
"name": "ui_describe",
|
|
636
|
+
"description": "Describe one node: role, name, states, rectangle, available actions, text.",
|
|
637
|
+
"inputSchema": {
|
|
638
|
+
"type": "object",
|
|
639
|
+
"properties": {"ref": {"type": "string", "description": "Element reference from ui_tree/ui_find."}},
|
|
640
|
+
"required": ["ref"],
|
|
641
|
+
},
|
|
642
|
+
"handler": tool_ui_describe,
|
|
643
|
+
},
|
|
644
|
+
{
|
|
645
|
+
"name": "ui_text",
|
|
646
|
+
"description": "Read the full text of a text-bearing node (label, entry, document).",
|
|
647
|
+
"inputSchema": {
|
|
648
|
+
"type": "object",
|
|
649
|
+
"properties": {"ref": {"type": "string"}},
|
|
650
|
+
"required": ["ref"],
|
|
651
|
+
},
|
|
652
|
+
"handler": tool_ui_text,
|
|
653
|
+
},
|
|
654
|
+
{
|
|
655
|
+
"name": "ui_action",
|
|
656
|
+
"description": (
|
|
657
|
+
"Invoke an accessibility action on a node (e.g. 'click', 'press', 'activate'). "
|
|
658
|
+
"More reliable than a coordinate click when the node exists."
|
|
659
|
+
),
|
|
660
|
+
"inputSchema": {
|
|
661
|
+
"type": "object",
|
|
662
|
+
"properties": {
|
|
663
|
+
"ref": {"type": "string"},
|
|
664
|
+
"action": {"type": "string", "description": "Action name; defaults to the first action."},
|
|
665
|
+
},
|
|
666
|
+
"required": ["ref"],
|
|
667
|
+
},
|
|
668
|
+
"handler": tool_ui_action,
|
|
669
|
+
},
|
|
670
|
+
{
|
|
671
|
+
"name": "ui_focus",
|
|
672
|
+
"description": "Give keyboard focus to a node, so a following key/type_text lands there.",
|
|
673
|
+
"inputSchema": {
|
|
674
|
+
"type": "object",
|
|
675
|
+
"properties": {"ref": {"type": "string"}},
|
|
676
|
+
"required": ["ref"],
|
|
677
|
+
},
|
|
678
|
+
"handler": tool_ui_focus,
|
|
679
|
+
},
|
|
680
|
+
{
|
|
681
|
+
"name": "ui_set_text",
|
|
682
|
+
"description": "Set the contents of an editable node directly (no keystrokes, no focus dance).",
|
|
683
|
+
"inputSchema": {
|
|
684
|
+
"type": "object",
|
|
685
|
+
"properties": {"ref": {"type": "string"}, "text": {"type": "string"}},
|
|
686
|
+
"required": ["ref", "text"],
|
|
687
|
+
},
|
|
688
|
+
"handler": tool_ui_set_text,
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
"name": "click",
|
|
692
|
+
"description": "Move the pointer to (x, y) and click. Supports button 1-3 and up to triple clicks.",
|
|
693
|
+
"inputSchema": {
|
|
694
|
+
"type": "object",
|
|
695
|
+
"properties": {
|
|
696
|
+
"x": {"type": "number"},
|
|
697
|
+
"y": {"type": "number"},
|
|
698
|
+
"button": {"type": "integer", "default": 1, "description": "1 left, 2 middle, 3 right."},
|
|
699
|
+
"count": {"type": "integer", "default": 1, "minimum": 1, "maximum": 3},
|
|
700
|
+
"space": SPACE_PROP,
|
|
701
|
+
},
|
|
702
|
+
"required": ["x", "y"],
|
|
703
|
+
},
|
|
704
|
+
"handler": tool_click,
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
"name": "move",
|
|
708
|
+
"description": "Move the pointer without clicking (useful to hover for menus and tooltips).",
|
|
709
|
+
"inputSchema": {
|
|
710
|
+
"type": "object",
|
|
711
|
+
"properties": {"x": {"type": "number"}, "y": {"type": "number"}, "space": SPACE_PROP},
|
|
712
|
+
"required": ["x", "y"],
|
|
713
|
+
},
|
|
714
|
+
"handler": tool_move,
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
"name": "drag",
|
|
718
|
+
"description": "Press at (x1, y1), move to (x2, y2) over duration_ms, then release.",
|
|
719
|
+
"inputSchema": {
|
|
720
|
+
"type": "object",
|
|
721
|
+
"properties": {
|
|
722
|
+
"x1": {"type": "number"},
|
|
723
|
+
"y1": {"type": "number"},
|
|
724
|
+
"x2": {"type": "number"},
|
|
725
|
+
"y2": {"type": "number"},
|
|
726
|
+
"duration_ms": {"type": "integer", "default": 450, "minimum": 100, "maximum": 5000},
|
|
727
|
+
"space": SPACE_PROP,
|
|
728
|
+
},
|
|
729
|
+
"required": ["x1", "y1", "x2", "y2"],
|
|
730
|
+
},
|
|
731
|
+
"handler": tool_drag,
|
|
732
|
+
},
|
|
733
|
+
{
|
|
734
|
+
"name": "scroll",
|
|
735
|
+
"description": "Scroll the pointer's position. Positive dy scrolls down, positive dx scrolls right.",
|
|
736
|
+
"inputSchema": {
|
|
737
|
+
"type": "object",
|
|
738
|
+
"properties": {
|
|
739
|
+
"dx": {"type": "integer", "default": 0, "description": "Horizontal wheel notches."},
|
|
740
|
+
"dy": {"type": "integer", "default": 0, "description": "Vertical wheel notches."},
|
|
741
|
+
},
|
|
742
|
+
},
|
|
743
|
+
"handler": tool_scroll,
|
|
744
|
+
},
|
|
745
|
+
{
|
|
746
|
+
"name": "pointer_button",
|
|
747
|
+
"description": "Hold or release a mouse button without moving (drag with explicit control).",
|
|
748
|
+
"inputSchema": {
|
|
749
|
+
"type": "object",
|
|
750
|
+
"properties": {
|
|
751
|
+
"action": {"type": "string", "enum": ["press", "release"]},
|
|
752
|
+
"button": {"type": "integer", "default": 1},
|
|
753
|
+
"x": {"type": "number"},
|
|
754
|
+
"y": {"type": "number"},
|
|
755
|
+
"space": SPACE_PROP,
|
|
756
|
+
},
|
|
757
|
+
"required": ["action"],
|
|
758
|
+
},
|
|
759
|
+
"handler": tool_pointer_button,
|
|
760
|
+
},
|
|
761
|
+
{
|
|
762
|
+
"name": "key",
|
|
763
|
+
"description": (
|
|
764
|
+
"Press a key combination, e.g. 'Return', 'Escape', 'ctrl+t', 'ctrl+shift+Tab', 'alt+F4'. "
|
|
765
|
+
"Modifiers are ctrl/alt/shift/super."
|
|
766
|
+
),
|
|
767
|
+
"inputSchema": {
|
|
768
|
+
"type": "object",
|
|
769
|
+
"properties": {"combo": {"type": "string"}},
|
|
770
|
+
"required": ["combo"],
|
|
771
|
+
},
|
|
772
|
+
"handler": tool_key,
|
|
773
|
+
},
|
|
774
|
+
{
|
|
775
|
+
"name": "type_text",
|
|
776
|
+
"description": "Type a string as keyboard input into whatever has focus (US layout).",
|
|
777
|
+
"inputSchema": {
|
|
778
|
+
"type": "object",
|
|
779
|
+
"properties": {"text": {"type": "string"}},
|
|
780
|
+
"required": ["text"],
|
|
781
|
+
},
|
|
782
|
+
"handler": tool_type_text,
|
|
783
|
+
},
|
|
784
|
+
{
|
|
785
|
+
"name": "clipboard_get",
|
|
786
|
+
"description": "Read the Wayland clipboard as text.",
|
|
787
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
788
|
+
"handler": tool_clipboard_get,
|
|
789
|
+
},
|
|
790
|
+
{
|
|
791
|
+
"name": "clipboard_set",
|
|
792
|
+
"description": "Replace the Wayland clipboard with text (useful to paste long answers).",
|
|
793
|
+
"inputSchema": {
|
|
794
|
+
"type": "object",
|
|
795
|
+
"properties": {"text": {"type": "string"}},
|
|
796
|
+
"required": ["text"],
|
|
797
|
+
},
|
|
798
|
+
"handler": tool_clipboard_set,
|
|
799
|
+
},
|
|
800
|
+
{
|
|
801
|
+
"name": "process_list",
|
|
802
|
+
"description": "List processes sorted by cpu/memory with pid, user, command line.",
|
|
803
|
+
"inputSchema": {
|
|
804
|
+
"type": "object",
|
|
805
|
+
"properties": {
|
|
806
|
+
"limit": {"type": "integer", "default": 25, "minimum": 1, "maximum": 200},
|
|
807
|
+
"sort": {"type": "string", "enum": ["cpu", "mem", "pid"], "default": "cpu"},
|
|
808
|
+
"name": {"type": "string", "description": "Only rows whose command or args contain this substring."},
|
|
809
|
+
},
|
|
810
|
+
},
|
|
811
|
+
"handler": tool_process_list,
|
|
812
|
+
},
|
|
813
|
+
{
|
|
814
|
+
"name": "process_kill",
|
|
815
|
+
"description": "Send a signal to a process (TERM by default). Refuses pid 1 and the server itself.",
|
|
816
|
+
"inputSchema": {
|
|
817
|
+
"type": "object",
|
|
818
|
+
"properties": {
|
|
819
|
+
"pid": {"type": "integer"},
|
|
820
|
+
"signal": {"type": "string", "enum": ["TERM", "KILL", "INT", "HUP"], "default": "TERM"},
|
|
821
|
+
},
|
|
822
|
+
"required": ["pid"],
|
|
823
|
+
},
|
|
824
|
+
"handler": tool_process_kill,
|
|
825
|
+
},
|
|
826
|
+
{
|
|
827
|
+
"name": "launch_app",
|
|
828
|
+
"description": "Start an application detached from the server, e.g. 'google-chrome https://...'.",
|
|
829
|
+
"inputSchema": {
|
|
830
|
+
"type": "object",
|
|
831
|
+
"properties": {"command": {"description": "A shell-like string or an argv list."}},
|
|
832
|
+
"required": ["command"],
|
|
833
|
+
},
|
|
834
|
+
"handler": tool_launch_app,
|
|
835
|
+
},
|
|
836
|
+
{
|
|
837
|
+
"name": "settings_get",
|
|
838
|
+
"description": "Read a gsettings value, e.g. schema 'org.gnome.desktop.interface', key 'clock-format'.",
|
|
839
|
+
"inputSchema": {
|
|
840
|
+
"type": "object",
|
|
841
|
+
"properties": {"schema": {"type": "string"}, "key": {"type": "string"}},
|
|
842
|
+
"required": ["schema", "key"],
|
|
843
|
+
},
|
|
844
|
+
"handler": tool_settings_get,
|
|
845
|
+
},
|
|
846
|
+
{
|
|
847
|
+
"name": "settings_set",
|
|
848
|
+
"description": "Write a gsettings value (the closest thing to the Windows registry).",
|
|
849
|
+
"inputSchema": {
|
|
850
|
+
"type": "object",
|
|
851
|
+
"properties": {"schema": {"type": "string"}, "key": {"type": "string"}, "value": {"type": "string"}},
|
|
852
|
+
"required": ["schema", "key", "value"],
|
|
853
|
+
},
|
|
854
|
+
"handler": tool_settings_set,
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
"name": "settings_list_keys",
|
|
858
|
+
"description": "List the keys of a gsettings schema.",
|
|
859
|
+
"inputSchema": {
|
|
860
|
+
"type": "object",
|
|
861
|
+
"properties": {"schema": {"type": "string"}},
|
|
862
|
+
"required": ["schema"],
|
|
863
|
+
},
|
|
864
|
+
"handler": tool_settings_list_keys,
|
|
865
|
+
},
|
|
866
|
+
{
|
|
867
|
+
"name": "notify",
|
|
868
|
+
"description": "Show a desktop notification (used to report progress or ask the user to step in).",
|
|
869
|
+
"inputSchema": {
|
|
870
|
+
"type": "object",
|
|
871
|
+
"properties": {
|
|
872
|
+
"summary": {"type": "string"},
|
|
873
|
+
"body": {"type": "string"},
|
|
874
|
+
"timeout_ms": {"type": "integer", "default": 8000},
|
|
875
|
+
},
|
|
876
|
+
"required": ["summary"],
|
|
877
|
+
},
|
|
878
|
+
"handler": tool_notify,
|
|
879
|
+
},
|
|
880
|
+
{
|
|
881
|
+
"name": "window_list",
|
|
882
|
+
"description": "List application windows with their title and which one looks active.",
|
|
883
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
884
|
+
"handler": tool_window_list,
|
|
885
|
+
},
|
|
886
|
+
{
|
|
887
|
+
"name": "display_info",
|
|
888
|
+
"description": (
|
|
889
|
+
"Report the monitor layout (logical size, per-monitor rectangles, scale) and the "
|
|
890
|
+
"coordinate mapping to use for clicks."
|
|
891
|
+
),
|
|
892
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
893
|
+
"handler": tool_display_info,
|
|
894
|
+
},
|
|
895
|
+
{
|
|
896
|
+
"name": "desktop_status",
|
|
897
|
+
"description": (
|
|
898
|
+
"Self-check of the desktop server: input backend, capture permission token, "
|
|
899
|
+
"accessibility reachability and optional helper binaries."
|
|
900
|
+
),
|
|
901
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
902
|
+
"handler": tool_desktop_status,
|
|
903
|
+
},
|
|
904
|
+
]
|
|
905
|
+
|
|
906
|
+
UNLOCK_TOOL: dict = {
|
|
907
|
+
"name": "unlock_screen",
|
|
908
|
+
"description": (
|
|
909
|
+
"Type the unlock password kept in the GNOME keyring into the lock screen and press Return. "
|
|
910
|
+
"It only exists while the user has switched unlocking on; with the default policy the tool "
|
|
911
|
+
"is not listed at all. The password is never sent to the model, never read from a chat, and "
|
|
912
|
+
"never written to a config file or the log."
|
|
913
|
+
),
|
|
914
|
+
"inputSchema": {
|
|
915
|
+
"type": "object",
|
|
916
|
+
"properties": {
|
|
917
|
+
"confirm": {
|
|
918
|
+
"type": "string",
|
|
919
|
+
"enum": ["unlock"],
|
|
920
|
+
"description": "Must be literally 'unlock'; a guard against accidental calls.",
|
|
921
|
+
}
|
|
922
|
+
},
|
|
923
|
+
"required": ["confirm"],
|
|
924
|
+
},
|
|
925
|
+
"handler": tool_unlock_screen,
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def visible_tools() -> list[dict]:
|
|
930
|
+
"""Tools the model may see right now.
|
|
931
|
+
|
|
932
|
+
``unlock_screen`` is opt-in per user setting, so when unlocking is off the
|
|
933
|
+
model does not even learn that the capability exists.
|
|
934
|
+
"""
|
|
935
|
+
specs = list(TOOLS)
|
|
936
|
+
if cu_unlock.unlock_enabled():
|
|
937
|
+
specs.append(UNLOCK_TOOL)
|
|
938
|
+
return specs
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def tool_index() -> dict[str, dict]:
|
|
942
|
+
return {spec["name"]: spec for spec in visible_tools()}
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def call_tool(name: str, arguments: dict) -> dict:
|
|
946
|
+
index = tool_index()
|
|
947
|
+
spec = index.get(name)
|
|
948
|
+
if spec is None:
|
|
949
|
+
raise ToolError(f"unknown tool {name!r}; available: {sorted(index)}")
|
|
950
|
+
handler = spec["handler"]
|
|
951
|
+
try:
|
|
952
|
+
result = handler(arguments or {})
|
|
953
|
+
except (ToolError, cu_a11y.A11yError, cu_display.PortalError, cu_sys.SysError,
|
|
954
|
+
cu_input.InputError) as error:
|
|
955
|
+
log(f"tool {name} failed: {error}")
|
|
956
|
+
return {"content": [{"type": "text", "text": str(error)}], "isError": True}
|
|
957
|
+
except Exception as error: # noqa: BLE001 - never kill the server on a tool bug
|
|
958
|
+
log(f"tool {name} crashed: {error}\n{traceback.format_exc()}")
|
|
959
|
+
return {
|
|
960
|
+
"content": [{"type": "text", "text": f"{type(error).__name__}: {error}"}],
|
|
961
|
+
"isError": True,
|
|
962
|
+
}
|
|
963
|
+
if isinstance(result, dict) and "content" in result:
|
|
964
|
+
return result
|
|
965
|
+
return {"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False, default=str)}]}
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
# --------------------------------------------------------------------------- #
|
|
969
|
+
# JSON-RPC plumbing
|
|
970
|
+
# --------------------------------------------------------------------------- #
|
|
971
|
+
def respond(payload: dict) -> None:
|
|
972
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
|
973
|
+
sys.stdout.flush()
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def error_response(identifier, code: int, message: str) -> dict:
|
|
977
|
+
return {"jsonrpc": "2.0", "id": identifier, "error": {"code": code, "message": message}}
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def handle(message: dict) -> dict | None:
|
|
981
|
+
method = message.get("method", "")
|
|
982
|
+
identifier = message.get("id")
|
|
983
|
+
params = message.get("params") or {}
|
|
984
|
+
is_notification = "id" not in message
|
|
985
|
+
|
|
986
|
+
if method == "initialize":
|
|
987
|
+
requested = params.get("protocolVersion") or PROTOCOL_VERSION
|
|
988
|
+
version = requested if requested in SUPPORTED_PROTOCOLS else PROTOCOL_VERSION
|
|
989
|
+
return {
|
|
990
|
+
"jsonrpc": "2.0",
|
|
991
|
+
"id": identifier,
|
|
992
|
+
"result": {
|
|
993
|
+
"protocolVersion": version,
|
|
994
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
995
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
996
|
+
"instructions": (
|
|
997
|
+
"Linux (Wayland GNOME) desktop control. Prefer screenshot to observe, "
|
|
998
|
+
"ui_tree/ui_find for GTK apps, and short waits between actions."
|
|
999
|
+
),
|
|
1000
|
+
},
|
|
1001
|
+
}
|
|
1002
|
+
if is_notification:
|
|
1003
|
+
return None
|
|
1004
|
+
if method == "ping":
|
|
1005
|
+
return {"jsonrpc": "2.0", "id": identifier, "result": {}}
|
|
1006
|
+
if method == "tools/list":
|
|
1007
|
+
return {
|
|
1008
|
+
"jsonrpc": "2.0",
|
|
1009
|
+
"id": identifier,
|
|
1010
|
+
"result": {
|
|
1011
|
+
"tools": [
|
|
1012
|
+
{
|
|
1013
|
+
"name": spec["name"],
|
|
1014
|
+
"description": spec["description"],
|
|
1015
|
+
"inputSchema": spec["inputSchema"],
|
|
1016
|
+
}
|
|
1017
|
+
for spec in visible_tools()
|
|
1018
|
+
]
|
|
1019
|
+
},
|
|
1020
|
+
}
|
|
1021
|
+
if method == "tools/call":
|
|
1022
|
+
name = params.get("name")
|
|
1023
|
+
arguments = params.get("arguments") or {}
|
|
1024
|
+
if not isinstance(name, str):
|
|
1025
|
+
return error_response(identifier, -32602, "tools/call requires a tool name")
|
|
1026
|
+
try:
|
|
1027
|
+
result = call_tool(name, arguments)
|
|
1028
|
+
except ToolError as error:
|
|
1029
|
+
return error_response(identifier, -32602, str(error))
|
|
1030
|
+
return {"jsonrpc": "2.0", "id": identifier, "result": result}
|
|
1031
|
+
if method == "resources/list":
|
|
1032
|
+
return {"jsonrpc": "2.0", "id": identifier, "result": {"resources": []}}
|
|
1033
|
+
if method == "prompts/list":
|
|
1034
|
+
return {"jsonrpc": "2.0", "id": identifier, "result": {"prompts": []}}
|
|
1035
|
+
return error_response(identifier, -32601, f"method not supported: {method}")
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
# --------------------------------------------------------------------------- #
|
|
1039
|
+
# self test (used by the linux_mcp_doctor DSH tool)
|
|
1040
|
+
# --------------------------------------------------------------------------- #
|
|
1041
|
+
def _check(checks: list, ident: str, status: str, title: str, detail: str = "", fix: str = "") -> None:
|
|
1042
|
+
entry = {"id": ident, "status": status, "title": title}
|
|
1043
|
+
if detail:
|
|
1044
|
+
entry["detail"] = detail
|
|
1045
|
+
if fix:
|
|
1046
|
+
entry["fix"] = fix
|
|
1047
|
+
checks.append(entry)
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def _portal_screencast_version() -> int | None:
|
|
1051
|
+
"""Read the Screencast portal version without triggering a permission dialog."""
|
|
1052
|
+
import gi
|
|
1053
|
+
|
|
1054
|
+
gi.require_version("Gio", "2.0")
|
|
1055
|
+
from gi.repository import Gio
|
|
1056
|
+
|
|
1057
|
+
try:
|
|
1058
|
+
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
|
1059
|
+
reply = bus.call_sync(
|
|
1060
|
+
"org.freedesktop.portal.Desktop",
|
|
1061
|
+
"/org/freedesktop/portal/desktop",
|
|
1062
|
+
"org.freedesktop.DBus.Properties",
|
|
1063
|
+
"Get",
|
|
1064
|
+
__import__("gi").repository.GLib.Variant(
|
|
1065
|
+
"(ss)", ("org.freedesktop.portal.ScreenCast", "version")
|
|
1066
|
+
),
|
|
1067
|
+
__import__("gi").repository.GLib.VariantType("(v)"),
|
|
1068
|
+
Gio.DBusCallFlags.NONE,
|
|
1069
|
+
3000,
|
|
1070
|
+
None,
|
|
1071
|
+
)
|
|
1072
|
+
return int(reply.unpack()[0])
|
|
1073
|
+
except Exception: # noqa: BLE001
|
|
1074
|
+
return None
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def selftest() -> dict:
|
|
1078
|
+
"""Collect everything the doctor tool needs, without asking for permissions."""
|
|
1079
|
+
checks: list[dict] = []
|
|
1080
|
+
|
|
1081
|
+
session = os.environ.get("XDG_SESSION_TYPE", "unknown")
|
|
1082
|
+
desktop = os.environ.get("XDG_CURRENT_DESKTOP", "unknown")
|
|
1083
|
+
if session == "wayland":
|
|
1084
|
+
_check(checks, "session", "ok", f"Wayland session ({desktop})", f"WAYLAND_DISPLAY={os.environ.get('WAYLAND_DISPLAY', '')}")
|
|
1085
|
+
elif session == "x11":
|
|
1086
|
+
_check(
|
|
1087
|
+
checks,
|
|
1088
|
+
"session",
|
|
1089
|
+
"warn",
|
|
1090
|
+
"X11 session",
|
|
1091
|
+
"This server targets Wayland. Screenshots still work, but use xdotool-style tools instead if you prefer Xorg.",
|
|
1092
|
+
)
|
|
1093
|
+
else:
|
|
1094
|
+
_check(checks, "session", "warn", f"Unknown session type ({session})", "XDG_SESSION_TYPE is not wayland/x11.")
|
|
1095
|
+
|
|
1096
|
+
# python + GI stack
|
|
1097
|
+
modules = ["gi", "gi.repository.Atspi", "gi.repository.Gst", "gi.repository.GdkPixbuf", "gi.repository.Gio"]
|
|
1098
|
+
missing = []
|
|
1099
|
+
for module in modules:
|
|
1100
|
+
try:
|
|
1101
|
+
__import__(module)
|
|
1102
|
+
except Exception as error: # noqa: BLE001
|
|
1103
|
+
missing.append(f"{module} ({error.__class__.__name__})")
|
|
1104
|
+
version = "%d.%d.%d" % sys.version_info[:3]
|
|
1105
|
+
if missing:
|
|
1106
|
+
_check(
|
|
1107
|
+
checks,
|
|
1108
|
+
"python",
|
|
1109
|
+
"fail",
|
|
1110
|
+
f"Python {version} is missing GI bindings",
|
|
1111
|
+
", ".join(missing),
|
|
1112
|
+
"sudo apt install python3-gi gir1.2-atspi-2.0 gir1.2-gstreamer-1.0 gir1.2-gst-plugins-base-1.0 gir1.2-gdkpixbuf-2.0",
|
|
1113
|
+
)
|
|
1114
|
+
else:
|
|
1115
|
+
_check(checks, "python", "ok", f"Python {version} with gi/Atspi/Gst/GdkPixbuf")
|
|
1116
|
+
|
|
1117
|
+
# input injection: /dev/uinput
|
|
1118
|
+
device = cu_input.DEFAULT_UINPUT
|
|
1119
|
+
if not os.path.exists(device):
|
|
1120
|
+
_check(
|
|
1121
|
+
checks,
|
|
1122
|
+
"uinput",
|
|
1123
|
+
"fail",
|
|
1124
|
+
f"{device} does not exist",
|
|
1125
|
+
"input injection cannot work without it",
|
|
1126
|
+
"sudo ./linux-computer-use-prep.sh, then log out and back in",
|
|
1127
|
+
)
|
|
1128
|
+
elif not (os.access(device, os.R_OK) and os.access(device, os.W_OK)):
|
|
1129
|
+
import grp
|
|
1130
|
+
|
|
1131
|
+
import stat as stat_module
|
|
1132
|
+
|
|
1133
|
+
info = os.stat(device)
|
|
1134
|
+
group = grp.getgrgid(info.st_gid).gr_name
|
|
1135
|
+
_check(
|
|
1136
|
+
checks,
|
|
1137
|
+
"uinput",
|
|
1138
|
+
"fail",
|
|
1139
|
+
f"{device} is not writable by this user",
|
|
1140
|
+
f"mode {stat_module.filemode(info.st_mode)}, group {group}; your groups: {' '.join(os.getgroups() and [grp.getgrgid(g).gr_name for g in os.getgroups()] or [])}",
|
|
1141
|
+
"sudo ./linux-computer-use-prep.sh, then LOG OUT and back in so the 'input' group applies",
|
|
1142
|
+
)
|
|
1143
|
+
else:
|
|
1144
|
+
_check(checks, "uinput", "ok", f"{device} is readable and writable")
|
|
1145
|
+
|
|
1146
|
+
socket_path = cu_input.DEFAULT_YDOTOOL_SOCKET
|
|
1147
|
+
if os.path.exists(socket_path) and os.access(socket_path, os.W_OK):
|
|
1148
|
+
_check(checks, "ydotool", "ok", "ydotool fallback socket is available", socket_path)
|
|
1149
|
+
else:
|
|
1150
|
+
_check(
|
|
1151
|
+
checks,
|
|
1152
|
+
"ydotool",
|
|
1153
|
+
"warn",
|
|
1154
|
+
"ydotool fallback is not available",
|
|
1155
|
+
"optional: only used when /dev/uinput cannot be opened",
|
|
1156
|
+
"sudo ./linux-computer-use-prep.sh installs and starts ydotoold",
|
|
1157
|
+
)
|
|
1158
|
+
|
|
1159
|
+
# clipboard + notification helpers
|
|
1160
|
+
for ident, binary, package, required in (
|
|
1161
|
+
("wl-clipboard", "wl-copy", "wl-clipboard", True),
|
|
1162
|
+
("wl-paste", "wl-paste", "wl-clipboard", True),
|
|
1163
|
+
("notify-send", "notify-send", "libnotify-bin", False),
|
|
1164
|
+
("gsettings", "gsettings", "libglib2.0-bin", False),
|
|
1165
|
+
):
|
|
1166
|
+
if cu_sys.have(binary):
|
|
1167
|
+
_check(checks, ident, "ok", f"{binary} found")
|
|
1168
|
+
else:
|
|
1169
|
+
_check(
|
|
1170
|
+
checks,
|
|
1171
|
+
ident,
|
|
1172
|
+
"fail" if required else "warn",
|
|
1173
|
+
f"{binary} is not installed",
|
|
1174
|
+
"" if required else "only needed for the corresponding tool",
|
|
1175
|
+
f"sudo apt install {package}",
|
|
1176
|
+
)
|
|
1177
|
+
|
|
1178
|
+
# portal + stream capture
|
|
1179
|
+
portal_version = _portal_screencast_version()
|
|
1180
|
+
if portal_version is None:
|
|
1181
|
+
_check(
|
|
1182
|
+
checks,
|
|
1183
|
+
"portal",
|
|
1184
|
+
"fail",
|
|
1185
|
+
"xdg-desktop-portal ScreenCast is not reachable",
|
|
1186
|
+
"screenshots are impossible without it",
|
|
1187
|
+
"make sure xdg-desktop-portal and xdg-desktop-portal-gnome are running",
|
|
1188
|
+
)
|
|
1189
|
+
else:
|
|
1190
|
+
_check(checks, "portal", "ok", f"ScreenCast portal version {portal_version}")
|
|
1191
|
+
|
|
1192
|
+
if not _have_gst("pipewiresrc"):
|
|
1193
|
+
_check(
|
|
1194
|
+
checks,
|
|
1195
|
+
"gstreamer",
|
|
1196
|
+
"fail",
|
|
1197
|
+
"GStreamer element pipewiresrc is missing",
|
|
1198
|
+
"the ScreenCast stream cannot be decoded into PNG",
|
|
1199
|
+
"sudo apt install gstreamer1.0-pipewire gstreamer1.0-plugins-base",
|
|
1200
|
+
)
|
|
1201
|
+
else:
|
|
1202
|
+
_check(checks, "gstreamer", "ok", "GStreamer pipewiresrc available")
|
|
1203
|
+
|
|
1204
|
+
locked = cu_sys.screen_locked()
|
|
1205
|
+
if locked is True:
|
|
1206
|
+
_check(
|
|
1207
|
+
checks,
|
|
1208
|
+
"screen-lock",
|
|
1209
|
+
"warn",
|
|
1210
|
+
"the session is locked right now",
|
|
1211
|
+
"screenshots still work; input tools refuse to type into the password field",
|
|
1212
|
+
"unlock the desktop to drive it",
|
|
1213
|
+
)
|
|
1214
|
+
elif locked is False:
|
|
1215
|
+
_check(checks, "screen-lock", "ok", "the session is unlocked")
|
|
1216
|
+
else:
|
|
1217
|
+
_check(checks, "screen-lock", "warn", "lock state is unknown", "org.gnome.ScreenSaver.GetActive did not answer")
|
|
1218
|
+
|
|
1219
|
+
unlock_state = cu_unlock.status()
|
|
1220
|
+
if unlock_state["unlock_policy"] == "off":
|
|
1221
|
+
_check(
|
|
1222
|
+
checks,
|
|
1223
|
+
"unlock-policy",
|
|
1224
|
+
"ok",
|
|
1225
|
+
"AI unlocking is switched off (the default)",
|
|
1226
|
+
"while the session is locked, input tools refuse to type; screenshots still work",
|
|
1227
|
+
"switch it on with: settings.json {\"unlock\": \"keyring\"} after storing a password",
|
|
1228
|
+
)
|
|
1229
|
+
elif unlock_state["password_stored"]:
|
|
1230
|
+
_check(
|
|
1231
|
+
checks,
|
|
1232
|
+
"unlock-policy",
|
|
1233
|
+
"ok",
|
|
1234
|
+
"AI unlocking is on; a password is stored in the keyring",
|
|
1235
|
+
"the lock screen now stops a person at the keyboard, not software running as you",
|
|
1236
|
+
"turn it off with: --unlock-policy off",
|
|
1237
|
+
)
|
|
1238
|
+
else:
|
|
1239
|
+
_check(
|
|
1240
|
+
checks,
|
|
1241
|
+
"unlock-policy",
|
|
1242
|
+
"warn",
|
|
1243
|
+
"AI unlocking is on but no password is stored",
|
|
1244
|
+
"unlock_screen will fail until a password is stored",
|
|
1245
|
+
"run: linux_desktop_mcp.py --set-unlock-password",
|
|
1246
|
+
)
|
|
1247
|
+
|
|
1248
|
+
token_path = cu_display.ScreencastSession.token_path() if hasattr(cu_display.ScreencastSession, "token_path") else None
|
|
1249
|
+
has_token = bool(cu_display.ScreencastSession.load_token())
|
|
1250
|
+
if has_token:
|
|
1251
|
+
_check(checks, "capture-permission", "ok", "screen capture permission is remembered")
|
|
1252
|
+
else:
|
|
1253
|
+
_check(
|
|
1254
|
+
checks,
|
|
1255
|
+
"capture-permission",
|
|
1256
|
+
"warn",
|
|
1257
|
+
"screen capture has not been granted yet",
|
|
1258
|
+
"the first screenshot shows a one-time approval dialog"
|
|
1259
|
+
+ (f"; token file: {token_path}" if token_path else ""),
|
|
1260
|
+
"run mcp__linux__screenshot once and approve the dialog",
|
|
1261
|
+
)
|
|
1262
|
+
|
|
1263
|
+
# display + a11y
|
|
1264
|
+
try:
|
|
1265
|
+
current = layout()
|
|
1266
|
+
_check(checks, "display", "ok", "display layout readable", current.describe().get("monitors_summary", "") or str(current.describe())[:200])
|
|
1267
|
+
except Exception as error: # noqa: BLE001
|
|
1268
|
+
_check(checks, "display", "warn", "display layout unavailable", str(error))
|
|
1269
|
+
|
|
1270
|
+
try:
|
|
1271
|
+
started = time.time()
|
|
1272
|
+
apps = A11Y.apps(max_age=2.0)
|
|
1273
|
+
elapsed = time.time() - started
|
|
1274
|
+
_check(
|
|
1275
|
+
checks,
|
|
1276
|
+
"a11y",
|
|
1277
|
+
"ok" if len(apps) > 1 else "warn",
|
|
1278
|
+
f"AT-SPI sees {len(apps)} applications",
|
|
1279
|
+
f"enumeration took {elapsed:.1f}s; Chromium/Electron apps expose an empty tree without accessibility enabled",
|
|
1280
|
+
)
|
|
1281
|
+
except Exception as error: # noqa: BLE001
|
|
1282
|
+
_check(checks, "a11y", "warn", "AT-SPI is unavailable", str(error), "check that org.a11y.Bus is running")
|
|
1283
|
+
|
|
1284
|
+
ok = not any(check["status"] == "fail" for check in checks)
|
|
1285
|
+
return {
|
|
1286
|
+
"ok": ok,
|
|
1287
|
+
"server": {"name": SERVER_NAME, "version": SERVER_VERSION, "log": LOG_PATH},
|
|
1288
|
+
"checks": checks,
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
def _cli_unlock(args: list[str]) -> int | None:
|
|
1293
|
+
"""Handle the unlock-related command line switches. Returns an exit code or None."""
|
|
1294
|
+
if "--set-unlock-password" in args:
|
|
1295
|
+
try:
|
|
1296
|
+
print(cu_unlock.prompt_and_store())
|
|
1297
|
+
except cu_unlock.UnlockError as error:
|
|
1298
|
+
print(f"error: {error}", file=sys.stderr)
|
|
1299
|
+
return 1
|
|
1300
|
+
return 0
|
|
1301
|
+
if "--clear-unlock-password" in args:
|
|
1302
|
+
removed = cu_unlock.clear_password()
|
|
1303
|
+
print("cleared the stored unlock password" if removed else "no unlock password was stored")
|
|
1304
|
+
return 0
|
|
1305
|
+
if "--unlock-status" in args:
|
|
1306
|
+
print(json.dumps(cu_unlock.status(), indent=2, ensure_ascii=False))
|
|
1307
|
+
return 0
|
|
1308
|
+
if "--unlock-policy" in args:
|
|
1309
|
+
position = args.index("--unlock-policy")
|
|
1310
|
+
value = args[position + 1] if position + 1 < len(args) else ""
|
|
1311
|
+
if not value or value.startswith("-"):
|
|
1312
|
+
print("usage: --unlock-policy off|keyring", file=sys.stderr)
|
|
1313
|
+
return 2
|
|
1314
|
+
try:
|
|
1315
|
+
chosen = cu_unlock.set_policy(value)
|
|
1316
|
+
except cu_unlock.UnlockError as error:
|
|
1317
|
+
print(f"error: {error}", file=sys.stderr)
|
|
1318
|
+
return 2
|
|
1319
|
+
print(f"unlock policy: {chosen}")
|
|
1320
|
+
return 0
|
|
1321
|
+
return None
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
def main() -> int:
|
|
1325
|
+
unlock_exit = _cli_unlock(sys.argv[1:])
|
|
1326
|
+
if unlock_exit is not None:
|
|
1327
|
+
return unlock_exit
|
|
1328
|
+
if "--selftest" in sys.argv[1:]:
|
|
1329
|
+
print(json.dumps(selftest(), indent=2, ensure_ascii=False))
|
|
1330
|
+
return 0
|
|
1331
|
+
if "--status" in sys.argv[1:]:
|
|
1332
|
+
print(json.dumps(tool_desktop_status({}), indent=2, ensure_ascii=False))
|
|
1333
|
+
return 0
|
|
1334
|
+
log(f"{SERVER_NAME} {SERVER_VERSION} starting (pid {os.getpid()})")
|
|
1335
|
+
stream = sys.stdin
|
|
1336
|
+
for line in stream:
|
|
1337
|
+
line = line.strip()
|
|
1338
|
+
if not line:
|
|
1339
|
+
continue
|
|
1340
|
+
try:
|
|
1341
|
+
message = json.loads(line)
|
|
1342
|
+
except ValueError:
|
|
1343
|
+
respond(error_response(None, -32700, "invalid JSON"))
|
|
1344
|
+
continue
|
|
1345
|
+
if not isinstance(message, dict):
|
|
1346
|
+
respond(error_response(None, -32600, "invalid request"))
|
|
1347
|
+
continue
|
|
1348
|
+
try:
|
|
1349
|
+
reply = handle(message)
|
|
1350
|
+
except Exception as error: # noqa: BLE001
|
|
1351
|
+
log(f"handler crashed: {error}\n{traceback.format_exc()}")
|
|
1352
|
+
if "id" in message:
|
|
1353
|
+
respond(error_response(message.get("id"), -32603, f"internal error: {error}"))
|
|
1354
|
+
continue
|
|
1355
|
+
if reply is not None:
|
|
1356
|
+
respond(reply)
|
|
1357
|
+
log("stdin closed; exiting")
|
|
1358
|
+
return 0
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
if __name__ == "__main__":
|
|
1362
|
+
raise SystemExit(main())
|