grasp-sdk 0.1.0__py3-none-any.whl → 0.1.1__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 grasp-sdk might be problematic. Click here for more details.

grasp_sdk/__init__.py CHANGED
@@ -24,7 +24,7 @@ from .models import (
24
24
  SandboxStatus,
25
25
  )
26
26
 
27
- __version__ = "0.1.0"
27
+ __version__ = "0.1.1"
28
28
  __author__ = "Grasp Team"
29
29
  __email__ = "team@grasp.dev"
30
30
 
@@ -40,6 +40,19 @@ class GraspServer:
40
40
  """
41
41
  if sandbox_config is None:
42
42
  sandbox_config = {}
43
+
44
+ # Extract browser-specific options
45
+ browser_type = sandbox_config.pop('type', 'chromium')
46
+ headless = sandbox_config.pop('headless', True)
47
+ adblock = sandbox_config.pop('adblock', False)
48
+
49
+ self.__browser_type = browser_type
50
+
51
+ # Create browser task
52
+ self.__browser_config = {
53
+ 'headless': headless,
54
+ 'envs': {'ADBLOCK': 'true' if adblock else 'false'}
55
+ }
43
56
 
44
57
  config = get_config()
45
58
  config['sandbox'].update(sandbox_config)
@@ -55,6 +68,22 @@ class GraspServer:
55
68
  f'GraspE2B initialized (templateId: {config["sandbox"]["templateId"]})'
56
69
  )
57
70
 
71
+ async def __aenter__(self):
72
+ connection = await self.create_browser_task()
73
+
74
+ # Register server
75
+ if connection['id']:
76
+ _servers[connection['id']] = self
77
+
78
+ return connection
79
+
80
+ async def __aexit__(self, exc_type, exc, tb):
81
+ if self.browser_service and self.browser_service.id:
82
+ service_id = self.browser_service.id
83
+ self.logger.info(f'Closing browser service {service_id}')
84
+ await _servers[service_id].cleanup()
85
+ del _servers[service_id]
86
+
58
87
  @property
59
88
  def sandbox(self) -> Optional[SandboxService]:
60
89
  """Get the underlying sandbox service.
@@ -82,8 +111,6 @@ class GraspServer:
82
111
 
83
112
  async def create_browser_task(
84
113
  self,
85
- browser_type: Literal['chrome-stable', 'chromium'] = 'chromium',
86
- config: Optional[Dict[str, Any]] = None
87
114
  ) -> Dict[str, Any]:
