dsh-plugin-linux-computer-use 0.1.2 → 0.3.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 CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 - 2026-11-27
4
+
5
+ - New `window_activate`: raise a window by title substring (or app name). Three
6
+ strategies are tried in order and the reply says which one worked: `xdotool
7
+ windowactivate` for XWayland surfaces, the AT-SPI default action for toolkits
8
+ that honour it, and Alt+Tab cycling verified against the accessibility tree
9
+ for native Wayland windows, which neither X11 nor AT-SPI can raise. Both
10
+ Alt+Tab (windows of the current application) and Super+Tab (applications)
11
+ are cycled, because GNOME binds them differently. A combination whose first
12
+ press moves no window is abandoned straight away, so raising a window of
13
+ another application takes one Super+Tab instead of thirteen Alt+Tabs.
14
+ - New `wait_until`: poll until a condition holds instead of sleeping a fixed
15
+ time. Conditions are a window appearing or disappearing
16
+ (`{"window": {"title": "...", "exists": false}}`), a window becoming active
17
+ (`{"window_active": "Chrome"}`), an accessibility node showing up
18
+ (`{"ui": {"app": "...", "name": "...", "role": "..."}}`), or the user being
19
+ idle for a while (`{"idle_at_least": 60000}`). On timeout it returns
20
+ `satisfied: false` with the last observed state instead of throwing.
21
+ - `window_list` now reports `active` from the AT-SPI `ACTIVE` state, which is
22
+ the flag most toolkits set on the toplevel frame (`FOCUSED` alone missed
23
+ them, so every window used to look inactive).
24
+ - MCP server version 1.2.0.
25
+
26
+ ## 0.2.0 - 2026-11-27
27
+
28
+ - `screenshot` gained `region` and `scale`. Cropping before downscaling is the
29
+ fix for HiDPI desktops: 11 px UI text on a 4480x1440 desktop used to turn to
30
+ mush once the capture was scaled to 1400 px wide, and re-reading a whole
31
+ screen to make out one label burned most of the tokens in a session. A
32
+ cropped capture keeps native sharpness and costs a fraction of the tokens.
33
+ `space: "screenshot"` adds the crop offset back, so coordinates stay correct.
34
+ - New idle guard: synthetic input is refused while the user has touched the
35
+ keyboard or pointer in the last 60 seconds (`org.gnome.Mutter.IdleMonitor`),
36
+ so automation cannot fight the person at the machine. Pass
37
+ `allow_active_input: true` on any input tool — the model does so when the
38
+ user explicitly asked it to drive — or set
39
+ `DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`; tune the window with
40
+ `DSH_LINUX_CU_IDLE_GUARD_MS`. Screenshots, UI reads and clipboard reads stay
41
+ available, and `desktop_status` reports `session.idle_ms`.
42
+ - `capture_shot` now converts logical coordinates to the physical pixels the
43
+ portal returns, so `region` is correct on fractional HiDPI scaling.
44
+ - MCP server version 1.1.0.
45
+
3
46
  ## 0.1.1 - 2026-11-25
4
47
 
5
48
  - fix: send the complete `input_absinfo` when creating the absolute pointer.
package/README.md CHANGED
@@ -24,8 +24,10 @@ English summary at the bottom.
24
24
  | "注册表"类比 | `gsettings` / dconf |
25
25
  | 通知 | `notify-send` |
26
26
  | 显示器信息 | Mutter `DisplayConfig`(坐标换算、多屏) |
27
+ | 窗口操作 | `window_list` 列出标题与是否 `active`;`window_activate` 按标题子串把窗口抬到前台——XWayland 走 `xdotool`,原生 Wayland 用 Alt+Tab / Super+Tab 循环并以无障碍树校验(GNOME 下 Alt+Tab 只切本应用窗口,Super+Tab 才切应用),返回里会说明这次用的是哪条路 |
28
+ | 等待条件 | `wait_until` 轮询直到满足条件:窗口出现/消失、某个窗口变成前台、某个 UI 节点出现、或用户空闲满多少毫秒;超时返回 `satisfied: false` 与最后一轮观察到的状态,不抛错 |
27
29
 
28
- 28 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
30
+ 30 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
29
31
 
30
32
  ## 安装
31
33
 
@@ -63,6 +65,9 @@ sudo ./linux-computer-use-prep.sh --verify # 不需要 sudo
63
65
  - AT-SPI 全量枚举约 3–4 秒(某个无响应应用会拖慢),所以应用列表有 5 秒缓存。
64
66
  - 截屏必须走 portal:第一次会弹一次系统授权框(GNOME 记住你的选择),之后每次截图静默、约 0.5 秒。ScreenCast 流式路径(`DSH_LINUX_CU_SCREENCAST=1` 可强制)在 GNOME 46 上画面静止时不产帧,只当兜底。
65
67
  - **锁屏时只截图、不注入**:服务器会向 `org.gnome.ScreenSaver.GetActive` 查询锁屏状态,处于锁屏时 `click` / `key` / `type_text` 等全部拒绝执行(锁屏焦点在密码框上,误打就会往密码里塞字符),`screenshot` 仍可用。`desktop_status` 的 `session.locked` 会告诉你当前状态。
68
+ - **你在用电脑时也不注入**:服务器用 `org.gnome.Mutter.IdleMonitor.GetIdletime` 查空闲时间,最近 60 秒内有键鼠动作就拒绝点击/输入(否则自动化会和你抢光标)。这一条可以放行:工具参数带 `allow_active_input: true`(模型在你明确让它代操作时会带),或设环境变量 `DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`;阈值用 `DSH_LINUX_CU_IDLE_GUARD_MS` 调(默认 `60000`)。截图、读 UI 树、读文件不受影响。`desktop_status` 的 `session.idle_ms` 就是当前空闲毫秒数。
69
+ - **原生 Wayland 窗口没法被 X11 抬起**:Chrome、GNOME 自家应用在 `xdotool search` 里完全不存在,`window_activate` 对它们会用 Alt+Tab(本应用内切窗口)与 Super+Tab(切应用)循环,需要 uinput 键盘可用。如果三条路都失败,返回 `activated: false` 与 `tried` 明细,而不是假装成功。
70
+ - **截图要看清小字就用 `region`**:整屏 4480×1440 缩到 1400 宽,11px 的小字会糊成一团;传 `{"region": {"x":120,"y":140,"width":900,"height":620}, "scale":1.0}` 只截那块、按原尺寸返回,既清楚又省 token。`space: "screenshot"` 会自动加回偏移,不用自己算。
66
71
  - 只能工作在**当前登录的图形会话**里;SSH / 无头环境下没有桌面可控制。
