tsugite-computer 0.30.0__tar.gz

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,201 @@
1
+ # ---> Python
2
+ # Byte-compiled / optimized / DLL files
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+
7
+ # C extensions
8
+ *.so
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ /lib/
19
+ /lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103
+ #poetry.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
111
+ .pdm.toml
112
+ .pdm-python
113
+ .pdm-build/
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ #.idea/
164
+
165
+ .env
166
+ .env
167
+ benchmark_results/
168
+ test_output/
169
+ .claude/settings.local.json
170
+ std*.txt
171
+ secrets/*
172
+
173
+
174
+ # TODO: temp - I need to clean up the docs
175
+ docs-old/
176
+ docs/design/
177
+ examples/*
178
+ !examples/tsugite-example-plugin/
179
+ /agents/
180
+ .claude/
181
+ .tsugite/
182
+ benchmarks/
183
+ docker-compose.test.yml
184
+ #### TODO ^^^
185
+
186
+ # Vite dep-optimizer cache. Normally under node_modules/.vite, but lands at the
187
+ # cwd's `.vite/` when vite/vitest is run from the repo root, so ignore it anywhere.
188
+ .vite/
189
+ # Built web UI - generated by `mise run web-build`; the wheel bundles it via
190
+ # hatch `artifacts`, git never carries it.
191
+ plugins/tsugite-daemon/tsugite_daemon/web/
192
+ # Re-include frontend source that generic lib/ rules (incl. contributors' global
193
+ # gitignores with Python-style `lib/`) would otherwise silently exclude.
194
+ !plugins/tsugite-daemon/frontend/src/lib/
195
+ !plugins/tsugite-daemon/frontend/src/lib/**
196
+ # Per-job git worktrees provisioned by the daemon.
197
+ .tsugite-jobs/
198
+ /packaging/runtime/.cache/
199
+ # Corporate CA certs dropped in for docker build.
200
+ /docker/ca-certificates/*
201
+ !/docker/ca-certificates/.gitkeep
@@ -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,37 @@
1
+ # Virtual Linux desktop for the tsugite-computer plugin.
2
+ FROM docker.io/library/ubuntu:24.04
3
+
4
+ ENV DEBIAN_FRONTEND=noninteractive
5
+ RUN apt-get update && apt-get install -y --no-install-recommends \
6
+ xvfb openbox x11vnc novnc websockify xdotool scrot x11-utils \
7
+ dbus-x11 at-spi2-core python3 python3-gi gir1.2-atspi-2.0 \
8
+ xterm fonts-dejavu-core ca-certificates curl gpg \
9
+ && curl -fsSL https://packages.mozilla.org/apt/repo-signing-key.gpg -o /etc/apt/keyrings/packages.mozilla.org.asc \
10
+ && gpg --show-keys --with-colons /etc/apt/keyrings/packages.mozilla.org.asc \
11
+ | awk -F: '/^fpr:/ { print $10; exit }' | grep -qx 35BAA0B33E9EB396F59CA838C0BA5CE6DC6315A3 \
12
+ && echo "deb [signed-by=/etc/apt/keyrings/packages.mozilla.org.asc] https://packages.mozilla.org/apt mozilla main" \
13
+ > /etc/apt/sources.list.d/mozilla.list \
14
+ && printf 'Package: *\nPin: origin packages.mozilla.org\nPin-Priority: 1000\n' > /etc/apt/preferences.d/mozilla \
15
+ && apt-get update && apt-get install -y --no-install-recommends firefox \
16
+ && rm -rf /var/lib/apt/lists/* \
17
+ && ln -s /usr/share/novnc/vnc.html /usr/share/novnc/index.html \
18
+ && curl -fsSL -o /opt/ublock-origin.xpi \
19
+ https://github.com/gorhill/uBlock/releases/download/1.75.0/uBlock0_1.75.0.firefox.signed.xpi \
20
+ && echo "5b74415860456370644bd80f16125e865b0e6c356bb5dfcfb84069967eaa5287 /opt/ublock-origin.xpi" | sha256sum -c -
21
+
22
+ RUN useradd -m -s /bin/bash desktop
23
+ COPY firefox-policies.json /etc/firefox/policies/policies.json
24
+ COPY --chmod=755 entrypoint.sh /usr/local/bin/entrypoint.sh
25
+ COPY NOTICE /usr/share/doc/tsugite-computer/NOTICE
26
+
27
+ USER desktop
28
+ WORKDIR /home/desktop
29
+ ENV WIDTH=1280 \
30
+ HEIGHT=800 \
31
+ DISPLAY=:1 \
32
+ DBUS_SESSION_BUS_ADDRESS=unix:path=/tmp/dbus-session \
33
+ GNOME_ACCESSIBILITY=1 \
34
+ QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1
35
+
36
+ EXPOSE 6080
37
+ ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
@@ -0,0 +1,23 @@
1
+ Dockerfile and entrypoint.sh are adapted from Anthropic's computer-use-demo:
2
+ https://github.com/anthropics/claude-quickstarts/tree/main/computer-use-demo
3
+
4
+ Copyright 2024 Anthropic, PBC.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
7
+ this software and associated documentation files (the "Software"), to deal in
8
+ the Software without restriction, including without limitation the rights to
9
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10
+ of the Software, and to permit persons to whom the Software is furnished to do
11
+ so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
@@ -0,0 +1,20 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ : "${VNC_PASSWORD:?VNC_PASSWORD must be set}"
4
+
5
+ dbus-daemon --session --address="$DBUS_SESSION_BUS_ADDRESS" --nofork --nopidfile &
6
+ Xvfb "$DISPLAY" -screen 0 "${WIDTH}x${HEIGHT}x24" -dpi 96 -nolisten tcp &
7
+
8
+ for _ in $(seq 50); do
9
+ xdpyinfo >/dev/null 2>&1 && break
10
+ sleep 0.2
11
+ done
12
+ xdpyinfo >/dev/null
13
+
14
+ /usr/libexec/at-spi-bus-launcher --launch-immediately &
15
+ openbox &
16
+ x11vnc -storepasswd "$VNC_PASSWORD" /tmp/vncpasswd >/dev/null
17
+ x11vnc -display "$DISPLAY" -forever -shared -rfbauth /tmp/vncpasswd -quiet -rfbport 5900 &
18
+ websockify --web /usr/share/novnc 6080 localhost:5900 &
19
+
20
+ wait -n
@@ -0,0 +1,38 @@
1
+ {
2
+ "policies": {
3
+ "SkipTermsOfUse": true,
4
+ "DisableTelemetry": true,
5
+ "DisableFirefoxStudies": true,
6
+ "DisableDefaultBrowserAgent": true,
7
+ "DontCheckDefaultBrowser": true,
8
+ "OverrideFirstRunPage": "",
9
+ "OverridePostUpdatePage": "",
10
+ "UserMessaging": {
11
+ "SkipOnboarding": true,
12
+ "ExtensionRecommendations": false,
13
+ "FeatureRecommendations": false,
14
+ "MoreFromMozilla": false,
15
+ "Locked": true
16
+ },
17
+ "NewTabPage": false,
18
+ "Homepage": {
19
+ "StartPage": "none"
20
+ },
21
+ "FirefoxHome": {
22
+ "Search": false,
23
+ "TopSites": false,
24
+ "SponsoredTopSites": false,
25
+ "Highlights": false,
26
+ "Stories": false,
27
+ "SponsoredStories": false,
28
+ "Snippets": false,
29
+ "Locked": true
30
+ },
31
+ "ExtensionSettings": {
32
+ "uBlock0@raymondhill.net": {
33
+ "installation_mode": "force_installed",
34
+ "install_url": "file:///opt/ublock-origin.xpi"
35
+ }
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "tsugite-computer"
3
+ version = "0.30.0"
4
+ description = "Tsugite plugin: computer use tools that drive a virtual Linux desktop in a container"
5
+ authors = [{ name = "Justyn Shull" }]
6
+ requires-python = ">=3.11"
7
+ dependencies = ["tsugite-cli==0.30.0"]
8
+
9
+ [project.entry-points."tsugite.plugins"]
10
+ computer = "tsugite_computer"
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.build.targets.wheel]
17
+ packages = ["tsugite_computer"]
18
+
19
+ [tool.hatch.build.targets.sdist]
20
+ include = [
21
+ "/tsugite_computer",
22
+ "/docker",
23
+ "/pyproject.toml",
24
+ ]
25
+
26
+ [tool.uv.sources]
27
+ tsugite-cli = { workspace = true }
@@ -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:])))