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.
@@ -0,0 +1,232 @@
1
+ """System-side tools for the Linux desktop MCP server.
2
+
3
+ Covers the pieces the Windows build got from Win32 that have no single Wayland
4
+ equivalent:
5
+
6
+ * clipboard -> wl-clipboard (``wl-copy`` / ``wl-paste``)
7
+ * process list -> ``ps`` (portable, no psutil dependency)
8
+ * app launch -> fork/exec of an argv, detached from the server
9
+ * "registry" -> ``gsettings`` / ``dconf`` (the user-facing settings store)
10
+ * notifications -> ``org.freedesktop.Notifications`` over the session bus
11
+ * lock state -> ``org.gnome.ScreenSaver.GetActive`` over the session bus
12
+ * capability probe -> what the doctor tool reports
13
+
14
+ Everything shells out to the system binaries the prep script installs, so the
15
+ module keeps working when those packages are missing: each helper reports a
16
+ precise reason instead of raising a traceback into the MCP layer.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import shutil
23
+ import subprocess
24
+
25
+ RUN_TIMEOUT = 10
26
+ WL_COPY = "wl-copy"
27
+ WL_PASTE = "wl-paste"
28
+ GSETTINGS = "gsettings"
29
+ DCONF = "dconf"
30
+
31
+
32
+ class SysError(RuntimeError):
33
+ """A system-side operation failed (missing binary, bad argument, ...)."""
34
+
35
+
36
+ def _run(argv: list[str], timeout: float = RUN_TIMEOUT, stdin: str | None = None) -> tuple[int, str, str]:
37
+ try:
38
+ completed = subprocess.run(
39
+ argv,
40
+ input=stdin,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ timeout=timeout,
45
+ check=False,
46
+ )
47
+ except FileNotFoundError as error:
48
+ raise SysError(f"{argv[0]} is not installed") from error
49
+ except subprocess.TimeoutExpired as error:
50
+ raise SysError(f"{argv[0]} timed out after {timeout:.0f}s") from error
51
+ return completed.returncode, completed.stdout, completed.stderr
52
+
53
+
54
+ def screen_locked() -> bool | None:
55
+ """Report whether the GNOME session is locked (``True``/``False``/``None``).
56
+
57
+ A locked screen still allows screenshots but must never receive injected
58
+ keystrokes or clicks: the lock screen's focused widget is the password
59
+ field, so synthetic input would type a password nobody asked for. ``None``
60
+ means the state could not be read (no session bus, no screen saver
61
+ service), in which case callers keep working and rely on the user.
62
+ """
63
+ try:
64
+ import gi
65
+
66
+ gi.require_version("Gio", "2.0")
67
+ gi.require_version("GLib", "2.0")
68
+ from gi.repository import Gio, GLib
69
+ except (ImportError, ValueError):
70
+ return None
71
+ try:
72
+ connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
73
+ reply = connection.call_sync(
74
+ "org.gnome.ScreenSaver",
75
+ "/org/gnome/ScreenSaver",
76
+ "org.gnome.ScreenSaver",
77
+ "GetActive",
78
+ None,
79
+ GLib.VariantType.new("(b)"),
80
+ Gio.DBusCallFlags.NONE,
81
+ 2000,
82
+ None,
83
+ )
84
+ return bool(reply.unpack()[0])
85
+ except Exception: # noqa: BLE001 - a missing service is not an error here
86
+ return None
87
+
88
+
89
+ def have(binary: str) -> bool:
90
+ return shutil.which(binary) is not None
91
+
92
+
93
+ # --------------------------------------------------------------------------- #
94
+ # clipboard
95
+ # --------------------------------------------------------------------------- #
96
+ def clipboard_available() -> bool:
97
+ return have(WL_COPY) and have(WL_PASTE)
98
+
99
+
100
+ def clipboard_get() -> dict:
101
+ if not clipboard_available():
102
+ raise SysError("wl-clipboard is missing; run the prep script to install wl-clipboard")
103
+ code, out, err = _run([WL_PASTE, "--no-newline"], timeout=8)
104
+ if code != 0:
105
+ raise SysError(f"wl-paste failed: {err.strip() or 'no clipboard content'}")
106
+ return {"text": out, "length": len(out)}
107
+
108
+
109
+ def clipboard_set(text: str) -> dict:
110
+ if not clipboard_available():
111
+ raise SysError("wl-clipboard is missing; run the prep script to install wl-clipboard")
112
+ # wl-copy forks into the background to keep serving the selection.
113
+ code, _out, err = _run([WL_COPY], timeout=8, stdin=text)
114
+ if code != 0:
115
+ raise SysError(f"wl-copy failed: {err.strip()}")
116
+ return {"ok": True, "length": len(text)}
117
+
118
+
119
+ # --------------------------------------------------------------------------- #
120
+ # processes
121
+ # --------------------------------------------------------------------------- #
122
+ def process_list(limit: int = 25, sort: str = "cpu", name_filter: str | None = None) -> list[dict]:
123
+ sort_key = {"cpu": "-pcpu", "mem": "-pmem", "pid": "pid"}.get(sort, "-pcpu")
124
+ code, out, err = _run(
125
+ ["ps", "-eo", "pid=,ppid=,user=,pcpu=,pmem=,etime=,comm=,args=", f"--sort={sort_key}"],
126
+ timeout=8,
127
+ )
128
+ if code != 0:
129
+ raise SysError(f"ps failed: {err.strip()}")
130
+ rows: list[dict] = []
131
+ needle = (name_filter or "").lower()
132
+ for line in out.splitlines():
133
+ parts = line.split(None, 7)
134
+ if len(parts) < 8:
135
+ continue
136
+ pid, ppid, user, cpu, mem, elapsed, comm, args = parts
137
+ if needle and needle not in comm.lower() and needle not in args.lower():
138
+ continue
139
+ rows.append({
140
+ "pid": int(pid),
141
+ "ppid": int(ppid),
142
+ "user": user,
143
+ "cpu_percent": float(cpu),
144
+ "mem_percent": float(mem),
145
+ "elapsed": elapsed,
146
+ "command": comm,
147
+ "args": args.strip()[:300],
148
+ })
149
+ if len(rows) >= max(1, min(limit, 200)):
150
+ break
151
+ return rows
152
+
153
+
154
+ def process_kill(pid: int, signal_name: str = "TERM") -> dict:
155
+ if pid <= 1:
156
+ raise SysError("refusing to signal pid 1 or an invalid pid")
157
+ if pid == os.getpid():
158
+ raise SysError("refusing to signal the desktop server itself")
159
+ allowed = {"TERM", "KILL", "INT", "HUP"}
160
+ if signal_name not in allowed:
161
+ raise SysError(f"unsupported signal {signal_name!r}; use one of {sorted(allowed)}")
162
+ code, _out, err = _run(["kill", f"-{signal_name}", str(pid)], timeout=5)
163
+ if code != 0:
164
+ raise SysError(f"kill {pid} failed: {err.strip()}")
165
+ return {"pid": pid, "signal": signal_name, "sent": True}
166
+
167
+
168
+ # --------------------------------------------------------------------------- #
169
+ # launching applications
170
+ # --------------------------------------------------------------------------- #
171
+ def launch(argv: list[str] | str, wait_ms: int = 1200) -> dict:
172
+ if isinstance(argv, str):
173
+ import shlex
174
+
175
+ args = shlex.split(argv)
176
+ else:
177
+ args = list(argv)
178
+ if not args:
179
+ raise SysError("no command given")
180
+ binary = args[0]
181
+ if not (have(binary) or os.path.isabs(binary)):
182
+ raise SysError(f"{binary!r} is not an executable on PATH")
183
+ try:
184
+ process = subprocess.Popen(
185
+ args,
186
+ stdout=subprocess.DEVNULL,
187
+ stderr=subprocess.DEVNULL,
188
+ stdin=subprocess.DEVNULL,
189
+ start_new_session=True,
190
+ )
191
+ except OSError as error:
192
+ raise SysError(f"cannot launch {binary}: {error}") from error
193
+ return {"pid": process.pid, "command": args, "started": True}
194
+
195
+
196
+ # --------------------------------------------------------------------------- #
197
+ # settings ("registry")
198
+ # --------------------------------------------------------------------------- #
199
+ def settings_get(schema: str, key: str) -> dict:
200
+ code, out, err = _run([GSETTINGS, "get", schema, key], timeout=5)
201
+ if code != 0:
202
+ raise SysError(f"gsettings get {schema} {key} failed: {err.strip()}")
203
+ return {"schema": schema, "key": key, "value": out.strip()}
204
+
205
+
206
+ def settings_set(schema: str, key: str, value: str) -> dict:
207
+ code, _out, err = _run([GSETTINGS, "set", schema, key, value], timeout=5)
208
+ if code != 0:
209
+ raise SysError(f"gsettings set {schema} {key} failed: {err.strip()}")
210
+ return {"schema": schema, "key": key, "value": value, "ok": True}
211
+
212
+
213
+ def settings_list_keys(schema: str) -> list[str]:
214
+ code, out, err = _run([GSETTINGS, "list-keys", schema], timeout=5)
215
+ if code != 0:
216
+ raise SysError(f"gsettings list-keys {schema} failed: {err.strip()}")
217
+ return [line.strip() for line in out.splitlines() if line.strip()]
218
+
219
+
220
+ # --------------------------------------------------------------------------- #
221
+ # notifications
222
+ # --------------------------------------------------------------------------- #
223
+ def notify(summary: str, body: str = "", timeout_ms: int = 8000) -> dict:
224
+ if not have("notify-send"):
225
+ raise SysError("notify-send is missing (install libnotify-bin)")
226
+ argv = ["notify-send", "--app-name=DSH Computer Use", "-t", str(int(timeout_ms)), summary]
227
+ if body:
228
+ argv.append(body)
229
+ code, _out, err = _run(argv, timeout=8)
230
+ if code != 0:
231
+ raise SysError(f"notify-send failed: {err.strip()}")
232
+ return {"sent": True}
@@ -0,0 +1,280 @@
1
+ """Opt-in screen unlocking (default: off).
2
+
3
+ The plugin never asks for, receives or logs the account password in a chat or a
4
+ config file. When the user turns this on (``unlock: "keyring"``) they store the
5
+ password themselves in the GNOME keyring — ``loginctl``/libsecret — and the
6
+ server only reads it at the moment ``unlock_screen`` runs.
7
+
8
+ What it changes, stated plainly: with this on, the lock screen no longer stops
9
+ *software running as you*. The way the password is typed is a real kernel
10
+ keyboard, so the lock screen cannot tell it apart from your hands. The lock
11
+ screen keeps stopping a person at the keyboard, and nothing more. That is why
12
+ the default is off and every call has to be an explicit ``unlock_screen``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import shutil
20
+ import subprocess
21
+ import time
22
+ from typing import Any
23
+
24
+ import cu_sys
25
+
26
+ SETTINGS_DIR = os.path.join(
27
+ os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"),
28
+ "dsh-linux-cu",
29
+ )
30
+ SETTINGS_PATH = os.path.join(SETTINGS_DIR, "settings.json")
31
+
32
+ SERVICE = "dsh-linux-cu"
33
+ LABEL = "DSH Linux Computer Use unlock password"
34
+ KEYRING_SCHEMA = "org.dsh.linux.computer.use"
35
+
36
+ POLICIES = ("off", "keyring")
37
+ DEFAULT_POLICY = "off"
38
+
39
+ MAX_ATTEMPTS = 2
40
+
41
+
42
+ class UnlockError(RuntimeError):
43
+ pass
44
+
45
+
46
+ # --------------------------------------------------------------------------- #
47
+ # settings
48
+ # --------------------------------------------------------------------------- #
49
+
50
+
51
+ def _account() -> str:
52
+ return os.environ.get("USER") or os.environ.get("LOGNAME") or "user"
53
+
54
+
55
+ def load_settings() -> dict[str, Any]:
56
+ data: dict[str, Any] = {}
57
+ try:
58
+ with open(SETTINGS_PATH, "r", encoding="utf-8") as handle:
59
+ loaded = json.load(handle)
60
+ if isinstance(loaded, dict):
61
+ data = loaded
62
+ except (OSError, ValueError):
63
+ data = {}
64
+ # an environment override wins, so a profile can pin the policy
65
+ env = os.environ.get("DSH_LINUX_CU_UNLOCK")
66
+ if env:
67
+ data["unlock"] = env
68
+ policy = str(data.get("unlock") or DEFAULT_POLICY).strip().lower()
69
+ if policy not in POLICIES:
70
+ policy = DEFAULT_POLICY
71
+ data["unlock"] = policy
72
+ return data
73
+
74
+
75
+ def save_settings(**changes: Any) -> dict[str, Any]:
76
+ data = load_settings()
77
+ data.update(changes)
78
+ os.makedirs(SETTINGS_DIR, mode=0o700, exist_ok=True)
79
+ tmp = SETTINGS_PATH + ".tmp"
80
+ with open(tmp, "w", encoding="utf-8") as handle:
81
+ json.dump(data, handle, indent=2, sort_keys=True)
82
+ handle.write("\n")
83
+ os.chmod(tmp, 0o600)
84
+ os.replace(tmp, SETTINGS_PATH)
85
+ return data
86
+
87
+
88
+ def policy() -> str:
89
+ return str(load_settings().get("unlock", DEFAULT_POLICY))
90
+
91
+
92
+ def set_policy(value: str) -> str:
93
+ value = value.strip().lower()
94
+ if value not in POLICIES:
95
+ raise UnlockError(f"unknown unlock policy {value!r}; expected one of {', '.join(POLICIES)}")
96
+ save_settings(unlock=value)
97
+ return value
98
+
99
+
100
+ def unlock_enabled() -> bool:
101
+ return policy() == "keyring"
102
+
103
+
104
+ # --------------------------------------------------------------------------- #
105
+ # keyring storage (libsecret, no plain files)
106
+ # --------------------------------------------------------------------------- #
107
+
108
+
109
+ def _attrs() -> dict[str, str]:
110
+ return {"service": SERVICE, "account": _account()}
111
+
112
+
113
+ def _gi_secret():
114
+ import gi
115
+
116
+ gi.require_version("Secret", "1")
117
+ from gi.repository import Secret # noqa: WPS433
118
+
119
+ return Secret
120
+
121
+
122
+ def _gi_schema(Secret):
123
+ return Secret.Schema.new(
124
+ KEYRING_SCHEMA,
125
+ Secret.SchemaFlags.NONE,
126
+ {
127
+ "service": Secret.SchemaAttributeType.STRING,
128
+ "account": Secret.SchemaAttributeType.STRING,
129
+ },
130
+ )
131
+
132
+
133
+ def store_password(password: str) -> None:
134
+ if not password:
135
+ raise UnlockError("empty password")
136
+ try:
137
+ Secret = _gi_secret()
138
+ ok = Secret.password_store_sync(
139
+ _gi_schema(Secret), _attrs(), Secret.COLLECTION_DEFAULT, LABEL, password, None
140
+ )
141
+ if not ok:
142
+ raise UnlockError("libsecret refused to store the password")
143
+ return
144
+ except UnlockError:
145
+ raise
146
+ except Exception:
147
+ pass
148
+ # fallback: the secret-tool helper, password on stdin (never argv)
149
+ binary = shutil.which("secret-tool")
150
+ if not binary:
151
+ raise UnlockError(
152
+ "no keyring backend available; install libsecret-tools or gir1.2-secret-1"
153
+ )
154
+ proc = subprocess.run(
155
+ [binary, "store", f"--label={LABEL}", "service", SERVICE, "account", _account()],
156
+ input=password,
157
+ text=True,
158
+ capture_output=True,
159
+ timeout=20,
160
+ )
161
+ if proc.returncode != 0:
162
+ raise UnlockError(f"secret-tool store failed: {proc.stderr.strip()}")
163
+
164
+
165
+ def fetch_password() -> str | None:
166
+ try:
167
+ Secret = _gi_secret()
168
+ value = Secret.password_lookup_sync(_gi_schema(Secret), _attrs(), None)
169
+ if value:
170
+ return str(value)
171
+ except Exception:
172
+ pass
173
+ binary = shutil.which("secret-tool")
174
+ if not binary:
175
+ return None
176
+ proc = subprocess.run(
177
+ [binary, "lookup", "service", SERVICE, "account", _account()],
178
+ text=True,
179
+ capture_output=True,
180
+ timeout=20,
181
+ )
182
+ if proc.returncode != 0:
183
+ return None
184
+ value = proc.stdout.rstrip("\n")
185
+ return value or None
186
+
187
+
188
+ def clear_password() -> bool:
189
+ removed = False
190
+ try:
191
+ Secret = _gi_secret()
192
+ Secret.password_clear_sync(_gi_schema(Secret), _attrs(), None)
193
+ removed = True
194
+ except Exception:
195
+ pass
196
+ binary = shutil.which("secret-tool")
197
+ if binary:
198
+ proc = subprocess.run(
199
+ [binary, "clear", "service", SERVICE, "account", _account()],
200
+ text=True,
201
+ capture_output=True,
202
+ timeout=20,
203
+ )
204
+ removed = removed or proc.returncode == 0
205
+ return removed
206
+
207
+
208
+ def has_password() -> bool:
209
+ return fetch_password() is not None
210
+
211
+
212
+ # --------------------------------------------------------------------------- #
213
+ # unlocking
214
+ # --------------------------------------------------------------------------- #
215
+
216
+
217
+ def status() -> dict[str, Any]:
218
+ policy_name = policy()
219
+ stored = has_password() if policy_name == "keyring" else None
220
+ return {
221
+ "unlock_policy": policy_name,
222
+ "password_stored": stored,
223
+ "settings_path": SETTINGS_PATH,
224
+ "available_policies": list(POLICIES),
225
+ }
226
+
227
+
228
+ def unlock(controller, timeout_s: float = 8.0) -> dict[str, Any]:
229
+ """Type the stored password into the lock screen. Never echoes it."""
230
+ if not unlock_enabled():
231
+ raise UnlockError(
232
+ 'unlocking is switched off; set the unlock policy to "keyring" first '
233
+ f"({SETTINGS_PATH})"
234
+ )
235
+ locked = cu_sys.screen_locked()
236
+ if locked is False:
237
+ return {"unlocked": True, "attempts": 0, "reason": "the session was not locked"}
238
+
239
+ password = fetch_password()
240
+ if not password:
241
+ raise UnlockError(
242
+ "no unlock password is stored; run "
243
+ "`python3 -u ~/.local/share/dsh-linux-computer-use/linux_desktop_mcp.py "
244
+ "--set-unlock-password` in your own terminal"
245
+ )
246
+
247
+ attempts = 0
248
+ try:
249
+ for attempts in range(1, MAX_ATTEMPTS + 1):
250
+ controller.key("Escape") # clear any half-typed leftovers
251
+ time.sleep(0.3)
252
+ controller.type_text(password)
253
+ time.sleep(0.2)
254
+ controller.key("Return")
255
+ deadline = time.monotonic() + timeout_s
256
+ while time.monotonic() < deadline:
257
+ time.sleep(0.5)
258
+ if cu_sys.screen_locked() is False:
259
+ return {"unlocked": True, "attempts": attempts}
260
+ raise UnlockError(
261
+ f"the session is still locked after {attempts} attempt(s); "
262
+ "the stored password may be wrong (or the screen is showing a system dialog)"
263
+ )
264
+ finally:
265
+ password = None # noqa: F841 (drop the reference as soon as possible)
266
+
267
+
268
+ def prompt_and_store() -> str:
269
+ """Interactive store, for the human's own terminal."""
270
+ import getpass
271
+
272
+ first = getpass.getpass("Unlock password (input hidden, not logged): ")
273
+ if not first:
274
+ raise UnlockError("cancelled: empty password")
275
+ second = getpass.getpass("Repeat to confirm: ")
276
+ if first != second:
277
+ raise UnlockError("cancelled: the two entries differ")
278
+ store_password(first)
279
+ set_policy("keyring")
280
+ return "stored the password in the keyring and set unlock policy to keyring"