67
72
 
68
73
  ## 安全模型
package/docs/DETAIL.md CHANGED
@@ -15,6 +15,8 @@ Wayland neither exists, so each capability has its own path:
15
15
  | Clipboard | `wl-copy` / `wl-paste` | `xclip` does not work on Wayland |
16
16
  | Settings ("registry") | `gsettings` / dconf | closest analogue to the registry |
17
17
  | Lock state | `org.gnome.ScreenSaver.GetActive` over the session bus | input must stop while the lock screen holds the password field; screenshots stay allowed |
18
+ | Idle state | `org.gnome.Mutter.IdleMonitor.GetIdletime` over the session bus | synthetic input stops while the user is at the keyboard, so automation cannot fight them |
19
+ | Raising a window | `xdotool windowactivate` (XWayland), the AT-SPI default action, then Alt+Tab and Super+Tab with an accessibility check | native Wayland surfaces are invisible to X11, `_NET_ACTIVE_WINDOW` cannot be honoured by the compositor, and the AT-SPI default action is a no-op for most toolkits |
18
20
  | Processes | `ps` and `/proc` | portable |
19
21
 
20
22
  ## Requirements
@@ -43,18 +45,31 @@ reload the page. `linux_mcp_doctor` works either way.
43
45
 
44
46
  | Group | Tools |
45
47
  | --- | --- |
46
- | Vision | `screenshot` — PNG + size + path; the first call asks for permission once |
48
+ | Vision | `screenshot` — PNG + size + path; `region` crops before scaling (sharp text), `scale` sets pixels per logical pixel; the first call asks for permission once |
47
49
  | Tree | `ui_apps`, `ui_tree`, `ui_find`, `ui_describe`, `ui_text` |
48
50
  | Act on elements | `ui_action` (invoke/press/toggle), `ui_focus`, `ui_set_text` |
49
51
  | Pointer | `click`, `move`, `drag`, `scroll`, `pointer_button` (hold/release) |
50
52
  | Keyboard | `key` (`ctrl+shift+t`), `type_text` (Unicode via clipboard paste) |
51
53
  | Clipboard | `clipboard_get`, `clipboard_set` |
52
- | System | `process_list`, `process_kill`, `launch_app`, `settings_get`, `settings_set`, `settings_list_keys`, `notify`, `window_list`, `display_info`, `desktop_status` |
54
+ | System | `process_list`, `process_kill`, `launch_app`, `settings_get`, `settings_set`, `settings_list_keys`, `notify`, `display_info`, `desktop_status` |
55
+ | Windows | `window_list` (titles + `active`), `window_activate` — raises a window by title substring; XWayland through `xdotool`, native Wayland by cycling Alt+Tab then Super+Tab and checking the accessibility tree (GNOME binds Alt+Tab to windows of the current app and Super+Tab to applications), and the reply names the strategy that worked |
56
+ | Waiting | `wait_until` — poll until `window` appears/disappears, `window_active` is raised, a `ui` node shows up, or `idle_at_least` ms pass; on timeout it returns `satisfied: false` with the last state instead of throwing |
53
57
  | Unlocking (opt-in) | `unlock_screen` — only listed while the unlock policy is on; see below |
54
58
 
55
59
  Coordinates are **logical desktop pixels**. Pass `space: "screenshot"` to give
56
60
  coordinates in the pixels of the most recent screenshot instead; on a HiDPI
57
- display those differ, and the tool converts for you.
61
+ display those differ, and the tool converts for you. A cropped screenshot keeps
62
+ the offset, so `space: "screenshot"` still lands on the right spot.
63
+
64
+ Reading one window is much cheaper than reading the whole desktop:
65
+
66
+ ```json
67
+ {"region": {"x": 120, "y": 140, "width": 900, "height": 620}, "scale": 1.0}
68
+ ```
69
+
70
+ The desktop is 4480x1440 on HiDPI; scaled to 1400 px wide the same capture
71
+ turns 11 px text into mush, while the crop above stays at native sharpness and
72
+ costs a third of the tokens.
58
73
 
59
74
  ## What works well and what does not
60
75
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-linux-computer-use",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
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
5
  "type": "module",
6
6
  "license": "MIT",
@@ -521,3 +521,36 @@ def downscale(path: str, max_width: int) -> tuple[int, int]:
521
521
  return png_size(path)
522
522
  except Exception: # noqa: BLE001 - scaling is best effort
523
523
  return (width, height)
524
+
525
+
526
+ def crop_and_scale(path: str, box: tuple[int, int, int, int], out_width: int) -> tuple[int, int]:
527
+ """Crop ``box`` (physical pixels) out of a PNG, then scale it to ``out_width``.
528
+
529
+ Cropping before scaling is the whole point: a 4480x1440 desktop scaled to
530
+ 1400 px makes small UI text unreadable, while a 900x400 region of it stays
531
+ sharp at the same output size. The box is clipped to the image, and every
532
+ failure falls back to the untouched file so a capture is never lost.
533
+ """
534
+ width, height = png_size(path)
535
+ x, y, w, h = box
536
+ x = max(0, min(int(x), max(0, width - 1)))
537
+ y = max(0, min(int(y), max(0, height - 1)))
538
+ w = max(1, min(int(w), width - x))
539
+ h = max(1, min(int(h), height - y))
540
+ target_width = out_width if out_width > 0 else w
541
+ target_height = max(1, round(h * target_width / w)) if w else h
542
+ try:
543
+ gi.require_version("GdkPixbuf", "2.0")
544
+ from gi.repository import GdkPixbuf
545
+
546
+ pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
547
+ cropped = pixbuf.new_subpixbuf(x, y, w, h)
548
+ out = cropped
549
+ if (target_width, target_height) != (w, h):
550
+ scaled = cropped.scale_simple(target_width, target_height, GdkPixbuf.InterpType.BILINEAR)
551
+ if scaled is not None:
552
+ out = scaled
553
+ out.savev(path, "png", [], [])
554
+ return png_size(path)
555
+ except Exception: # noqa: BLE001 - cropping is best effort
556
+ return (width, height)
package/server/cu_sys.py CHANGED
@@ -86,6 +86,40 @@ def screen_locked() -> bool | None:
86
86
  return None
87
87
 
88
88
 
