starfold 0.3.2__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.
starfold-0.3.2/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kyora
4
+ Copyright (c) 2026 Tembo
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do 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.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: starfold
3
+ Version: 0.3.2
4
+ Summary: Python SDK for starfold
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: httpx>=0.27
8
+ Requires-Dist: pillow>=10 ; extra == 'pillow'
9
+ Requires-Python: >=3.10
10
+ Project-URL: Repository, https://github.com/kyora-sh/starfold
11
+ Provides-Extra: pillow
12
+ Description-Content-Type: text/markdown
13
+
14
+ # starfold (Python)
15
+
16
+ A client for agents and scripts driving a starfold desktop: screenshots, waiting for the
17
+ screen, mouse and keyboard, recordings and files.
18
+
19
+ ```sh
20
+ uv add starfold # or: pip install starfold
21
+ ```
22
+
23
+ From a checkout: `uv add --editable path/to/starfold/python/starfold` (or `pip install -e python/starfold`).
24
+
25
+ ```python
26
+ from starfold import Starfold, act
27
+
28
+ # password defaults to $STARFOLD_PASSWORD
29
+ with Starfold("http://localhost:6901", password="...") as sf:
30
+ shot = sf.screenshot() # shot.png (bytes), shot.seq, shot.size
31
+ shot.save("before.png")
32
+
33
+ sf.click(400, 300)
34
+ r = sf.type_text("hello\n")
35
+ sf.wait(change=True, since=r.seq) # returns once the typing changed the screen
36
+ sf.wait(idle_ms=300) # and once it settled
37
+
38
+ sf.key("ctrl+shift+t")
39
+ sf.scroll(dy=3, x=400, y=300)
40
+ sf.drag(100, 100, 400, 100)
41
+ sf.actions([act.key("ctrl+l"), act.type_text("example.com"), act.key("Enter")])
42
+
43
+ clips = sf.record(5) # a list of MP4s: one, or more if the encoder changed mid-recording
44
+ sf.files_upload("data.csv", "local/data.csv")
45
+ print([e.name for e in sf.files_list().entries])
46
+ ```
47
+
48
+ `AsyncStarfold` has the same methods for asyncio. `Screenshot.image()` returns a Pillow
49
+ image if Pillow is installed (`starfold[pillow]`).
50
+
51
+ Errors: `AuthError` (wrong or missing password), `ReadOnlyError` (the server runs with
52
+ `--read-only`), `RecordingOffError` (it runs without `--enable-recording`), `ForbiddenError`,
53
+ `NotFoundError`, `StarfoldTimeoutError`, `StarfoldConnectionError`, and for the server on this
54
+ machine (below) `BinaryNotFoundError`, `MissingLibrariesError` and `ServerStartError`, all
55
+ `StarfoldError`. `wait()` reports a timeout in its result
56
+ (`timed_out`) rather than raising.
57
+
58
+ Keys for `key()` are a single character or a name (Enter, Tab, Escape, BackSpace, Delete,
59
+ Home, End, PageUp, PageDown, Up, Down, Left, Right, F1-F24, ...), joined with `+` after
60
+ modifiers (ctrl, shift, alt, altgr, super). With shift, a letter or a US-layout digit or
61
+ punctuation key means the shifted key: `ctrl+shift+t`, `cmd+shift+4`.
62
+
63
+ ## The server, from the same install
64
+
65
+ On Linux x86_64 and aarch64, macOS arm64 and Windows x86_64, `pip install starfold` gets a
66
+ wheel with the starfold server binary in it. On other platforms it installs the client alone,
67
+ which works against a server running elsewhere.
68
+
69
+ ```python
70
+ import starfold
71
+
72
+ with starfold.start_server() as server: # loopback, a free port, a generated password
73
+ sf = server.client() # signed in already
74
+ sf.screenshot().save("desktop.png")
75
+ ```
76
+
77
+ `start_server()` listens on 127.0.0.1 unless you pass `addr=`; `port=`, `password=` (an
78
+ empty one counts as none), `args=` (more server flags, `starfold --help`), `env=` (merged onto
79
+ this process's environment), `cwd=`, `binary=` (default `binary_path()`) and `timeout=`
80
+ (seconds until it answers, default 30) are optional. If the server exits, doesn't answer in
81
+ time or can't have its port, it raises `ServerStartError` with the server's last output in
82
+ `output`. It returns a `LocalServer` with `url`, `password`, `process`, `stderr_tail` (the
83
+ server's last lines of output), `client()`, `async_client()` and `close()`; the server stops on
84
+ `close()`, at the end of the `with` block, at exit, and when your process ends, however it
85
+ ends. On Linux and macOS `process` is a small `sh` guard whose child is the server. On Linux it
86
+ needs a display (`DISPLAY`, e.g. from Xvfb); it doesn't start one.
87
+
88
+ `starfold.binary_path()` is the binary: `$STARFOLD_BIN` if set, else the wheel's. The
89
+ `starfold` command runs it (`starfold --help`).
90
+
91
+ On Linux the server uses the system's libyuv, Opus and PulseAudio libraries and needs glibc
92
+ 2.39 or newer (Ubuntu 24.04 or newer):
93
+
94
+ ```sh
95
+ sudo apt install libyuv0 libopus0 libpulse0
96
+ ```
97
+
98
+ Without them, `start_server()` and `starfold` say which libraries are missing.
99
+
100
+ ## Tests
101
+
102
+ ```sh
103
+ uv run pytest # unit tests, no server
104
+ STARFOLD_BIN=../../target/release/starfold uv run pytest -m integration # Linux, Xvfb + xterm
105
+ ```
@@ -0,0 +1,92 @@
1
+ # starfold (Python)
2
+
3
+ A client for agents and scripts driving a starfold desktop: screenshots, waiting for the
4
+ screen, mouse and keyboard, recordings and files.
5
+
6
+ ```sh
7
+ uv add starfold # or: pip install starfold
8
+ ```
9
+
10
+ From a checkout: `uv add --editable path/to/starfold/python/starfold` (or `pip install -e python/starfold`).
11
+
12
+ ```python
13
+ from starfold import Starfold, act
14
+
15
+ # password defaults to $STARFOLD_PASSWORD
16
+ with Starfold("http://localhost:6901", password="...") as sf:
17
+ shot = sf.screenshot() # shot.png (bytes), shot.seq, shot.size
18
+ shot.save("before.png")
19
+
20
+ sf.click(400, 300)
21
+ r = sf.type_text("hello\n")
22
+ sf.wait(change=True, since=r.seq) # returns once the typing changed the screen
23
+ sf.wait(idle_ms=300) # and once it settled
24
+
25
+ sf.key("ctrl+shift+t")
26
+ sf.scroll(dy=3, x=400, y=300)
27
+ sf.drag(100, 100, 400, 100)
28
+ sf.actions([act.key("ctrl+l"), act.type_text("example.com"), act.key("Enter")])
29
+
30
+ clips = sf.record(5) # a list of MP4s: one, or more if the encoder changed mid-recording
31
+ sf.files_upload("data.csv", "local/data.csv")
32
+ print([e.name for e in sf.files_list().entries])
33
+ ```
34
+
35
+ `AsyncStarfold` has the same methods for asyncio. `Screenshot.image()` returns a Pillow
36
+ image if Pillow is installed (`starfold[pillow]`).
37
+
38
+ Errors: `AuthError` (wrong or missing password), `ReadOnlyError` (the server runs with
39
+ `--read-only`), `RecordingOffError` (it runs without `--enable-recording`), `ForbiddenError`,
40
+ `NotFoundError`, `StarfoldTimeoutError`, `StarfoldConnectionError`, and for the server on this
41
+ machine (below) `BinaryNotFoundError`, `MissingLibrariesError` and `ServerStartError`, all
42
+ `StarfoldError`. `wait()` reports a timeout in its result
43
+ (`timed_out`) rather than raising.
44
+
45
+ Keys for `key()` are a single character or a name (Enter, Tab, Escape, BackSpace, Delete,
46
+ Home, End, PageUp, PageDown, Up, Down, Left, Right, F1-F24, ...), joined with `+` after
47
+ modifiers (ctrl, shift, alt, altgr, super). With shift, a letter or a US-layout digit or
48
+ punctuation key means the shifted key: `ctrl+shift+t`, `cmd+shift+4`.
49
+
50
+ ## The server, from the same install
51
+
52
+ On Linux x86_64 and aarch64, macOS arm64 and Windows x86_64, `pip install starfold` gets a
53
+ wheel with the starfold server binary in it. On other platforms it installs the client alone,
54
+ which works against a server running elsewhere.
55
+
56
+ ```python
57
+ import starfold
58
+
59
+ with starfold.start_server() as server: # loopback, a free port, a generated password
60
+ sf = server.client() # signed in already
61
+ sf.screenshot().save("desktop.png")
62
+ ```
63
+
64
+ `start_server()` listens on 127.0.0.1 unless you pass `addr=`; `port=`, `password=` (an
65
+ empty one counts as none), `args=` (more server flags, `starfold --help`), `env=` (merged onto
66
+ this process's environment), `cwd=`, `binary=` (default `binary_path()`) and `timeout=`
67
+ (seconds until it answers, default 30) are optional. If the server exits, doesn't answer in
68
+ time or can't have its port, it raises `ServerStartError` with the server's last output in
69
+ `output`. It returns a `LocalServer` with `url`, `password`, `process`, `stderr_tail` (the
70
+ server's last lines of output), `client()`, `async_client()` and `close()`; the server stops on
71
+ `close()`, at the end of the `with` block, at exit, and when your process ends, however it
72
+ ends. On Linux and macOS `process` is a small `sh` guard whose child is the server. On Linux it
73
+ needs a display (`DISPLAY`, e.g. from Xvfb); it doesn't start one.
74
+
75
+ `starfold.binary_path()` is the binary: `$STARFOLD_BIN` if set, else the wheel's. The
76
+ `starfold` command runs it (`starfold --help`).
77
+
78
+ On Linux the server uses the system's libyuv, Opus and PulseAudio libraries and needs glibc
79
+ 2.39 or newer (Ubuntu 24.04 or newer):
80
+
81
+ ```sh
82
+ sudo apt install libyuv0 libopus0 libpulse0
83
+ ```
84
+
85
+ Without them, `start_server()` and `starfold` say which libraries are missing.
86
+
87
+ ## Tests
88
+
89
+ ```sh
90
+ uv run pytest # unit tests, no server
91
+ STARFOLD_BIN=../../target/release/starfold uv run pytest -m integration # Linux, Xvfb + xterm
92
+ ```
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "starfold"
3
+ version = "0.3.2"
4
+ description = "Python SDK for starfold"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ dependencies = ["httpx>=0.27"]
10
+
11
+ [project.scripts]
12
+ starfold = "starfold._native:main"
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/kyora-sh/starfold"
16
+
17
+ [project.optional-dependencies]
18
+ pillow = ["pillow>=10"]
19
+
20
+ [dependency-groups]
21
+ dev = ["pytest>=8", "ruff>=0.8"]
22
+
23
+ [build-system]
24
+ requires = ["uv_build>=0.11,<0.12"]
25
+ build-backend = "uv_build"
26
+
27
+ [tool.ruff]
28
+ line-length = 120
29
+ target-version = "py310"
30
+
31
+ [tool.ruff.lint]
32
+ select = ["E", "F", "I", "UP", "B", "SIM"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
36
+ markers = ["integration: starts the server on Xvfb (set STARFOLD_BIN to run)"]
@@ -0,0 +1,60 @@
1
+ """Drive a starfold desktop from Python: screenshots, waiting for the screen, mouse and keyboard."""
2
+
3
+ from . import act
4
+ from ._client import AsyncStarfold, Starfold
5
+ from ._native import (
6
+ BinaryNotFoundError,
7
+ LocalServer,
8
+ MissingLibrariesError,
9
+ ServerStartError,
10
+ binary_path,
11
+ check_libraries,
12
+ start_server,
13
+ )
14
+ from ._types import (
15
+ AuthError,
16
+ FileEntry,
17
+ FileList,
18
+ ForbiddenError,
19
+ InputResult,
20
+ NotFoundError,
21
+ ReadOnlyError,
22
+ Recording,
23
+ RecordingOffError,
24
+ Screenshot,
25
+ Segments,
26
+ StarfoldConnectionError,
27
+ StarfoldError,
28
+ StarfoldTimeoutError,
29
+ Upload,
30
+ WaitResult,
31
+ )
32
+
33
+ __all__ = [
34
+ "AsyncStarfold",
35
+ "AuthError",
36
+ "BinaryNotFoundError",
37
+ "FileEntry",
38
+ "FileList",
39
+ "ForbiddenError",
40
+ "InputResult",
41
+ "LocalServer",
42
+ "MissingLibrariesError",
43
+ "NotFoundError",
44
+ "ReadOnlyError",
45
+ "Recording",
46
+ "RecordingOffError",
47
+ "Screenshot",
48
+ "Segments",
49
+ "ServerStartError",
50
+ "Starfold",
51
+ "StarfoldConnectionError",
52
+ "StarfoldError",
53
+ "StarfoldTimeoutError",
54
+ "Upload",
55
+ "WaitResult",
56
+ "act",
57
+ "binary_path",
58
+ "check_libraries",
59
+ "start_server",
60
+ ]
@@ -0,0 +1,417 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import os
6
+ import warnings
7
+ import zipfile
8
+ from collections.abc import Callable, Iterable
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any, Generic, TypeVar
12
+
13
+ import httpx
14
+
15
+ from . import act
16
+ from ._types import (
17
+ AuthError,
18
+ FileList,
19
+ ForbiddenError,
20
+ InputResult,
21
+ NotFoundError,
22
+ ReadOnlyError,
23
+ Recording,
24
+ RecordingOffError,
25
+ Screenshot,
26
+ Segments,
27
+ StarfoldConnectionError,
28
+ StarfoldError,
29
+ StarfoldTimeoutError,
30
+ Upload,
31
+ WaitResult,
32
+ )
33
+
34
+ T = TypeVar("T")
35
+
36
+ DEFAULT_TIMEOUT = 30.0
37
+ DEFAULT_URL = "http://localhost:6901"
38
+
39
+
40
+ @dataclass
41
+ class _Req(Generic[T]):
42
+ method: str
43
+ path: str
44
+ parse: Callable[[httpx.Response], T]
45
+ params: dict[str, Any] | None = None
46
+ json: Any = None
47
+ content: bytes | None = None
48
+ headers: dict[str, str] = field(default_factory=dict)
49
+ extra_s: float = 0.0
50
+ """Seconds the server may take on purpose (a wait, a recording), on top of the timeout."""
51
+
52
+
53
+ def _error(resp: httpx.Response) -> StarfoldError:
54
+ try:
55
+ body = resp.json()
56
+ message = str(body["error"])
57
+ except Exception:
58
+ body = None
59
+ message = resp.text.strip() or resp.reason_phrase
60
+ code = resp.status_code
61
+ if code == 401:
62
+ return AuthError(message, code)
63
+ if code == 403:
64
+ if isinstance(body, dict) and body.get("read_only") is True:
65
+ return ReadOnlyError(message, code)
66
+ if isinstance(body, dict) and body.get("recording") is False:
67
+ return RecordingOffError(message, code)
68
+ return ForbiddenError(message, code)
69
+ if code == 404:
70
+ return NotFoundError(message, code)
71
+ return StarfoldError(f"{code}: {message}", code)
72
+
73
+
74
+ def _check(resp: httpx.Response) -> httpx.Response:
75
+ if resp.is_success:
76
+ return resp
77
+ raise _error(resp)
78
+
79
+
80
+ def _transport_error(e: httpx.TransportError) -> StarfoldError:
81
+ if isinstance(e, httpx.TimeoutException):
82
+ return StarfoldTimeoutError(f"no answer in time: {e}")
83
+ return StarfoldConnectionError(f"cannot reach the server: {e}")
84
+
85
+
86
+ def _screenshot() -> _Req[Screenshot]:
87
+ return _Req("GET", "/screenshot", lambda r: Screenshot(png=r.content, seq=int(_seq_header(r.headers))))
88
+
89
+
90
+ def _seq_header(headers: httpx.Headers) -> str:
91
+ return headers.get("x-starfold-seq") or headers["x-voxl-seq"]
92
+
93
+
94
+ def _env_password() -> str | None:
95
+ new, old = os.environ.get("STARFOLD_PASSWORD"), os.environ.get("VOXL_PASSWORD")
96
+ if old is not None:
97
+ msg = (
98
+ "VOXL_PASSWORD is ignored: STARFOLD_PASSWORD is set"
99
+ if new is not None
100
+ else "VOXL_PASSWORD is deprecated: use STARFOLD_PASSWORD"
101
+ )
102
+ warnings.warn(msg, DeprecationWarning, stacklevel=4)
103
+ return new if new is not None else old
104
+
105
+
106
+ def _wait(
107
+ idle_ms: int | None,
108
+ timeout_ms: int | None,
109
+ change: bool,
110
+ region: tuple[int, int, int, int] | None,
111
+ since: int | None,
112
+ ) -> _Req[WaitResult]:
113
+ params: dict[str, Any] = {}
114
+ if idle_ms is not None:
115
+ params["idle"] = idle_ms
116
+ if timeout_ms is not None:
117
+ params["timeout"] = timeout_ms
118
+ if change:
119
+ params["change"] = 1
120
+ if region is not None:
121
+ params["region"] = ",".join(str(int(v)) for v in region)
122
+ if since is not None:
123
+ params["since"] = since
124
+ extra = (timeout_ms if timeout_ms is not None else 10_000) / 1000
125
+ return _Req("GET", "/wait", lambda r: WaitResult.from_json(r.json()), params=params, extra_s=extra)
126
+
127
+
128
+ def _input(actions: Iterable[act.Action | list[act.Action]]) -> _Req[InputResult]:
129
+ flat: list[act.Action] = []
130
+ for a in actions:
131
+ flat.extend(a if isinstance(a, list) else [a])
132
+ paused = sum(a.get("ms", 0) for a in flat if a.get("type") == "pause") / 1000
133
+ # The answer comes once the input is done; a character the keymap lacks takes ~10 ms.
134
+ typing = sum(len(a.get("text", "")) for a in flat if a.get("type") == "type") / 100
135
+ return _Req(
136
+ "POST",
137
+ "/input",
138
+ lambda r: InputResult(seq=int(r.json()["seq"]), events=int(r.json()["events"])),
139
+ json=flat,
140
+ extra_s=paused + typing,
141
+ )
142
+
143
+
144
+ def _segments(r: httpx.Response) -> Segments:
145
+ if r.headers.get("content-type", "").split(";")[0].strip().lower() != "application/zip":
146
+ return Segments([r.content])
147
+ with zipfile.ZipFile(io.BytesIO(r.content)) as z:
148
+ manifest = json.loads(z.read("manifest.json"))
149
+ return Segments([z.read(s["file"]) for s in manifest["segments"]], manifest["end_reason"])
150
+
151
+
152
+ def _record(seconds: float) -> _Req[Segments]:
153
+ return _Req("GET", "/record", _segments, params={"seconds": seconds, "format": "zip"}, extra_s=seconds)
154
+
155
+
156
+ def _record_start() -> _Req[Recording]:
157
+ return _Req(
158
+ "POST", "/record/start", lambda r: Recording(id=str(r.json()["id"]), max_seconds=int(r.json()["max_seconds"]))
159
+ )
160
+
161
+
162
+ def _record_stop(recording: Recording | str) -> _Req[Segments]:
163
+ rid = recording.id if isinstance(recording, Recording) else recording
164
+ if not isinstance(rid, str):
165
+ raise TypeError(
166
+ f"a recording id is a string (the Recording record_start returned, or its .id), not {type(rid).__name__}"
167
+ )
168
+ return _Req("POST", "/record/stop", _segments, params={"id": rid, "format": "zip"})
169
+
170
+
171
+ def _files_list(path: str) -> _Req[FileList]:
172
+ return _Req("GET", "/files/list", lambda r: FileList.from_json(r.json()), params={"path": path})
173
+
174
+
175
+ def _files_download(path: str) -> _Req[bytes]:
176
+ return _Req("GET", "/files/download", lambda r: r.content, params={"path": path})
177
+
178
+
179
+ def _files_upload(name: str, data: bytes | str | os.PathLike[str], path: str | None, sub: str | None) -> _Req[Upload]:
180
+ body = data if isinstance(data, bytes) else Path(data).read_bytes()
181
+ params = {"name": name}
182
+ if path is not None:
183
+ params["path"] = path
184
+ if sub is not None:
185
+ params["sub"] = sub
186
+ return _Req(
187
+ "PUT",
188
+ "/files/upload",
189
+ lambda r: Upload(path=r.json()["path"], size=int(r.json()["size"])),
190
+ params=params,
191
+ content=body,
192
+ headers={"X-Starfold-Upload": "1", "X-Voxl-Upload": "1"},
193
+ )
194
+
195
+
196
+ class _Base:
197
+ def __init__(self, url: str, password: str | None, timeout: float) -> None:
198
+ self.url = url.rstrip("/")
199
+ password = password if password is not None else _env_password()
200
+ self._headers = {"Authorization": f"Bearer {password}"} if password else {}
201
+ self.timeout = timeout
202
+
203
+ def _kwargs(self, req: _Req[Any]) -> dict[str, Any]:
204
+ return {
205
+ "params": req.params,
206
+ "json": req.json,
207
+ "content": req.content,
208
+ "headers": req.headers,
209
+ "timeout": self.timeout + req.extra_s,
210
+ }
211
+
212
+
213
+ class Starfold(_Base):
214
+ """A starfold desktop, for agents: screenshots, waiting for the screen, mouse and keyboard.
215
+
216
+ `password` defaults to $STARFOLD_PASSWORD. `timeout` is in seconds; waits and recordings
217
+ get their own length on top.
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ url: str = DEFAULT_URL,
223
+ password: str | None = None,
224
+ timeout: float = DEFAULT_TIMEOUT,
225
+ *,
226
+ transport: httpx.BaseTransport | None = None,
227
+ ) -> None:
228
+ super().__init__(url, password, timeout)
229
+ self._http = httpx.Client(base_url=self.url, headers=self._headers, transport=transport)
230
+
231
+ def __enter__(self) -> Starfold:
232
+ return self
233
+
234
+ def __exit__(self, *exc: object) -> None:
235
+ self.close()
236
+
237
+ def close(self) -> None:
238
+ self._http.close()
239
+
240
+ def _do(self, req: _Req[T]) -> T:
241
+ try:
242
+ resp = self._http.request(req.method, req.path, **self._kwargs(req))
243
+ except httpx.TransportError as e:
244
+ raise _transport_error(e) from e
245
+ return req.parse(_check(resp))
246
+
247
+ def screenshot(self) -> Screenshot:
248
+ return self._do(_screenshot())
249
+
250
+ def wait(
251
+ self,
252
+ idle_ms: int | None = None,
253
+ timeout_ms: int | None = None,
254
+ change: bool = False,
255
+ region: tuple[int, int, int, int] | None = None,
256
+ since: int | None = None,
257
+ ) -> WaitResult:
258
+ """Until the screen stays still for `idle_ms` (default 300), or with `change` until it changes."""
259
+ return self._do(_wait(idle_ms, timeout_ms, change, region, since))
260
+
261
+ def actions(self, actions: Iterable[act.Action | list[act.Action]]) -> InputResult:
262
+ """Sends `starfold.act` actions in one request, applied in order."""
263
+ return self._do(_input(actions))
264
+
265
+ def move(self, x: int, y: int) -> InputResult:
266
+ return self.actions([act.move(x, y)])
267
+
268
+ def click(
269
+ self, x: int | None = None, y: int | None = None, button: act.Button = "left", count: int = 1
270
+ ) -> InputResult:
271
+ return self.actions([act.click(x, y, button, count)])
272
+
273
+ def double_click(self, x: int | None = None, y: int | None = None, button: act.Button = "left") -> InputResult:
274
+ return self.actions([act.click(x, y, button, 2)])
275
+
276
+ def mouse_down(self, x: int | None = None, y: int | None = None, button: act.Button = "left") -> InputResult:
277
+ return self.actions([act.down(x, y, button)])
278
+
279
+ def mouse_up(self, x: int | None = None, y: int | None = None, button: act.Button = "left") -> InputResult:
280
+ return self.actions([act.up(x, y, button)])
281
+
282
+ def drag(
283
+ self, x1: int, y1: int, x2: int, y2: int, button: act.Button = "left", steps: int = 10, step_ms: int = 10
284
+ ) -> InputResult:
285
+ return self.actions(act.drag(x1, y1, x2, y2, button, steps, step_ms))
286
+
287
+ def scroll(self, dx: int = 0, dy: int = 0, x: int | None = None, y: int | None = None) -> InputResult:
288
+ return self.actions([act.scroll(dx, dy, x, y)])
289
+
290
+ def key(self, combo: str) -> InputResult:
291
+ return self.actions([act.key(combo)])
292
+
293
+ def type_text(self, text: str) -> InputResult:
294
+ return self.actions([act.type_text(text)])
295
+
296
+ def record(self, seconds: float) -> Segments:
297
+ """An MP4 of the next `seconds`."""
298
+ return self._do(_record(seconds))
299
+
300
+ def record_start(self) -> Recording:
301
+ return self._do(_record_start())
302
+
303
+ def record_stop(self, recording: Recording | str) -> Segments:
304
+ return self._do(_record_stop(recording))
305
+
306
+ def files_list(self, path: str = "") -> FileList:
307
+ return self._do(_files_list(path))
308
+
309
+ def files_download(self, path: str) -> bytes:
310
+ """A file's bytes, or a folder as a zip."""
311
+ return self._do(_files_download(path))
312
+
313
+ def files_upload(
314
+ self, name: str, data: bytes | str | os.PathLike[str], path: str | None = None, sub: str | None = None
315
+ ) -> Upload:
316
+ """Uploads `data` (bytes or a local file) as `name` into `path` (default: the upload folder)."""
317
+ return self._do(_files_upload(name, data, path, sub))
318
+
319
+
320
+ class AsyncStarfold(_Base):
321
+ """`Starfold` for asyncio: the same methods, awaited."""
322
+
323
+ def __init__(
324
+ self,
325
+ url: str = DEFAULT_URL,
326
+ password: str | None = None,
327
+ timeout: float = DEFAULT_TIMEOUT,
328
+ *,
329
+ transport: httpx.AsyncBaseTransport | None = None,
330
+ ) -> None:
331
+ super().__init__(url, password, timeout)
332
+ self._http = httpx.AsyncClient(base_url=self.url, headers=self._headers, transport=transport)
333
+
334
+ async def __aenter__(self) -> AsyncStarfold:
335
+ return self
336
+
337
+ async def __aexit__(self, *exc: object) -> None:
338
+ await self.close()
339
+
340
+ async def close(self) -> None:
341
+ await self._http.aclose()
342
+
343
+ async def _do(self, req: _Req[T]) -> T:
344
+ try:
345
+ resp = await self._http.request(req.method, req.path, **self._kwargs(req))
346
+ except httpx.TransportError as e:
347
+ raise _transport_error(e) from e
348
+ return req.parse(_check(resp))
349
+
350
+ async def screenshot(self) -> Screenshot:
351
+ return await self._do(_screenshot())
352
+
353
+ async def wait(
354
+ self,
355
+ idle_ms: int | None = None,
356
+ timeout_ms: int | None = None,
357
+ change: bool = False,
358
+ region: tuple[int, int, int, int] | None = None,
359
+ since: int | None = None,
360
+ ) -> WaitResult:
361
+ return await self._do(_wait(idle_ms, timeout_ms, change, region, since))
362
+
363
+ async def actions(self, actions: Iterable[act.Action | list[act.Action]]) -> InputResult:
364
+ return await self._do(_input(actions))
365
+
366
+ async def move(self, x: int, y: int) -> InputResult:
367
+ return await self.actions([act.move(x, y)])
368
+
369
+ async def click(
370
+ self, x: int | None = None, y: int | None = None, button: act.Button = "left", count: int = 1
371
+ ) -> InputResult:
372
+ return await self.actions([act.click(x, y, button, count)])
373
+
374
+ async def double_click(
375
+ self, x: int | None = None, y: int | None = None, button: act.Button = "left"
376
+ ) -> InputResult:
377
+ return await self.actions([act.click(x, y, button, 2)])
378
+
379
+ async def mouse_down(self, x: int | None = None, y: int | None = None, button: act.Button = "left") -> InputResult:
380
+ return await self.actions([act.down(x, y, button)])
381
+
382
+ async def mouse_up(self, x: int | None = None, y: int | None = None, button: act.Button = "left") -> InputResult:
383
+ return await self.actions([act.up(x, y, button)])
384
+
385
+ async def drag(
386
+ self, x1: int, y1: int, x2: int, y2: int, button: act.Button = "left", steps: int = 10, step_ms: int = 10
387
+ ) -> InputResult:
388
+ return await self.actions(act.drag(x1, y1, x2, y2, button, steps, step_ms))
389
+
390
+ async def scroll(self, dx: int = 0, dy: int = 0, x: int | None = None, y: int | None = None) -> InputResult:
391
+ return await self.actions([act.scroll(dx, dy, x, y)])
392
+
393
+ async def key(self, combo: str) -> InputResult:
394
+ return await self.actions([act.key(combo)])
395
+
396
+ async def type_text(self, text: str) -> InputResult:
397
+ return await self.actions([act.type_text(text)])
398
+
399
+ async def record(self, seconds: float) -> Segments:
400
+ return await self._do(_record(seconds))
401
+
402
+ async def record_start(self) -> Recording:
403
+ return await self._do(_record_start())
404
+
405
+ async def record_stop(self, recording: Recording | str) -> Segments:
406
+ return await self._do(_record_stop(recording))
407
+
408
+ async def files_list(self, path: str = "") -> FileList:
409
+ return await self._do(_files_list(path))
410
+
411
+ async def files_download(self, path: str) -> bytes:
412
+ return await self._do(_files_download(path))
413
+
414
+ async def files_upload(
415
+ self, name: str, data: bytes | str | os.PathLike[str], path: str | None = None, sub: str | None = None
416
+ ) -> Upload:
417
+ return await self._do(_files_upload(name, data, path, sub))
@@ -0,0 +1,419 @@
1
+ """The starfold server binary the platform wheels carry, and starting it locally."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import collections
7
+ import contextlib
8
+ import os
9
+ import platform
10
+ import re
11
+ import secrets
12
+ import shutil
13
+ import signal
14
+ import socket
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ import weakref
20
+ from collections.abc import Mapping, Sequence
21
+ from pathlib import Path
22
+
23
+ import httpx
24
+
25
+ from ._client import AsyncStarfold, Starfold
26
+ from ._types import StarfoldError
27
+
28
+ SUPPORTED = ("Linux x86_64 (glibc 2.39+)", "Linux aarch64 (glibc 2.39+)", "macOS arm64", "Windows x86_64")
29
+ APT_LINE = "sudo apt install libyuv0 libopus0 libpulse0"
30
+
31
+
32
+ class BinaryNotFoundError(StarfoldError):
33
+ """No starfold server binary for this platform: neither $STARFOLD_BIN nor a platform wheel's."""
34
+
35
+
36
+ class MissingLibrariesError(StarfoldError):
37
+ """The server binary's shared libraries don't all resolve on this Linux system."""
38
+
39
+
40
+ class ServerStartError(StarfoldError):
41
+ """start_server() failed: the server exited, didn't answer in time, or its port was taken.
42
+
43
+ `output` holds the server's last lines of output.
44
+ """
45
+
46
+ def __init__(self, message: str, output: str = "") -> None:
47
+ super().__init__(message)
48
+ self.output = output
49
+
50
+
51
+ def _platform() -> str:
52
+ return f"{platform.system() or sys.platform} {platform.machine() or 'unknown'}"
53
+
54
+
55
+ def _bundled() -> Path:
56
+ name = "starfold.exe" if sys.platform == "win32" else "starfold"
57
+ return Path(__file__).parent / "_bin" / name
58
+
59
+
60
+ def binary_path() -> str:
61
+ """The starfold server binary: $STARFOLD_BIN if set, else the one this platform's wheel carries.
62
+
63
+ Raises BinaryNotFoundError when there is neither; the client still works against a server
64
+ running elsewhere.
65
+ """
66
+ env = os.environ.get("STARFOLD_BIN")
67
+ if env:
68
+ if not Path(env).is_file():
69
+ raise BinaryNotFoundError(f"STARFOLD_BIN is {env}, which isn't a file")
70
+ return env
71
+ bundled = _bundled()
72
+ if bundled.is_file():
73
+ return str(bundled)
74
+ raise BinaryNotFoundError(
75
+ f"no starfold server binary for this platform ({_platform()}): the starfold wheels carry one for "
76
+ f"{', '.join(SUPPORTED)}, and this install has none. Set STARFOLD_BIN to a starfold binary to start "
77
+ "one here; the client (Starfold(url)) still works against a server running elsewhere."
78
+ )
79
+
80
+
81
+ def _ldd_missing(output: str) -> list[str]:
82
+ missing = []
83
+ for line in output.splitlines():
84
+ line = line.strip()
85
+ if "=> not found" in line:
86
+ missing.append(line.split("=>")[0].strip())
87
+ elif m := re.search(r"version `([^']+)' not found", line):
88
+ missing.append(m.group(1))
89
+ return list(dict.fromkeys(missing))
90
+
91
+
92
+ def missing_libraries_message(missing: Sequence[str]) -> str:
93
+ return (
94
+ f"the starfold server can't start: these shared libraries are missing: {', '.join(missing)}. "
95
+ f"It needs glibc 2.39+ (Ubuntu 24.04 or newer) and:\n\n {APT_LINE}\n"
96
+ )
97
+
98
+
99
+ def check_libraries(path: str) -> None:
100
+ """On Linux, raises MissingLibrariesError naming the shared libraries `path` needs and can't find."""
101
+ if not sys.platform.startswith("linux"):
102
+ return
103
+ ldd = shutil.which("ldd")
104
+ if ldd is None:
105
+ return
106
+ try:
107
+ r = subprocess.run([ldd, "--", path], capture_output=True, text=True, timeout=30)
108
+ except (OSError, subprocess.TimeoutExpired):
109
+ return
110
+ missing = _ldd_missing(r.stdout + "\n" + r.stderr)
111
+ if missing:
112
+ raise MissingLibrariesError(missing_libraries_message(missing))
113
+
114
+
115
+ def main() -> None:
116
+ """The `starfold` command: runs the server binary with the given arguments and its exit code."""
117
+ try:
118
+ path = binary_path()
119
+ check_libraries(path)
120
+ except StarfoldError as e:
121
+ print(f"starfold: {e}", file=sys.stderr)
122
+ sys.exit(1)
123
+ if sys.platform == "win32":
124
+ sys.exit(subprocess.call([path, *sys.argv[1:]]))
125
+ os.execv(path, [path, *sys.argv[1:]])
126
+
127
+
128
+ GUARD = """exec 3<&0 0</dev/null
129
+ "$0" "$@" 3<&- &
130
+ p=$!
131
+ trap '' TERM
132
+ { while read -r _ <&3; do :; done; kill -TERM 0; } >/dev/null 2>&1 &
133
+ exec 3<&-
134
+ wait "$p"
135
+ rc=$?
136
+ trap '' USR1
137
+ kill -USR1 0 2>/dev/null
138
+ exit "$rc"
139
+ """
140
+ """Runs the server with the guard's stdin, a pipe from this process, held by a watcher.
141
+
142
+ The guard leads its own process group (a new session), and nothing in it signals a pid: when
143
+ the pipe closes (this process ended, however it ended, or close() closed it) the watcher sends
144
+ TERM to its group, which stops the server, and then ends. The guard and the watcher ignore TERM
145
+ (set after the server started, so the server keeps the default), so the guard's wait is never
146
+ cut short and its exit status is the server's. Once the server has exited and been reaped, the
147
+ guard ignores USR1 itself and sends it to its group, which ends the watcher: its USR1 was never
148
+ trapped or ignored, so this holds however soon the server exits (unless this process itself
149
+ ignores USR1: then the watcher lingers, holding no output, until the pipe closes). A process
150
+ group can't be reused while a member is alive, and the sender is always a member. The
151
+ TypeScript SDK starts its server through the same script (a test compares the two)."""
152
+
153
+ _live: weakref.WeakSet[LocalServer] = weakref.WeakSet()
154
+ _jobs: list[int] = []
155
+
156
+
157
+ @atexit.register
158
+ def _close_all() -> None:
159
+ for s in list(_live):
160
+ s.close()
161
+
162
+
163
+ def _free_port(addr: str) -> int:
164
+ family = socket.AF_INET6 if ":" in addr else socket.AF_INET
165
+ with socket.socket(family) as s:
166
+ s.bind((addr, 0))
167
+ return s.getsockname()[1]
168
+
169
+
170
+ def _url(addr: str, port: int) -> str:
171
+ host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(addr, addr)
172
+ return f"http://[{host}]:{port}" if ":" in host else f"http://{host}:{port}"
173
+
174
+
175
+ def _base_path(args: Sequence[str]) -> str:
176
+ """The --base-path (or --base_path) among the server flags, if any, without a trailing slash."""
177
+ found = ""
178
+ for i, a in enumerate(args):
179
+ name, eq, value = a.partition("=")
180
+ if name not in ("--base-path", "--base_path"):
181
+ continue
182
+ if eq:
183
+ found = value
184
+ elif i + 1 < len(args) and not args[i + 1].startswith("--"):
185
+ found = args[i + 1]
186
+ return found.rstrip("/")
187
+
188
+
189
+ class LocalServer:
190
+ """A starfold server this process started: `url`, `password`, `process`, `client()`, `close()`.
191
+
192
+ The server stops on `close()`, when the `with` block ends, at interpreter exit, and when this
193
+ process ends however it ends: on Linux and macOS `process` is a small sh guard whose child is
194
+ the server and which stops it when this process's pipe to it closes; on Windows the server is
195
+ in a job object that ends with this process.
196
+ """
197
+
198
+ def __init__(self, process: subprocess.Popen[bytes], url: str, password: str, output: _Output) -> None:
199
+ self.process = process
200
+ self.url = url
201
+ self.password = password
202
+ self._output = output
203
+ self._client: Starfold | None = None
204
+ _live.add(self)
205
+
206
+ @property
207
+ def stderr_tail(self) -> str:
208
+ """The server's last lines of output."""
209
+ return self._output.tail()
210
+
211
+ def client(self, timeout: float = 30.0) -> Starfold:
212
+ """A Starfold client signed in to this server, closed with it.
213
+
214
+ The first call's timeout holds; for another one, use
215
+ Starfold(server.url, password=server.password, timeout=...).
216
+ """
217
+ if self._client is None:
218
+ self._client = Starfold(self.url, password=self.password, timeout=timeout)
219
+ return self._client
220
+
221
+ def async_client(self, timeout: float = 30.0) -> AsyncStarfold:
222
+ """A new AsyncStarfold client signed in to this server; close it yourself (`async with`)."""
223
+ return AsyncStarfold(self.url, password=self.password, timeout=timeout)
224
+
225
+ def close(self, timeout: float = 10.0) -> None:
226
+ """Stops the server: SIGTERM (on Windows, terminate), then SIGKILL after `timeout` seconds.
227
+
228
+ On Linux and macOS the guard sends the SIGTERM and reaps the server itself, so no signal
229
+ goes to a pid this process has already reaped.
230
+ """
231
+ if self._client is not None:
232
+ self._client.close()
233
+ self._client = None
234
+ p = self.process
235
+ if p.stdin is not None and not p.stdin.closed:
236
+ p.stdin.close()
237
+ elif p.stdin is None and p.poll() is None:
238
+ p.terminate()
239
+ try:
240
+ p.wait(timeout=timeout)
241
+ except subprocess.TimeoutExpired:
242
+ if sys.platform == "win32":
243
+ p.kill()
244
+ else:
245
+ with contextlib.suppress(ProcessLookupError):
246
+ os.killpg(p.pid, signal.SIGKILL)
247
+ p.wait()
248
+ _live.discard(self)
249
+
250
+ def __enter__(self) -> LocalServer:
251
+ return self
252
+
253
+ def __exit__(self, *_: object) -> None:
254
+ self.close()
255
+
256
+
257
+ class _Output:
258
+ """The server's output, read as it comes so the pipe never fills, its last lines kept."""
259
+
260
+ def __init__(self, stream) -> None:
261
+ self.lines: collections.deque[str] = collections.deque(maxlen=40)
262
+ self._thread = threading.Thread(target=self._read, args=(stream,), daemon=True)
263
+ self._thread.start()
264
+
265
+ def _read(self, stream) -> None:
266
+ for line in iter(stream.readline, b""):
267
+ self.lines.append(line.decode(errors="replace"))
268
+ stream.close()
269
+
270
+ def tail(self, wait: float = 0.0) -> str:
271
+ self._thread.join(wait)
272
+ return "".join(self.lines)
273
+
274
+
275
+ def _spawn(
276
+ path: str, args: list[str], env: dict[str, str], cwd: str | Path | None
277
+ ) -> tuple[subprocess.Popen[bytes], _Output]:
278
+ if sys.platform == "win32":
279
+ p = subprocess.Popen(
280
+ [path, *args],
281
+ env=env,
282
+ cwd=cwd,
283
+ stdin=subprocess.DEVNULL,
284
+ stdout=subprocess.PIPE,
285
+ stderr=subprocess.STDOUT,
286
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
287
+ )
288
+ _kill_on_close(p)
289
+ else:
290
+ p = subprocess.Popen(
291
+ ["/bin/sh", "-c", GUARD, path, *args],
292
+ env=env,
293
+ cwd=cwd,
294
+ stdin=subprocess.PIPE,
295
+ stdout=subprocess.PIPE,
296
+ stderr=subprocess.STDOUT,
297
+ start_new_session=True,
298
+ )
299
+ return p, _Output(p.stdout)
300
+
301
+
302
+ def _kill_on_close(p: subprocess.Popen[bytes]) -> None:
303
+ """Windows: puts the server in a job object that ends with this process."""
304
+ import ctypes
305
+ from ctypes import wintypes
306
+
307
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
308
+
309
+ class Basic(ctypes.Structure):
310
+ _fields_ = [
311
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
312
+ ("PerJobUserTimeLimit", ctypes.c_int64),
313
+ ("LimitFlags", wintypes.DWORD),
314
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
315
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
316
+ ("ActiveProcessLimit", wintypes.DWORD),
317
+ ("Affinity", ctypes.c_size_t),
318
+ ("PriorityClass", wintypes.DWORD),
319
+ ("SchedulingClass", wintypes.DWORD),
320
+ ]
321
+
322
+ class Io(ctypes.Structure):
323
+ _fields_ = [(n, ctypes.c_uint64) for n in ("r", "w", "o", "rb", "wb", "ob")]
324
+
325
+ class Extended(ctypes.Structure):
326
+ _fields_ = [
327
+ ("BasicLimitInformation", Basic),
328
+ ("IoInfo", Io),
329
+ ("ProcessMemoryLimit", ctypes.c_size_t),
330
+ ("JobMemoryLimit", ctypes.c_size_t),
331
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
332
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
333
+ ]
334
+
335
+ k32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR]
336
+ k32.CreateJobObjectW.restype = wintypes.HANDLE
337
+ k32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
338
+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
339
+ k32.OpenProcess.restype = wintypes.HANDLE
340
+ k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
341
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
342
+ job = k32.CreateJobObjectW(None, None)
343
+ info = Extended()
344
+ info.BasicLimitInformation.LimitFlags = 0x2000
345
+ k32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info))
346
+ proc = k32.OpenProcess(0x0100 | 0x0001, False, p.pid)
347
+ k32.AssignProcessToJobObject(job, proc)
348
+ k32.CloseHandle(proc)
349
+ _jobs.append(job)
350
+
351
+
352
+ def start_server(
353
+ *,
354
+ addr: str = "127.0.0.1",
355
+ port: int | None = None,
356
+ password: str | None = None,
357
+ args: Sequence[str] = (),
358
+ env: Mapping[str, str] | None = None,
359
+ cwd: str | Path | None = None,
360
+ timeout: float = 30.0,
361
+ binary: str | None = None,
362
+ ) -> LocalServer:
363
+ """Starts a starfold server on this machine and waits until it answers.
364
+
365
+ It listens on `addr` (loopback unless you pass another address) and `port` (a free one by
366
+ default), with `password` (generated by default, also when empty; the client from `client()`
367
+ holds it). `args` are further server flags (`starfold --help`); `env` is merged onto this
368
+ process's environment for the server; `binary` defaults to `binary_path()`. On Linux it needs
369
+ a display (DISPLAY, e.g. from Xvfb); it doesn't start one. Raises ServerStartError, with the
370
+ server's last output in `output`, if it exits, doesn't answer within `timeout` seconds or
371
+ can't have its port.
372
+ """
373
+ path = binary or binary_path()
374
+ check_libraries(path)
375
+ password = password or secrets.token_urlsafe(24)
376
+ child_env = {**os.environ, **(env or {})}
377
+ child_env["STARFOLD_PASSWORD"] = password
378
+ child_env.pop("SELKIES_BASIC_AUTH_PASSWORD", None)
379
+ deadline = time.monotonic() + timeout
380
+ for attempt in range(3):
381
+ chosen = port if port is not None else _free_port(addr)
382
+ flags = [f"--addr={addr}", f"--port={chosen}", *args]
383
+ p, out = _spawn(path, flags, child_env, cwd)
384
+ server = LocalServer(p, _url(addr, chosen) + _base_path(args), password, out)
385
+ try:
386
+ _wait_ready(server, deadline)
387
+ return server
388
+ except _PortTaken:
389
+ server.close()
390
+ if port is not None or attempt == 2:
391
+ tail = server.stderr_tail
392
+ raise ServerStartError(f"port {chosen} is taken:\n{tail}", tail) from None
393
+ except BaseException:
394
+ server.close()
395
+ raise
396
+ raise AssertionError("unreachable")
397
+
398
+
399
+ class _PortTaken(Exception):
400
+ pass
401
+
402
+
403
+ def _wait_ready(server: LocalServer, deadline: float) -> None:
404
+ with httpx.Client(timeout=1.0, trust_env=False) as http:
405
+ while True:
406
+ if server.process.poll() is not None:
407
+ tail = server._output.tail(wait=2.0)
408
+ if "Address already in use" in tail or "address in use" in tail.lower():
409
+ raise _PortTaken()
410
+ raise ServerStartError(f"the starfold server exited with {server.process.returncode}:\n{tail}", tail)
411
+ try:
412
+ if http.get(f"{server.url}/healthz").status_code == 200:
413
+ return
414
+ except httpx.TransportError:
415
+ pass
416
+ if time.monotonic() > deadline:
417
+ tail = server.stderr_tail
418
+ raise ServerStartError(f"the starfold server didn't answer at {server.url} in time:\n{tail}", tail)
419
+ time.sleep(0.1)
@@ -0,0 +1,146 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import struct
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Iterable
11
+
12
+ from PIL.Image import Image
13
+
14
+
15
+ class StarfoldError(Exception):
16
+ """A request the server refused or could not answer."""
17
+
18
+ def __init__(self, message: str, status: int | None = None) -> None:
19
+ super().__init__(message)
20
+ self.message = message
21
+ self.status = status
22
+
23
+
24
+ class AuthError(StarfoldError):
25
+ """Missing or wrong password (401)."""
26
+
27
+
28
+ class ForbiddenError(StarfoldError):
29
+ """The server refuses this (403), e.g. file transfer is turned off."""
30
+
31
+
32
+ class ReadOnlyError(ForbiddenError):
33
+ """The server runs with --read-only and takes no input."""
34
+
35
+
36
+ class RecordingOffError(ForbiddenError):
37
+ """The server runs without --enable-recording, so it doesn't record."""
38
+
39
+
40
+ class NotFoundError(StarfoldError):
41
+ """No such file, folder or recording (404)."""
42
+
43
+
44
+ class StarfoldTimeoutError(StarfoldError):
45
+ """The server did not answer in time."""
46
+
47
+
48
+ class StarfoldConnectionError(StarfoldError):
49
+ """The server could not be reached."""
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Screenshot:
54
+ png: bytes
55
+ seq: int
56
+ """Pass as `since` to `wait(change=True)` for changes after this screenshot."""
57
+
58
+ @property
59
+ def size(self) -> tuple[int, int]:
60
+ width, height = struct.unpack(">II", self.png[16:24])
61
+ return width, height
62
+
63
+ def save(self, path: str | Path) -> Path:
64
+ path = Path(path)
65
+ path.write_bytes(self.png)
66
+ return path
67
+
68
+ def image(self) -> Image:
69
+ """The screenshot as a Pillow image (needs `pillow` installed)."""
70
+ try:
71
+ from PIL import Image as PILImage
72
+ except ImportError as e:
73
+ raise ImportError("Screenshot.image() needs Pillow: pip install pillow") from e
74
+ return PILImage.open(io.BytesIO(self.png))
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class WaitResult:
79
+ changed: bool
80
+ timed_out: bool
81
+ seq: int
82
+ waited_ms: int
83
+
84
+ @classmethod
85
+ def from_json(cls, d: dict[str, Any]) -> WaitResult:
86
+ return cls(
87
+ changed=bool(d["changed"]),
88
+ timed_out=bool(d["timed_out"]),
89
+ seq=int(d["seq"]),
90
+ waited_ms=int(d["waited_ms"]),
91
+ )
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class InputResult:
96
+ seq: int
97
+ """The screen's change count before the input: `wait(change=True, since=seq)` returns once it changed."""
98
+ events: int
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class Recording:
103
+ """A started recording. `id` is the string the server returned once, to this caller; any
104
+ holder of it can stop the recording and obtain its clip, so treat it like a secret."""
105
+
106
+ id: str
107
+ max_seconds: int
108
+
109
+
110
+ class Segments(list[bytes]):
111
+ """A recording's MP4s, in order: one, unless another encoder took over mid-recording."""
112
+
113
+ def __init__(self, parts: Iterable[bytes], end_reason: str | None = None) -> None:
114
+ super().__init__(parts)
115
+ self.end_reason = end_reason
116
+ """Why it ended: stopped, time_limit, resized, segment_cap, bad_parameter_sets, segment_lost or closed."""
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class FileEntry:
121
+ name: str
122
+ dir: bool
123
+ size: int
124
+ mtime_ms: int
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class FileList:
129
+ path: str
130
+ entries: list[FileEntry]
131
+
132
+ @classmethod
133
+ def from_json(cls, d: dict[str, Any]) -> FileList:
134
+ return cls(
135
+ path=d["path"],
136
+ entries=[
137
+ FileEntry(name=e["name"], dir=bool(e["dir"]), size=int(e["size"]), mtime_ms=int(e["mtime"]))
138
+ for e in d["entries"]
139
+ ],
140
+ )
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Upload:
145
+ path: str
146
+ size: int
@@ -0,0 +1,69 @@
1
+ """Builders for `Starfold.actions()`: each returns one action of `POST /input`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ Action = dict[str, Any]
8
+ Button = str | int
9
+
10
+
11
+ def _at(action: Action, x: int | None, y: int | None) -> Action:
12
+ if (x is None) != (y is None):
13
+ raise ValueError("give both x and y, or neither")
14
+ if x is not None:
15
+ action.update(x=x, y=y)
16
+ return action
17
+
18
+
19
+ def move(x: int, y: int) -> Action:
20
+ return {"type": "move", "x": x, "y": y}
21
+
22
+
23
+ def click(x: int | None = None, y: int | None = None, button: Button = "left", count: int = 1) -> Action:
24
+ return _at({"type": "click", "button": button, "count": count}, x, y)
25
+
26
+
27
+ def down(x: int | None = None, y: int | None = None, button: Button = "left") -> Action:
28
+ return _at({"type": "down", "button": button}, x, y)
29
+
30
+
31
+ def up(x: int | None = None, y: int | None = None, button: Button = "left") -> Action:
32
+ return _at({"type": "up", "button": button}, x, y)
33
+
34
+
35
+ def scroll(dx: int = 0, dy: int = 0, x: int | None = None, y: int | None = None) -> Action:
36
+ """Wheel notches: positive `dy` scrolls down, positive `dx` right."""
37
+ return _at({"type": "scroll", "dx": dx, "dy": dy}, x, y)
38
+
39
+
40
+ def key(combo: str) -> Action:
41
+ """Press and release keys together: "Enter", "ctrl+c", "ctrl+shift+t", "alt+F4"."""
42
+ return {"type": "key", "key": combo}
43
+
44
+
45
+ def key_down(combo: str) -> Action:
46
+ return {"type": "key_down", "key": combo}
47
+
48
+
49
+ def key_up(combo: str) -> Action:
50
+ return {"type": "key_up", "key": combo}
51
+
52
+
53
+ def type_text(text: str) -> Action:
54
+ return {"type": "type", "text": text}
55
+
56
+
57
+ def pause(ms: int) -> Action:
58
+ return {"type": "pause", "ms": ms}
59
+
60
+
61
+ def drag(
62
+ x1: int, y1: int, x2: int, y2: int, button: Button = "left", steps: int = 10, step_ms: int = 10
63
+ ) -> list[Action]:
64
+ """Press at (x1, y1), move to (x2, y2) in `steps` moves `step_ms` apart, release."""
65
+ steps = max(1, steps)
66
+ path: list[Action] = [down(x1, y1, button)]
67
+ for i in range(1, steps + 1):
68
+ path += [pause(step_ms), move(x1 + (x2 - x1) * i // steps, y1 + (y2 - y1) * i // steps)]
69
+ return [*path, up(button=button)]
File without changes