raytrace-sdk 0.1.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.
- raytrace_sdk-0.1.0/LICENSE +21 -0
- raytrace_sdk-0.1.0/PKG-INFO +88 -0
- raytrace_sdk-0.1.0/README.md +71 -0
- raytrace_sdk-0.1.0/pyproject.toml +26 -0
- raytrace_sdk-0.1.0/raytrace_sdk/__init__.py +4 -0
- raytrace_sdk-0.1.0/raytrace_sdk/client.py +296 -0
- raytrace_sdk-0.1.0/raytrace_sdk.egg-info/PKG-INFO +88 -0
- raytrace_sdk-0.1.0/raytrace_sdk.egg-info/SOURCES.txt +10 -0
- raytrace_sdk-0.1.0/raytrace_sdk.egg-info/dependency_links.txt +1 -0
- raytrace_sdk-0.1.0/raytrace_sdk.egg-info/top_level.txt +1 -0
- raytrace_sdk-0.1.0/setup.cfg +4 -0
- raytrace_sdk-0.1.0/tests/test_sdk.py +76 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RayTrace contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: raytrace-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for RayTrace cloud sandboxes: create, run commands, stop, start and destroy over the /v1 API
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://raytracer.si
|
|
7
|
+
Project-URL: Source, https://github.com/Godcreatebugs/raytrace-cli/tree/main/sdk/python
|
|
8
|
+
Project-URL: Issues, https://github.com/Godcreatebugs/raytrace-cli/issues
|
|
9
|
+
Keywords: raytrace,sandbox,coding-agents,sdk
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# raytrace-sdk
|
|
19
|
+
|
|
20
|
+
Create and drive [RayTrace](https://raytracer.si) cloud sandboxes from Python. Every coding-agent session in a sandbox is recorded to your organization's dashboard.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install raytrace-sdk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Python 3.10 or newer. No dependencies.
|
|
27
|
+
|
|
28
|
+
## Authenticate
|
|
29
|
+
|
|
30
|
+
Create an org API key on your RayTrace account page (**Account → API keys**) and set it in the environment:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
export RAYTRACE_API_KEY=rtk_...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Or pass it directly: `RayTrace(api_key="rtk_...")`.
|
|
37
|
+
|
|
38
|
+
## Quickstart
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from raytrace_sdk import RayTrace
|
|
42
|
+
|
|
43
|
+
rt = RayTrace()
|
|
44
|
+
|
|
45
|
+
# Upload a project folder (.git, .env, keys and credentials are left out).
|
|
46
|
+
sandbox = rt.sandboxes.create(name="my-app", directory=".", size="small")
|
|
47
|
+
|
|
48
|
+
result = sandbox.exec("pytest", timeout_seconds=300)
|
|
49
|
+
print(result.exit_code, result.stdout)
|
|
50
|
+
|
|
51
|
+
sandbox.stop()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Sandboxes
|
|
55
|
+
|
|
56
|
+
| Call | What it does |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `rt.sandboxes.create(name=, size=, directory= \| files= \| archive=)` | New sandbox from a folder, an in-memory file map, or `.tar.gz` bytes |
|
|
59
|
+
| `rt.sandboxes.list()` / `rt.sandboxes.get(id)` | Your organization's sandboxes |
|
|
60
|
+
| `sandbox.exec(command, timeout_seconds=)` | Runs a command and waits for the result (`exit_code`, `stdout`, `stderr`, `state`) |
|
|
61
|
+
| `sandbox.stop()` | Stops it; files are kept and billing stops |
|
|
62
|
+
| `sandbox.start(size=)` | Starts it again, restoring an archived sandbox first |
|
|
63
|
+
| `sandbox.keep_alive(minutes)` | Holds off the idle stop for a long-running job (up to 4 hours) |
|
|
64
|
+
| `sandbox.destroy(keep_traces=)` | Deletes it; `keep_traces=True` keeps its recordings on paid plans |
|
|
65
|
+
| `sandbox.status`, `sandbox.size` | From the last fetch |
|
|
66
|
+
|
|
67
|
+
Sizes are `small`, `medium` and `large`.
|
|
68
|
+
|
|
69
|
+
## Usage and keys
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
rt.usage.get(days=30) # credits spent and remaining
|
|
73
|
+
rt.api_keys.create("ci") # the key is returned once
|
|
74
|
+
rt.api_keys.list()
|
|
75
|
+
rt.api_keys.revoke(key_id)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Billing and errors
|
|
79
|
+
|
|
80
|
+
Running sandboxes are paid from prepaid credits in 15-minute blocks, and stop by themselves after 15 minutes of no activity. Failed calls raise `RayTraceError` with `status` and `code`:
|
|
81
|
+
|
|
82
|
+
| `code` | Meaning |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `insufficient_balance` | Not enough credit for the next 15 minutes; top up on the account page |
|
|
85
|
+
| `recording_plan_required` | Cloud sandboxes need an Individual or Team plan |
|
|
86
|
+
| `no_capacity` | No room right now; retry shortly |
|
|
87
|
+
|
|
88
|
+
The full HTTP contract is in [`docs/v1-contract.md`](https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/v1-contract.md).
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# raytrace-sdk
|
|
2
|
+
|
|
3
|
+
Create and drive [RayTrace](https://raytracer.si) cloud sandboxes from Python. Every coding-agent session in a sandbox is recorded to your organization's dashboard.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install raytrace-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Python 3.10 or newer. No dependencies.
|
|
10
|
+
|
|
11
|
+
## Authenticate
|
|
12
|
+
|
|
13
|
+
Create an org API key on your RayTrace account page (**Account → API keys**) and set it in the environment:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
export RAYTRACE_API_KEY=rtk_...
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Or pass it directly: `RayTrace(api_key="rtk_...")`.
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from raytrace_sdk import RayTrace
|
|
25
|
+
|
|
26
|
+
rt = RayTrace()
|
|
27
|
+
|
|
28
|
+
# Upload a project folder (.git, .env, keys and credentials are left out).
|
|
29
|
+
sandbox = rt.sandboxes.create(name="my-app", directory=".", size="small")
|
|
30
|
+
|
|
31
|
+
result = sandbox.exec("pytest", timeout_seconds=300)
|
|
32
|
+
print(result.exit_code, result.stdout)
|
|
33
|
+
|
|
34
|
+
sandbox.stop()
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Sandboxes
|
|
38
|
+
|
|
39
|
+
| Call | What it does |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `rt.sandboxes.create(name=, size=, directory= \| files= \| archive=)` | New sandbox from a folder, an in-memory file map, or `.tar.gz` bytes |
|
|
42
|
+
| `rt.sandboxes.list()` / `rt.sandboxes.get(id)` | Your organization's sandboxes |
|
|
43
|
+
| `sandbox.exec(command, timeout_seconds=)` | Runs a command and waits for the result (`exit_code`, `stdout`, `stderr`, `state`) |
|
|
44
|
+
| `sandbox.stop()` | Stops it; files are kept and billing stops |
|
|
45
|
+
| `sandbox.start(size=)` | Starts it again, restoring an archived sandbox first |
|
|
46
|
+
| `sandbox.keep_alive(minutes)` | Holds off the idle stop for a long-running job (up to 4 hours) |
|
|
47
|
+
| `sandbox.destroy(keep_traces=)` | Deletes it; `keep_traces=True` keeps its recordings on paid plans |
|
|
48
|
+
| `sandbox.status`, `sandbox.size` | From the last fetch |
|
|
49
|
+
|
|
50
|
+
Sizes are `small`, `medium` and `large`.
|
|
51
|
+
|
|
52
|
+
## Usage and keys
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
rt.usage.get(days=30) # credits spent and remaining
|
|
56
|
+
rt.api_keys.create("ci") # the key is returned once
|
|
57
|
+
rt.api_keys.list()
|
|
58
|
+
rt.api_keys.revoke(key_id)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Billing and errors
|
|
62
|
+
|
|
63
|
+
Running sandboxes are paid from prepaid credits in 15-minute blocks, and stop by themselves after 15 minutes of no activity. Failed calls raise `RayTraceError` with `status` and `code`:
|
|
64
|
+
|
|
65
|
+
| `code` | Meaning |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `insufficient_balance` | Not enough credit for the next 15 minutes; top up on the account page |
|
|
68
|
+
| `recording_plan_required` | Cloud sandboxes need an Individual or Team plan |
|
|
69
|
+
| `no_capacity` | No room right now; retry shortly |
|
|
70
|
+
|
|
71
|
+
The full HTTP contract is in [`docs/v1-contract.md`](https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/v1-contract.md).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "raytrace-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK for RayTrace cloud sandboxes: create, run commands, stop, start and destroy over the /v1 API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["raytrace", "sandbox", "coding-agents", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://raytracer.si"
|
|
22
|
+
Source = "https://github.com/Godcreatebugs/raytrace-cli/tree/main/sdk/python"
|
|
23
|
+
Issues = "https://github.com/Godcreatebugs/raytrace-cli/issues"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
include = ["raytrace_sdk*"]
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"""RayTrace Python SDK over the frozen /v1 API (stdlib only)."""
|
|
2
|
+
from .client import CommandResult, RayTrace, RayTraceError, Sandbox, archive_from_directory, build_tar_gz
|
|
3
|
+
|
|
4
|
+
__all__ = ['RayTrace', 'Sandbox', 'CommandResult', 'RayTraceError', 'archive_from_directory', 'build_tar_gz']
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""Typed stdlib-only Python SDK for RayTrace's frozen /v1 API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import gzip
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import tarfile
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Callable, Mapping
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
import uuid
|
|
18
|
+
|
|
19
|
+
DEFAULT_BASE_URL = 'https://api.raytracer.si'
|
|
20
|
+
TERMINAL_STATES = frozenset({'completed', 'cancelled', 'timed_out', 'interrupted'})
|
|
21
|
+
DEFAULT_EXCLUDED = frozenset({
|
|
22
|
+
'.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config',
|
|
23
|
+
'.claude', '.codex', '.docker', '.kube', '.gnupg', 'node_modules',
|
|
24
|
+
'.venv', '__pycache__', '.next', 'dist', 'coverage', '.DS_Store',
|
|
25
|
+
})
|
|
26
|
+
# Files that usually hold credentials, never uploaded (the same rules as the
|
|
27
|
+
# CLI's `raytrace sandbox create`). Compared in lower case.
|
|
28
|
+
SECRET_NAMES = frozenset({
|
|
29
|
+
'.npmrc', '.netrc', '.pypirc', '.htpasswd', '.dockercfg', 'credentials', 'credentials.json', 'credentials.ini',
|
|
30
|
+
'auth.json', 'service-account.json', 'service_account.json', 'serviceaccountkey.json',
|
|
31
|
+
'client_secret.json', 'client_secrets.json', 'token.json', 'id_rsa', 'id_dsa', 'id_ecdsa',
|
|
32
|
+
'id_ed25519', 'id_ecdsa_sk', 'id_ed25519_sk', 'known_hosts',
|
|
33
|
+
})
|
|
34
|
+
SECRET_EXTENSIONS = ('.pem', '.key', '.p12', '.pfx')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_secret_file(name: str) -> bool:
|
|
38
|
+
lower = name.lower()
|
|
39
|
+
return (lower.startswith('.env') or lower.startswith('.secret')
|
|
40
|
+
or lower.endswith(SECRET_EXTENSIONS) or lower in SECRET_NAMES)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RayTraceError(RuntimeError):
|
|
44
|
+
def __init__(self, message: str, *, status: int = 0, code: str | None = None,
|
|
45
|
+
topup_url: str | None = None, body: Any = None):
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.status = status
|
|
48
|
+
self.code = code
|
|
49
|
+
self.topup_url = topup_url
|
|
50
|
+
self.body = body
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class CommandResult:
|
|
55
|
+
command_id: str
|
|
56
|
+
state: str
|
|
57
|
+
exit_code: int | None
|
|
58
|
+
stdout: str
|
|
59
|
+
stderr: str
|
|
60
|
+
timed_out: bool = False
|
|
61
|
+
output_truncated: bool = False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_tar_gz(files: Mapping[str, str | bytes]) -> bytes:
|
|
65
|
+
"""Packs `{relative_path: content}` into a normalized `.tar.gz` archive."""
|
|
66
|
+
if not files:
|
|
67
|
+
raise ValueError('Archive must contain at least one file')
|
|
68
|
+
buf = io.BytesIO()
|
|
69
|
+
with gzip.GzipFile(fileobj=buf, mode='wb', mtime=0) as gz:
|
|
70
|
+
with tarfile.open(fileobj=gz, mode='w') as tar:
|
|
71
|
+
for raw_path, content in files.items():
|
|
72
|
+
rel = str(raw_path).lstrip('/')
|
|
73
|
+
if not rel or '..' in Path(rel).parts:
|
|
74
|
+
raise ValueError(f'Invalid archive path: {raw_path}')
|
|
75
|
+
data = content.encode('utf-8') if isinstance(content, str) else bytes(content)
|
|
76
|
+
info = tarfile.TarInfo(rel)
|
|
77
|
+
info.size = len(data)
|
|
78
|
+
info.mode = 0o644
|
|
79
|
+
info.uid = 1000
|
|
80
|
+
info.gid = 1000
|
|
81
|
+
tar.addfile(info, io.BytesIO(data))
|
|
82
|
+
return buf.getvalue()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def archive_from_directory(directory: str | os.PathLike[str]) -> bytes:
|
|
86
|
+
root = Path(directory).resolve()
|
|
87
|
+
files: dict[str, bytes] = {}
|
|
88
|
+
for path in sorted(root.rglob('*')):
|
|
89
|
+
rel = path.relative_to(root)
|
|
90
|
+
if (any(part in DEFAULT_EXCLUDED for part in rel.parts) or path.is_symlink() or not path.is_file()
|
|
91
|
+
or is_secret_file(path.name)):
|
|
92
|
+
continue
|
|
93
|
+
if path.stat().st_size <= 25 * 1024 * 1024:
|
|
94
|
+
files[rel.as_posix()] = path.read_bytes()
|
|
95
|
+
return build_tar_gz(files)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _Transport:
|
|
99
|
+
def __init__(self, api_key: str, base_url: str, transport: Callable[..., tuple[int, Any]] | None = None):
|
|
100
|
+
self.api_key = api_key
|
|
101
|
+
self.base_url = base_url.rstrip('/')
|
|
102
|
+
self._custom = transport
|
|
103
|
+
|
|
104
|
+
def request(self, method: str, path: str, *, headers: dict[str, str] | None = None,
|
|
105
|
+
body: Any = None, timeout: float = 120.0) -> tuple[int, Any]:
|
|
106
|
+
req_headers = {'Authorization': f'Bearer {self.api_key}', 'User-Agent': 'raytrace-python-sdk/0.1.0',
|
|
107
|
+
**(headers or {})}
|
|
108
|
+
raw_body: bytes | None
|
|
109
|
+
if body is None:
|
|
110
|
+
raw_body = None
|
|
111
|
+
elif isinstance(body, (bytes, bytearray)):
|
|
112
|
+
raw_body = bytes(body)
|
|
113
|
+
else:
|
|
114
|
+
req_headers.setdefault('Content-Type', 'application/json')
|
|
115
|
+
raw_body = json.dumps(body).encode('utf-8')
|
|
116
|
+
url = f'{self.base_url}{path if path.startswith("/") else "/" + path}'
|
|
117
|
+
if self._custom is not None:
|
|
118
|
+
status, data = self._custom(method, url, req_headers, raw_body)
|
|
119
|
+
else:
|
|
120
|
+
req = urllib.request.Request(url, method=method, data=raw_body, headers=req_headers)
|
|
121
|
+
try:
|
|
122
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
123
|
+
status = resp.status
|
|
124
|
+
raw = resp.read()
|
|
125
|
+
data = json.loads(raw) if raw else None
|
|
126
|
+
except urllib.error.HTTPError as err:
|
|
127
|
+
status = err.code
|
|
128
|
+
raw = err.read()
|
|
129
|
+
try:
|
|
130
|
+
data = json.loads(raw) if raw else {'error': str(err)}
|
|
131
|
+
except ValueError:
|
|
132
|
+
data = {'error': raw.decode('utf-8', 'replace') or str(err)}
|
|
133
|
+
if not 200 <= status < 300:
|
|
134
|
+
msg = data.get('error') if isinstance(data, dict) else f'RayTrace API error (HTTP {status})'
|
|
135
|
+
raise RayTraceError(
|
|
136
|
+
msg or f'HTTP {status}',
|
|
137
|
+
status=status,
|
|
138
|
+
code=data.get('code') if isinstance(data, dict) else None,
|
|
139
|
+
topup_url=data.get('topup_url') if isinstance(data, dict) else None,
|
|
140
|
+
body=data,
|
|
141
|
+
)
|
|
142
|
+
return status, data
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Sandbox:
|
|
146
|
+
def __init__(self, transport: _Transport, info: dict[str, Any]):
|
|
147
|
+
self._t = transport
|
|
148
|
+
self.id: str = info['id']
|
|
149
|
+
self.info: dict[str, Any] = dict(info)
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def status(self) -> str:
|
|
153
|
+
return str(self.info.get('status') or '')
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def size(self) -> str:
|
|
157
|
+
return str(self.info.get('size') or 'small')
|
|
158
|
+
|
|
159
|
+
def exec(self, command: str, *, timeout_seconds: int = 120, poll_interval: float = 0.25,
|
|
160
|
+
request_id: str | None = None) -> CommandResult:
|
|
161
|
+
req_id = request_id or f'req_{uuid.uuid4().hex[:24]}'
|
|
162
|
+
_, job = self._t.request(
|
|
163
|
+
'POST', f'/v1/sandboxes/{urllib.parse.quote(self.id)}/commands',
|
|
164
|
+
body={'command': command, 'timeout_seconds': timeout_seconds, 'request_id': req_id},
|
|
165
|
+
)
|
|
166
|
+
while job.get('state') not in TERMINAL_STATES:
|
|
167
|
+
time.sleep(poll_interval)
|
|
168
|
+
_, job = self._t.request(
|
|
169
|
+
'GET',
|
|
170
|
+
f'/v1/sandboxes/{urllib.parse.quote(self.id)}/commands/{urllib.parse.quote(job["command_id"])}',
|
|
171
|
+
)
|
|
172
|
+
return CommandResult(
|
|
173
|
+
command_id=job['command_id'],
|
|
174
|
+
state=job['state'],
|
|
175
|
+
exit_code=job.get('exit_code'),
|
|
176
|
+
stdout=job.get('stdout') or '',
|
|
177
|
+
stderr=job.get('stderr') or '',
|
|
178
|
+
timed_out=bool(job.get('timed_out')),
|
|
179
|
+
output_truncated=bool(job.get('output_truncated')),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def start(self, *, size: str | None = None, wait_for_restore: bool = True,
|
|
183
|
+
poll_interval: float = 0.5) -> dict[str, Any]:
|
|
184
|
+
body = {'size': size} if size else {}
|
|
185
|
+
status, data = self._t.request('POST', f'/v1/sandboxes/{urllib.parse.quote(self.id)}/start', body=body)
|
|
186
|
+
if isinstance(data, dict):
|
|
187
|
+
self.info.update(data)
|
|
188
|
+
if status == 202 and isinstance(data, dict) and data.get('restoring') and wait_for_restore:
|
|
189
|
+
while True:
|
|
190
|
+
time.sleep(poll_interval)
|
|
191
|
+
_, items = self._t.request('GET', '/v1/sandboxes')
|
|
192
|
+
current = next((x for x in (items or []) if x.get('id') == self.id), None)
|
|
193
|
+
if not current:
|
|
194
|
+
break
|
|
195
|
+
self.info = current
|
|
196
|
+
if current.get('restore_error'):
|
|
197
|
+
raise RayTraceError(f"Archive restore failed: {current['restore_error']}", status=500, body=current)
|
|
198
|
+
if current.get('status') in ('running', 'archived'):
|
|
199
|
+
break
|
|
200
|
+
return self.info
|
|
201
|
+
|
|
202
|
+
def stop(self) -> dict[str, Any]:
|
|
203
|
+
_, data = self._t.request('POST', f'/v1/sandboxes/{urllib.parse.quote(self.id)}/stop')
|
|
204
|
+
if isinstance(data, dict):
|
|
205
|
+
self.info.update(data)
|
|
206
|
+
return self.info
|
|
207
|
+
|
|
208
|
+
def keep_alive(self, minutes: int | float) -> dict[str, Any]:
|
|
209
|
+
_, data = self._t.request('POST', f'/v1/sandboxes/{urllib.parse.quote(self.id)}/keep-alive',
|
|
210
|
+
body={'minutes': minutes})
|
|
211
|
+
return data
|
|
212
|
+
|
|
213
|
+
def destroy(self, *, keep_traces: bool = False) -> dict[str, Any]:
|
|
214
|
+
qs = '?keep_traces=1' if keep_traces else ''
|
|
215
|
+
_, data = self._t.request('DELETE', f'/v1/sandboxes/{urllib.parse.quote(self.id)}{qs}')
|
|
216
|
+
self.info['status'] = 'deleted'
|
|
217
|
+
return data
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class _SandboxesResource:
|
|
221
|
+
def __init__(self, transport: _Transport):
|
|
222
|
+
self._t = transport
|
|
223
|
+
|
|
224
|
+
def list(self) -> list[Sandbox]:
|
|
225
|
+
_, items = self._t.request('GET', '/v1/sandboxes')
|
|
226
|
+
return [Sandbox(self._t, item) for item in (items or [])]
|
|
227
|
+
|
|
228
|
+
def get(self, sandbox_id: str) -> Sandbox:
|
|
229
|
+
for sb in self.list():
|
|
230
|
+
if sb.id == sandbox_id:
|
|
231
|
+
return sb
|
|
232
|
+
raise RayTraceError(f'Sandbox not found: {sandbox_id}', status=404)
|
|
233
|
+
|
|
234
|
+
def create(self, *, name: str | None = None, size: str = 'small', archive: bytes | None = None,
|
|
235
|
+
files: Mapping[str, str | bytes] | None = None, directory: str | os.PathLike[str] | None = None,
|
|
236
|
+
repo: str | None = None, idempotency_key: str | None = None) -> Sandbox:
|
|
237
|
+
payload = archive
|
|
238
|
+
if payload is None:
|
|
239
|
+
if files is not None:
|
|
240
|
+
payload = build_tar_gz(files)
|
|
241
|
+
elif directory is not None:
|
|
242
|
+
payload = archive_from_directory(directory)
|
|
243
|
+
elif repo is not None:
|
|
244
|
+
payload = build_tar_gz({'README.md': f'# {repo}\n'})
|
|
245
|
+
else:
|
|
246
|
+
raise ValueError('Provide one of archive, files, directory, or repo')
|
|
247
|
+
derived = name or (repo.rstrip('/').split('/')[-1] if repo else 'sandbox')
|
|
248
|
+
clean_name = re.sub(r'[^A-Za-z0-9._ -]', '-', derived)[:100] or 'sandbox'
|
|
249
|
+
headers = {
|
|
250
|
+
'Content-Type': 'application/gzip',
|
|
251
|
+
'X-RayTrace-Name': clean_name,
|
|
252
|
+
'X-RayTrace-Size': size,
|
|
253
|
+
}
|
|
254
|
+
if idempotency_key:
|
|
255
|
+
headers['Idempotency-Key'] = idempotency_key
|
|
256
|
+
_, data = self._t.request('POST', '/v1/sandboxes', headers=headers, body=payload)
|
|
257
|
+
return Sandbox(self._t, data)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class _UsageResource:
|
|
261
|
+
def __init__(self, transport: _Transport):
|
|
262
|
+
self._t = transport
|
|
263
|
+
|
|
264
|
+
def get(self, *, days: int = 30) -> dict[str, Any]:
|
|
265
|
+
_, data = self._t.request('GET', f'/v1/usage?days={int(days)}')
|
|
266
|
+
return data
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class _ApiKeysResource:
|
|
270
|
+
def __init__(self, transport: _Transport):
|
|
271
|
+
self._t = transport
|
|
272
|
+
|
|
273
|
+
def create(self, name: str) -> dict[str, Any]:
|
|
274
|
+
_, data = self._t.request('POST', '/v1/api-keys', body={'name': name})
|
|
275
|
+
return data
|
|
276
|
+
|
|
277
|
+
def list(self) -> list[dict[str, Any]]:
|
|
278
|
+
_, data = self._t.request('GET', '/v1/api-keys')
|
|
279
|
+
return (data or {}).get('keys', [])
|
|
280
|
+
|
|
281
|
+
def revoke(self, key_id: str) -> dict[str, Any]:
|
|
282
|
+
_, data = self._t.request('DELETE', f'/v1/api-keys/{urllib.parse.quote(key_id)}')
|
|
283
|
+
return data
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class RayTrace:
|
|
287
|
+
def __init__(self, api_key: str | None = None, base_url: str | None = None,
|
|
288
|
+
transport: Callable[..., tuple[int, Any]] | None = None):
|
|
289
|
+
key = api_key or os.environ.get('RAYTRACE_API_KEY')
|
|
290
|
+
if not key:
|
|
291
|
+
raise ValueError('RayTrace API key is required (pass api_key= or set RAYTRACE_API_KEY)')
|
|
292
|
+
url = base_url or os.environ.get('RAYTRACE_API_URL') or DEFAULT_BASE_URL
|
|
293
|
+
self._t = _Transport(key, url, transport=transport)
|
|
294
|
+
self.sandboxes = _SandboxesResource(self._t)
|
|
295
|
+
self.usage = _UsageResource(self._t)
|
|
296
|
+
self.api_keys = _ApiKeysResource(self._t)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: raytrace-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for RayTrace cloud sandboxes: create, run commands, stop, start and destroy over the /v1 API
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://raytracer.si
|
|
7
|
+
Project-URL: Source, https://github.com/Godcreatebugs/raytrace-cli/tree/main/sdk/python
|
|
8
|
+
Project-URL: Issues, https://github.com/Godcreatebugs/raytrace-cli/issues
|
|
9
|
+
Keywords: raytrace,sandbox,coding-agents,sdk
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# raytrace-sdk
|
|
19
|
+
|
|
20
|
+
Create and drive [RayTrace](https://raytracer.si) cloud sandboxes from Python. Every coding-agent session in a sandbox is recorded to your organization's dashboard.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install raytrace-sdk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Python 3.10 or newer. No dependencies.
|
|
27
|
+
|
|
28
|
+
## Authenticate
|
|
29
|
+
|
|
30
|
+
Create an org API key on your RayTrace account page (**Account → API keys**) and set it in the environment:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
export RAYTRACE_API_KEY=rtk_...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Or pass it directly: `RayTrace(api_key="rtk_...")`.
|
|
37
|
+
|
|
38
|
+
## Quickstart
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from raytrace_sdk import RayTrace
|
|
42
|
+
|
|
43
|
+
rt = RayTrace()
|
|
44
|
+
|
|
45
|
+
# Upload a project folder (.git, .env, keys and credentials are left out).
|
|
46
|
+
sandbox = rt.sandboxes.create(name="my-app", directory=".", size="small")
|
|
47
|
+
|
|
48
|
+
result = sandbox.exec("pytest", timeout_seconds=300)
|
|
49
|
+
print(result.exit_code, result.stdout)
|
|
50
|
+
|
|
51
|
+
sandbox.stop()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Sandboxes
|
|
55
|
+
|
|
56
|
+
| Call | What it does |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `rt.sandboxes.create(name=, size=, directory= \| files= \| archive=)` | New sandbox from a folder, an in-memory file map, or `.tar.gz` bytes |
|
|
59
|
+
| `rt.sandboxes.list()` / `rt.sandboxes.get(id)` | Your organization's sandboxes |
|
|
60
|
+
| `sandbox.exec(command, timeout_seconds=)` | Runs a command and waits for the result (`exit_code`, `stdout`, `stderr`, `state`) |
|
|
61
|
+
| `sandbox.stop()` | Stops it; files are kept and billing stops |
|
|
62
|
+
| `sandbox.start(size=)` | Starts it again, restoring an archived sandbox first |
|
|
63
|
+
| `sandbox.keep_alive(minutes)` | Holds off the idle stop for a long-running job (up to 4 hours) |
|
|
64
|
+
| `sandbox.destroy(keep_traces=)` | Deletes it; `keep_traces=True` keeps its recordings on paid plans |
|
|
65
|
+
| `sandbox.status`, `sandbox.size` | From the last fetch |
|
|
66
|
+
|
|
67
|
+
Sizes are `small`, `medium` and `large`.
|
|
68
|
+
|
|
69
|
+
## Usage and keys
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
rt.usage.get(days=30) # credits spent and remaining
|
|
73
|
+
rt.api_keys.create("ci") # the key is returned once
|
|
74
|
+
rt.api_keys.list()
|
|
75
|
+
rt.api_keys.revoke(key_id)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Billing and errors
|
|
79
|
+
|
|
80
|
+
Running sandboxes are paid from prepaid credits in 15-minute blocks, and stop by themselves after 15 minutes of no activity. Failed calls raise `RayTraceError` with `status` and `code`:
|
|
81
|
+
|
|
82
|
+
| `code` | Meaning |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `insufficient_balance` | Not enough credit for the next 15 minutes; top up on the account page |
|
|
85
|
+
| `recording_plan_required` | Cloud sandboxes need an Individual or Team plan |
|
|
86
|
+
| `no_capacity` | No room right now; retry shortly |
|
|
87
|
+
|
|
88
|
+
The full HTTP contract is in [`docs/v1-contract.md`](https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/v1-contract.md).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
raytrace_sdk/__init__.py
|
|
5
|
+
raytrace_sdk/client.py
|
|
6
|
+
raytrace_sdk.egg-info/PKG-INFO
|
|
7
|
+
raytrace_sdk.egg-info/SOURCES.txt
|
|
8
|
+
raytrace_sdk.egg-info/dependency_links.txt
|
|
9
|
+
raytrace_sdk.egg-info/top_level.txt
|
|
10
|
+
tests/test_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
raytrace_sdk
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Unit tests for the Python `raytrace_sdk` SDK."""
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from raytrace_sdk import CommandResult, RayTrace, RayTraceError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PythonSdkTests(unittest.TestCase):
|
|
8
|
+
def test_sandbox_lifecycle_exec_and_usage(self):
|
|
9
|
+
sid = 'rtp-' + 'b' * 32
|
|
10
|
+
polls = {'cmd': 0, 'restore': 0}
|
|
11
|
+
seen = []
|
|
12
|
+
|
|
13
|
+
def transport(method, url, headers, body):
|
|
14
|
+
seen.append((method, url, headers, body))
|
|
15
|
+
if method == 'POST' and url.endswith('/v1/sandboxes'):
|
|
16
|
+
return 201, {'id': sid, 'name': 'app', 'size': 'small', 'status': 'running'}
|
|
17
|
+
if method == 'POST' and url.endswith(f'/v1/sandboxes/{sid}/commands'):
|
|
18
|
+
return 202, {'command_id': 'cmd-1', 'state': 'queued'}
|
|
19
|
+
if method == 'GET' and url.endswith(f'/v1/sandboxes/{sid}/commands/cmd-1'):
|
|
20
|
+
polls['cmd'] += 1
|
|
21
|
+
if polls['cmd'] == 1:
|
|
22
|
+
return 200, {'command_id': 'cmd-1', 'state': 'running'}
|
|
23
|
+
return 200, {'command_id': 'cmd-1', 'state': 'completed', 'exit_code': 0, 'stdout': 'passed\n', 'stderr': ''}
|
|
24
|
+
if method == 'POST' and url.endswith(f'/v1/sandboxes/{sid}/stop'):
|
|
25
|
+
return 200, {'id': sid, 'status': 'exited'}
|
|
26
|
+
if method == 'POST' and url.endswith(f'/v1/sandboxes/{sid}/start'):
|
|
27
|
+
return 202, {'id': sid, 'status': 'starting', 'restoring': True, 'size': 'small'}
|
|
28
|
+
if method == 'GET' and url.endswith('/v1/sandboxes'):
|
|
29
|
+
polls['restore'] += 1
|
|
30
|
+
return 200, [{'id': sid, 'name': 'app', 'size': 'small',
|
|
31
|
+
'status': 'starting' if polls['restore'] == 1 else 'running'}]
|
|
32
|
+
if method == 'POST' and url.endswith(f'/v1/sandboxes/{sid}/keep-alive'):
|
|
33
|
+
return 200, {'sandbox_id': sid, 'keep_alive_until': 9999}
|
|
34
|
+
if method == 'DELETE' and url.endswith(f'/v1/sandboxes/{sid}?keep_traces=1'):
|
|
35
|
+
return 200, {'id': sid, 'status': 'deleted'}
|
|
36
|
+
if method == 'GET' and url.endswith('/v1/usage?days=30'):
|
|
37
|
+
return 200, {'days': 30, 'blocks_this_month': 3, 'wallet': {'balance_usd': 9.97}}
|
|
38
|
+
return 404, {'error': f'unexpected {method} {url}'}
|
|
39
|
+
|
|
40
|
+
rt = RayTrace(api_key='rtk_test', base_url='https://api.example.test', transport=transport)
|
|
41
|
+
sb = rt.sandboxes.create(size='small', files={'main.py': 'print(1)\n'})
|
|
42
|
+
self.assertEqual(sb.id, sid)
|
|
43
|
+
self.assertEqual(seen[0][2]['X-RayTrace-Size'], 'small')
|
|
44
|
+
|
|
45
|
+
res = sb.exec('pytest', poll_interval=0)
|
|
46
|
+
self.assertIsInstance(res, CommandResult)
|
|
47
|
+
self.assertEqual(res.exit_code, 0)
|
|
48
|
+
self.assertEqual(res.stdout, 'passed\n')
|
|
49
|
+
|
|
50
|
+
sb.stop()
|
|
51
|
+
self.assertEqual(sb.status, 'exited')
|
|
52
|
+
|
|
53
|
+
sb.start(poll_interval=0)
|
|
54
|
+
self.assertEqual(sb.status, 'running')
|
|
55
|
+
self.assertEqual(polls['restore'], 2)
|
|
56
|
+
|
|
57
|
+
self.assertEqual(sb.keep_alive(30)['keep_alive_until'], 9999)
|
|
58
|
+
sb.destroy(keep_traces=True)
|
|
59
|
+
self.assertEqual(sb.status, 'deleted')
|
|
60
|
+
self.assertEqual(rt.usage.get()['blocks_this_month'], 3)
|
|
61
|
+
|
|
62
|
+
def test_error_surfaces_code_and_topup_url(self):
|
|
63
|
+
def transport(_m, _u, _h, _b):
|
|
64
|
+
return 402, {'error': 'Insufficient credit', 'code': 'insufficient_balance',
|
|
65
|
+
'topup_url': 'https://raytracer.si/account.html'}
|
|
66
|
+
|
|
67
|
+
rt = RayTrace(api_key='rtk_test', transport=transport)
|
|
68
|
+
with self.assertRaises(RayTraceError) as ctx:
|
|
69
|
+
rt.sandboxes.create(size='small', repo='github.com/acme/app')
|
|
70
|
+
self.assertEqual(ctx.exception.status, 402)
|
|
71
|
+
self.assertEqual(ctx.exception.code, 'insufficient_balance')
|
|
72
|
+
self.assertEqual(ctx.exception.topup_url, 'https://raytracer.si/account.html')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == '__main__':
|
|
76
|
+
unittest.main()
|