-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaio_data.py
More file actions
559 lines (477 loc) · 15.8 KB
/
aio_data.py
File metadata and controls
559 lines (477 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
"""
This file is auto generated by the code generation script.
Do not modify this file manually.
Use the `make codegen` command to regenerate.
当前文件为自动生成的控制 API 客户端代码。请勿手动修改此文件。
使用 `make codegen` 命令重新生成。
source: agentrun/sandbox/api/__aio_data_async_template.py
All-in-One 沙箱数据API模板 / All-in-One Sandbox Data API Template
此模板用于生成 All-in-One 沙箱数据API代码,结合了浏览器和代码解释器的功能。
This template is used to generate All-in-One sandbox data API code,
combining browser and code interpreter capabilities.
"""
from typing import Any, Dict, Optional
from urllib.parse import parse_qs, urlencode, urlparse
from agentrun.sandbox.model import CodeLanguage
from agentrun.utils.config import Config
from .sandbox_data import SandboxDataAPI
class AioDataAPI(SandboxDataAPI):
"""All-in-One Sandbox Data API
This class combines the functionality of BrowserDataAPI and CodeInterpreterDataAPI,
providing a unified interface for all-in-one sandbox operations.
"""
def __init__(
self,
sandbox_id: str,
config: Optional[Config] = None,
):
self.sandbox_id = sandbox_id
super().__init__(
sandbox_id=sandbox_id,
config=config,
)
# ========================================
# Browser API Methods
# ========================================
def get_cdp_url(self, record: Optional[bool] = False):
"""
Generate the WebSocket URL for Chrome DevTools Protocol (CDP) connection.
This method constructs a WebSocket URL by:
1. Converting the HTTP endpoint to WebSocket protocol (ws://)
2. Parsing the existing URL and query parameters
3. Adding the session ID to the query parameters
4. Reconstructing the complete WebSocket URL
Returns:
str: The complete WebSocket URL for CDP automation connection,
including the session ID in the query parameters.
Example:
>>> api = AioDataAPI("sandbox123")
>>> api.get_cdp_url()
'ws://example.com/ws/automation?sessionId=session456'
"""
cdp_url = self.with_path("/ws/automation").replace("http", "ws")
u = urlparse(cdp_url)
query_dict = parse_qs(u.query)
query_dict["tenantId"] = [self.config.get_account_id()]
if record:
query_dict["recording"] = ["true"]
new_query = urlencode(query_dict, doseq=True)
new_u = u._replace(query=new_query)
return new_u.geturl()
def get_vnc_url(self, record: Optional[bool] = False):
"""
Generate the WebSocket URL for VNC (Virtual Network Computing) live view connection.
This method constructs a WebSocket URL for real-time browser viewing by:
1. Converting the HTTP endpoint to WebSocket protocol (ws://)
2. Parsing the existing URL and query parameters
3. Adding the session ID to the query parameters
4. Reconstructing the complete WebSocket URL
Returns:
str: The complete WebSocket URL for VNC live view connection,
including the session ID in the query parameters.
Example:
>>> api = AioDataAPI("sandbox123")
>>> api.get_vnc_url()
'ws://example.com/ws/liveview?sessionId=session456'
"""
vnc_url = self.with_path("/ws/liveview").replace("http", "ws")
u = urlparse(vnc_url)
query_dict = parse_qs(u.query)
query_dict["tenantId"] = [self.config.get_account_id()]
if record:
query_dict["recording"] = ["true"]
new_query = urlencode(query_dict, doseq=True)
new_u = u._replace(query=new_query)
return new_u.geturl()
def sync_playwright(
self,
browser_type: str = "chrome",
record: Optional[bool] = False,
config: Optional[Config] = None,
):
from .playwright_sync import BrowserPlaywrightSync
cfg = Config.with_configs(self.config, config)
url = self.get_cdp_url(record=record)
url, headers, _ = self.auth(
url=url, headers=cfg.get_headers(), config=cfg
)
return BrowserPlaywrightSync(
url,
browser_type=browser_type,
headers=headers,
)
def async_playwright(
self,
browser_type: str = "chrome",
record: Optional[bool] = False,
config: Optional[Config] = None,
):
from .playwright_async import BrowserPlaywrightAsync
cfg = Config.with_configs(self.config, config)
url = self.get_cdp_url(record=record)
url, headers, _ = self.auth(
url=url, headers=cfg.get_headers(), config=cfg
)
return BrowserPlaywrightAsync(
url,
browser_type=browser_type,
headers=headers,
)
async def list_recordings_async(self):
return await self.get_async("/recordings")
def list_recordings(self):
return self.get("/recordings")
async def delete_recording_async(self, filename: str):
return await self.delete_async(f"/recordings/{filename}")
def delete_recording(self, filename: str):
return self.delete(f"/recordings/{filename}")
async def download_recording_async(self, filename: str, save_path: str):
"""
Asynchronously download a recording video file and save it to local path.
Args:
filename: The name of the recording file to download
save_path: Local file path to save the downloaded video file (.mkv)
Returns:
Dictionary with 'saved_path' and 'size' keys
Examples:
>>> await api.download_recording_async("recording.mp4", "/local/video.mkv")
"""
return await self.get_video_async(
f"/recordings/{filename}", save_path=save_path
)
# ========================================
# Code Interpreter API Methods
# ========================================
def download_recording(self, filename: str, save_path: str):
"""
Synchronously download a recording video file and save it to local path.
Args:
filename: The name of the recording file to download
save_path: Local file path to save the downloaded video file (.mkv)
Returns:
Dictionary with 'saved_path' and 'size' keys
Examples:
>>> api.download_recording("recording.mp4", "/local/video.mkv")
"""
return self.get_video(f"/recordings/{filename}", save_path=save_path)
# ========================================
# Code Interpreter API Methods
# ========================================
async def list_directory_async(
self,
path: Optional[str] = None,
depth: Optional[int] = None,
):
query = {}
if path is not None:
query["path"] = path
if depth is not None:
query["depth"] = depth
return await self.get_async("/filesystem", query=query)
def list_directory(
self,
path: Optional[str] = None,
depth: Optional[int] = None,
):
query = {}
if path is not None:
query["path"] = path
if depth is not None:
query["depth"] = depth
return self.get("/filesystem", query=query)
async def stat_async(
self,
path: str,
):
query = {
"path": path,
}
return await self.get_async("/filesystem/stat", query=query)
def stat(
self,
path: str,
):
query = {
"path": path,
}
return self.get("/filesystem/stat", query=query)
async def mkdir_async(
self,
path: str,
parents: Optional[bool] = True,
mode: Optional[str] = "0755",
):
data = {
"path": path,
"parents": parents,
"mode": mode,
}
return await self.post_async("/filesystem/mkdir", data=data)
def mkdir(
self,
path: str,
parents: Optional[bool] = True,
mode: Optional[str] = "0755",
):
data = {
"path": path,
"parents": parents,
"mode": mode,
}
return self.post("/filesystem/mkdir", data=data)
async def move_file_async(
self,
source: str,
destination: str,
):
data = {
"source": source,
"destination": destination,
}
return await self.post_async("/filesystem/move", data=data)
def move_file(
self,
source: str,
destination: str,
):
data = {
"source": source,
"destination": destination,
}
return self.post("/filesystem/move", data=data)
async def remove_file_async(
self,
path: str,
):
data = {
"path": path,
}
return await self.post_async("/filesystem/remove", data=data)
def remove_file(
self,
path: str,
):
data = {
"path": path,
}
return self.post("/filesystem/remove", data=data)
async def list_contexts_async(self):
return await self.get_async("/contexts")
def list_contexts(self):
return self.get("/contexts")
async def create_context_async(
self,
language: Optional[CodeLanguage] = CodeLanguage.PYTHON,
cwd: str = "/home/user",
):
# Validate language parameter
if language not in ("python", "javascript"):
raise ValueError(
f"language must be 'python' or 'javascript', got: {language}"
)
data: Dict[str, Any] = {
"cwd": cwd,
"language": language,
}
return await self.post_async("/contexts", data=data)
def create_context(
self,
language: Optional[CodeLanguage] = CodeLanguage.PYTHON,
cwd: str = "/home/user",
):
# Validate language parameter
if language not in ("python", "javascript"):
raise ValueError(
f"language must be 'python' or 'javascript', got: {language}"
)
data: Dict[str, Any] = {
"cwd": cwd,
"language": language,
}
return self.post("/contexts", data=data)
async def get_context_async(
self,
context_id: str,
):
return await self.get_async(f"/contexts/{context_id}")
def get_context(
self,
context_id: str,
):
return self.get(f"/contexts/{context_id}")
async def execute_code_async(
self,
code: str,
context_id: Optional[str],
language: Optional[CodeLanguage] = None,
timeout: Optional[int] = 30,
):
if language and language not in ("python", "javascript"):
raise ValueError(
f"language must be 'python' or 'javascript', got: {language}"
)
data: Dict[str, Any] = {
"code": code,
}
if timeout is not None:
data["timeout"] = timeout
if language is not None:
data["language"] = language
if context_id is not None:
data["contextId"] = context_id
return await self.post_async(f"/contexts/execute", data=data)
def execute_code(
self,
code: str,
context_id: Optional[str],
language: Optional[CodeLanguage] = None,
timeout: Optional[int] = 30,
):
if language and language not in ("python", "javascript"):
raise ValueError(
f"language must be 'python' or 'javascript', got: {language}"
)
data: Dict[str, Any] = {
"code": code,
}
if timeout is not None:
data["timeout"] = timeout
if language is not None:
data["language"] = language
if context_id is not None:
data["contextId"] = context_id
return self.post(f"/contexts/execute", data=data)
async def delete_context_async(
self,
context_id: str,
):
return await self.delete_async(f"/contexts/{context_id}")
def delete_context(
self,
context_id: str,
):
return self.delete(f"/contexts/{context_id}")
async def read_file_async(
self,
path: str,
):
query = {
"path": path,
}
return await self.get_async("/files", query=query)
def read_file(
self,
path: str,
):
query = {
"path": path,
}
return self.get("/files", query=query)
async def write_file_async(
self,
path: str,
content: str,
mode: Optional[str] = "644",
encoding: Optional[str] = "utf-8",
create_dir: Optional[bool] = True,
):
data = {
"path": path,
"content": content,
"mode": mode,
"encoding": encoding,
"createDir": create_dir,
}
return await self.post_async("/files", data=data)
def write_file(
self,
path: str,
content: str,
mode: Optional[str] = "644",
encoding: Optional[str] = "utf-8",
create_dir: Optional[bool] = True,
):
data = {
"path": path,
"content": content,
"mode": mode,
"encoding": encoding,
"createDir": create_dir,
}
return self.post("/files", data=data)
async def upload_file_async(
self,
local_file_path: str,
target_file_path: str,
):
return await self.post_file_async(
path="/filesystem/upload",
local_file_path=local_file_path,
target_file_path=target_file_path,
)
def upload_file(
self,
local_file_path: str,
target_file_path: str,
):
return self.post_file(
path="/filesystem/upload",
local_file_path=local_file_path,
target_file_path=target_file_path,
)
async def download_file_async(
self,
path: str,
save_path: str,
):
query = {"path": path}
return await self.get_file_async(
path="/filesystem/download", save_path=save_path, query=query
)
def download_file(
self,
path: str,
save_path: str,
):
query = {"path": path}
return self.get_file(
path="/filesystem/download", save_path=save_path, query=query
)
async def cmd_async(
self,
command: str,
cwd: str,
timeout: Optional[int] = 30,
):
data: Dict[str, Any] = {
"command": command,
"cwd": cwd,
}
if timeout is not None:
data["timeout"] = timeout
return await self.post_async("/processes/cmd", data=data)
def cmd(
self,
command: str,
cwd: str,
timeout: Optional[int] = 30,
):
data: Dict[str, Any] = {
"command": command,
"cwd": cwd,
}
if timeout is not None:
data["timeout"] = timeout
return self.post("/processes/cmd", data=data)
async def list_processes_async(self):
return await self.get_async("/processes")
def list_processes(self):
return self.get("/processes")
async def get_process_async(self, pid: str):
return await self.get_async(f"/processes/{pid}")
def get_process(self, pid: str):
return self.get(f"/processes/{pid}")
async def kill_process_async(self, pid: str):
return await self.delete_async(f"/processes/{pid}")
def kill_process(self, pid: str):
return self.delete(f"/processes/{pid}")