89
+ def idle_ms() -> int | None:
90
+ """Milliseconds since the last keyboard or pointer event, or ``None``.
91
+
92
+ Mutter's IdleMonitor is the compositor's own idea of idleness, so it sees
93
+ input delivered to any client (including the ones synthetic input misses).
94
+ ``None`` means the service is not there (not GNOME, or a very old release);
95
+ callers then fall back to behaving as before.
96
+ """
97
+ try:
98
+ import gi
99
+
100
+ gi.require_version("Gio", "2.0")
101
+ gi.require_version("GLib", "2.0")
102
+ from gi.repository import Gio, GLib
103
+ except (ImportError, ValueError):
104
+ return None
105
+ try:
106
+ connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
107
+ reply = connection.call_sync(
108
+ "org.gnome.Mutter.IdleMonitor",
109
+ "/org/gnome/Mutter/IdleMonitor/Core",
110
+ "org.gnome.Mutter.IdleMonitor",
111
+ "GetIdletime",
112
+ None,
113
+ GLib.VariantType.new("(t)"),
114
+ Gio.DBusCallFlags.NONE,
115
+ 2000,
116
+ None,
117
+ )
118
+ return int(reply.unpack()[0])
119
+ except Exception: # noqa: BLE001 - a missing service is not an error here
120
+ return None
121
+
122
+
89
123
  def have(binary: str) -> bool:
90
124
  return shutil.which(binary) is not None
91
125
 
@@ -32,6 +32,7 @@ from __future__ import annotations
32
32
  import base64
33
33
  import json
34
34
  import os
35
+ import subprocess
35
36
  import sys
36
37
  import time
37
38
  import traceback
@@ -45,16 +46,17 @@ import cu_sys # noqa: E402
45
46
  import cu_unlock # noqa: E402
46
47
 
47
48
  SERVER_NAME = "linux-desktop-mcp"
48
- SERVER_VERSION = "1.0.0"
49
+ SERVER_VERSION = "1.2.0"
49
50
  PROTOCOL_VERSION = "2025-06-18"
50
51
  SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
51
52
  LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
52
53
  MAX_IMAGE_BYTES = 3_500_000
53
54
  SHOT_MAX_WIDTH = 1600
55
+ IDLE_GUARD_MS = int(os.environ.get("DSH_LINUX_CU_IDLE_GUARD_MS", "60000"))
54
56
 
55
57
  A11Y = cu_a11y.A11y()
56
58
  INPUT: cu_input.InputController | None = None
57
- LAST_SHOT: dict = {"path": None, "width": 0, "height": 0, "logical": None, "at": 0.0}
59
+ LAST_SHOT: dict = {"path": None, "width": 0, "height": 0, "logical": None, "origin": (0, 0), "ratio": 1.0, "at": 0.0}
58
60
 
59
61
 
60
62
  BUTTON_NAMES = {1: "left", 2: "middle", 3: "right"}
@@ -106,29 +108,50 @@ def controller(reload_layout: bool = False) -> cu_input.InputController:
106
108
  return INPUT
107
109
 
108
110
 
109
- def _guard_input(what: str) -> None:
110
- """Refuse to inject input while the session is locked.
111
+ def _guard_input(what: str, args: dict | None = None) -> None:
112
+ """Refuse to inject input while the session is locked or the user is active.
111
113
 
112
114
  A locked GNOME session keeps the password field focused, so a stray click
113
115
  or keystroke lands inside it. Screenshots stay allowed; only input is
114
116
  blocked. ``DSH_LINUX_CU_ALLOW_LOCKED_INPUT=1`` is the escape hatch for
115
117
  someone who really knows what they are doing.
118
+
119
+ The second guard covers a subtler failure: driving the pointer while the
120
+ user is typing fights them for the keyboard and moves their cursor mid
121
+ gesture. When the compositor reports recent input, injection is refused
122
+ unless the caller says the user asked for it right now
123
+ (``allow_active_input=true``) or the machine-wide escape hatch
124
+ ``DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`` is set.
116
125
  """
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
+ if os.environ.get("DSH_LINUX_CU_ALLOW_LOCKED_INPUT") != "1":
127
+ if cu_sys.screen_locked() is True:
128
+ if cu_unlock.unlock_enabled():
129
+ hint = "unlock_screen is available because the user turned AI unlocking on."
130
+ else:
131
+ hint = (
132
+ "Unlock the desktop and retry; the user can also switch AI unlocking "
133
+ "on (unlock policy) to let this be handled here."
134
+ )
135
+ raise ToolError(
136
+ f"refusing to {what}: the session is locked. The lock screen's focused "
137
+ f"widget is the password field, so injected input would type into it. "
138
+ f"{hint} mcp__linux__screenshot still works."
126
139
  )
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
- )
140
+
141
+ if os.environ.get("DSH_LINUX_CU_ALLOW_ACTIVE_INPUT") == "1":
142
+ return
143
+ if args and args.get("allow_active_input"):
144
+ return
145
+ idle = cu_sys.idle_ms()
146
+ if idle is None or idle >= IDLE_GUARD_MS:
147
+ return
148
+ raise ToolError(
149
+ f"refusing to {what}: the user is at the keyboard (last input {idle / 1000:.1f}s ago), "
150
+ f"so synthetic input would fight them. Wait until they have been idle for "
151
+ f"{IDLE_GUARD_MS // 1000}s, or pass allow_active_input=true when they just asked you "
152
+ f"to drive the desktop. Screenshots and reads stay available."
153
+ )
154
+
132
155
 
133
156
 
134
157
  def _to_logical(x: float, y: float, space: str) -> tuple[float, float]:
@@ -137,18 +160,50 @@ def _to_logical(x: float, y: float, space: str) -> tuple[float, float]:
137
160
  logical = LAST_SHOT.get("logical") or None
138
161
  if not shot_w or not logical:
139
162
  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)
163
+ ratio = LAST_SHOT.get("ratio") or ((logical[0] / shot_w) if shot_w else 1.0)
164
+ origin = LAST_SHOT.get("origin") or (0, 0)
165
+ return (origin[0] + x * ratio, origin[1] + y * ratio)
142
166
  return (x, y)
143
167
 
144
168
 
145
- def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
169
+ def _parse_region(value) -> tuple[float, float, float, float] | None:
170
+ """Accept ``{x, y, width, height}`` (logical pixels) or ``[x, y, w, h]``."""
171
+ if value is None:
172
+ return None
173
+ if isinstance(value, dict):
174
+ try:
175
+ x = float(value.get("x", 0))
176
+ y = float(value.get("y", 0))
177
+ w = float(value["width"] if "width" in value else value["w"])
178
+ h = float(value["height"] if "height" in value else value["h"])
179
+ except (KeyError, TypeError, ValueError) as error:
180
+ raise ToolError("region must be {x, y, width, height} in logical pixels") from error
181
+ elif isinstance(value, (list, tuple)) and len(value) == 4:
182
+ x, y, w, h = (float(v) for v in value)
183
+ else:
184
+ raise ToolError("region must be {x, y, width, height} in logical pixels")
185
+ if w <= 0 or h <= 0:
186
+ raise ToolError("region width and height must be positive")
187
+ return (x, y, w, h)
188
+
189
+
190
+ def capture_shot(
191
+ max_width: int = SHOT_MAX_WIDTH,
192
+ region: tuple[float, float, float, float] | None = None,
193
+ scale: float | None = None,
194
+ ) -> dict:
146
195
  """Grab the desktop, preferring the screenshot portal over a pipewire stream.
