computesdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
computesdk/__init__.py ADDED
@@ -0,0 +1,218 @@
1
+ """
2
+ ComputeSDK - A unified SDK for running code in remote sandboxes.
3
+
4
+ ComputeSDK provides a consistent interface for executing code in remote
5
+ sandbox environments across multiple cloud providers.
6
+
7
+ Quick Start:
8
+ ```python
9
+ import asyncio
10
+ from computesdk import compute
11
+
12
+ async def main():
13
+ # Create a sandbox (auto-config from environment)
14
+ sandbox = await compute.sandbox.create()
15
+
16
+ try:
17
+ # Execute Python code
18
+ result = await sandbox.run_code('print("Hello, World!")', 'python')
19
+ print(result.output)
20
+
21
+ # Execute shell commands
22
+ cmd = await sandbox.run_command('ls -la')
23
+ print(cmd.stdout)
24
+
25
+ # File operations
26
+ await sandbox.filesystem.write_file('/tmp/test.txt', 'Hello!')
27
+ content = await sandbox.filesystem.read_file('/tmp/test.txt')
28
+
29
+ finally:
30
+ await sandbox.destroy()
31
+
32
+ asyncio.run(main())
33
+ ```
34
+
35
+ Environment Variables:
36
+ COMPUTESDK_API_KEY: Your ComputeSDK API key (required)
37
+ COMPUTESDK_PROVIDER: Provider to use (optional, auto-detected)
38
+ COMPUTESDK_GATEWAY_URL: Gateway URL (optional)
39
+
40
+ Provider-specific variables are also required:
41
+ - E2B: E2B_API_KEY
42
+ - Modal: MODAL_TOKEN_ID, MODAL_TOKEN_SECRET
43
+ - Railway: RAILWAY_API_KEY, RAILWAY_PROJECT_ID, RAILWAY_ENVIRONMENT_ID
44
+ - etc.
45
+
46
+ For more information, visit: https://docs.computesdk.com
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ # Core classes
52
+ from .compute import Compute, compute
53
+ from .sandbox import FileSystem, Sandbox
54
+
55
+ # Configuration
56
+ from .config import (
57
+ GATEWAY_URL,
58
+ GatewayConfig,
59
+ auto_config,
60
+ create_config,
61
+ detect_provider,
62
+ get_provider_headers,
63
+ )
64
+
65
+ # Types
66
+ from .types import (
67
+ # Enums
68
+ CommandStatus,
69
+ FileType,
70
+ Runtime,
71
+ SandboxStatus,
72
+ ServerStatus,
73
+ TerminalStatus,
74
+ WatcherStatus,
75
+ # Result types
76
+ CodeResult,
77
+ CommandResult,
78
+ StreamingCommandResult,
79
+ SandboxInfo,
80
+ # File system types
81
+ FileEntry,
82
+ FileInfo,
83
+ # Terminal types
84
+ TerminalInfo,
85
+ CommandInfo,
86
+ # Server types
87
+ ServerInfo,
88
+ # Watcher types
89
+ WatcherInfo,
90
+ WatcherEvent,
91
+ # Auth types
92
+ SessionToken,
93
+ MagicLink,
94
+ AuthInfo,
95
+ # Signal types
96
+ SignalStatus,
97
+ PortEvent,
98
+ # Options types
99
+ CreateSandboxOptions,
100
+ RunCommandOptions,
101
+ CreateTerminalOptions,
102
+ CreateWatcherOptions,
103
+ StartServerOptions,
104
+ CreateSessionTokenOptions,
105
+ CreateMagicLinkOptions,
106
+ GetUrlOptions,
107
+ # Response types
108
+ SandboxResponse,
109
+ HealthResponse,
110
+ ChildSandboxInfo,
111
+ )
112
+
113
+ # Exceptions
114
+ from .exceptions import (
115
+ AuthenticationError,
116
+ ComputeSDKError,
117
+ ConfigurationError,
118
+ ConnectionError,
119
+ ForbiddenError,
120
+ NotFoundError,
121
+ ProviderError,
122
+ RateLimitError,
123
+ SandboxError,
124
+ TimeoutError,
125
+ ValidationError,
126
+ WebSocketError,
127
+ )
128
+
129
+ # WebSocket (optional, may not be available)
130
+ try:
131
+ from .websocket_client import TerminalSession, WebSocketClient
132
+ except ImportError:
133
+ WebSocketClient = None # type: ignore
134
+ TerminalSession = None # type: ignore
135
+
136
+ # Protocol
137
+ from .protocol import BinaryProtocol
138
+
139
+ __version__ = "0.1.0"
140
+
141
+ __all__ = [
142
+ # Version
143
+ "__version__",
144
+ # Core
145
+ "compute",
146
+ "Compute",
147
+ "Sandbox",
148
+ "FileSystem",
149
+ # Configuration
150
+ "GatewayConfig",
151
+ "auto_config",
152
+ "create_config",
153
+ "detect_provider",
154
+ "get_provider_headers",
155
+ "GATEWAY_URL",
156
+ # Enums
157
+ "Runtime",
158
+ "SandboxStatus",
159
+ "TerminalStatus",
160
+ "CommandStatus",
161
+ "ServerStatus",
162
+ "WatcherStatus",
163
+ "FileType",
164
+ # Result types
165
+ "CodeResult",
166
+ "CommandResult",
167
+ "StreamingCommandResult",
168
+ "SandboxInfo",
169
+ # File system types
170
+ "FileEntry",
171
+ "FileInfo",
172
+ # Terminal types
173
+ "TerminalInfo",
174
+ "CommandInfo",
175
+ # Server types
176
+ "ServerInfo",
177
+ # Watcher types
178
+ "WatcherInfo",
179
+ "WatcherEvent",
180
+ # Auth types
181
+ "SessionToken",
182
+ "MagicLink",
183
+ "AuthInfo",
184
+ # Signal types
185
+ "SignalStatus",
186
+ "PortEvent",
187
+ # Options types
188
+ "CreateSandboxOptions",
189
+ "RunCommandOptions",
190
+ "CreateTerminalOptions",
191
+ "CreateWatcherOptions",
192
+ "StartServerOptions",
193
+ "CreateSessionTokenOptions",
194
+ "CreateMagicLinkOptions",
195
+ "GetUrlOptions",
196
+ # Response types
197
+ "SandboxResponse",
198
+ "HealthResponse",
199
+ "ChildSandboxInfo",
200
+ # Exceptions
201
+ "ComputeSDKError",
202
+ "AuthenticationError",
203
+ "ForbiddenError",
204
+ "NotFoundError",
205
+ "ValidationError",
206
+ "RateLimitError",
207
+ "TimeoutError",
208
+ "WebSocketError",
209
+ "ConnectionError",
210
+ "ConfigurationError",
211
+ "SandboxError",
212
+ "ProviderError",
213
+ # WebSocket
214
+ "WebSocketClient",
215
+ "TerminalSession",
216
+ # Protocol
217
+ "BinaryProtocol",
218
+ ]
computesdk/compute.py ADDED
@@ -0,0 +1,325 @@
1
+ """
2
+ Gateway client for ComputeSDK.
3
+
4
+ Provides the main `compute` singleton for interacting with sandboxes
5
+ through the ComputeSDK gateway.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import asdict
11
+ from typing import TYPE_CHECKING, Optional
12
+
13
+ from .config import GatewayConfig, auto_config
14
+ from .http_client import HTTPClient
15
+ from .types import CreateSandboxOptions
16
+
17
+ if TYPE_CHECKING:
18
+ from .sandbox import Sandbox
19
+
20
+
21
+ class SandboxResource:
22
+ """
23
+ Sandbox CRUD operations via the gateway.
24
+
25
+ Provides methods for creating, retrieving, finding, and managing sandboxes.
26
+ """
27
+
28
+ def __init__(self, client: HTTPClient, config: GatewayConfig):
29
+ self._client = client
30
+ self._config = config
31
+
32
+ async def create(self, options: Optional[CreateSandboxOptions] = None) -> "Sandbox":
33
+ """
34
+ Create a new sandbox.
35
+
36
+ Args:
37
+ options: Sandbox creation options (timeout, template, metadata, etc.)
38
+
39
+ Returns:
40
+ A Sandbox instance ready for use.
41
+
42
+ Example:
43
+ sandbox = await compute.sandbox.create()
44
+ sandbox = await compute.sandbox.create(CreateSandboxOptions(
45
+ timeout=300000,
46
+ template_id="python-dev",
47
+ metadata={"project": "my-app"},
48
+ ))
49
+ """
50
+ from .sandbox import Sandbox
51
+
52
+ body = {}
53
+ if options:
54
+ # Convert dataclass to dict, filtering None values
55
+ body = {
56
+ k: v
57
+ for k, v in {
58
+ "timeout": options.timeout,
59
+ "templateId": options.template_id,
60
+ "metadata": options.metadata,
61
+ "envs": options.envs,
62
+ "name": options.name,
63
+ "namespace": options.namespace,
64
+ }.items()
65
+ if v is not None
66
+ }
67
+
68
+ response = await self._client.post("/v1/sandboxes", json=body)
69
+
70
+ # Extract data from wrapped response
71
+ data = response.get("data", response)
72
+
73
+ return Sandbox(
74
+ sandbox_id=data["sandboxId"],
75
+ sandbox_url=data["url"],
76
+ token=data["token"],
77
+ provider=data["provider"],
78
+ metadata=data.get("metadata"),
79
+ name=data.get("name"),
80
+ namespace=data.get("namespace"),
81
+ gateway_client=self._client,
82
+ )
83
+
84
+ async def get_by_id(self, sandbox_id: str) -> "Sandbox":
85
+ """
86
+ Get an existing sandbox by its ID.
87
+
88
+ Args:
89
+ sandbox_id: The unique sandbox identifier
90
+
91
+ Returns:
92
+ A Sandbox instance for the existing sandbox.
93
+
94
+ Raises:
95
+ NotFoundError: If the sandbox does not exist.
96
+ """
97
+ from .sandbox import Sandbox
98
+
99
+ response = await self._client.get(f"/v1/sandboxes/{sandbox_id}")
100
+
101
+ # Extract data from wrapped response
102
+ data = response.get("data", response)
103
+
104
+ return Sandbox(
105
+ sandbox_id=sandbox_id,
106
+ sandbox_url=data["url"],
107
+ token=data["token"],
108
+ provider=data["provider"],
109
+ metadata=data.get("metadata"),
110
+ gateway_client=self._client,
111
+ )
112
+
113
+ async def find(
114
+ self,
115
+ name: str,
116
+ namespace: str = "default",
117
+ ) -> Optional["Sandbox"]:
118
+ """
119
+ Find a sandbox by name and namespace.
120
+
121
+ Args:
122
+ name: Sandbox name
123
+ namespace: Sandbox namespace (default: "default")
124
+
125
+ Returns:
126
+ A Sandbox instance if found, None otherwise.
127
+ """
128
+ from .sandbox import Sandbox
129
+
130
+ response = await self._client.post(
131
+ "/v1/sandboxes/find",
132
+ json={
133
+ "name": name,
134
+ "namespace": namespace,
135
+ },
136
+ )
137
+
138
+ if response is None:
139
+ return None
140
+
141
+ # Extract data from wrapped response
142
+ data = response.get("data", response)
143
+ if data is None:
144
+ return None
145
+
146
+ return Sandbox(
147
+ sandbox_id=data["sandboxId"],
148
+ sandbox_url=data["url"],
149
+ token=data["token"],
150
+ provider=data["provider"],
151
+ metadata=data.get("metadata"),
152
+ name=data.get("name"),
153
+ namespace=data.get("namespace"),
154
+ gateway_client=self._client,
155
+ )
156
+
157
+ async def find_or_create(
158
+ self,
159
+ name: str,
160
+ namespace: str = "default",
161
+ options: Optional[CreateSandboxOptions] = None,
162
+ ) -> "Sandbox":
163
+ """
164
+ Find an existing sandbox or create a new one.
165
+
166
+ This is useful for persistent sandboxes that should survive
167
+ across sessions.
168
+
169
+ Args:
170
+ name: Sandbox name (must be unique within namespace)
171
+ namespace: Sandbox namespace (default: "default")
172
+ options: Creation options (used only if creating)
173
+
174
+ Returns:
175
+ A Sandbox instance (existing or newly created).
176
+
177
+ Example:
178
+ # Get or create a development sandbox
179
+ sandbox = await compute.sandbox.find_or_create(
180
+ name="my-dev-sandbox",
181
+ namespace="development",
182
+ )
183
+ """
184
+ from .sandbox import Sandbox
185
+
186
+ body: dict = {
187
+ "name": name,
188
+ "namespace": namespace,
189
+ }
190
+
191
+ if options:
192
+ if options.timeout is not None:
193
+ body["timeout"] = options.timeout
194
+ if options.template_id is not None:
195
+ body["templateId"] = options.template_id
196
+ if options.metadata is not None:
197
+ body["metadata"] = options.metadata
198
+ if options.envs is not None:
199
+ body["envs"] = options.envs
200
+
201
+ response = await self._client.post("/v1/sandboxes/find-or-create", json=body)
202
+
203
+ # Extract data from wrapped response
204
+ data = response.get("data", response)
205
+
206
+ return Sandbox(
207
+ sandbox_id=data["sandboxId"],
208
+ sandbox_url=data["url"],
209
+ token=data["token"],
210
+ provider=data["provider"],
211
+ metadata=data.get("metadata"),
212
+ name=data.get("name"),
213
+ namespace=data.get("namespace"),
214
+ gateway_client=self._client,
215
+ )
216
+
217
+
218
+ class Compute:
219
+ """
220
+ Main ComputeSDK gateway client.
221
+
222
+ Provides access to sandbox operations through the ComputeSDK gateway.
223
+ Can be used with auto-configuration from environment variables or
224
+ explicit configuration.
225
+
226
+ Example (auto-config):
227
+ from computesdk import compute
228
+
229
+ sandbox = await compute.sandbox.create()
230
+ result = await sandbox.run_code('print("Hello!")', 'python')
231
+ await sandbox.destroy()
232
+
233
+ Example (explicit config):
234
+ from computesdk import Compute, GatewayConfig
235
+
236
+ config = GatewayConfig(
237
+ api_key="your-api-key",
238
+ provider="e2b",
239
+ provider_headers={"X-E2B-API-Key": "your-e2b-key"},
240
+ )
241
+ compute = Compute(config=config)
242
+ sandbox = await compute.sandbox.create()
243
+ """
244
+
245
+ def __init__(self, config: Optional[GatewayConfig] = None):
246
+ """
247
+ Initialize the Compute client.
248
+
249
+ Args:
250
+ config: Optional explicit configuration. If not provided,
251
+ configuration will be auto-detected from environment
252
+ variables on first use.
253
+ """
254
+ self._config = config
255
+ self._client: Optional[HTTPClient] = None
256
+ self._sandbox: Optional[SandboxResource] = None
257
+
258
+ def _ensure_config(self) -> GatewayConfig:
259
+ """Ensure configuration is available, auto-detecting if needed."""
260
+ if self._config is None:
261
+ self._config = auto_config()
262
+ return self._config
263
+
264
+ def _ensure_client(self) -> HTTPClient:
265
+ """Ensure HTTP client is initialized."""
266
+ if self._client is None:
267
+ config = self._ensure_config()
268
+ headers = {
269
+ "X-ComputeSDK-API-Key": config.api_key,
270
+ "X-Provider": config.provider,
271
+ "Content-Type": "application/json",
272
+ **config.provider_headers,
273
+ }
274
+ self._client = HTTPClient(
275
+ base_url=config.gateway_url,
276
+ headers=headers,
277
+ timeout=config.timeout,
278
+ )
279
+ return self._client
280
+
281
+ @property
282
+ def sandbox(self) -> SandboxResource:
283
+ """
284
+ Access sandbox operations.
285
+
286
+ Returns:
287
+ SandboxResource for creating and managing sandboxes.
288
+ """
289
+ if self._sandbox is None:
290
+ self._sandbox = SandboxResource(
291
+ self._ensure_client(),
292
+ self._ensure_config(),
293
+ )
294
+ return self._sandbox
295
+
296
+ def set_config(self, config: GatewayConfig) -> None:
297
+ """
298
+ Set explicit configuration.
299
+
300
+ This resets any existing client connections.
301
+
302
+ Args:
303
+ config: New gateway configuration
304
+ """
305
+ self._config = config
306
+ self._client = None
307
+ self._sandbox = None
308
+
309
+ async def close(self) -> None:
310
+ """Close HTTP client connections and release resources."""
311
+ if self._client is not None:
312
+ await self._client.close()
313
+ self._client = None
314
+
315
+ async def __aenter__(self) -> "Compute":
316
+ """Async context manager entry."""
317
+ return self
318
+
319
+ async def __aexit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None:
320
+ """Async context manager exit."""
321
+ await self.close()
322
+
323
+
324
+ # Default singleton instance for convenience
325
+ compute = Compute()