dsh-plugin-linux-computer-use 0.0.0-stage → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "dsh-plugin-linux-computer-use",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Computer Use for a Wayland Linux desktop in DeepSeek Harness: screenshots, UI tree, pointer and keyboard input, clipboard, processes and settings, bridged as mcp__linux__* tools. · 让 DSH 接管 Ubuntu/GNOME 桌面:截屏、UI 树、鼠标键盘、剪贴板、进程与系统设置。",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "deepseek-harness",
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "computer-use",
12
+ "desktop-automation",
13
+ "mcp",
14
+ "wayland",
15
+ "gnome",
16
+ "at-spi",
17
+ "uinput",
18
+ "ubuntu",
19
+ "ubuntu-24-04",
20
+ "linux-desktop",
21
+ "screenshot",
22
+ "accessibility"
23
+ ],
24
+ "exports": {
25
+ ".": "./index.js",
26
+ "./locale/*.json": "./locale/*.json",
27
+ "./icon": "./icon.svg"
28
+ },
29
+ "files": [
30
+ "index.js",
31
+ "cordis.patch.yml",
32
+ "locale/*.json",
33
+ "docs",
34
+ "icon.svg",
35
+ "server/*.py",
36
+ "linux-computer-use-prep.sh",
37
+ "README.md",
38
+ "LICENSE",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "scripts": {
42
+ "selftest": "python3 -u server/linux_desktop_mcp.py --selftest",
43
+ "status": "python3 -u server/linux_desktop_mcp.py --status",
44
+ "check": "node --check index.js && python3 -m py_compile server/*.py && npm pack --dry-run"
45
+ },
46
+ "engines": {
47
+ "node": ">=20"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/1804608397/dsh-plugin-linux-computer-use.git"
52
+ },
53
+ "homepage": "https://github.com/1804608397/dsh-plugin-linux-computer-use#readme",
54
+ "bugs": {
55
+ "url": "https://github.com/1804608397/dsh-plugin-linux-computer-use/issues"
56
+ },
57
+ "author": "Beining Cheng <1804608397@users.noreply.github.com>",
58
+ "dsh": {
59
+ "bundle": {
60
+ "patch": "./cordis.patch.yml"
61
+ }
62
+ }
63
+ }
@@ -0,0 +1,495 @@
1
+ """AT-SPI2 accessibility-tree access for the Linux desktop MCP server.
2
+
3
+ Every X11 trick for "look at the UI" is unavailable on Wayland, so this module
4
+ reads the accessibility tree that GNOME exposes over ``org.a11y.Bus``. It gives
5
+ the model the same three things the Windows build got from UIA:
6
+
7
+ * a structural snapshot of the running applications and their widgets;
8
+ * stable element references the model can act on (``do_action``, ``focus``);
9
+ * text read/write and screen rectangles, so a click can target a widget
10
+ instead of a guessed pixel.
11
+
12
+ Tree walks are bounded by both a node cap and a wall-clock deadline: a single
13
+ unresponsive application must not hang the whole server.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import subprocess
19
+ import sys
20
+ import time
21
+
22
+ import gi
23
+
24
+ gi.require_version("Atspi", "2.0")
25
+ from gi.repository import Atspi # noqa: E402
26
+
27
+ STATE_FLAGS = (
28
+ "ENABLED", "SENSITIVE", "SHOWING", "VISIBLE", "FOCUSED", "FOCUSABLE",
29
+ "CHECKED", "EDITABLE", "SELECTED", "EXPANDED", "PRESSED",
30
+ )
31
+
32
+
33
+ _PROBE_CACHE: "list[bool]" = []
34
+
35
+
36
+ def a11y_reachable() -> bool:
37
+ """True when Atspi.init() can run without aborting this process.
38
+
39
+ libatspi calls g_error() when it cannot reach the accessibility bus, which
40
+ kills the whole process instead of raising. The only safe test is to try it
41
+ in a throwaway child, so do that once and cache the answer.
42
+ """
43
+ # Only a positive result is cached: the accessibility bus starts a moment
44
+ # after the desktop session does, so a failure now can become a success a
45
+ # second later.
46
+ if _PROBE_CACHE:
47
+ return _PROBE_CACHE[0]
48
+ code = (
49
+ "import gi;gi.require_version('Atspi','2.0');"
50
+ "from gi.repository import Atspi;Atspi.init();print('ok')"
51
+ )
52
+ try:
53
+ proc = subprocess.run(
54
+ [sys.executable, "-c", code], capture_output=True, timeout=20, check=False
55
+ )
56
+ ok = proc.returncode == 0 and b"ok" in proc.stdout
57
+ except Exception: # noqa: BLE001
58
+ ok = False
59
+ if ok:
60
+ _PROBE_CACHE.append(True)
61
+ return ok
62
+
63
+
64
+ class A11yError(RuntimeError):
65
+ """The accessibility tree could not be read or the element is gone."""
66
+
67
+
68
+ def _state_names(acc) -> list[str]:
69
+ try:
70
+ state_set = acc.get_state_set()
71
+ except Exception: # noqa: BLE001 - dead proxies raise many GLib errors
72
+ return []
73
+ found = []
74
+ for flag in STATE_FLAGS:
75
+ value = getattr(Atspi.StateType, flag, None)
76
+ if value is None:
77
+ continue
78
+ try:
79
+ if state_set.contains(value):
80
+ found.append(flag.lower())
81
+ except Exception: # noqa: BLE001
82
+ break
83
+ return found
84
+
85
+
86
+ def _extents(acc) -> dict | None:
87
+ try:
88
+ iface = acc.get_component_iface()
89
+ except Exception: # noqa: BLE001
90
+ return None
91
+ if iface is None:
92
+ return None
93
+ try:
94
+ x, y, width, height = iface.get_extents(Atspi.CoordType.SCREEN)
95
+ except Exception: # noqa: BLE001
96
+ return None
97
+ if width <= 0 or height <= 0:
98
+ return None
99
+ return {"x": int(x), "y": int(y), "width": int(width), "height": int(height)}
100
+
101
+
102
+ def _actions(acc) -> list[str]:
103
+ try:
104
+ iface = acc.get_action_iface()
105
+ except Exception: # noqa: BLE001
106
+ return []
107
+ if iface is None:
108
+ return []
109
+ names = []
110
+ try:
111
+ count = iface.get_n_actions()
112
+ except Exception: # noqa: BLE001
113
+ return []
114
+ for index in range(min(count, 8)):
115
+ try:
116
+ names.append(iface.get_action_name(index) or f"action{index}")
117
+ except Exception: # noqa: BLE001
118
+ break
119
+ return names
120
+
121
+
122
+ def _text_preview(acc, limit: int = 160) -> str:
123
+ try:
124
+ iface = acc.get_text_iface()
125
+ except Exception: # noqa: BLE001
126
+ return ""
127
+ if iface is None:
128
+ return ""
129
+ try:
130
+ count = iface.get_character_count()
131
+ if not count:
132
+ return ""
133
+ text = iface.get_text(0, min(int(count), limit))
134
+ except Exception: # noqa: BLE001
135
+ return ""
136
+ return (text or "").replace("\n", " ").strip()
137
+
138
+
139
+ class A11y:
140
+ """Thin, defensive wrapper around the AT-SPI2 tree."""
141
+
142
+ def __init__(self) -> None:
143
+ self._started = False
144
+ self._registry: dict[str, object] = {}
145
+ self._by_id: dict[int, str] = {}
146
+ self._counter = 0
147
+ self._apps: dict[str, object] = {}
148
+ self._apps_cache: list[dict] | None = None
149
+ self._apps_at = 0.0
150
+ self.apps_ttl = 5.0
151
+
152
+ # -- lifecycle --------------------------------------------------------- #
153
+ def start(self) -> None:
154
+ if self._started:
155
+ return
156
+ # libatspi aborts the whole process (dbind-ERROR) when the session bus
157
+ # is gone, which is exactly what happens after the user logs out and
158
+ # back in while this server keeps running. Check first so the tools can
159
+ # report a fixable error instead of the server dying.
160
+ if not a11y_reachable():
161
+ raise A11yError(
162
+ "the accessibility bus is unreachable: this server has no working "
163
+ "session D-Bus connection. Restart the app that launched it (dsh web) "
164
+ "from a terminal in the current desktop session."
165
+ )
166
+ try:
167
+ # Tighten the D-Bus timeouts used for tree queries: one hung
168
+ # application must not stall a whole snapshot. 1s is far above the
169
+ # reply time of any healthy local toolkit.
170
+ Atspi.set_timeout(1000, 3000)
171
+ except Exception: # noqa: BLE001 - older libatspi may not export it
172
+ pass
173
+ try:
174
+ Atspi.init()
175
+ except Exception as error: # noqa: BLE001
176
+ raise A11yError(f"cannot initialise AT-SPI: {error}") from error
177
+ try:
178
+ desktop = Atspi.get_desktop(0)
179
+ except Exception as error: # noqa: BLE001
180
+ raise A11yError(
181
+ "AT-SPI is not reachable; is at-spi2-core running and "
182
+ "org.a11y.Bus available on the session bus? "
183
+ f"({error})"
184
+ ) from error
185
+ if desktop is None:
186
+ raise A11yError("AT-SPI returned no desktop; accessibility is unavailable")
187
+ self._started = True
188
+
189
+ def _desktop(self):
190
+ self.start()
191
+ return Atspi.get_desktop(0)
192
+
193
+ # -- references -------------------------------------------------------- #
194
+ def _ref(self, acc) -> str:
195
+ key = id(acc)
196
+ known = self._by_id.get(key)
197
+ if known is not None and self._registry.get(known) is acc:
198
+ return known
199
+ self._counter += 1
200
+ ref = f"e{self._counter}"
201
+ self._registry[ref] = acc
202
+ self._by_id[key] = ref
203
+ if len(self._registry) > 4000:
204
+ # Keep memory bounded: forget the oldest quarter of the refs.
205
+ for stale in list(self._registry)[:1000]:
206
+ self._registry.pop(stale, None)
207
+ self._by_id = {id(obj): name for name, obj in self._registry.items()}
208
+ return ref
209
+
210
+ def resolve(self, ref: str):
211
+ self.start()
212
+ acc = self._registry.get(ref)
213
+ if acc is None:
214
+ raise A11yError(f"unknown element reference {ref!r}; take a fresh snapshot")
215
+ return acc
216
+
217
+ # -- applications ------------------------------------------------------ #
218
+ def apps(self, max_age: float | None = None) -> list[dict]:
219
+ ttl = self.apps_ttl if max_age is None else max_age
220
+ if self._apps_cache is not None and (time.monotonic() - self._apps_at) < ttl:
221
+ return [dict(item) for item in self._apps_cache]
222
+ desktop = self._desktop()
223
+ try:
224
+ count = desktop.get_child_count()
225
+ except Exception as error: # noqa: BLE001
226
+ raise A11yError(f"cannot enumerate applications: {error}") from error
227
+ found = []
228
+ self._apps.clear()
229
+ for index in range(count):
230
+ try:
231
+ app = desktop.get_child_at_index(index)
232
+ except Exception: # noqa: BLE001
233
+ continue
234
+ if app is None:
235
+ continue
236
+ try:
237
+ name = app.get_name() or ""
238
+ role = app.get_role_name() or ""
239
+ pid = app.get_process_id() or 0
240
+ except Exception: # noqa: BLE001
241
+ continue
242
+ ref = self._ref(app)
243
+ self._apps[name] = app
244
+ found.append({"ref": ref, "name": name, "role": role, "pid": int(pid)})
245
+ found.sort(key=lambda item: item["name"].lower())
246
+ self._apps_cache = found
247
+ self._apps_at = time.monotonic()
248
+ return [dict(item) for item in found]
249
+
250
+ def _app(self, name: str | None):
251
+ if not name:
252
+ return None
253
+ if not self._apps:
254
+ self.apps()
255
+ exact = self._apps.get(name)
256
+ if exact is not None:
257
+ return exact
258
+ lowered = name.lower()
259
+ for app_name, app in self._apps.items():
260
+ if lowered in app_name.lower():
261
+ return app
262
+ return None
263
+
264
+ # -- snapshot ---------------------------------------------------------- #
265
+ def node(self, acc, depth: int, budget: dict, deadline: float) -> dict | None:
266
+ if budget["nodes"] <= 0 or time.monotonic() > deadline:
267
+ budget["truncated"] = True
268
+ return None
269
+ budget["nodes"] -= 1
270
+ try:
271
+ role = acc.get_role_name() or ""
272
+ name = acc.get_name() or ""
273
+ except Exception: # noqa: BLE001
274
+ return None
275
+ item: dict = {"ref": self._ref(acc), "role": role}
276
+ if name:
277
+ item["name"] = name[:120]
278
+ states = _state_names(acc)
279
+ if states:
280
+ item["states"] = states
281
+ rect = _extents(acc)
282
+ if rect:
283
+ item["rect"] = rect
284
+ actions = _actions(acc)
285
+ if actions:
286
+ item["actions"] = actions
287
+ text = _text_preview(acc)
288
+ if text:
289
+ item["text"] = text
290
+ if depth > 0:
291
+ children = []
292
+ try:
293
+ count = acc.get_child_count()
294
+ except Exception: # noqa: BLE001
295
+ count = 0
296
+ for index in range(count):
297
+ child = self.node(acc.get_child_at_index(index), depth - 1, budget, deadline)
298
+ if child is None:
299
+ if budget["truncated"]:
300
+ break
301
+ continue
302
+ children.append(child)
303
+ if children:
304
+ item["children"] = children
305
+ return item
306
+
307
+ def snapshot(self, app: str | None = None, max_depth: int = 3,
308
+ max_nodes: int = 220, timeout_s: float = 20.0) -> dict:
309
+ self.start()
310
+ deadline = time.monotonic() + timeout_s
311
+ budget = {"nodes": max_nodes, "truncated": False}
312
+ if app:
313
+ target = self._app(app)
314
+ if target is None:
315
+ available = [item["name"] for item in self.apps()]
316
+ raise A11yError(f"no application matches {app!r}; running: {available}")
317
+ roots = [(target, app)]
318
+ else:
319
+ roots = []
320
+ for item in self.apps()[:12]:
321
+ target = self._apps.get(item["name"])
322
+ if target is not None:
323
+ roots.append((target, item["name"]))
324
+ tree = []
325
+ for root, label in roots:
326
+ node = self.node(root, max_depth, budget, deadline)
327
+ if node is not None:
328
+ node.setdefault("name", label)
329
+ node["app"] = label
330
+ tree.append(node)
331
+ return {
332
+ "applications": tree,
333
+ "truncated": bool(budget["truncated"]),
334
+ "nodes_used": max_nodes - max(0, budget["nodes"]),
335
+ }
336
+
337
+ # -- search ------------------------------------------------------------ #
338
+ def find(self, query: str | None = None, role: str | None = None,
339
+ app: str | None = None, limit: int = 20, timeout_s: float = 15.0) -> list[dict]:
340
+ self.start()
341
+ deadline = time.monotonic() + timeout_s
342
+ needle = (query or "").lower()
343
+ role_needle = (role or "").lower()
344
+ matches: list[dict] = []
345
+ queue: list[tuple] = []
346
+ if app:
347
+ target = self._app(app)
348
+ if target is None:
349
+ raise A11yError(f"no application matches {app!r}")
350
+ queue.append(target)
351
+ else:
352
+ for item in self.apps()[:20]:
353
+ target = self._apps.get(item["name"])
354
+ if target is not None:
355
+ queue.append(target)
356
+ visited = 0
357
+ while queue and len(matches) < limit and time.monotonic() < deadline and visited < 6000:
358
+ acc = queue.pop(0)
359
+ visited += 1
360
+ try:
361
+ name = acc.get_name() or ""
362
+ role_name = acc.get_role_name() or ""
363
+ except Exception: # noqa: BLE001
364
+ continue
365
+ haystack = f"{name}\n{_text_preview(acc, 200)}".lower()
366
+ hit = (not needle or needle in haystack) and (not role_needle or role_needle in role_name.lower())
367
+ if hit and (needle or role_needle):
368
+ matches.append(self.describe_object(acc, name, role_name))
369
+ try:
370
+ count = acc.get_child_count()
371
+ except Exception: # noqa: BLE001
372
+ count = 0
373
+ for index in range(count):
374
+ try:
375
+ queue.append(acc.get_child_at_index(index))
376
+ except Exception: # noqa: BLE001
377
+ continue
378
+ return matches
379
+
380
+ def describe_object(self, acc, name: str | None = None, role_name: str | None = None) -> dict:
381
+ try:
382
+ name = name if name is not None else (acc.get_name() or "")
383
+ role_name = role_name if role_name is not None else (acc.get_role_name() or "")
384
+ except Exception as error: # noqa: BLE001
385
+ raise A11yError(f"element is no longer available: {error}") from error
386
+ info: dict = {"ref": self._ref(acc), "role": role_name}
387
+ if name:
388
+ info["name"] = name[:160]
389
+ states = _state_names(acc)
390
+ if states:
391
+ info["states"] = states
392
+ rect = _extents(acc)
393
+ if rect:
394
+ info["rect"] = rect
395
+ info["center"] = [rect["x"] + rect["width"] // 2, rect["y"] + rect["height"] // 2]
396
+ actions = _actions(acc)
397
+ if actions:
398
+ info["actions"] = actions
399
+ text = _text_preview(acc, 400)
400
+ if text:
401
+ info["text"] = text
402
+ try:
403
+ description = acc.get_description() or ""
404
+ except Exception: # noqa: BLE001
405
+ description = ""
406
+ if description:
407
+ info["description"] = description[:200]
408
+ return info
409
+
410
+ def describe(self, ref: str) -> dict:
411
+ return self.describe_object(self.resolve(ref))
412
+
413
+ # -- interaction ------------------------------------------------------- #
414
+ def action(self, ref: str, action: str | int | None = None) -> dict:
415
+ acc = self.resolve(ref)
416
+ try:
417
+ iface = acc.get_action_iface()
418
+ except Exception as error: # noqa: BLE001
419
+ raise A11yError(f"element {ref} exposes no actions: {error}") from error
420
+ if iface is None:
421
+ raise A11yError(f"element {ref} exposes no actions")
422
+ index: int | None = None
423
+ names: list[str] = []
424
+ try:
425
+ count = iface.get_n_actions()
426
+ names = [(iface.get_action_name(i) or "") for i in range(count)]
427
+ except Exception: # noqa: BLE001
428
+ count = 0
429
+ if isinstance(action, int):
430
+ index = action
431
+ elif isinstance(action, str) and action:
432
+ lowered = action.lower()
433
+ for position, name in enumerate(names):
434
+ if name.lower() == lowered:
435
+ index = position
436
+ break
437
+ if index is None:
438
+ for position, name in enumerate(names):
439
+ if lowered in name.lower():
440
+ index = position
441
+ break
442
+ else:
443
+ index = 0 if count else None
444
+ if index is None or (count and index >= count):
445
+ raise A11yError(f"element {ref} has no matching action; available: {names}")
446
+ try:
447
+ done = bool(iface.do_action(index))
448
+ except Exception as error: # noqa: BLE001
449
+ raise A11yError(f"action failed on {ref}: {error}") from error
450
+ return {"ref": ref, "action": names[index] if index < len(names) else index, "performed": done}
451
+
452
+ def focus(self, ref: str) -> dict:
453
+ acc = self.resolve(ref)
454
+ try:
455
+ iface = acc.get_component_iface()
456
+ except Exception as error: # noqa: BLE001
457
+ raise A11yError(f"element {ref} has no component interface: {error}") from error
458
+ if iface is None:
459
+ raise A11yError(f"element {ref} has no component interface")
460
+ try:
461
+ done = bool(iface.grab_focus())
462
+ except Exception as error: # noqa: BLE001
463
+ raise A11yError(f"cannot focus {ref}: {error}") from error
464
+ return {"ref": ref, "focused": done}
465
+
466
+ def text(self, ref: str) -> dict:
467
+ acc = self.resolve(ref)
468
+ try:
469
+ iface = acc.get_text_iface()
470
+ except Exception as error: # noqa: BLE001
471
+ raise A11yError(f"element {ref} has no text interface: {error}") from error
472
+ if iface is None:
473
+ raise A11yError(f"element {ref} has no text interface")
474
+ try:
475
+ count = int(iface.get_character_count())
476
+ value = iface.get_text(0, count) if count else ""
477
+ except Exception as error: # noqa: BLE001
478
+ raise A11yError(f"cannot read text of {ref}: {error}") from error
479
+ return {"ref": ref, "text": value or "", "length": count}
480
+
481
+ def set_text(self, ref: str, value: str) -> dict:
482
+ acc = self.resolve(ref)
483
+ try:
484
+ iface = acc.get_editable_text_iface()
485
+ except Exception: # noqa: BLE001
486
+ iface = None
487
+ if iface is None:
488
+ raise A11yError(
489
+ f"element {ref} is not directly editable; focus it and type instead"
490
+ )
491
+ try:
492
+ ok = bool(iface.set_text_contents(value))
493
+ except Exception as error: # noqa: BLE001
494
+ raise A11yError(f"cannot set text of {ref}: {error}") from error
495
+ return {"ref": ref, "set": ok, "length": len(value)}