147
196
 
148
197
  The portal Screenshot interface is a single round trip (~0.5s) and needs no
149
198
  long-lived session, so it is the default. The ScreenCast + GStreamer path
150
199
  stays as a fallback because it is the only one that can stream frames when
151
200
  capture permission exists but the screenshot interface is missing.
201
+
202
+ ``region`` (logical pixels) crops before downscaling, which is what makes
203
+ small UI text readable: a 900 px wide slice of the desktop stays sharp at
204
+ 1400 px of output, while the same output from a 4480 px desktop is mush.
205
+ ``scale`` sets output pixels per logical pixel (1.0 = native size) and takes
206
+ precedence over ``max_width``.
152
207
  """
153
208
  name = f"shot-{time.strftime('%Y%m%d-%H%M%S')}-{int(time.time() * 1000) % 1000:03d}.png"
154
209
  path = os.path.join(cu_display.SHOT_DIR, name)
@@ -177,25 +232,59 @@ def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
177
232
  "run linux_mcp_doctor to see the current state."
178
233
  ) from error
179
234
 
180
- width, height = cu_display.downscale(path, max_width)
181
235
  current = layout()
236
+ raw_width, raw_height = cu_display.png_size(path)
237
+ # The portal hands back physical pixels; logical desktop size can be smaller
238
+ # on HiDPI, and region/scale are both expressed in logical pixels.
239
+ physical = (raw_width / current.width) if current.width and raw_width else 1.0
240
+ origin = (0.0, 0.0)
241
+ region_used = None
242
+
243
+ if region is not None:
244
+ x, y, w, h = region
245
+ box = (
246
+ round(x * physical),
247
+ round(y * physical),
248
+ max(1, round(w * physical)),
249
+ max(1, round(h * physical)),
250
+ )
251
+ target = round(w * scale) if scale else max_width
252
+ width, height = cu_display.crop_and_scale(path, box, max(1, int(target)))
253
+ origin = (x, y)
254
+ region_used = {"x": round(x), "y": round(y), "width": round(w), "height": round(h)}
255
+ ratio = (w / width) if width else 1.0
256
+ elif scale:
257
+ width, height = cu_display.crop_and_scale(
258
+ path, (0, 0, raw_width, raw_height), max(1, round(current.width * scale))
259
+ )
260
+ ratio = (current.width / width) if width else 1.0
261
+ else:
262
+ width, height = cu_display.downscale(path, max_width)
263
+ ratio = (current.width / width) if width else 1.0
264
+
182
265
  LAST_SHOT.update({
183
266
  "path": path,
184
267
  "width": width,
185
268
  "height": height,
186
269
  "logical": (current.width, current.height),
270
+ "origin": origin,
271
+ "ratio": ratio,
187
272
  "at": time.time(),
188
273
  })
189
- return {
274
+ info = {
190
275
  "path": path,
191
276
  "width": width,
192
277
  "height": height,
193
278
  "logical_width": current.width,
194
279
  "logical_height": current.height,
195
- "coordinate_scale": round(current.width / width, 6) if width else 1.0,
280
+ "coordinate_scale": round(ratio, 6),
196
281
  "captured_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
197
282
  "method": method,
198
283
  }
284
+ if region_used:
285
+ info["region"] = region_used
286
+ info["origin_x"], info["origin_y"] = region_used["x"], region_used["y"]
287
+ return info
199
288
 
200
289
 
201
290
  # --------------------------------------------------------------------------- #
@@ -203,7 +292,12 @@ def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
203
292
  # --------------------------------------------------------------------------- #
204
293
  def tool_screenshot(args: dict) -> dict:
205
294
  max_width = int(args.get("max_width", SHOT_MAX_WIDTH))
206
- info = capture_shot(max_width)
295
+ region = _parse_region(args.get("region"))
296
+ scale = args.get("scale")
297
+ scale = float(scale) if scale else None
298
+ if scale is not None and scale <= 0:
299
+ raise ToolError("scale must be positive (1.0 = one screenshot pixel per logical pixel)")
300
+ info = capture_shot(max_width, region=region, scale=scale)
207
301
  try:
208
302
  with open(info["path"], "rb") as handle:
209
303
  payload = handle.read()
@@ -215,14 +309,29 @@ def tool_screenshot(args: dict) -> dict:
215
309
  payload = handle.read()
216
310
  width, height = cu_display.png_size(info["path"])
217
311
  info["width"], info["height"] = width, height
218
- info["coordinate_scale"] = round(info["logical_width"] / width, 6) if width else 1.0
312
+ # The ratio must follow the *visible* slice, not the whole desktop, so a
313
+ # cropped capture still maps screenshot pixels back to logical ones.
314
+ logical_width = (info.get("region") or {}).get("width") or info["logical_width"]
315
+ info["coordinate_scale"] = round(logical_width / width, 6) if width else 1.0
316
+ LAST_SHOT.update({"width": width, "height": height, "ratio": info["coordinate_scale"]})
219
317
  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
- )
318
+ if info.get("region"):
319
+ note = (
320
+ f"screenshot {info['width']}x{info['height']} px saved at {info['path']}; it shows the "
321
+ f"logical region x={info['origin_x']} y={info['origin_y']} "
322
+ f"{info['region']['width']}x{info['region']['height']} of a "
323
+ f"{info['logical_width']}x{info['logical_height']} desktop. "
324
+ f"To click at a pixel of this image pass space='screenshot'; "
325
+ f"otherwise add ({info['origin_x']}, {info['origin_y']}) and multiply by "
326
+ f"{info['coordinate_scale']}."
327
+ )
328
+ else:
329
+ note = (
330
+ f"screenshot {info['width']}x{info['height']} px saved at {info['path']}; "
331
+ f"logical desktop is {info['logical_width']}x{info['logical_height']}. "
332
+ f"To click at a pixel of this image pass space='screenshot'; "
333
+ f"otherwise multiply by {info['coordinate_scale']}."
334
+ )
226
335
  return {
227
336
  "content": [
228
337
  {"type": "image", "data": encoded, "mimeType": "image/png"},
@@ -271,20 +380,20 @@ def tool_ui_text(args: dict) -> dict:
271
380
 
272
381
 
273
382
  def tool_ui_action(args: dict) -> dict:
274
- _guard_input("tool_ui_action")
383
+ _guard_input("act on an accessibility node", args)
275
384
  ref = _require(args, "ref")
276
385
  action = args.get("action")
277
386
  return A11Y.action(ref, action)
278
387
 
279
388
 
280
389
  def tool_ui_focus(args: dict) -> dict:
281
- _guard_input("tool_ui_focus")
390
+ _guard_input("move focus", args)
282
391
  ref = _require(args, "ref")
283
392
  return A11Y.focus(ref)
284
393
 
285
394
 
286
395
  def tool_ui_set_text(args: dict) -> dict:
287
- _guard_input("tool_ui_set_text")
396
+ _guard_input("set a widget value", args)
288
397
  ref = _require(args, "ref")
289
398
  text = args.get("text")
290
399
  if not isinstance(text, str):
@@ -293,7 +402,7 @@ def tool_ui_set_text(args: dict) -> dict:
293
402
 
294
403
 
295
404
  def tool_click(args: dict) -> dict:
296
- _guard_input("click")
405
+ _guard_input("click", args)
297
406
  x, y = _point(args)
298
407
  x, y = _to_logical(x, y, str(args.get("space", "logical")))
299
408
  button = _button_name(args.get("button", 1))
@@ -303,7 +412,7 @@ def tool_click(args: dict) -> dict:
303
412
 
304
413
 
305
414
  def tool_move(args: dict) -> dict:
306
- _guard_input("move the pointer")
415
+ _guard_input("move the pointer", args)
307
416
  x, y = _point(args)
308
417
  x, y = _to_logical(x, y, str(args.get("space", "logical")))
309
418
  controller().move(x, y)
@@ -311,7 +420,7 @@ def tool_move(args: dict) -> dict:
311
420
 
312
421
 
313
422
  def tool_drag(args: dict) -> dict:
314
- _guard_input("drag")
423
+ _guard_input("drag", args)
315
424
  start = (float(args.get("x1", 0)), float(args.get("y1", 0)))
316
425
  end = (float(args.get("x2", 0)), float(args.get("y2", 0)))
317
426
  space = str(args.get("space", "logical"))
@@ -323,7 +432,7 @@ def tool_drag(args: dict) -> dict:
323
432
 
324
433
 
325
434
  def tool_scroll(args: dict) -> dict:
326
- _guard_input("scroll")
435
+ _guard_input("scroll", args)
327
436
  dx = int(args.get("dx", 0))
328
437
  dy = int(args.get("dy", 0))
329
438
  if not dx and not dy:
@@ -333,7 +442,7 @@ def tool_scroll(args: dict) -> dict:
333
442
 
334
443
 
335
444
  def tool_pointer_button(args: dict) -> dict:
336
- _guard_input("press a mouse button")
445
+ _guard_input("press a mouse button", args)
337
446
  action = str(args.get("action", "press")).lower()
338
447
  button = _button_name(args.get("button", 1))
339
448
  if args.get("x") is not None and args.get("y") is not None:
@@ -349,14 +458,14 @@ def tool_pointer_button(args: dict) -> dict:
349
458
 
350
459
 
351
460
  def tool_key(args: dict) -> dict:
352
- _guard_input("press a key")
461
+ _guard_input("press a key", args)
353
462
  combo = _require(args, "combo")
354
463
  controller().key(str(combo))
355
464
  return {"pressed": combo}
356
465
 
357
466
 
358
467
  def tool_type_text(args: dict) -> dict:
359
- _guard_input("type text")
468
+ _guard_input("type text", args)
360
469
  text = _require(args, "text")
361
470
  controller().type_text(str(text))
362
471
  return {"typed": len(str(text))}
@@ -427,22 +536,219 @@ def tool_window_list(args: dict) -> dict:
427
536
  node = A11Y.describe(app["ref"])
428
537
  except cu_a11y.A11yError:
429
538
  continue
430
- target = _first_frame(A11Y.resolve(app["ref"]))
431
- if target is None:
539
+ frame = _first_frame_obj(A11Y.resolve(app["ref"]))
540
+ if frame is None:
432
541
  windows.append({"app": app["name"], "title": "", "ref": app["ref"], "pid": app["pid"]})
433
542
  continue
434
- title, states = target
543
+ title = frame.get_name() or ""
435
544
  windows.append({
436
545
  "app": app["name"],
437
546
  "title": title,
438
547
  "ref": app["ref"],
439
548
  "pid": app["pid"],
440
- "active": "active" in states or "focused" in states,
549
+ "active": _window_is_active(frame),
441
550
  })
442
551
  del node
443
552
  return {"windows": windows, "count": len(windows)}
444
553
 
445
554
 
555
+ def tool_window_activate(args: dict) -> dict:
556
+ _guard_input("activate a window", args)
557
+ title = str(args.get("title") or "").strip()
558
+ app = str(args.get("app") or "").strip()
559
+ if not title and not app:
560
+ raise ToolError("window_activate needs either a title substring or an app name")
561
+ rows = _frame_rows()
562
+ match = _match_window(rows, title, app)
563
+ if match is None:
564
+ known = sorted({f"{row['app']}: {row['title']}" for row in rows if row["title"]})[:8]
565
+ raise ToolError(
566
+ "no window matches "
567
+ + (f"title {title!r} " if title else "")
568
+ + (f"app {app!r}" if app else "")
569
+ + ("; known windows: " + "; ".join(known) if known else "")
570
+ )
571
+ window = {"app": match["app"], "title": match["title"]}
572
+ if match["active"]:
573
+ return {"activated": True, "method": "already-active", "window": window, "tried": []}
574
+
575
+ tried: list[dict] = []
576
+ needle = title or match["title"]
577
+
578
+ # XWayland windows answer to xdotool; native Wayland ones never show up here.
579
+ if needle:
580
+ if not os.environ.get("DISPLAY"):
581
+ tried.append({"method": "xdotool", "result": "no DISPLAY in this session"})
582
+ else:
583
+ code, out = _xdotool("search", "--name", needle)
584
+ ids = [line for line in out.splitlines() if line.strip().isdigit()] if code == 0 else []
585
+ if not ids:
586
+ tried.append({"method": "xdotool", "result": "no X11 match (native Wayland window)"})
587
+ for wid in ids[:4]:
588
+ _xdotool("windowactivate", wid)
589
+ if _wait_active(match["title"], 1.2):
590
+ return {"activated": True, "method": "xdotool", "window": window, "tried": tried}
591
+ else:
592
+ if ids:
593
+ tried.append({"method": "xdotool", "result": "activate did not raise it"})
594
+
595
+ try:
596
+ iface = match["acc"].get_action_iface()
597
+ if iface is not None and iface.get_n_actions() > 0:
598
+ iface.do_action(0)
599
+ if _wait_active(match["title"], 1.0):
600
+ return {"activated": True, "method": "atspi", "window": window, "tried": tried}
601
+ tried.append({"method": "atspi", "result": "default action did not raise it"})
602
+ else:
603
+ tried.append({"method": "atspi", "result": "frame exposes no actions"})
604
+ except Exception as error: # noqa: BLE001
605
+ tried.append({"method": "atspi", "result": str(error)})
606
+
607
+ cycles = max(1, min(int(args.get("max_cycles", WINDOW_ACTIVATE_MAX_CYCLES)), 30))
608
+ # GNOME binds Alt+Tab to switching windows *inside* the current application
609
+ # and Super+Tab to switching applications, so both are worth trying. A
610
+ # combination that changes nothing on its first press is not bound here (or
611
+ # the application has a single window), so move on instead of cycling.
612
+ for combo in ("alt+Tab", "super+Tab"):
613
+ try:
614
+ before = _active_titles()
615
+ for index in range(cycles):
616
+ controller().key(combo)
617
+ time.sleep(0.35)
618
+ if _is_active(match["title"]):
619
+ return {"activated": True, "method": combo.lower().replace("+", "-"), "window": window, "tried": tried}
620
+ now = _active_titles()
621
+ if now != before:
622
+ before = now
623
+ continue
624
+ if index == 0:
625
+ tried.append({"method": combo, "result": "no effect here (not bound, or the application has a single window)"})
626
+ break
627
+ else:
628
+ tried.append({"method": combo, "result": f"{cycles} cycles without reaching it"})
629
+ except cu_input.InputError as error:
630
+ tried.append({"method": combo, "result": str(error)})
631
+ break
632
+ except Exception as error: # noqa: BLE001
633
+ tried.append({"method": combo, "result": str(error)})
634
+
635
+ return {
636
+ "activated": False,
637
+ "method": "none",
638
+ "window": window,
639
+ "tried": tried,
640
+ "hint": (
641
+ "none of the three strategies raised it: X11 sees only XWayland surfaces, the "
642
+ "accessibility default action is a no-op for most toolkits, and the keyboard "
643
+ "fallback needs uinput plus a matching keybinding (Alt+Tab switches windows of "
644
+ "the current application, Super+Tab switches applications). Raise it by hand, or "
645
+ "pass a more distinctive title"
646
+ ),
647
+ }
648
+
649
+
650
+ WAIT_CONDITIONS = ("window", "window_active", "ui", "idle_at_least")
651
+
652
+
653
+ def _check_condition(condition: dict) -> tuple[bool, dict]:
654
+ for key in WAIT_CONDITIONS:
655
+ if key not in condition:
656
+ continue
657
+ if key == "window":
658
+ spec = condition["window"]
659
+ if isinstance(spec, str):
660
+ spec = {"title": spec}
661
+ if not isinstance(spec, dict):
662
+ raise ToolError("condition.window must be a title string or an object")
663
+ want = bool(spec.get("exists", True))
664
+ rows = _frame_rows()
665
+ hit = _match_window(rows, str(spec.get("title") or ""), str(spec.get("app") or ""))
666
+ return (hit is not None) == want, {"windows": len(rows), "found": hit is not None}
667
+ if key == "window_active":
668
+ spec = condition["window_active"]
669
+ needle = str(spec.get("title") if isinstance(spec, dict) else spec or "").lower()
670
+ if not needle:
671
+ raise ToolError("condition.window_active needs a title substring")
672
+ active = [row["title"] for row in _frame_rows() if row["active"]]
673
+ hit = any(needle in (title or "").lower() for title in active)
674
+ return hit, {"active": active[:6]}
675
+ if key == "ui":
676
+ spec = condition["ui"]
677
+ if not isinstance(spec, dict):
678
+ raise ToolError("condition.ui must be an object such as {app, name, role}")
679
+ hits = A11Y.find(
680
+ query=spec.get("name"),
681
+ role=spec.get("role"),
682
+ app=spec.get("app"),
683
+ limit=3,
684
+ timeout_s=2.0,
685
+ )
686
+ return len(hits) > 0, {"matches": len(hits)}
687
+ idle = cu_sys.idle_ms()
688
+ want_idle = int(condition["idle_at_least"])
689
+ return (idle is not None and idle >= want_idle), {"idle_ms": idle}
690
+ raise ToolError(
691
+ "condition must contain one of: " + ", ".join(WAIT_CONDITIONS) + " (got " + repr(sorted(condition)) + ")"
692
+ )
693
+
694
+
695
+ def tool_wait_until(args: dict) -> dict:
696
+ condition = args.get("condition")
697
+ if not isinstance(condition, dict) or not condition:
698
+ raise ToolError(
699
+ "wait_until needs a condition object, for example "
700
+ '{"window": {"title": "Build finished"}} or {"window_active": "Chrome"}'
701
+ )
702
+ timeout_ms = max(100, min(int(args.get("timeout_ms", 15000)), 120000))
703
+ interval_ms = max(80, min(int(args.get("interval_ms", 300)), 5000))
704
+ started = time.monotonic()
705
+ deadline = started + timeout_ms / 1000.0
706
+ polls = 0
707
+ detail: dict = {}
708
+ satisfied = False
709
+ while True:
710
+ polls += 1
711
+ try:
712
+ satisfied, detail = _check_condition(condition)
713
+ except ToolError:
714
+ raise
715
+ except Exception as error: # noqa: BLE001
716
+ detail = {"error": str(error)}
717
+ satisfied = False
718
+ if satisfied or time.monotonic() >= deadline:
719
+ break
720
+ time.sleep(interval_ms / 1000.0)
721
+ elapsed_ms = int((time.monotonic() - started) * 1000)
722
+ return {
723
+ "satisfied": satisfied,
724
+ "waited_ms": elapsed_ms,
725
+ "polls": polls,
726
+ "timeout_ms": timeout_ms,
727
+ "condition": condition,
728
+ "state": detail,
729
+ }
730
+
731
+
732
+ def _first_frame_obj(app):
733
+ """The first frame child of an application, or None."""
734
+ if app is None:
735
+ return None
736
+ try:
737
+ count = app.get_child_count()
738
+ except Exception: # noqa: BLE001
739
+ return None
740
+ for index in range(min(count, 4)):
741
+ try:
742
+ child = app.get_child_at_index(index)
743
+ if child is None:
744
+ continue
745
+ if (child.get_role_name() or "") == "frame":
746
+ return child
747
+ except Exception: # noqa: BLE001
748
+ continue
749
+ return None
750
+
751
+
446
752
  def _first_frame(app):
447
753
  try:
448
754
  count = app.get_child_count()
@@ -460,6 +766,132 @@ def _first_frame(app):
460
766
  return None
461
767
 
462
768
 
769
+ # --------------------------------------------------------------------------- #
770
+ # Windows: enumerate frames, raise one, wait for conditions
771
+ # --------------------------------------------------------------------------- #
772
+
773
+ WINDOW_ACTIVATE_MAX_CYCLES = int(os.environ.get("DSH_LINUX_CU_MAX_TAB_CYCLES", "12"))
774
+
775
+
776
+ def _xdotool(*argv: str, timeout: float = 3.0) -> tuple[int, str]:
777
+ """Run xdotool against the XWayland display; (127, "") when unavailable."""
778
+ if not os.environ.get("DISPLAY"):
779
+ return (127, "")
780
+ try:
781
+ done = subprocess.run(
782
+ ["xdotool", *argv], capture_output=True, text=True, timeout=timeout
783
+ )
784
+ except (OSError, subprocess.SubprocessError):
785
+ return (127, "")
786
+ return (done.returncode, (done.stdout or "").strip())
787
+
788
+
789
+ def _window_is_active(acc) -> bool:
790
+ """True when the toolkit marks this window ACTIVE (raised/focused).
791
+
792
+ cu_a11y.STATE_FLAGS stops at FOCUSED, and most toolkits set ACTIVE on the
793
+ toplevel frame instead, so the flag is queried directly here.
794
+ """
795
+ try:
796
+ state_set = acc.get_state_set()
797
+ except Exception: # noqa: BLE001
798
+ return False
799
+ for flag in ("ACTIVE", "FOCUSED"):
800
+ value = getattr(cu_a11y.Atspi.StateType, flag, None)
801
+ if value is None:
802
+ continue
803
+ try:
804
+ if state_set.contains(value):
805
+ return True
806
+ except Exception: # noqa: BLE001
807
+ return False
808
+ return False
809
+
810
+
811
+ def _frame_rows() -> list[dict]:
812
+ """Every top-level window frame the accessibility bus can see."""
813
+ rows: list[dict] = []
814
+ for app in A11Y.apps(max_age=1.5):
815
+ try:
816
+ target = A11Y.resolve(app["ref"])
817
+ if target is None:
818
+ continue
819
+ count = target.get_child_count()
820
+ except Exception: # noqa: BLE001
821
+ continue
822
+ for index in range(min(count, 4)):
823
+ try:
824
+ child = target.get_child_at_index(index)
825
+ if child is None or (child.get_role_name() or "") != "frame":
826
+ continue
827
+ except Exception: # noqa: BLE001
828
+ continue
829
+ active = _window_is_active(child)
830
+ rows.append(
831
+ {
832
+ "app": app.get("name") or "",
833
+ "title": child.get_name() or "",
834
+ "ref": app.get("ref"),
835
+ "pid": app.get("pid"),
836
+ "active": active,
837
+ "acc": child,
838
+ }
839
+ )
840
+ break
841
+ return rows
842
+
843
+
844
+ def _match_window(rows: list[dict], title: str, app: str) -> dict | None:
845
+ """Prefer an exact title, then a title substring, then the app name."""
846
+ needle = (title or "").strip().lower()
847
+ app_needle = (app or "").strip().lower()
848
+ if needle:
849
+ for row in rows:
850
+ if (row["title"] or "").lower() == needle:
851
+ return row
852
+ for row in rows:
853
+ if needle in (row["title"] or "").lower():
854
+ return row
855
+ for row in rows:
856
+ if needle in (row["app"] or "").lower():
857
+ return row
858
+ if app_needle:
859
+ for row in rows:
860
+ if (row["app"] or "").lower() == app_needle:
861
+ return row
862
+ for row in rows:
863
+ if app_needle in (row["app"] or "").lower():
864
+ return row
865
+ return None
866
+
867
+
868
+ def _active_titles() -> set:
869
+ """Titles of the windows the accessibility tree currently reports as ACTIVE."""
870
+ return {row["title"] for row in _frame_rows() if row["active"]}
871
+
872
+
873
+ def _is_active(title: str) -> bool:
874
+ needle = (title or "").strip().lower()
875
+ if not needle:
876
+ return False
877
+ for row in _frame_rows():
878
+ if not row["active"]:
879
+ continue
880
+ if (row["title"] or "").lower() == needle or needle in (row["title"] or "").lower():
881
+ return True
882
+ return False
883
+
884
+
885
+ def _wait_active(title: str, timeout_s: float) -> bool:
886
+ deadline = time.monotonic() + timeout_s
887
+ while time.monotonic() < deadline:
888
+ if _is_active(title):
889
+ return True
890
+ time.sleep(0.12)
891
+ return _is_active(title)
892
+
893
+
894
+
463
895
  def tool_display_info(args: dict) -> dict:
464
896
  current = layout()
465
897
  info = current.describe()
@@ -479,6 +911,8 @@ def tool_desktop_status(args: dict) -> dict:
479
911
  "type": os.environ.get("XDG_SESSION_TYPE", ""),
480
912
  "desktop": os.environ.get("XDG_CURRENT_DESKTOP", ""),
481
913
  "locked": cu_sys.screen_locked(),
914
+ "idle_ms": cu_sys.idle_ms(),
915
+ "input_guard_ms": IDLE_GUARD_MS,
482
916
  "unlock": cu_unlock.status(),
483
917
  }
484
918
  try:
@@ -554,6 +988,30 @@ SPACE_PROP = {
554
988
  "description": "Coordinate space: 'logical' desktop pixels, or 'screenshot' pixels of the last screenshot.",
555
989
  }
556
990
 
991
+ ALLOW_ACTIVE_PROP = {
992
+ "type": "boolean",
993
+ "default": False,
994
+ "description": (
995
+ "Set true when the user just asked you to drive the desktop: it skips the idle guard, "
996
+ "which otherwise refuses injected input while they are using the keyboard or pointer."
997
+ ),
998
+ }
999
+
1000
+ # Tools that inject input all accept the same escape hatch; adding it here keeps
1001
+ # the schema in one place instead of ten copies.
1002
+ _INJECTING_TOOLS = {
1003
+ "click",
1004
+ "move",
1005
+ "drag",
1006
+ "scroll",
1007
+ "pointer_button",
1008
+ "key",
1009
+ "type_text",
1010
+ "ui_action",
1011
+ "ui_focus",
1012
+ "ui_set_text",
1013
+ }
1014
+
557
1015
  def tool_unlock_screen(args: dict) -> dict:
558
1016
  confirm = str(args.get("confirm") or "").strip().lower()
559
1017
  if confirm != "unlock":
@@ -574,10 +1032,11 @@ TOOLS: list[dict] = [
574
1032
  {
575
1033
  "name": "screenshot",
576
1034
  "description": (
577
- "Capture the whole desktop and return it as a PNG image plus its size and path. "
578
- "Use it to see the screen before deciding where to click. The desktop asks for a "
579
- "one-time screen-capture approval; after that every capture is silent and takes "
580
- "about half a second."
1035
+ "Capture the desktop (or one region of it) and return a PNG image plus its size and path. "
1036
+ "Use it to see the screen before deciding where to click. Pass region {x, y, width, height} "
1037
+ "in logical pixels when you only need one window or one corner: a cropped capture stays "
1038
+ "sharp, while the whole 4K desktop scaled down does not. The desktop asks for a one-time "
1039
+ "screen-capture approval; after that every capture is silent and takes about half a second."
581
1040
  ),
582
1041
  "inputSchema": {
583
1042
  "type": "object",
@@ -585,8 +1044,29 @@ TOOLS: list[dict] = [
585
1044
  "max_width": {
586
1045
  "type": "integer",
587
1046
  "default": SHOT_MAX_WIDTH,
588
- "description": "Downscale the image to this pixel width (0 keeps native resolution).",
589
- }
1047
+ "description": "Downscale the image to this pixel width (0 keeps native resolution). Ignored when scale is given.",
1048
+ },
1049
+ "region": {
1050
+ "type": "object",
1051
+ "description": (
1052
+ "Capture only this rectangle, in logical desktop pixels. Cropping before "
1053
+ "downscaling is what keeps small UI text readable."
1054
+ ),
1055
+ "properties": {
1056
+ "x": {"type": "number"},
1057
+ "y": {"type": "number"},
1058
+ "width": {"type": "number"},
1059
+ "height": {"type": "number"},
1060
+ },
1061
+ "required": ["x", "y", "width", "height"],
1062
+ },
1063
+ "scale": {
1064
+ "type": "number",
1065
+ "description": (
1066
+ "Output pixels per logical pixel: 1.0 keeps native size, 2.0 doubles it. "
1067
+ "Takes precedence over max_width."
1068
+ ),
1069
+ },
590
1070
  },
591
1071
  },
592
1072
  "handler": tool_screenshot,
@@ -886,6 +1366,55 @@ TOOLS: list[dict] = [
886
1366
  "inputSchema": {"type": "object", "properties": {}},
887
1367
  "handler": tool_window_list,
888
1368
  },
1369
+ {
1370
+ "name": "window_activate",
1371
+ "description": (
1372
+ "Raise a window by title substring (or app name) and report which method worked: "
1373
+ "xdotool for XWayland surfaces, the AT-SPI default action, or Alt+Tab cycling for "
1374
+ "native Wayland windows."
1375
+ ),
1376
+ "inputSchema": {
1377
+ "type": "object",
1378
+ "properties": {
1379
+ "title": {"type": "string", "description": "Case-insensitive substring of the window title."},
1380
+ "app": {"type": "string", "description": "Application name, used when the title is unknown."},
1381
+ "max_cycles": {
1382
+ "type": "integer",
1383
+ "minimum": 1,
1384
+ "maximum": 30,
1385
+ "default": 12,
1386
+ "description": "How many Alt+Tab presses to try before giving up.",
1387
+ },
1388
+ "allow_active_input": ALLOW_ACTIVE_PROP,
1389
+ },
1390
+ },
1391
+ "handler": tool_window_activate,
1392
+ },
1393
+ {
1394
+ "name": "wait_until",
1395
+ "description": (
1396
+ "Poll the desktop until a condition holds, instead of sleeping a fixed time: a window "
1397
+ "appears or disappears, a window becomes active, an accessibility node shows up, or the "
1398
+ "user has been idle long enough. Returns satisfied=false on timeout with the last state."
1399
+ ),
1400
+ "inputSchema": {
1401
+ "type": "object",
1402
+ "properties": {
1403
+ "condition": {
1404
+ "type": "object",
1405
+ "description": (
1406
+ 'One of: {"window": {"title": "...", "app": "...", "exists": true}}, '
1407
+ '{"window_active": "Chrome"}, {"ui": {"app": "...", "name": "...", "role": "..."}}, '
1408
+ '{"idle_at_least": 60000}.'
1409
+ ),
1410
+ },
1411
+ "timeout_ms": {"type": "integer", "minimum": 100, "maximum": 120000, "default": 15000},
1412
+ "interval_ms": {"type": "integer", "minimum": 80, "maximum": 5000, "default": 300},
1413
+ },
1414
+ "required": ["condition"],
1415
+ },
1416
+ "handler": tool_wait_until,
1417
+ },
889
1418
  {
890
1419
  "name": "display_info",
891
1420
  "description": (
@@ -918,6 +1447,12 @@ TOOLS: list[dict] = [
918
1447
  },
919
1448
  ]
920
1449
 
1450
+ # Every input-injecting tool advertises the idle-guard escape hatch.
1451
+ for _spec in TOOLS:
1452
+ if _spec["name"] in _INJECTING_TOOLS:
1453
+ _spec["inputSchema"].setdefault("properties", {})["allow_active_input"] = ALLOW_ACTIVE_PROP
1454
+
1455
+
921
1456
  UNLOCK_TOOL: dict = {
922
1457
  "name": "unlock_screen",
923
1458
  "description": (