tsugite-computer 0.30.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,269 @@
1
+ """Tsugite plugin: computer use tools that drive a virtual Linux desktop in a container."""
2
+
3
+ import json
4
+ import os
5
+ import secrets
6
+ import subprocess
7
+ import time
8
+ from datetime import datetime
9
+ from importlib.metadata import version
10
+ from pathlib import Path
11
+ from typing import Optional
12
+
13
+ from tsugite.cli.helpers import resolve_workspace_path
14
+ from tsugite.config import load_config
15
+ from tsugite.tools import deny_when_sandboxed, tool
16
+
17
+ HELPER_SOURCE = (Path(__file__).parent / "atspi_helper.py").read_text()
18
+ READY_PROBE = ["bash", "-c", "xdpyinfo >/dev/null && : </dev/tcp/127.0.0.1/5900 && : </dev/tcp/127.0.0.1/6080"]
19
+ DEFAULT_IMAGE = f"ghcr.io/justyns/tsugite-desktop:{version('tsugite-computer')}"
20
+ BUTTONS = {"left": 1, "middle": 2, "right": 3}
21
+ SCROLL_BUTTONS = {"up": 4, "down": 5, "left": 6, "right": 7}
22
+ TYPE_ARGS = ("type", "--delay", 12, "--")
23
+ KEY_STATES = ("focused", "checked", "pressed", "selected", "expanded")
24
+
25
+
26
+ def _config() -> dict:
27
+ return {"engine": "podman", "container": "tsugite-desktop", **load_config().plugins.get("computer", {})}
28
+
29
+
30
+ def _local_config() -> dict:
31
+ cfg = _config()
32
+ if cfg.get("exec"):
33
+ raise RuntimeError(
34
+ "computer_start and computer_stop manage only a local container. With a custom `exec` prefix, "
35
+ "start and stop the desktop outside tsugite."
36
+ )
37
+ return cfg
38
+
39
+
40
+ def _check(
41
+ argv: list, timeout: Optional[float], label: Optional[str] = None, env: Optional[dict] = None
42
+ ) -> subprocess.CompletedProcess:
43
+ result = subprocess.run(argv, capture_output=True, timeout=timeout, env=env)
44
+ if result.returncode != 0:
45
+ stderr = result.stderr.decode(errors="replace").strip()
46
+ raise RuntimeError(f"`{label or argv[0]}` failed (exit {result.returncode}): {stderr}")
47
+ return result
48
+
49
+
50
+ def _exec(*argv) -> subprocess.CompletedProcess:
51
+ cfg = _config()
52
+ prefix = cfg.get("exec") or [cfg["engine"], "exec", cfg["container"]]
53
+ return _check([*prefix, *map(str, argv)], cfg.get("timeout", 60), label=argv[0])
54
+
55
+
56
+ def _helper(*args) -> dict:
57
+ return json.loads(_exec("python3", "-c", HELPER_SOURCE, *args).stdout)
58
+
59
+
60
+ def _xdotool(*args) -> None:
61
+ _exec("xdotool", *args)
62
+
63
+
64
+ def _interactive(node: dict) -> bool:
65
+ return bool(node["actions"]) or node["editable"]
66
+
67
+
68
+ def _quote(text: Optional[str]) -> str:
69
+ return json.dumps(text or "", ensure_ascii=False)
70
+
71
+
72
+ def _format_node(node: dict) -> str:
73
+ line = f"[{node['id']}] {node['role']} {_quote(node['name'])}"
74
+ if node["editable"] or (node["text"] and node["text"] != node["name"]):
75
+ line += f" = {_quote(node['text'])}"
76
+ if node["rect"] and node["rect"][2] > 0 and node["rect"][3] > 0:
77
+ x, y, w, h = node["rect"]
78
+ line += f" @({x + w // 2},{y + h // 2})"
79
+ states = [s for s in KEY_STATES if s in node["states"]]
80
+ if node["editable"]:
81
+ states.append("editable")
82
+ if _interactive(node) and "sensitive" not in node["states"]:
83
+ states.append("disabled")
84
+ return " ".join([line, *states])
85
+
86
+
87
+ def format_tree(apps: list) -> str:
88
+ """Render the visible nodes that have a name, text or action as an indented tree."""
89
+ lines = []
90
+
91
+ def walk(node: dict, depth: int) -> None:
92
+ rect = node["rect"]
93
+ # AT-SPI reports unknown extents as -1. Those nodes stay, without coords.
94
+ visible = "showing" in node["states"] and "visible" in node["states"] and rect and rect[2] != 0 and rect[3] != 0
95
+ if node["role"] == "application" or (visible and (node["name"] or node["text"] or _interactive(node))):
96
+ lines.append(" " * depth + _format_node(node))
97
+ depth += 1
98
+ for child in node["children"]:
99
+ walk(child, depth)
100
+
101
+ for app in apps:
102
+ walk(app, 0)
103
+ return "\n".join(lines)
104
+
105
+
106
+ @tool(category="computer", parent_only=True)
107
+ @deny_when_sandboxed
108
+ def computer_start() -> dict:
109
+ """Start the local desktop container and return its noVNC URL and VNC password."""
110
+ cfg = _local_config()
111
+ engine, container, port = cfg["engine"], cfg["container"], cfg.get("vnc_port", 6080)
112
+ volume = ["-v", f"{cfg['home_volume']}:/home/desktop"] if cfg.get("home_volume") else []
113
+ # VNC authentication uses only the first 8 characters.
114
+ password = secrets.token_urlsafe(6)
115
+ _check(
116
+ [
117
+ engine,
118
+ "run",
119
+ "-d",
120
+ "--name",
121
+ container,
122
+ # A stable hostname keeps Firefox's profile lock valid on a persisted home volume.
123
+ "--hostname",
124
+ container,
125
+ "-p",
126
+ f"127.0.0.1:{port}:6080",
127
+ "-e",
128
+ f"WIDTH={cfg.get('width', 1280)}",
129
+ "-e",
130
+ f"HEIGHT={cfg.get('height', 800)}",
131
+ "-e",
132
+ "VNC_PASSWORD",
133
+ *volume,
134
+ cfg.get("image", DEFAULT_IMAGE),
135
+ ],
136
+ None,
137
+ env={**os.environ, "VNC_PASSWORD": password},
138
+ )
139
+ for _ in range(50):
140
+ try:
141
+ up = (
142
+ subprocess.run([engine, "exec", container, *READY_PROBE], capture_output=True, timeout=5).returncode
143
+ == 0
144
+ )
145
+ except subprocess.TimeoutExpired:
146
+ up = False
147
+ if up:
148
+ break
149
+ time.sleep(0.2)
150
+ else:
151
+ subprocess.run([engine, "rm", "-f", container], capture_output=True)
152
+ raise RuntimeError(f"Container {container} started but its display and noVNC did not come up after 50 checks")
153
+ return {
154
+ "container": container,
155
+ "vnc_url": f"http://127.0.0.1:{port}/vnc.html?password={password}",
156
+ "vnc_password": password,
157
+ }
158
+
159
+
160
+ @tool(category="computer", parent_only=True)
161
+ @deny_when_sandboxed
162
+ def computer_stop() -> str:
163
+ """Stop and remove the local desktop container."""
164
+ cfg = _local_config()
165
+ _check([cfg["engine"], "rm", "-f", cfg["container"]], cfg.get("timeout", 60))
166
+ return f"Removed {cfg['container']}"
167
+
168
+
169
+ @tool(category="computer", parent_only=True)
170
+ @deny_when_sandboxed
171
+ def computer_screenshot(path: Optional[str] = None) -> str:
172
+ """Save a PNG screenshot of the desktop into the workspace and return its path."""
173
+ target = resolve_workspace_path(path or f"screenshots/computer-{datetime.now():%Y%m%d-%H%M%S-%f}.png")
174
+ png = _exec("scrot", "--overwrite", "-").stdout
175
+ target.parent.mkdir(parents=True, exist_ok=True)
176
+ target.write_bytes(png)
177
+ return str(target)
178
+
179
+
180
+ @tool(category="computer", parent_only=True)
181
+ @deny_when_sandboxed
182
+ def computer_launch(command: str) -> str:
183
+ """Start a program on the desktop in the background (e.g. "firefox https://example.com", "xterm")."""
184
+ _exec("setsid", "-f", "sh", "-c", f"exec >/dev/null 2>&1 </dev/null; {command}")
185
+ return f"Launched {command}"
186
+
187
+
188
+ @tool(category="computer", parent_only=True)
189
+ @deny_when_sandboxed
190
+ def computer_click(x: int, y: int, button: str = "left", count: int = 1) -> str:
191
+ """Click at screen coordinates (button: left, middle or right)."""
192
+ if button not in BUTTONS:
193
+ raise ValueError(f"Invalid button '{button}': must be one of {', '.join(BUTTONS)}")
194
+ _xdotool("mousemove", x, y, "click", "--repeat", count, BUTTONS[button])
195
+ return f"Clicked {button} x{count} at ({x},{y})"
196
+
197
+
198
+ @tool(category="computer", parent_only=True)
199
+ @deny_when_sandboxed
200
+ def computer_move(x: int, y: int) -> str:
201
+ """Move the mouse pointer to screen coordinates."""
202
+ _xdotool("mousemove", x, y)
203
+ return f"Moved to ({x},{y})"
204
+
205
+
206
+ @tool(category="computer", parent_only=True)
207
+ @deny_when_sandboxed
208
+ def computer_drag(x1: int, y1: int, x2: int, y2: int) -> str:
209
+ """Drag with the left button from (x1, y1) to (x2, y2)."""
210
+ _xdotool("mousemove", x1, y1, "mousedown", 1, "mousemove", x2, y2, "mouseup", 1)
211
+ return f"Dragged ({x1},{y1}) to ({x2},{y2})"
212
+
213
+
214
+ @tool(category="computer", parent_only=True)
215
+ @deny_when_sandboxed
216
+ def computer_scroll(x: int, y: int, direction: str, amount: int = 3) -> str:
217
+ """Scroll at screen coordinates (direction: up, down, left or right)."""
218
+ if direction not in SCROLL_BUTTONS:
219
+ raise ValueError(f"Invalid direction '{direction}': must be one of {', '.join(SCROLL_BUTTONS)}")
220
+ _xdotool("mousemove", x, y, "click", "--repeat", amount, SCROLL_BUTTONS[direction])
221
+ return f"Scrolled {direction} x{amount} at ({x},{y})"
222
+
223
+
224
+ @tool(category="computer", parent_only=True)
225
+ @deny_when_sandboxed
226
+ def computer_type(text: str) -> str:
227
+ """Type text into the focused window."""
228
+ _xdotool(*TYPE_ARGS, text)
229
+ return f"Typed {len(text)} characters"
230
+
231
+
232
+ @tool(category="computer", parent_only=True)
233
+ @deny_when_sandboxed
234
+ def computer_key(keys: str) -> str:
235
+ """Press xdotool key combos, space separated (e.g. "ctrl+s", "ctrl+a BackSpace", "Return")."""
236
+ _xdotool("key", "--", *keys.split())
237
+ return f"Pressed {keys}"
238
+
239
+
240
+ @tool(category="computer", parent_only=True)
241
+ @deny_when_sandboxed
242
+ def computer_ui_tree(app: Optional[str] = None, max_depth: int = 40) -> str:
243
+ """Show the accessibility tree of visible apps (id, role, name, text, center coords, states), optionally filtered by app name. Ids are child-index paths and shift when the UI changes."""
244
+ tree = format_tree(_helper("tree", max_depth, *([app] if app else [])))
245
+ return tree or "No accessible applications found"
246
+
247
+
248
+ @tool(category="computer", parent_only=True)
249
+ @deny_when_sandboxed
250
+ def computer_ui_click(id: str) -> str:
251
+ """Activate a UI element by its computer_ui_tree id, clicking its center when it has no action. Read the tree again after the UI changes."""
252
+ result = _helper("click", id)
253
+ if "action" in result:
254
+ return f"Ran '{result['action']}' on {id}"
255
+ x, y = result["center"]
256
+ return computer_click(x, y)
257
+
258
+
259
+ @tool(category="computer", parent_only=True)
260
+ @deny_when_sandboxed
261
+ def computer_ui_set_text(id: str, text: str) -> str:
262
+ """Replace the text of an editable UI element by its computer_ui_tree id, typing it in when the direct set fails."""
263
+ result = _helper("set_text", id, text)
264
+ if "center" not in result:
265
+ return f"Set text of {id}"
266
+ x, y = result["center"]
267
+ replacement = TYPE_ARGS + (text,) if text else ("key", "BackSpace")
268
+ _xdotool("mousemove", x, y, "click", 1, "key", "ctrl+a", *replacement)
269
+ return f"Typed text into {id}"
@@ -0,0 +1,105 @@
1
+ """AT-SPI helper run inside the desktop as `python3 -c <source> <subcommand> ...`.
2
+
3
+ It imports only the stdlib and gi. Node ids are child-index paths from the desktop root.
4
+ """
5
+
6
+ import json
7
+ import sys
8
+
9
+ import gi
10
+
11
+ gi.require_version("Atspi", "2.0")
12
+ from gi.repository import Atspi # noqa: E402
13
+
14
+ CLICK_ACTIONS = ("click", "press", "activate", "jump", "toggle")
15
+
16
+
17
+ def extents(acc):
18
+ r = Atspi.Component.get_extents(acc, Atspi.CoordType.SCREEN)
19
+ return [r.x, r.y, r.width, r.height]
20
+
21
+
22
+ def action_names(acc):
23
+ if acc.get_action_iface() is None:
24
+ return []
25
+ return [Atspi.Action.get_action_name(acc, i) for i in range(Atspi.Action.get_n_actions(acc))]
26
+
27
+
28
+ def own_text(acc):
29
+ """Text of this node alone, without the U+FFFC placeholders AT-SPI inserts for child objects."""
30
+ if acc.get_text_iface() is None:
31
+ return None
32
+ return Atspi.Text.get_text(acc, 0, -1).replace("\ufffc", "").strip()
33
+
34
+
35
+ def node_json(acc, node_id, depth, max_depth):
36
+ editable = acc.get_editable_text_iface() is not None and acc.get_state_set().contains(Atspi.StateType.EDITABLE)
37
+ children = []
38
+ if depth < max_depth:
39
+ for i in range(acc.get_child_count()):
40
+ child = acc.get_child_at_index(i)
41
+ if child is not None:
42
+ children.append(node_json(child, f"{node_id}.{i}", depth + 1, max_depth))
43
+ return {
44
+ "id": node_id,
45
+ "role": acc.get_role_name(),
46
+ "name": acc.get_name() or "",
47
+ "states": [s.value_nick for s in acc.get_state_set().get_states()],
48
+ "rect": extents(acc) if acc.get_component_iface() is not None else None,
49
+ "actions": action_names(acc),
50
+ "editable": editable,
51
+ "text": own_text(acc),
52
+ "children": children,
53
+ }
54
+
55
+
56
+ def center(acc, node_id):
57
+ x, y, w, h = extents(acc)
58
+ if w <= 0 or h <= 0:
59
+ sys.exit(f"UI element {node_id} has no on-screen position")
60
+ return [x + w // 2, y + h // 2]
61
+
62
+
63
+ def resolve(node_id):
64
+ acc = Atspi.get_desktop(0)
65
+ for index in node_id.split("."):
66
+ acc = acc.get_child_at_index(int(index)) if acc is not None else None
67
+ if acc is None:
68
+ sys.exit(f"No UI element with id {node_id}; call computer_ui_tree() again")
69
+ return acc
70
+
71
+
72
+ def tree(max_depth, app=None):
73
+ desktop = Atspi.get_desktop(0)
74
+ apps = []
75
+ for i in range(desktop.get_child_count()):
76
+ acc = desktop.get_child_at_index(i)
77
+ if acc is None or (app and app.lower() not in (acc.get_name() or "").lower()):
78
+ continue
79
+ apps.append(node_json(acc, str(i), 0, int(max_depth)))
80
+ return apps
81
+
82
+
83
+ def click(node_id):
84
+ acc = resolve(node_id)
85
+ names = action_names(acc)
86
+ if names:
87
+ index = next((names.index(n) for n in CLICK_ACTIONS if n in names), 0)
88
+ if not Atspi.Action.do_action(acc, index):
89
+ sys.exit(f"UI element {node_id} rejected the {names[index]} action")
90
+ return {"action": names[index]}
91
+ return {"center": center(acc, node_id)}
92
+
93
+
94
+ def set_text(node_id, text):
95
+ acc = resolve(node_id)
96
+ if acc.get_editable_text_iface() is None:
97
+ sys.exit(f"UI element {node_id} ({acc.get_role_name()}) is not editable")
98
+ if Atspi.EditableText.set_text_contents(acc, text) and Atspi.Text.get_text(acc, 0, -1) == text:
99
+ return {"ok": True}
100
+ return {"center": center(acc, node_id)}
101
+
102
+
103
+ if __name__ == "__main__":
104
+ commands = {"tree": tree, "click": click, "set_text": set_text}
105
+ print(json.dumps(commands[sys.argv[1]](*sys.argv[2:])))
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.5
2
+ Name: tsugite-computer
3
+ Version: 0.30.0
4
+ Summary: Tsugite plugin: computer use tools that drive a virtual Linux desktop in a container
5
+ Author: Justyn Shull
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: tsugite-cli==0.30.0
@@ -0,0 +1,6 @@
1
+ tsugite_computer/__init__.py,sha256=NEcgj-IbDlzeesJg3Gmw_AU1dImmI2GGhSbj388xSnI,10197
2
+ tsugite_computer/atspi_helper.py,sha256=uaups5o2hpUtubmjjtiWFpul0TxfefUBdPjFEALTiWw,3486
3
+ tsugite_computer-0.30.0.dist-info/METADATA,sha256=3cU7c6dLD0wIjP7LvOYK0hU03IrygnncprV6fNiWt-c,235
4
+ tsugite_computer-0.30.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ tsugite_computer-0.30.0.dist-info/entry_points.txt,sha256=A5c0lMIa8b9qdu-toHG5_htU4wmGsrYNNTNO2GFW57g,46
6
+ tsugite_computer-0.30.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [tsugite.plugins]
2
+ computer = tsugite_computer