88
115
  """Create and launch a browser task.
89
116
 
@@ -100,6 +127,9 @@ class GraspServer:
100
127
  if self.browser_service:
101
128
  raise RuntimeError('Browser service can only be initialized once')
102
129
 
130
+ config = self.__browser_config
131
+ browser_type = self.__browser_type
132
+
103
133
  if config is None:
104
134
  config = {}
105
135
 
@@ -180,25 +210,11 @@ async def launch_browser(
180
210
 
181
211
  Returns:
182
212
  Dictionary containing connection information
183
- """
184
- if options is None:
185
- options = {}
186
-
187
- # Extract browser-specific options
188
- browser_type = options.pop('type', 'chromium')
189
- headless = options.pop('headless', True)
190
- adblock = options.pop('adblock', False)
191
-
213
+ """
192
214
  # Create server instance
193
215
  server = GraspServer(options)
194
216
 
195
- # Create browser task
196
- browser_config = {
197
- 'headless': headless,
198
- 'envs': {'ADBLOCK': 'true' if adblock else 'false'}
199
- }
200
-
201
- connection = await server.create_browser_task(browser_type, browser_config)
217
+ connection = await server.create_browser_task()
202
218
 
203
219
  # Register server
204
220
  if connection['id']:
@@ -258,5 +274,5 @@ __all__ = [
258
274
 
259
275
  # Default export equivalent
260
276
  default = {
261
- 'launch_browser': launch_browser,
277
+ 'GraspServer': GraspServer,
262
278
  }
@@ -6,7 +6,7 @@ import http from 'http';
6
6
  import { Logtail } from '@logtail/node';
7
7
  import * as Sentry from "@sentry/node";
8
8
 
9
- console.log(`💬 ${JSON.stringify(process.env)}`)
9
+ // console.log(`💬 ${JSON.stringify(process.env)}`)
10
10
 
11
11
  const logtail = new Logtail(process.env.BS_SOURCE_TOKEN, {
12
12
  endpoint: `https://${process.env.BS_INGESTING_HOST}`,
@@ -307,7 +307,7 @@ class BrowserService:
307
307
 
308
308
  async def _start_health_check(self) -> None:
309
309
  """Start health check for browser process."""
310
- while self.cdp_connection and self.browser_process:
310
+ while self.cdp_connection:
311
311
  try:
312
312
  await asyncio.sleep(5)
313
313
 
@@ -48,8 +48,9 @@ class CommandEventEmitter:
48
48
  self._callbacks[event] = []
49
49
  self._callbacks[event].append(callback)
50
50
 
51
- def emit(self, event: str, *args) -> None:
51
+ def emit(self, event: Any, *args) -> None:
52
52
  """Emit event to all registered listeners."""
53
+ # print(f'🚀 emit ${event}')
53
54
  if event in self._callbacks:
54
55
  for callback in self._callbacks[event]:
55
56
  try:
@@ -244,7 +245,7 @@ class SandboxService:
244
245
  # Generate log file name using sandbox id
245
246
  log_file = f'~/logs/grasp/log-{self.id}.log'
246
247
  nohup_command = f'nohup {command} > {log_file} 2>&1 &'
247
- print(f"💬 {nohup_command}")
248
+ # print(f"💬 {nohup_command}")
248
249
  await self.sandbox.commands.run(
249
250
  nohup_command,
250
251
  cwd=cwd,
@@ -287,8 +288,11 @@ class SandboxService:
287
288
  # Wait for command completion (for non-nohup commands)
288
289
  if not use_nohup:
289
290
  try:
291
+ # print(f"⏳ {command}")
290
292
  result = await handle.wait()
291
- event_emitter.emit('exit', result.exit_code, result)
293
+ # print(f"✅ {command} 执行完毕")
294
+ # event_emitter.emit('stdout', '🎉 ok')
295
+ event_emitter.emit('exit', result.exit_code)
292
296
  except Exception as error:
293
297
  event_emitter.emit('error', error)
294
298
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: grasp_sdk
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Python SDK for Grasp E2B - Browser automation and sandbox management
5
5
  Home-page: https://github.com/grasp-team/grasp-e2b
6
6
  Author: Grasp Team
@@ -73,35 +73,90 @@ pip install -e ".[dev]"
73
73
 
74
74
  ## 🔧 Quick Start
75
75
 
76
+ ### Using GraspServer Context Manager (Recommended)
77
+
76
78
  ```python
77
79
  import asyncio
80
+ import os
81
+ from pathlib import Path
82
+ from playwright.async_api import async_playwright
83
+ from dotenv import load_dotenv
84
+
78
85
  from grasp_sdk import GraspServer
86
+ from grasp_sdk.models import IBrowserConfig, ISandboxConfig
87
+
88
+ # 加载环境变量
89
+ load_dotenv("../.env.grasp")
79
90
 
80
91
  async def main():
81
- # Initialize Grasp server
82
- server = GraspServer({
83
- "key": api_key,
84
- "timeout": 30000,
85
- })
92
+ """主函数:演示 Grasp SDK 的基本用法"""
86
93
 
87
- try:
88
- # Start sandbox
89
- await server.start()
90
-
91
- # Execute command
92
- result = await server.execute_command("echo 'Hello from Python!'")
93
- print(f"Output: {result.stdout}")
94
-
95
- # Browser automation
96
- browser_task = await server.create_browser_task()
97
- await browser_task.navigate("https://example.com")
98
- screenshot = await browser_task.screenshot("example.png")
94
+ # 检查是否有 API key
95
+ api_key = os.getenv('GRASP_KEY')
96
+ if not api_key:
97
+ print("⚠️ 警告:未设置 GRASP_KEY 环境变量")
98
+ print("请设置 GRASP_KEY 环境变量或在 .env 文件中配置")
99
+ print("示例:export GRASP_KEY=your_api_key_here")
100
+ return
101
+
102
+ print("🚀 正在启动浏览器...")
103
+
104
+ async with GraspServer({
105
+ # 'key': api_key,
106
+ # 'type': 'chrome-stable',
107
+ # 'headless': False,
108
+ # 'adblock': True,
109
+ # 'debug': True,
110
+ 'timeout': 3600000, # 容器最长运行1小时(最大值可以为一天 86400000)
111
+ }) as connection:
112
+
113
+ try:
114
+ print(f"连接信息: {connection}")
115
+ print(f"WebSocket URL: {connection['ws_url']}")
116
+ print(f"HTTP URL: {connection['http_url']}")
117
+
118
+ # 使用 Playwright 连接到 CDP
119
+ async with async_playwright() as p:
120
+ browser = await p.chromium.connect_over_cdp(
121
+ connection['ws_url'],
122
+ timeout=150000
123
+ )
124
+
125
+ # 创建第一个页面并访问网站
126
+ page1 = await browser.new_page()
127
+ await page1.goto('https://getgrasp.ai/', wait_until='domcontentloaded')
128
+ await page1.screenshot(path='grasp-ai.png')
129
+ await page1.close()
130
+
131
+ # 获取或创建上下文
132
+ contexts = browser.contexts
133
+ context = contexts[0] if contexts else await browser.new_context()
134
+
135
+ # 创建第二个页面
136
+ page2 = await context.new_page()
137
+
138
+ # 将 HTML 字符串渲染到页面中
139
+ await page2.set_content('<h1>Hello Grasp</h1>', wait_until='networkidle')
140
+
141
+ # 截图演示
142
+ await page2.screenshot(path='hello-world.png', full_page=True)
143
+
144
+ # 清理资源
145
+ await page2.close()
146
+ await context.close()
147
+ await browser.close()
148
+
149
+ print('✅ 任务完成。')
150
+
151
+ except Exception as e:
152
+ print(f"❌ 执行过程中出现错误: {str(e)}")
153
+ raise
99
154
 
100
- finally:
101
- # Clean up
102
- await server.close()
155
+ finally:
156
+ # 注意:使用 GraspServer 上下文管理器时,资源会自动清理
157
+ print("程序结束,资源将自动清理")
103
158
 
104
- if __name__ == "__main__":
159
+ if __name__ == '__main__':
105
160
  asyncio.run(main())
106
161
  ```
107
162
 
@@ -145,13 +200,32 @@ GRASP_TEMPLATE=python
145
200
 
146
201
  ## 🧪 Development
147
202
 
203
+ ### Quick Setup
204
+
148
205
  ```bash
149
- # Install development dependencies
206
+ # Install development dependencies automatically
207
+ python install_dev_deps.py
208
+
209
+ # Or manually install
150
210
  pip install -e ".[dev]"
211
+ ```
212
+
213
+ ### Running Tests
214
+
215
+ ```bash
216
+ # Simple tests (no pytest required)
217
+ python test_connect_simple.py
218
+
219
+ # Full test suite (requires pytest)
220
+ pytest tests/
221
+
222
+ # Run specific test file
223
+ pytest tests/test_connect.py -v
224
+ ```
151
225
 
152
- # Run tests
153
- pytest
226
+ ### Code Quality
154
227
 
228
+ ```bash
155
229
  # Format code
156
230
  black .
157
231
  isort .
@@ -163,22 +237,54 @@ mypy .
163
237
  flake8 .
164
238
  ```
165
239
 
240
+ ### Examples
241
+
242
+ ```bash
243
+ # Run Connect usage examples
244
+ python example_connect.py
245
+ ```
246
+
166
247
  ## 📚 API Reference
167
248
 
249
+ ### GraspServer (Recommended)
250
+
251
+ Async context manager for automatic sandbox resource management and browser automation.
252
+
253
+ ```python
254
+ class GraspServer:
255
+ def __init__(self, options: Optional[Dict[str, Any]] = None)
256
+ async def __aenter__(self) -> Dict[str, Any] # Returns connection info
257
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None
258
+ ```
259
+
260
+ **Usage:**
261
+ ```python
262
+ async with GraspServer(options) as connection:
263
+ # connection contains: {'id', 'ws_url', 'http_url'}
264
+ # Automatic cleanup on exit
265
+ ```
266
+
267
+ **Options:**
268
+ - `key`: Your Grasp API key (loaded from environment if not provided)
269
+ - `type`: Browser type ('chromium' or 'chrome-stable')
270
+ - `headless`: Run in headless mode (default: True)
271
+ - `adblock`: Enable adblock (default: False)
272
+ - `debug`: Enable debug mode (default: False)
273
+ - `timeout`: Container maximum runtime in milliseconds (default: 30000, max: 86400000)
274
+
168
275
  ### GraspServer
169
276
 
170
277
  Main class for interacting with E2B sandboxes and browser automation.
171
278
 
172
279
  ```python
173
280
  class GraspServer:
174
- def __init__(self, config: ISandboxConfig = None)
175
- async def start(self) -> None
176
- async def close(self) -> None
177
- async def execute_command(self, command: str, options: ICommandOptions = None) -> CommandResult
178
- async def execute_script(self, script_path: str, options: IScriptOptions = None) -> CommandResult
179
- async def create_browser_task(self, config: IBrowserConfig = None) -> BrowserTask
180
- def get_sandbox_status(self) -> SandboxStatus
181
- def get_sandbox_id(self) -> str
281
+ def __init__(self, sandbox_config: Optional[Dict[str, Any]] = None)
282
+ async def create_browser_task(self, browser_type: str = 'chromium', config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]
283
+ async def cleanup(self) -> None
284
+ def get_status(self) -> Optional[SandboxStatus]
285
+ def get_sandbox_id(self) -> Optional[str]
286
+ @property
287
+ def sandbox(self) -> Optional[SandboxService]
182
288
  ```
183
289
 
184
290
  ## 🤝 Compatibility
@@ -1,17 +1,17 @@
1
- grasp_sdk/__init__.py,sha256=7P4CFKAv1YgmbEog1s5uKMTVljSC0FDkC4ePhS0j_rE,7475
1
+ grasp_sdk/__init__.py,sha256=iG8-Tq66syI3P7skVKIRPf7JwmHMEhgFU21oEmvYEMM,8026
2
2
  grasp_sdk/models/__init__.py,sha256=lAlbb9tG8fsKz1fo2IVr30pGVytU5V-KblDAzZnLbVQ,2738
3
3
  grasp_sdk/sandbox/chrome-stable.mjs,sha256=8e20N7tlNRlQZ6bO3qpAdwllCBWE9cdbMN-iEW19F30,11281
4
- grasp_sdk/sandbox/chromium.mjs,sha256=DTepEfkJ75mQE_nLLRE11ZrnODpjZXw0ahAFaaFSVX4,11477
4
+ grasp_sdk/sandbox/chromium.mjs,sha256=OICv9etmhuwSCALSxi1-pfqYlz2216acam-znR_eycg,11480
5
5
  grasp_sdk/sandbox/jsconfig.json,sha256=XkAgp68pCDDdHNpggzFb_dYB8hk3MHfJBOsUZZJXNCs,418
6
6
  grasp_sdk/services/__init__.py,sha256=HqRD-WRedLwOb2gZPXPFzI-3892VT9IknKSbuDyiss8,327
7
- grasp_sdk/services/browser.py,sha256=KBLy0ySJ8Zr7-XO_xVENhvP6h5-DLGi5eYDEHd4_CA4,14863
8
- grasp_sdk/services/sandbox.py,sha256=VFlRuBFe5AjIbTvK80ntWK6xt2dsCfh7MwkUC-1FvpU,21783
7
+ grasp_sdk/services/browser.py,sha256=YG4EKMurrc9M8JVMwPbdxj7DvREdwruD9VQJNRIXUjc,14838
8
+ grasp_sdk/services/sandbox.py,sha256=rT6SNG-GOX5P5S7uERZlp-SYoVL39FN0DqFzj1cnBiQ,22019
9
9
  grasp_sdk/utils/__init__.py,sha256=IQzRV-iZJXanSlaXBcgXBCcOXTVBCY6ZujxQpDTGW9w,816
10
10
  grasp_sdk/utils/auth.py,sha256=M_SX3uKTjjfi6fzk384IqPvUtqt98bif22HHMgio1D4,7258
11
11
  grasp_sdk/utils/config.py,sha256=txnmKQ6nxw-wvOBmr9mkZiWX7ROKwyHQLBpM_Wy9XZI,4171
12
12
  grasp_sdk/utils/logger.py,sha256=k6WDmzL3cPTcQbiiTD4Q6fsDdUO_kyXQHz7nlmtv7G4,7228
13
- grasp_sdk-0.1.0.dist-info/METADATA,sha256=y0oJ0nxQMqEDxzUAWFW6atYg9xcTxwQeFpLF5cwEGDM,6113
14
- grasp_sdk-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
- grasp_sdk-0.1.0.dist-info/entry_points.txt,sha256=roDjUu4JR6b1tUtRmq018mw167AbfC5zQiOtv3o6IMo,45
16
- grasp_sdk-0.1.0.dist-info/top_level.txt,sha256=C9GL798_aP9Hgjq7UUlaGHLDfUohO2PSGYuGDV0cMx8,10
17
- grasp_sdk-0.1.0.dist-info/RECORD,,
13
+ grasp_sdk-0.1.1.dist-info/METADATA,sha256=J-YOxqym39aRexIyX-l_UoaCOs4XSE1K2aTdFMrD1Uw,9522
14
+ grasp_sdk-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ grasp_sdk-0.1.1.dist-info/entry_points.txt,sha256=roDjUu4JR6b1tUtRmq018mw167AbfC5zQiOtv3o6IMo,45
16
+ grasp_sdk-0.1.1.dist-info/top_level.txt,sha256=C9GL798_aP9Hgjq7UUlaGHLDfUohO2PSGYuGDV0cMx8,10
17
+ grasp_sdk-0.1.1.dist-info/RECORD,,