fleet-python 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.
Potentially problematic release.
This version of fleet-python might be problematic. Click here for more details.
- examples/quickstart.py +130 -0
- fleet/__init__.py +42 -0
- fleet/client.py +318 -0
- fleet/config.py +125 -0
- fleet/env/__init__.py +30 -0
- fleet/env/base.py +328 -0
- fleet/env/factory.py +446 -0
- fleet/exceptions.py +73 -0
- fleet/facets/__init__.py +7 -0
- fleet/facets/base.py +223 -0
- fleet/facets/factory.py +29 -0
- fleet/manager_client.py +177 -0
- fleet_python-0.1.0.dist-info/METADATA +110 -0
- fleet_python-0.1.0.dist-info/RECORD +17 -0
- fleet_python-0.1.0.dist-info/WHEEL +5 -0
- fleet_python-0.1.0.dist-info/licenses/LICENSE +201 -0
- fleet_python-0.1.0.dist-info/top_level.txt +2 -0
fleet/env/base.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Fleet SDK Base Environment Classes."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
import asyncio
|
|
7
|
+
import time
|
|
8
|
+
import logging
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
from ..facets.base import Facet
|
|
12
|
+
from ..exceptions import FleetEnvironmentError, FleetAPIError
|
|
13
|
+
from ..client import FleetAPIClient, InstanceRequest, InstanceResponse
|
|
14
|
+
from ..manager_client import FleetManagerClient, ManagerHealthResponse
|
|
15
|
+
from ..config import FleetConfig, get_config
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class EnvironmentConfig(BaseModel):
|
|
22
|
+
"""Configuration for Fleet environments."""
|
|
23
|
+
|
|
24
|
+
environment_type: str = Field(..., description="Type of environment (e.g., 'chrome-desktop-v1')")
|
|
25
|
+
api_key: Optional[str] = Field(None, description="Fleet API key")
|
|
26
|
+
base_url: str = Field(default="https://fleet.new", description="Fleet API base URL")
|
|
27
|
+
metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional configuration")
|
|
28
|
+
|
|
29
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
30
|
+
"""Convert config to dictionary."""
|
|
31
|
+
return self.model_dump()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Environment(ABC):
|
|
35
|
+
"""Base class for all Fleet environments."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, config: EnvironmentConfig):
|
|
38
|
+
self.config = config
|
|
39
|
+
self._facets: Dict[str, Facet] = {}
|
|
40
|
+
self._session_id: Optional[str] = None
|
|
41
|
+
self._instance_id: Optional[str] = None
|
|
42
|
+
self._step_count: int = 0
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
async def reset(
|
|
46
|
+
self,
|
|
47
|
+
seed: Optional[int] = None,
|
|
48
|
+
timestamp: Optional[Union[str, datetime]] = None,
|
|
49
|
+
options: Optional[Dict[str, Any]] = None
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Reset the environment.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
seed: Integer seed for deterministic RNG in the env (physics, action noise, etc.)
|
|
55
|
+
timestamp: ISO8601 string or datetime for the "current time" the sim should use
|
|
56
|
+
options: Any additional flags the env impl supports (e.g. viewport size, login creds, feature flags)
|
|
57
|
+
"""
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
@abstractmethod
|
|
61
|
+
async def step(self, action: Dict[str, Any]) -> Tuple[Dict[str, Any], float, bool]:
|
|
62
|
+
"""Execute one step in the environment.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
action: The action to execute as a dictionary
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Tuple of (state, reward, done)
|
|
69
|
+
"""
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
@abstractmethod
|
|
73
|
+
async def close(self) -> None:
|
|
74
|
+
"""Close the environment and clean up resources."""
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
@abstractmethod
|
|
78
|
+
def state(self, facet_uri: str) -> Facet:
|
|
79
|
+
"""Get a facet for accessing environment state.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
facet_uri: URI identifying the facet (e.g., 'sqlite://crm', 'browser://dom')
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
Facet instance for the requested state
|
|
86
|
+
"""
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def session_id(self) -> Optional[str]:
|
|
91
|
+
"""Get the current session ID."""
|
|
92
|
+
return self._session_id
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def instance_id(self) -> Optional[str]:
|
|
96
|
+
"""Get the current instance ID."""
|
|
97
|
+
return self._instance_id
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def step_count(self) -> int:
|
|
101
|
+
"""Get the current step count."""
|
|
102
|
+
return self._step_count
|
|
103
|
+
|
|
104
|
+
def _increment_step(self) -> None:
|
|
105
|
+
"""Increment the step counter."""
|
|
106
|
+
self._step_count += 1
|
|
107
|
+
|
|
108
|
+
def _reset_step_count(self) -> None:
|
|
109
|
+
"""Reset the step counter."""
|
|
110
|
+
self._step_count = 0
|
|
111
|
+
|
|
112
|
+
def _register_facet(self, uri: str, facet: Facet) -> None:
|
|
113
|
+
"""Register a facet for this environment."""
|
|
114
|
+
self._facets[uri] = facet
|
|
115
|
+
|
|
116
|
+
def _get_facet(self, uri: str) -> Optional[Facet]:
|
|
117
|
+
"""Get a registered facet."""
|
|
118
|
+
return self._facets.get(uri)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class RemoteEnvironment(Environment):
|
|
122
|
+
"""Environment that connects to a remote Fleet API."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, config: EnvironmentConfig, instance_response: Optional[InstanceResponse] = None, instance_id: Optional[str] = None):
|
|
125
|
+
super().__init__(config)
|
|
126
|
+
|
|
127
|
+
# Create Fleet config from environment config
|
|
128
|
+
self._fleet_config = FleetConfig(
|
|
129
|
+
api_key=config.api_key,
|
|
130
|
+
base_url=config.base_url,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# Initialize API client
|
|
134
|
+
self._client = FleetAPIClient(self._fleet_config)
|
|
135
|
+
|
|
136
|
+
# Set instance details
|
|
137
|
+
if instance_response:
|
|
138
|
+
self._instance_response = instance_response
|
|
139
|
+
self._instance_id = instance_response.instance_id
|
|
140
|
+
else:
|
|
141
|
+
self._instance_id = instance_id
|
|
142
|
+
self._instance_response = None
|
|
143
|
+
|
|
144
|
+
# Initialize manager client (will be set when instance URLs are available)
|
|
145
|
+
self._manager_client: Optional[FleetManagerClient] = None
|
|
146
|
+
|
|
147
|
+
async def reset(
|
|
148
|
+
self,
|
|
149
|
+
seed: Optional[int] = None,
|
|
150
|
+
timestamp: Optional[Union[str, datetime]] = None,
|
|
151
|
+
options: Optional[Dict[str, Any]] = None
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Reset the environment state.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
seed: Integer seed for deterministic RNG in the env (physics, action noise, etc.)
|
|
157
|
+
timestamp: ISO8601 string or datetime for the "current time" the sim should use
|
|
158
|
+
options: Any additional flags the env impl supports (e.g. viewport size, login creds, feature flags)
|
|
159
|
+
"""
|
|
160
|
+
raise NotImplementedError("reset() is not implemented yet.")
|
|
161
|
+
|
|
162
|
+
async def step(self, action: Dict[str, Any]) -> Tuple[Dict[str, Any], float, bool]:
|
|
163
|
+
"""Execute one step in the environment."""
|
|
164
|
+
if not self._instance_id:
|
|
165
|
+
raise FleetEnvironmentError("Environment not initialized. Call reset() first.")
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
# Increment step count
|
|
169
|
+
self._increment_step()
|
|
170
|
+
|
|
171
|
+
# Execute action through instance manager API
|
|
172
|
+
# This is a placeholder - actual implementation depends on the manager API spec
|
|
173
|
+
state, reward, done = await self._execute_action(action)
|
|
174
|
+
|
|
175
|
+
return state, reward, done
|
|
176
|
+
|
|
177
|
+
except Exception as e:
|
|
178
|
+
raise FleetEnvironmentError(f"Failed to execute step: {e}")
|
|
179
|
+
|
|
180
|
+
async def close(self) -> None:
|
|
181
|
+
"""Close the environment and clean up resources."""
|
|
182
|
+
try:
|
|
183
|
+
# Delete instance if it exists
|
|
184
|
+
if self._instance_id:
|
|
185
|
+
try:
|
|
186
|
+
await self._client.delete_instance(self._instance_id)
|
|
187
|
+
logger.info(f"Deleted instance: {self._instance_id}")
|
|
188
|
+
except FleetAPIError as e:
|
|
189
|
+
logger.warning(f"Failed to delete instance: {e}")
|
|
190
|
+
finally:
|
|
191
|
+
self._instance_id = None
|
|
192
|
+
self._instance_response = None
|
|
193
|
+
|
|
194
|
+
# Close manager client
|
|
195
|
+
if self._manager_client:
|
|
196
|
+
await self._manager_client.close()
|
|
197
|
+
self._manager_client = None
|
|
198
|
+
|
|
199
|
+
# Close API client
|
|
200
|
+
await self._client.close()
|
|
201
|
+
|
|
202
|
+
except Exception as e:
|
|
203
|
+
logger.error(f"Error closing environment: {e}")
|
|
204
|
+
|
|
205
|
+
def state(self, facet_uri: str) -> Facet:
|
|
206
|
+
"""Get a facet for accessing environment state."""
|
|
207
|
+
# Check if facet is already registered
|
|
208
|
+
facet = self._get_facet(facet_uri)
|
|
209
|
+
if facet:
|
|
210
|
+
return facet
|
|
211
|
+
|
|
212
|
+
# Create new facet based on URI
|
|
213
|
+
from ..facets.factory import create_facet
|
|
214
|
+
facet = create_facet(facet_uri, self)
|
|
215
|
+
self._register_facet(facet_uri, facet)
|
|
216
|
+
return facet
|
|
217
|
+
|
|
218
|
+
async def manager_health_check(self) -> Optional[ManagerHealthResponse]:
|
|
219
|
+
"""Check the health of the manager API.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
ManagerHealthResponse if manager is available, None otherwise
|
|
223
|
+
"""
|
|
224
|
+
await self._ensure_manager_client()
|
|
225
|
+
if not self._manager_client:
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
return await self._manager_client.health_check()
|
|
230
|
+
except Exception as e:
|
|
231
|
+
logger.warning(f"Manager health check failed: {e}")
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
async def _ensure_manager_client(self) -> None:
|
|
235
|
+
"""Ensure manager client is initialized if instance URLs are available."""
|
|
236
|
+
if self._manager_client is not None:
|
|
237
|
+
return
|
|
238
|
+
|
|
239
|
+
# Need instance response to get manager URLs
|
|
240
|
+
if not self._instance_response and self._instance_id:
|
|
241
|
+
try:
|
|
242
|
+
self._instance_response = await self._client.get_instance(self._instance_id)
|
|
243
|
+
except Exception as e:
|
|
244
|
+
logger.warning(f"Failed to get instance details for manager client: {e}")
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
if self._instance_response and self._instance_response.urls.manager:
|
|
248
|
+
manager_base_url = self._instance_response.urls.manager.api
|
|
249
|
+
self._manager_client = FleetManagerClient(manager_base_url)
|
|
250
|
+
logger.debug(f"Initialized manager client for {manager_base_url}")
|
|
251
|
+
|
|
252
|
+
async def _wait_for_instance_ready(self, timeout: float = 300.0) -> None:
|
|
253
|
+
"""Wait for instance to be ready.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
timeout: Maximum time to wait in seconds
|
|
257
|
+
"""
|
|
258
|
+
start_time = time.time()
|
|
259
|
+
|
|
260
|
+
while time.time() - start_time < timeout:
|
|
261
|
+
try:
|
|
262
|
+
instance = await self._client.get_instance(self._instance_id)
|
|
263
|
+
self._instance_response = instance
|
|
264
|
+
|
|
265
|
+
if instance.status == "running":
|
|
266
|
+
logger.info(f"Instance {self._instance_id} is ready")
|
|
267
|
+
return
|
|
268
|
+
|
|
269
|
+
elif instance.status == "error":
|
|
270
|
+
raise FleetEnvironmentError(f"Instance {self._instance_id} failed to start")
|
|
271
|
+
|
|
272
|
+
# Wait before checking again
|
|
273
|
+
await asyncio.sleep(5)
|
|
274
|
+
|
|
275
|
+
except FleetAPIError as e:
|
|
276
|
+
if time.time() - start_time >= timeout:
|
|
277
|
+
raise FleetEnvironmentError(f"Timeout waiting for instance to be ready: {e}")
|
|
278
|
+
await asyncio.sleep(5)
|
|
279
|
+
|
|
280
|
+
raise FleetEnvironmentError(f"Timeout waiting for instance {self._instance_id} to be ready")
|
|
281
|
+
|
|
282
|
+
async def _execute_action(self, action: Dict[str, Any]) -> Tuple[Dict[str, Any], float, bool]:
|
|
283
|
+
"""Execute an action through the instance manager API.
|
|
284
|
+
|
|
285
|
+
This is a placeholder implementation that should be extended based on
|
|
286
|
+
the actual manager API specification.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
action: The action to execute as a dictionary
|
|
290
|
+
|
|
291
|
+
Returns:
|
|
292
|
+
Tuple of (state, reward, done)
|
|
293
|
+
"""
|
|
294
|
+
# Ensure manager client is available
|
|
295
|
+
await self._ensure_manager_client()
|
|
296
|
+
|
|
297
|
+
# TODO: In the future, this would use the manager API to execute actions
|
|
298
|
+
# For example: await self._manager_client.log_action(action)
|
|
299
|
+
# For now, return placeholder values
|
|
300
|
+
|
|
301
|
+
# Create a placeholder state
|
|
302
|
+
state = self._create_state_from_action(action)
|
|
303
|
+
|
|
304
|
+
# Create a placeholder reward
|
|
305
|
+
reward = 0.0
|
|
306
|
+
|
|
307
|
+
# Determine if episode is done (placeholder logic)
|
|
308
|
+
done = self._step_count >= 100 # Example: done after 100 steps
|
|
309
|
+
|
|
310
|
+
return state, reward, done
|
|
311
|
+
|
|
312
|
+
def _create_state_from_action(self, action: Dict[str, Any]) -> Dict[str, Any]:
|
|
313
|
+
"""Create state based on executed action."""
|
|
314
|
+
return {
|
|
315
|
+
"instance_id": self._instance_id,
|
|
316
|
+
"step": self._step_count,
|
|
317
|
+
"last_action": action,
|
|
318
|
+
"timestamp": time.time(),
|
|
319
|
+
"status": "running"
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async def __aenter__(self):
|
|
323
|
+
"""Async context manager entry."""
|
|
324
|
+
return self
|
|
325
|
+
|
|
326
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
327
|
+
"""Async context manager exit."""
|
|
328
|
+
await self.close()
|