starfold 0.3.2__py3-none-win_amd64.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.
Files changed (42) hide show
  1. starfold/__init__.py +60 -0
  2. starfold/_bin/starfold.exe +0 -0
  3. starfold/_bin/starfold.exe.sha256 +1 -0
  4. starfold/_client.py +417 -0
  5. starfold/_native.py +419 -0
  6. starfold/_types.py +146 -0
  7. starfold/act.py +69 -0
  8. starfold/py.typed +0 -0
  9. starfold-0.3.2.dist-info/METADATA +134 -0
  10. starfold-0.3.2.dist-info/RECORD +42 -0
  11. starfold-0.3.2.dist-info/WHEEL +4 -0
  12. starfold-0.3.2.dist-info/entry_points.txt +3 -0
  13. starfold-0.3.2.dist-info/licenses/LICENSE +22 -0
  14. starfold-0.3.2.dist-info/licenses/THIRD_PARTY.md +93 -0
  15. starfold-0.3.2.dist-info/licenses/licenses/COPYING-dav1d +23 -0
  16. starfold-0.3.2.dist-info/licenses/licenses/COPYING-wasi-libc +267 -0
  17. starfold-0.3.2.dist-info/licenses/licenses/GCC-runtime-copyright.txt +1714 -0
  18. starfold-0.3.2.dist-info/licenses/licenses/GPL-3.0.txt +674 -0
  19. starfold-0.3.2.dist-info/licenses/licenses/MinGW-w64-copyright.txt +998 -0
  20. starfold-0.3.2.dist-info/licenses/licenses/Opus-COPYING.txt +44 -0
  21. starfold-0.3.2.dist-info/licenses/licenses/inter-LICENSE.txt +93 -0
  22. starfold-0.3.2.dist-info/licenses/licenses/libaom-LICENSE-fastfeat.txt +30 -0
  23. starfold-0.3.2.dist-info/licenses/licenses/libaom-LICENSE-vector.txt +19 -0
  24. starfold-0.3.2.dist-info/licenses/licenses/libaom-LICENSE-x86inc.txt +18 -0
  25. starfold-0.3.2.dist-info/licenses/licenses/libaom-LICENSE.txt +27 -0
  26. starfold-0.3.2.dist-info/licenses/licenses/libaom-PATENTS.txt +107 -0
  27. starfold-0.3.2.dist-info/licenses/licenses/libvpl-LICENSE.txt +21 -0
  28. starfold-0.3.2.dist-info/licenses/licenses/libyuv-LICENSE.txt +29 -0
  29. starfold-0.3.2.dist-info/licenses/licenses/rust-crates.txt +2500 -0
  30. starfold-0.3.2.dist-info/licenses/licenses/rust-std/Apache-2.0.txt +73 -0
  31. starfold-0.3.2.dist-info/licenses/licenses/rust-std/BSD-2-Clause.txt +9 -0
  32. starfold-0.3.2.dist-info/licenses/licenses/rust-std/CC-BY-SA-4.0.txt +427 -0
  33. starfold-0.3.2.dist-info/licenses/licenses/rust-std/COPYRIGHT-library.html +8266 -0
  34. starfold-0.3.2.dist-info/licenses/licenses/rust-std/GCC-exception-3.1.txt +30 -0
  35. starfold-0.3.2.dist-info/licenses/licenses/rust-std/GPL-2.0-only.txt +133 -0
  36. starfold-0.3.2.dist-info/licenses/licenses/rust-std/GPL-3.0-or-later.txt +202 -0
  37. starfold-0.3.2.dist-info/licenses/licenses/rust-std/ISC.txt +7 -0
  38. starfold-0.3.2.dist-info/licenses/licenses/rust-std/LLVM-exception.txt +15 -0
  39. starfold-0.3.2.dist-info/licenses/licenses/rust-std/MIT.txt +9 -0
  40. starfold-0.3.2.dist-info/licenses/licenses/rust-std/NCSA.txt +29 -0
  41. starfold-0.3.2.dist-info/licenses/licenses/rust-std/OFL-1.1.txt +43 -0
  42. starfold-0.3.2.dist-info/licenses/licenses/rust-std/Unicode-3.0.txt +39 -0
starfold/__init__.py ADDED
@@ -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
+ ]
Binary file
@@ -0,0 +1 @@
1
+ f54452704f898267ffbcc21608a4831541e9d9f40c8c3c7212a6024b5a0c144d starfold.exe
starfold/_client.py ADDED
@@ -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))