@grasplabs/grasp
v0.4.16
Published
TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud browser environments
Maintainers
Readme
🚀 Grasp SDK
Multi-language SDK for browser automation and secure command execution in highly available and scalable cloud browser environments
Grasp SDK provides a type-safe, event-driven API for browser automation and command execution in isolated cloud environments. Available for both TypeScript/JavaScript and Python.
✨ Features
- 🌐 Cloud Browser Automation: Launch and control Chromium browsers in isolated cloud environments
- 🔗 CDP Integration: Chrome DevTools Protocol support with optimized WebSocket frame parsing
- ⚡ Command Execution: Execute shell commands with real-time monitoring and enhanced logging
- 🔒 Secure Execution: Run code in isolated E2B cloud environments
- 🧪 TypeScript Support: Full type safety and IntelliSense with improved development environment
- 🛠️ Developer Experience: Enhanced debugging capabilities and error handling
🚀 Quick Start
Installation
# Install the package
npm install @grasplabs/grasp
# or
yarn add @grasplabs/grasp
# or
pnpm add @grasplabs/graspInitialization
# Generate API key and initialize configuration
npx -y grasp-keygen <your-app-id>This will create a .env.grasp file with your credentials.
Configuration
After running grasp-keygen, you'll have a .env.grasp file with your credentials:
GRASP_APP_ID=your-app-id
GRASP_APP_KEY=your-app-keyBasic Usage
// Import types if needed
import type { GraspOptions } from '@grasplabs/grasp';
import grasp from '@grasplabs/grasp';
import { chromium } from 'playwright';
async function main() {
// Launch browser in cloud environment with enhanced options
const connection = await grasp.launchBrowser({
// API key is auto-loaded from .env.grasp
type: 'chromium', // Browser type: 'chromium' or 'chrome-stable'
headless: true, // Run in headless mode
adblock: false, // Disable adblock extension
timeout: 150000, // Connection timeout in milliseconds
keepAliveMS: 5000, // Keep browser alive for 5 sec
logLevel: 'info', // Set logging level
debug: false, // Disable debug mode for production
});
// Connect to the browser using Playwright
const browser = await chromium.connectOverCDP(connection.wsUrl, {
timeout: 150000,
});
// Create a new page and navigate
const page = await browser.newPage();
await page.goto('https://getgrasp.ai/', { waitUntil: 'domcontentloaded' });
await page.screenshot({ path: 'grasp-ai.png' });
await page.close();
// Create another page with custom content
const context = browser.contexts()[0] || await browser.newContext();
const page2 = await context.newPage();
await page2.setContent('<h1>Hello Grasp</h1>', { waitUntil: 'networkidle' });
await page2.screenshot({ path: 'hello-world.png', fullPage: true });
await page2.close();
// Clean up
await context.close();
await browser.close();
}
main();📚 API Reference
grasp.launchBrowser(options)
Launches a browser instance in the cloud environment.
Parameters:
options(object, optional):key(string): Your Grasp API key (loaded from .env.grasp by default)type(string, optional): Browser type to launch. Default: 'chromium'. Available: 'chromium', 'chrome-stable'headless(boolean, optional): Whether to run browser in headless mode. Default: trueadblock(boolean, optional): Whether to enable adblock extension. Default: falsetimeout(number, optional): Connection timeout in milliseconds. Default: 30000keepAliveMS(number, optional): Keep-alive duration in milliseconds. Default: 0logLevel(string, optional): Logging level. Available: 'debug', 'info', 'warn', 'error'. Default: 'info'debug(boolean, optional): Enable debug mode for detailed logging. Default: falselaunchTimeout(number, optional): Browser launch timeout in milliseconds. Default: 30000envs(object, optional): Environment variables for the browser processslowMo(number, optional): Slows down operations by specified milliseconds
Returns:
Promise<Connection>: Connection object with:id(string): Unique browser instance IDwsUrl(string): WebSocket URL for CDP connection (recommended)httpUrl(string): HTTP URL for CDP connection (legacy)
Example:
const connection = await grasp.launchBrowser({
// key: process.env.GRASP_APP_KEY, // Loaded from .env.grasp
type: 'chromium', // Browser type: 'chromium' or 'chrome-stable'
headless: true, // Run in headless mode
adblock: false, // Enable adblock extension
timeout: 150000, // Connection timeout
keepAliveMS: 3600000, // Keep browser alive for 1 hour
logLevel: 'info', // Logging level: 'debug', 'info', 'warn', 'error'
debug: false, // Enable debug mode
launchTimeout: 30000, // Browser launch timeout
envs: { // Environment variables
'CUSTOM_VAR': 'value'
}
});Using with Playwright
After launching a browser, connect to it using Playwright's connectOverCDP method:
import { chromium } from 'playwright';
const connection = await grasp.launchBrowser();
const browser = await chromium.connectOverCDP(connection.wsUrl, {
timeout: 150000
});
// Use browser as normal Playwright browser instance
const page = await browser.newPage();
// ... your automation code
await browser.close();🐍 Python SDK
Grasp also provides a Python SDK with the same powerful features for browser automation and command execution.
Installation
# Install from PyPI (latest: v0.1.6)
pip install grasp_sdk
# Install from source
pip install -e ./py-src
# Install with development dependencies
pip install -e "./py-src[dev]"Environment Setup
Create a .env.grasp file or set environment variables:
# Required
GRASP_KEY=your_grasp_api_key_here
# Optional
GRASP_LOG_LEVEL=info
GRASP_TIMEOUT=3600000Basic Usage
import asyncio
import os
from playwright.async_api import async_playwright
from dotenv import load_dotenv
from grasp_sdk import GraspServer
# 加载环境变量
load_dotenv(".env.grasp")
async def main():
"""演示 Grasp SDK 的基本用法"""
# 检查 API key
api_key = os.getenv('GRASP_KEY')
if not api_key:
print("⚠️ 请设置 GRASP_KEY 环境变量")
return
print("🚀 正在启动浏览器...")
# 使用 GraspServer 上下文管理器
async with GraspServer({
'timeout': 3600000, # 容器最长运行1小时
}) as connection:
print(f"WebSocket URL: {connection['ws_url']}")
# 使用 Playwright 连接到 CDP
async with async_playwright() as p:
browser = await p.chromium.connect_over_cdp(
connection['ws_url'],
timeout=150000
)
# 创建页面并访问网站
page = await browser.new_page()
await page.goto('https://getgrasp.ai/', wait_until='domcontentloaded')
await page.screenshot(path='grasp-ai.png')
# 创建自定义内容页面
page2 = await browser.new_page()
await page2.set_content('<h1>Hello Grasp</h1>', wait_until='networkidle')
await page2.screenshot(path='hello-world.png', full_page=True)
# 清理资源
await page.close()
await page2.close()
await browser.close()
print('✅ 任务完成,资源自动清理')
if __name__ == "__main__":
asyncio.run(main())Python API Reference
GraspServer(sandbox_config=None)
Main class for browser automation and command execution.
Parameters:
sandbox_config(dict, optional): Sandbox configuration overridestemplate(str): E2B template to use (default: 'python')timeout(int): Connection timeout in milliseconds (default: 30000)api_key(str): E2B API key (loaded from environment by default)
Methods:
async start(): Start the sandbox environmentasync execute_command(command, options=None): Execute shell commandasync run_script(script_path, options=None): Run script fileasync create_browser_task(): Create browser automation taskasync close(): Clean up and close connections
Example with Browser Automation:
import asyncio
from grasp_sdk import GraspServer
async def browser_example():
server = GraspServer()
try:
await server.start()
# Launch browser
browser = await server.launch_browser({
"headless": True,
"timeout": 150000
})
# Navigate and interact
await browser.navigate("https://getgrasp.ai/")
await browser.screenshot("grasp-ai.png")
# Execute JavaScript
title = await browser.evaluate("document.title")
print(f"Page title: {title}")
finally:
await server.close()
asyncio.run(browser_example())Features
- 🔒 Secure Execution: Run commands in isolated E2B cloud environments
- 🌐 Browser Automation: Control Chromium browsers with async/await
- ⚡ Real-time Communication: WebSocket-based command execution
- 🧪 Type Safety: Complete type hints with Pydantic models
- 🔄 Async/Await: Full async support for modern Python development
- 🛠️ Developer Experience: Enhanced debugging and error handling
🔗 Language Support
Grasp SDK is available in multiple languages:
- TypeScript/JavaScript:
@grasplabs/grasp(this package) - Python:
grasp_sdk(see Python SDK section above)
Both SDKs provide the same core functionality with language-specific optimizations and idioms.
📋 Release History
Python SDK (grasp_sdk)
v0.1.8 (2025-01-27)
- 🚀 Latest release with file path handling feature
- 🔧 Added support for file paths starting with '/home/user/' in run_script
- ⚡ Aligned Python SDK behavior with Node.js SDK runScript function
- 📦 Enhanced backward compatibility and flexibility
v0.1.7 (2025-01-27)
- 🚀 Configuration simplification release
- 🔧 Removed templateId configuration for simplified setup
- ⚡ Code structure optimization and cleanup
- 📦 Enhanced package stability and maintainability
v0.1.6 (2025-01-27)
- 🚀 Version synchronization release
- 🔧 Continuous improvements and optimizations
- ⚡ Enhanced stability and performance
- 📦 Updated package metadata
v0.1.5 (2025-01-27)
- 🚀 Latest release with continuous improvements
- 📚 Enhanced documentation and examples
- 🔧 Stability improvements and optimizations
- 📦 Updated package metadata
v0.1.4 (2025-01-27)
- ✅ Version synchronization with project metadata
- 📦 Updated package metadata and documentation
- 🔧 Enhanced build and publishing workflow
- 📚 Improved README with version badges and installation instructions
v0.1.0 (2025-01-27)
- 🎉 Initial release of Python SDK
- 🌐 Core browser automation functionality
- 🔒 Secure command execution in E2B environments
- 🧪 Full async/await support with type hints
- 📖 Complete API compatibility with TypeScript version
TypeScript/JavaScript SDK (@grasplabs/grasp)
v0.1.3 (2025-01-27)
- 🚀 Latest release with enhanced stability
- 📦 Updated package metadata and build process
- 🔧 Improved configuration and error handling
- 📚 Enhanced documentation and examples
Latest Updates (v0.1.1+)
- 🚀 Enhanced browser automation capabilities with new configuration options
- ⚡ Improved CDP integration and WebSocket frame parsing
- 🛠️ Better developer experience with enhanced debugging and logging
- 🔧 Added new parameters:
keepAliveMS: Configure browser keep-alive durationlogLevel: Granular logging control ('debug', 'info', 'warn', 'error')adblock: Built-in adblock extension supportlaunchTimeout: Configurable browser launch timeoutenvs: Environment variables for browser process
- 🎯 Optimized performance and error handling
- 📚 Updated documentation with comprehensive parameter examples
- 🔄 Enhanced graceful shutdown and resource cleanup
