grasp-sdk 0.1.0__py3-none-any.whl → 0.1.2__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.
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
 
@@ -132,6 +162,12 @@ class GraspServer:
132
162
  browser_config
133
163
  )
134
164
  await self.browser_service.initialize()
165
+
166
+ # Register server
167
+ _servers[str(self.browser_service.id)] = self
168
+ self.logger.info("🚀 Browser service initialized", {
169
+ 'id': self.browser_service.id,
170
+ })
135
171
 
136
172
  self.logger.info('🌐 Launching Chromium browser with CDP...')
137
173
  cdp_connection = await self.browser_service.launch_browser(browser_type)
@@ -180,25 +216,11 @@ async def launch_browser(
180
216
 
181
217
  Returns:
182
218
  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
-
219
+ """
192
220
  # Create server instance
193
221
  server = GraspServer(options)
194
222
 
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)
223
+ connection = await server.create_browser_task()
202
224
 
203
225
  # Register server
204
226
  if connection['id']:
@@ -258,5 +280,5 @@ __all__ = [
258
280
 
259
281
  # Default export equivalent
260
282
  default = {
261
- 'launch_browser': launch_browser,
283
+ 'GraspServer': GraspServer,
262
284
  }
@@ -232,6 +232,10 @@ try {
232
232
  });
233
233
 
234
234
  const server = http.createServer(async (req, res) => {
235
+ if (req.url === '/health') {
236
+ res.end('ok');
237
+ return;
238
+ }
235
239
  if (req.url === '/json/version' || req.url === '/json/version/') {
236
240
  try {
237
241
  // 向本地 CDP 发请求,获取原始 JSON
@@ -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}`,
@@ -229,6 +229,10 @@ try {
229
229
  });
230
230
 
231
231
  const server = http.createServer(async (req, res) => {
232
+ if (req.url === '/health') {
233
+ res.end('ok');
234
+ return;
235
+ }
232
236
  if (req.url === '/json/version' || req.url === '/json/version/') {
233
237
  try {
234
238
  // 向本地 CDP 发请求,获取原始 JSON
@@ -80,27 +80,18 @@ class BrowserService:
80
80
  self._health_check_task: Optional[asyncio.Task] = None
81
81
 
82
82
  def _get_default_logger(self):
83
- """Get default logger instance.
84
-
85
- Returns:
86
- Logger instance
87
- """
83
+ """Gets or creates a default logger instance."""
88
84
  try:
89
- from utils.logger import Logger
90
85
  return get_logger().child('BrowserService')
91
86
  except Exception:
92
87
  # If logger is not initialized, create a default one
93
- logger = logging.getLogger('BrowserService')
94
- if not logger.handlers:
95
- handler = logging.StreamHandler()
96
- formatter = logging.Formatter(
97
- '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
98
- )
99
- handler.setFormatter(formatter)
100
- logger.addHandler(handler)
101
- logger.setLevel(logging.INFO)
102
- return logger
103
-
88
+ from ..utils.logger import Logger
89
+ default_logger = Logger({
90
+ 'level': 'debug' if self.config.get('debug', False) else 'info',
91
+ 'console': True,
92
+ })
93
+ return default_logger.child('BrowserService')
94
+
104
95
  async def initialize(self) -> None:
105
96
  """Initialize the Grasp sandbox.
106
97
 
@@ -307,7 +298,7 @@ class BrowserService:
307
298
 
308
299
  async def _start_health_check(self) -> None:
309
300
  """Start health check for browser process."""
310
- while self.cdp_connection and self.browser_process:
301
+ while self.cdp_connection:
311
302
  try:
312
303
  await asyncio.sleep(5)
313
304
 
@@ -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:
@@ -132,9 +133,6 @@ class SandboxService:
132
133
 
133
134
  try:
134
135
  self.status = SandboxStatus.CREATING
135
- self.logger.info('Creating Grasp sandbox', {
136
- 'templateId': self.config['templateId'],
137
- })
138
136
 
139
137
  # Verify authentication
140
138
  res = await verify(self.config)
@@ -144,7 +142,9 @@ class SandboxService:
144
142
  api_key = res['data']['token']
145
143
 
146
144
  # Create sandbox
147
-
145
+ self.logger.info('Creating Grasp sandbox', {
146
+ 'templateId': self.config['templateId'],
147
+ })
148
148
  # Use Sandbox constructor directly (e2b SDK 1.5.3+)
149
149
  self.sandbox = await AsyncSandbox.create(
150
150
  template=self.config['templateId'],
@@ -244,7 +244,7 @@ class SandboxService:
244
244
  # Generate log file name using sandbox id
245
245
  log_file = f'~/logs/grasp/log-{self.id}.log'
246
246
  nohup_command = f'nohup {command} > {log_file} 2>&1 &'
247
- print(f"💬 {nohup_command}")
247
+ # print(f"💬 {nohup_command}")
248
248
  await self.sandbox.commands.run(
249
249
  nohup_command,
250
250
  cwd=cwd,
@@ -287,8 +287,11 @@ class SandboxService:
287
287
  # Wait for command completion (for non-nohup commands)
288
288
  if not use_nohup:
289
289
  try:
290
+ # print(f"⏳ {command}")
290
291
  result = await handle.wait()
291
- event_emitter.emit('exit', result.exit_code, result)
292
+ # print(f"✅ {command} 执行完毕")
293
+ # event_emitter.emit('stdout', '🎉 ok')
294
+ event_emitter.emit('exit', result.exit_code)
292
295
  except Exception as error:
293
296
  event_emitter.emit('error', error)
294
297
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: grasp_sdk
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
@@ -0,0 +1,17 @@
1
+ grasp_sdk/__init__.py,sha256=Rc6jzte40bC_ux1-MUOlvdnGJvprb6yI7Jvg8R1_Xjs,8227
2
+ grasp_sdk/models/__init__.py,sha256=lAlbb9tG8fsKz1fo2IVr30pGVytU5V-KblDAzZnLbVQ,2738
3
+ grasp_sdk/sandbox/chrome-stable.mjs,sha256=TxEegvv_UzDj8VkHGZvqWoMeTEq_mref2UxlJ9rw-as,11355
4
+ grasp_sdk/sandbox/chromium.mjs,sha256=5_IymhmGjLmOiRv6fOP_Zgc1yEdhBFriQ2bDe4xh33w,11554
5
+ grasp_sdk/sandbox/jsconfig.json,sha256=XkAgp68pCDDdHNpggzFb_dYB8hk3MHfJBOsUZZJXNCs,418
6
+ grasp_sdk/services/__init__.py,sha256=HqRD-WRedLwOb2gZPXPFzI-3892VT9IknKSbuDyiss8,327
7
+ grasp_sdk/services/browser.py,sha256=7pHvAFgEVwY4w_QQf_wr70F6DM4q1OntF700P217PHI,14566
8
+ grasp_sdk/services/sandbox.py,sha256=QWOvuv7RO7zU67bsKFottBSCa9039fLqw8cn5d83qAw,22018
9
+ grasp_sdk/utils/__init__.py,sha256=IQzRV-iZJXanSlaXBcgXBCcOXTVBCY6ZujxQpDTGW9w,816
10
+ grasp_sdk/utils/auth.py,sha256=M_SX3uKTjjfi6fzk384IqPvUtqt98bif22HHMgio1D4,7258
11
+ grasp_sdk/utils/config.py,sha256=txnmKQ6nxw-wvOBmr9mkZiWX7ROKwyHQLBpM_Wy9XZI,4171
12
+ grasp_sdk/utils/logger.py,sha256=k6WDmzL3cPTcQbiiTD4Q6fsDdUO_kyXQHz7nlmtv7G4,7228
13
+ grasp_sdk-0.1.2.dist-info/METADATA,sha256=yXxCCnLB2H3_y0goMWjfwYYhR87gSQ7JDLdolEHaCVI,9522
14
+ grasp_sdk-0.1.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ grasp_sdk-0.1.2.dist-info/entry_points.txt,sha256=roDjUu4JR6b1tUtRmq018mw167AbfC5zQiOtv3o6IMo,45
16
+ grasp_sdk-0.1.2.dist-info/top_level.txt,sha256=C9GL798_aP9Hgjq7UUlaGHLDfUohO2PSGYuGDV0cMx8,10
17
+ grasp_sdk-0.1.2.dist-info/RECORD,,
@@ -1,17 +0,0 @@
1
- grasp_sdk/__init__.py,sha256=7P4CFKAv1YgmbEog1s5uKMTVljSC0FDkC4ePhS0j_rE,7475
2
- grasp_sdk/models/__init__.py,sha256=lAlbb9tG8fsKz1fo2IVr30pGVytU5V-KblDAzZnLbVQ,2738
3
- grasp_sdk/sandbox/chrome-stable.mjs,sha256=8e20N7tlNRlQZ6bO3qpAdwllCBWE9cdbMN-iEW19F30,11281
4
- grasp_sdk/sandbox/chromium.mjs,sha256=DTepEfkJ75mQE_nLLRE11ZrnODpjZXw0ahAFaaFSVX4,11477
5
- grasp_sdk/sandbox/jsconfig.json,sha256=XkAgp68pCDDdHNpggzFb_dYB8hk3MHfJBOsUZZJXNCs,418
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
9
- grasp_sdk/utils/__init__.py,sha256=IQzRV-iZJXanSlaXBcgXBCcOXTVBCY6ZujxQpDTGW9w,816
10
- grasp_sdk/utils/auth.py,sha256=M_SX3uKTjjfi6fzk384IqPvUtqt98bif22HHMgio1D4,7258
11
- grasp_sdk/utils/config.py,sha256=txnmKQ6nxw-wvOBmr9mkZiWX7ROKwyHQLBpM_Wy9XZI,4171
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,,