🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
Fix: cdp browser (#2920)
Puzhen Zhang6a8d58cfa969
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.tsindex b174a12e3..38120ff9c 100644--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts@@ -50,20 +50,28 @@ export class HybridBrowserSession {// Handle existing pagesconst pages = this.context.pages();if (pages.length > 0) {- // Map existing pages+ // Map existing pages - for CDP, only use pages with about:blank URL+ let availablePageFound = false;for (const page of pages) {- const tabId = this.generateTabId();- this.pages.set(tabId, page);- if (!this.currentTabId) {- this.currentTabId = tabId;+ const pageUrl = page.url();+ // In CDP mode, only consider pages with about:blank as available+ if (pageUrl === 'about:blank') {+ const tabId = this.generateTabId();+ this.pages.set(tabId, page);+ if (!this.currentTabId) {+ this.currentTabId = tabId;+ availablePageFound = true;+ }}}++ // If no available blank pages found in CDP mode, we cannot create new ones+ if (!availablePageFound) {+ throw new Error('No available blank tabs found in CDP mode. The frontend should have pre-created blank tabs.');+ }} else {- // Create initial page if none exist- const initialPage = await this.context.newPage();- const initialTabId = this.generateTabId();- this.pages.set(initialTabId, initialPage);- this.currentTabId = initialTabId;+ // In CDP mode, newPage is not supported+ throw new Error('No pages available in CDP mode and newPage() is not supported. Ensure the frontend has pre-created blank tabs.');}} else {// Original launch logic@@ -626,18 +634,39 @@ export class HybridBrowserSession {throw new Error('Browser context not initialized');}-const navigationStart = Date.now();- // Create a new page (tab)- const newPage = await this.context.newPage();+ // In CDP mode, find an available blank tab instead of creating new page+ let newPage: Page | null = null;+ let newTabId: string | null = null;- // Generate tab ID for the new page- const newTabId = this.generateTabId();- this.pages.set(newTabId, newPage);+ const browserConfig = this.configLoader.getBrowserConfig();+ if (browserConfig.connectOverCdp) {+ // CDP mode: find an available blank tab+ const allPages = this.context.pages();+ for (const page of allPages) {+ const pageUrl = page.url();+ // Check if this page is not already tracked and is blank+ const isTracked = Array.from(this.pages.values()).includes(page);+ if (!isTracked && pageUrl === 'about:blank') {+ newPage = page;+ newTabId = this.generateTabId();+ this.pages.set(newTabId, newPage);+ break;+ }+ }++ if (!newPage || !newTabId) {+ throw new Error('No available blank tabs in CDP mode. Frontend should create more blank tabs when half are used.');+ }+ } else {+ // Non-CDP mode: create new page as usual+ newPage = await this.context.newPage();+ newTabId = this.generateTabId();+ this.pages.set(newTabId, newPage);+ }// Set up page properties- const browserConfig = this.configLoader.getBrowserConfig();newPage.setDefaultNavigationTimeout(browserConfig.navigationTimeout);newPage.setDefaultTimeout(browserConfig.navigationTimeout);diff --git a/hatch_build_npm.py b/hatch_build_npm.pyindex 81d5ff8e3..ba304e9f1 100644--- a/hatch_build_npm.py+++ b/hatch_build_npm.py@@ -11,7 +11,6 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-# !/usr/bin/env python3"""Hatch build hook for building TypeScript dependencies inhybrid_browser_toolkit.@@ -20,27 +19,28 @@ This script runs during package building to compile TypeScript code.It gracefully handles cases where Node.js/npm is not available."""+import json+import reimport subprocessfrom pathlib import Path+from typing import Optional, Tuplefrom hatchling.builders.hooks.plugin.interface import BuildHookInterfaceclass NpmBuildHook(BuildHookInterface):- """Hatch build hook for TypeScript compilation."""+ r"""Hatch build hook for TypeScript compilation."""PLUGIN_NAME = "npm-build"def initialize(self, version, build_data):- """Initialize the build hook and run npm build."""+ r"""Initialize the build hook and run npm build."""self.build_npm_dependencies()def finalize(self, version, build_data, artifact_path):- """Finalize the build - ensure TypeScript was built."""+ r"""Finalize the build - ensure TypeScript was built."""base_dir = Path(self.root)- ts_dir = (- base_dir / "camel" / "toolkits" / "hybrid_browser_toolkit" / "ts"- )+ ts_dir = self._get_ts_directory(base_dir)dist_dir = ts_dir / "dist"if dist_dir.exists():@@ -48,157 +48,237 @@ class NpmBuildHook(BuildHookInterface):else:print("Warning: TypeScript build artifacts not found")- def build_npm_dependencies(self):- """Build TypeScript dependencies during wheel/sdist creation."""- base_dir = Path(self.root)- ts_dir = (+ def _get_ts_directory(self, base_dir: Path) -> Path:+ r"""Get the TypeScript directory path."""+ return (base_dir / "camel" / "toolkits" / "hybrid_browser_toolkit" / "ts")- print(f"Checking TypeScript directory: {ts_dir}")+ def _parse_version(self, version_str: str) -> Tuple[int, int, int]:+ r"""Parse version string into major, minor, patch numbers."""+ version_str = version_str.strip().lstrip('v')+ match = re.match(r'(\d+)\.(\d+)\.(\d+)', version_str)+ if match:+ return tuple(map(int, match.groups()))+ return (0, 0, 0)++ def _check_version_requirement(self, current: str, required: str) -> bool:+ r"""Check if current version meets requirement."""+ if required.startswith('>='):+ required_version = self._parse_version(required[2:])+ current_version = self._parse_version(current)+ return current_version >= required_version+ elif required.startswith('^'):+ required_version = self._parse_version(required[1:])+ current_version = self._parse_version(current)+ return (+ current_version[0] == required_version[0]+ and current_version >= required_version+ )+ return True- if not ts_dir.exists():- print("TypeScript directory not found, skipping npm build")- return+ def _get_package_requirements(self, ts_dir: Path) -> Optional[dict]:+ r"""Get Node.js/npm version requirements from package.json or+ package-lock.json.+ """+ package_json = ts_dir / "package.json"+ package_lock = ts_dir / "package-lock.json"- # Check if dist already exists and is not empty- dist_dir = ts_dir / "dist"- if dist_dir.exists() and any(dist_dir.iterdir()):- print(- "TypeScript already built (dist directory exists), "- "skipping build"- )- return+ try:+ if package_json.exists():+ with open(package_json, 'r') as f:+ data = json.load(f)+ if 'engines' in data:+ return data['engines']++ if package_lock.exists():+ with open(package_lock, 'r') as f:+ data = json.load(f)+ for pkg_name, pkg_data in data.get('packages', {}).items():+ if not pkg_name and 'engines' in pkg_data:+ return pkg_data['engines']++ except (json.JSONDecodeError, IOError) as e:+ print(f"Warning: Could not read package requirements: {e}")++ return None++ def _check_node_npm_versions(+ self, ts_dir: Path+ ) -> Tuple[Optional[str], Optional[str], bool]:+ r"""Check Node.js and npm versions against requirements."""+ node_version = None+ npm_version = None+ versions_ok = Truetry:- # Check if npm is availableresult = subprocess.run(- ["npm", "--version"],+ ["node", "--version"],check=True,capture_output=True,text=True,+ timeout=30,)- print(f"Found npm version: {result.stdout.strip()}")+ node_version = result.stdout.strip()+ print(f"Found Node.js version: {node_version}")+ except (FileNotFoundError, subprocess.CalledProcessError):+ print("Warning: Node.js not found in PATH")+ return None, None, False- # Check if Node.js is available+ try:result = subprocess.run(- ["node", "--version"],+ ["npm", "--version"],check=True,capture_output=True,text=True,+ timeout=30,)- print(f"Found Node.js version: {result.stdout.strip()}")-+ npm_version = result.stdout.strip()+ print(f"Found npm version: {npm_version}")+ except (FileNotFoundError, subprocess.CalledProcessError):+ print("Warning: npm not found in PATH")+ return node_version, None, False++ requirements = self._get_package_requirements(ts_dir)+ if requirements:+ if 'node' in requirements:+ node_req = requirements['node']+ if not self._check_version_requirement(node_version, node_req):+ print(+ f"Warning: Node.js version {node_version} "+ f"does not meet requirement {node_req}"+ )+ versions_ok = False+ else:+ print(+ f"✓ Node.js version {node_version} meets "+ f"requirement {node_req}"+ )++ if 'npm' in requirements:+ npm_req = requirements['npm']+ if not self._check_version_requirement(npm_version, npm_req):+ print(+ f"Warning: npm version {npm_version} does not "+ f"meet requirement {npm_req}"+ )+ versions_ok = False+ else:+ print(+ f"✓ npm version {npm_version} meets "+ f"requirement {npm_req}"+ )++ return node_version, npm_version, versions_ok++ def _run_npm_build_process(self, ts_dir: Path, dist_dir: Path) -> bool:+ r"""Run the npm build process."""+ try:print("Installing npm dependencies...")- # Use npm install to ensure- # devDependencies like TypeScript are installedsubprocess.run(- ["npm", "install"], cwd=ts_dir, check=True, text=True+ ["npm", "install"],+ cwd=ts_dir,+ check=True,+ text=True,+ timeout=300,)print("Building TypeScript...")subprocess.run(- ["npm", "run", "build"], cwd=ts_dir, check=True, text=True+ ["npm", "run", "build"],+ cwd=ts_dir,+ check=True,+ text=True,+ timeout=300,)- # Verify build output+ print("Installing Playwright browsers...")+ try:+ subprocess.run(+ ["npx", "playwright", "install"],+ cwd=ts_dir,+ check=True,+ text=True,+ timeout=600,+ )+ print("Playwright browsers installed successfully")+ except subprocess.CalledProcessError as e:+ print(f"Warning: Playwright browser installation failed: {e}")+ print(+ "Users will need to run 'npx playwright install' manually"+ )+ print(" npx playwright install")+index_js = dist_dir / "index.js"if index_js.exists():print("TypeScript build completed successfully")+ return Trueelse:print("Warning: TypeScript build may have failed (index.js ""not found)")-- except FileNotFoundError:- print("Warning: npm or node not found in PATH")- print("Installing without TypeScript support")- print(- "To use hybrid_browser_toolkit, please install Node.js and "- "run:"- )- print(f" cd {ts_dir}")- print(" npm install && npm run build")+ return Falseexcept subprocess.CalledProcessError as e:print(f"Warning: TypeScript build failed with error: {e}")print("Installing without TypeScript support")print("This may affect hybrid_browser_toolkit functionality")+ return Falseexcept Exception as e:print(f"Warning: Unexpected error during TypeScript build: {e}")print("Installing without TypeScript support")+ return False+ def _print_manual_instructions(self, ts_dir: Path):+ r"""Print manual installation instructions."""+ print("Installing without TypeScript support")+ print("To use hybrid_browser_toolkit, please install Node.js and run:")+ print(f" cd {ts_dir}")+ print(" npm install && npm run build")+ print(" npx playwright install")-def build_npm_dependencies_standalone():- """Standalone function for testing purposes."""- base_dir = Path(__file__).parent- ts_dir = base_dir / "camel" / "toolkits" / "hybrid_browser_toolkit" / "ts"-- print(f"Checking TypeScript directory: {ts_dir}")-- if not ts_dir.exists():- print("TypeScript directory not found, skipping npm build")- return-- # Check if dist already exists and is not empty- dist_dir = ts_dir / "dist"- if dist_dir.exists() and any(dist_dir.iterdir()):- print(- "TypeScript already built (dist directory exists), skipping "- "build"- )- return+ def build_npm_dependencies(self):+ r"""Build TypeScript dependencies during wheel/sdist creation."""+ base_dir = Path(self.root)+ ts_dir = self._get_ts_directory(base_dir)- try:- # Check if npm is available- result = subprocess.run(- ["npm", "--version"], check=True, capture_output=True, text=True- )- print(f"Found npm version: {result.stdout.strip()}")+ print(f"Checking TypeScript directory: {ts_dir}")- # Check if Node.js is available- result = subprocess.run(- ["node", "--version"], check=True, capture_output=True, text=True- )- print(f"Found Node.js version: {result.stdout.strip()}")+ if not ts_dir.exists():+ print("TypeScript directory not found, skipping npm build")+ return- print("Installing npm dependencies...")- # Use npm install to ensure- # devDependencies like TypeScript are installed- subprocess.run(["npm", "install"], cwd=ts_dir, check=True, text=True)+ dist_dir = ts_dir / "dist"+ if dist_dir.exists() and any(dist_dir.iterdir()):+ print(+ "TypeScript already built (dist directory exists), "+ "skipping build"+ )+ return- print("Building TypeScript...")- subprocess.run(- ["npm", "run", "build"], cwd=ts_dir, check=True, text=True+ node_version, npm_version, versions_ok = self._check_node_npm_versions(+ ts_dir)- # Verify build output- index_js = dist_dir / "index.js"- if index_js.exists():- print("TypeScript build completed successfully")- else:- print(- "Warning: TypeScript build may have failed (index.js not "- "found)"- )+ if node_version is None or npm_version is None:+ print("Warning: npm or node not found in PATH")+ self._print_manual_instructions(ts_dir)+ return- except FileNotFoundError:- print("Warning: npm or node not found in PATH")- print("Installing without TypeScript support")- print("To use hybrid_browser_toolkit, please install Node.js and run:")- print(f" cd {ts_dir}")- print(" npm install && npm run build")+ if not versions_ok:+ print("Warning: Node.js/npm version requirements not met")+ print("Continuing anyway, but build may fail")- except subprocess.CalledProcessError as e:- print(f"Warning: TypeScript build failed with error: {e}")- print("Installing without TypeScript support")- print("This may affect hybrid_browser_toolkit functionality")+ self._run_npm_build_process(ts_dir, dist_dir)- except Exception as e:- print(f"Warning: Unexpected error during TypeScript build: {e}")- print("Installing without TypeScript support")++def build_npm_dependencies_standalone():+ r"""Standalone function for testing purposes."""+ hook = NpmBuildHook(None, None)+ hook.root = Path(__file__).parent.absolute()+ hook.build_npm_dependencies()if __name__ == "__main__":