### Install Dependencies and Start Dev Server Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md Installs project dependencies using npm and starts the website development server. Use `npm ci` for a clean install based on the lockfile. ```bash npm i # Or `npm ci` if you don't want to change the lockfile npm start # Start website dev server npm run build # Build everything ``` -------------------------------- ### Website Development and Build Commands Source: https://github.com/alibaba/page-agent/blob/main/packages/website/AGENTS.md Use these npm commands from the repository root to start the development server or build the website. ```bash npm start # Dev server (from root) npm run build:website # Build website (from root) ``` -------------------------------- ### Install Page Agent with NPM Source: https://github.com/alibaba/page-agent/blob/main/README.md Install the Page Agent package using npm. This is the recommended approach for programmatic usage. ```bash npm install page-agent ``` -------------------------------- ### Serve Local IIFE for Testing Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md Starts a local development server to serve the IIFE script for Page-Agent. The script will auto-rebuild on changes. Access it at http://localhost:5174/page-agent.demo.js. ```bash npm run dev:demo # Serving IIFE with auto rebuild at http://localhost:5174/page-agent.demo.js ``` -------------------------------- ### Install Page Agent Core Types Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Install the type definitions for the Page Agent core library as a development dependency. ```bash npm install @page-agent/core --save-dev ``` -------------------------------- ### Configure LLM API via Environment Variables Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md Set up your local environment to use a custom LLM API by creating a `.env` file in the repository root. This example shows configuration for a generic LLM provider. ```env LLM_MODEL_NAME=gpt-5.2 LLM_API_KEY=your-api-key LLM_BASE_URL=https://api.your-llm-provider.com/v1 ``` -------------------------------- ### Install MCP Server for Claude Desktop Source: https://github.com/alibaba/page-agent/blob/main/packages/mcp/README.md Add this JSON configuration to your Claude Desktop settings to enable the MCP server. Ensure your LLM API details are correctly set. ```json { "mcpServers": { "page-agent": { "command": "npx", "args": ["-y", "@page-agent/mcp"], "env": { "LLM_BASE_URL": "https://dashscope.aliyuncs.com/compatible-mode/v1", "LLM_API_KEY": "sk-xxx", "LLM_MODEL_NAME": "qwen3.5-plus" } } } } ``` -------------------------------- ### PageController and PageAgent Communication Examples Source: https://github.com/alibaba/page-agent/blob/main/AGENTS.md Illustrates asynchronous communication patterns between PageAgent and PageController for DOM operations and state retrieval. ```typescript // PageAgent delegates DOM operations to PageController await this.pageController.updateTree() await this.pageController.clickElement(index) await this.pageController.inputText(index, text) await this.pageController.scroll({ down: true, numPages: 1 }) ``` ```typescript // PageController exposes state via async methods const simplifiedHTML = await this.pageController.getSimplifiedHTML() const pageInfo = await this.pageController.getPageInfo() ``` -------------------------------- ### Configure Ollama for LLM API Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md Example configuration for using Ollama as the LLM API. Ensure Ollama is running and accessible at the specified base URL. This configuration is tested with Ollama 0.15 and a qwen3:14b model. ```env LLM_BASE_URL="http://localhost:11434/v1" LLM_API_KEY="NA" LLM_MODEL_NAME="qwen3:14b" ``` -------------------------------- ### Development Commands for Page Agent Monorepo Source: https://github.com/alibaba/page-agent/blob/main/AGENTS.md Common npm commands for managing the Page Agent monorepo, including starting the dev server, building packages, type checking, testing, and linting. ```bash npm start # Start website dev server npm run build # Build all packages npm run build:libs # Build all libraries npm run build:ext # Build and zip the extension package npm run typecheck # Typecheck all packages npm run test # Run unit tests across all workspaces npm run lint # ESLint ``` -------------------------------- ### Execute Task with Page Agent Extension Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Execute a task using the Page Agent extension after confirming its injection. This example demonstrates calling the `execute` method with task instructions and configuration, including API keys and callbacks for status and activity changes. ```typescript if (await waitForExtension()) { const result = await window.PAGE_AGENT_EXT!.execute('Click the login button', { baseURL: 'https://api.openai.com/v1', apiKey: 'your-api-key', model: 'gpt-5.2', onStatusChange: (status) => console.log('Status:', status), onActivity: (activity) => console.log('Activity:', activity), }) console.log('Result:', result) } ``` -------------------------------- ### Handle Page Agent Extension Connection Source: https://github.com/alibaba/page-agent/blob/main/packages/mcp/src/launcher.html This script checks for the Page Agent browser extension, attempts to open the hub, and displays installation instructions if the extension is missing or outdated. It handles internationalization for Chinese. ```javascript const EXT_ID = '__EXT_ID__' const wsPort = __WS_PORT__ const zh = { connecting_title: '正在连接 Page Agent', connecting_sub: '正在浏览器中打开 Hub…', install_title: '需要安装浏览器插件', install_sub: 'Page Agent 需要安装最新版浏览器插件才能运行。', install_btn: '从 Chrome 应用商店安装', tip_outdated: '如果插件版本过旧,请更新到最新版本。', tip_other_browser: '如果该浏览器中未安装插件,请从装有插件的浏览器打开此页面。', tip_refresh: '安装或更新后,请刷新此页面。', link_docs: '文档', link_issues: '问题反馈', } if (/^zh\b/i.test(navigator.language)) { document.querySelectorAll('body [data-i18n]').forEach((el) => { const key = el.getAttribute('data-i18n') if (zh[key]) el.textContent = zh[key] }) } const showInstall = () => { document.getElementById('connecting').style.display = 'none' document.getElementById('install').classList.add('show') } try { if (!globalThis.chrome?.runtime?.sendMessage) { showInstall() } else { chrome.runtime.sendMessage(EXT_ID, { type: 'OPEN_HUB', wsPort }, (response) => { if (chrome.runtime.lastError || !response?.ok) showInstall() }) } } catch { showInstall() } ``` -------------------------------- ### Add shadcn/ui or Magic UI Component Source: https://github.com/alibaba/page-agent/blob/main/packages/website/AGENTS.md Run these commands from the `packages/website/` directory to add new UI components from shadcn/ui or Magic UI. ```bash cd packages/website npx shadcn@latest add npx shadcn@latest add "@magicui/" ``` -------------------------------- ### Extension Development Commands Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md Commands to run the development server for the browser extension and to build the extension for production. ```bash npm run dev:ext npm run build:ext ``` -------------------------------- ### Include Page Agent via CDN Source: https://github.com/alibaba/page-agent/blob/main/README.md Fastest way to try Page Agent. This demo CDN uses a free testing LLM API. Add '?autoInit=false' to load the script without automatic agent creation. ```html ``` -------------------------------- ### Initialize and Execute with Page Agent Source: https://github.com/alibaba/page-agent/blob/main/README.md Import and instantiate PageAgent with your API key and model configuration. Then, use the execute method to perform actions on the web page. ```javascript import { PageAgent } from 'page-agent' const agent = new PageAgent({ model: 'qwen3.5-plus', baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1', apiKey: 'YOUR_API_KEY', language: 'en-US', }) await agent.execute('Click the login button') ``` -------------------------------- ### MCP Server Development Commands Source: https://github.com/alibaba/page-agent/blob/main/packages/mcp/README.md Commands for developing the extension and running the MCP server with the inspector. ```bash npm run dev:ext ``` ```bash npx @modelcontextprotocol/inspector node packages/mcp/src/index.js ``` -------------------------------- ### Initialize Google Analytics Data Layer Source: https://github.com/alibaba/page-agent/blob/main/packages/website/index.html Sets up the Google Analytics data layer and configures the tracking ID. This should be included before other gtag commands. ```javascript window.dataLayer = window.dataLayer || [] function gtag() { dataLayer.push(arguments) } gtag('js', new Date()) gtag('config', 'G-HCGRJTN3HM') ``` -------------------------------- ### Documentation Page Structure Source: https://github.com/alibaba/page-agent/blob/main/packages/website/AGENTS.md Follow this structure for creating new documentation pages: `src/pages/docs/
//page.tsx`. Ensure consistency in slug usage across file paths, imports, routes, and links. ```bash src/ └── pages/ └── docs/ ├── index.tsx # Docs route switch ├── Layout.tsx # Sidebar navigation └── [section]/[topic]/page.tsx ``` -------------------------------- ### Configure wouter Router with Base Path Source: https://github.com/alibaba/page-agent/blob/main/packages/website/AGENTS.md Set up the wouter router with a base path for deployment on GitHub Pages. Ensure Header and Footer components are outside the Switch for root context. ```tsx import { Router } from "wouter"; import PagesRouter from "./router"; // main.tsx ``` -------------------------------- ### PAGE_AGENT_EXT.execute(task, config) Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Executes a single agent task with the provided description and configuration. This is the primary method for initiating agent operations. ```APIDOC #### `PAGE_AGENT_EXT.execute(task, config)` Execute one agent task. Parameters: | Name | Type | Required | Description | | -------- | --------------- | -------- | ------------------------------------ | | `task` | `string` | Yes | Task description | | `config` | `ExecuteConfig` | Yes | LLM settings, options, and callbacks | Returns: `Promise` ``` -------------------------------- ### MCP Server Architecture Overview Source: https://github.com/alibaba/page-agent/blob/main/packages/mcp/README.md Illustrates the communication flow between the AI client, the Node.js MCP server, and the browser extension's hub tab. ```text ┌──────────────┐ stdio ┌──────────────────┐ WebSocket ┌──────────────┐ │ Claude / │◄────────►│ @page-agent/mcp │◄────────────►│ Hub tab │ │ Copilot │ (MCP) │ (Node.js) │ (localhost) │ (extension) │ └──────────────┘ └──────────────────┘ └──────┬───────┘ │ │ │ HTTP │ useAgent ▼ ▼ ┌──────────────────┐ ┌──────────────┐ │ Launcher page │ │ MultiPage │ │ (localhost:PORT) │ │ Agent │ └──────────────────┘ └──────────────┘ ``` -------------------------------- ### Running Tests with npm Source: https://github.com/alibaba/page-agent/blob/main/AGENTS.md Use these commands to run tests across all packages or a single package. The 'npx vitest' command is useful for running tests in watch mode within a specific package. ```bash npm test ``` ```bash npm test -w @page-agent/llms ``` ```bash cd packages/llms && npx vitest ``` -------------------------------- ### SPA Routing on GitHub Pages Source: https://github.com/alibaba/page-agent/blob/main/packages/website/AGENTS.md To enable Single Page Application routing on GitHub Pages, copy `index.html` into every route directory. Add new routes to the `SPA_ROUTES` array in `vite.config.js`. ```javascript // vite.config.js // Add new routes to the SPA_ROUTES array ``` -------------------------------- ### Browser Use License and Copyright Source: https://github.com/alibaba/page-agent/blob/main/README.md This block details the license and copyright information for the browser-use project, which PageAgent builds upon. It is provided for acknowledgment purposes. ```plaintext DOM processing components and prompt are derived from browser-use: Browser Use Copyright (c) 2024 Gregor Zunic Licensed under the MIT License We gratefully acknowledge the browser-use project and its contributors for their excellent work on web automation and DOM interaction patterns that helped make this project possible. ``` -------------------------------- ### Extension Version Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Access the extension's version string to perform capability checks before interacting with the main API. ```APIDOC ## Global API After token match, the extension injects APIs into `window`. ### `window.PAGE_AGENT_EXT_VERSION` Extension version string (for capability checks before using the main API). ``` -------------------------------- ### Execute Task Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Executes a given instruction on the current page using the Page Agent extension. It allows for configuration of the API endpoint, model, and various callbacks for status and activity updates. ```APIDOC ## execute ### Description Executes a natural language instruction on the current web page. ### Method Signature `window.PAGE_AGENT_EXT.execute(instruction: string, config: ExecuteConfig): Promise` ### Parameters #### instruction - **instruction** (string) - Required - The natural language instruction to execute. #### config - **config** (ExecuteConfig) - Required - Configuration object for the execution. - **baseURL** (string) - Required - The base URL for the API endpoint. - **model** (string) - Required - The AI model to use for execution. - **apiKey** (string) - Optional - The API key for authentication. - **systemInstruction** (string) - Optional - A system-level instruction to guide the AI. - **includeInitialTab** (boolean) - Optional - Whether to include the initial tab in the execution context. Defaults to true. - **experimentalIncludeAllTabs** (boolean) - Optional - Experimental feature to include all tabs. - **onStatusChange** (function) - Optional - Callback function triggered when the agent's status changes. - **onActivity** (function) - Optional - Callback function triggered when the agent performs an activity. - **onHistoryUpdate** (function) - Optional - Callback function triggered when the execution history is updated. ### Request Example ```typescript const result = await window.PAGE_AGENT_EXT!.execute( 'Fill in the email field with test@example.com and click Submit', { baseURL: 'https://api.openai.com/v1', apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-5.2', includeInitialTab: false, onStatusChange: (status) => console.log(status), onActivity: (activity) => console.log(activity), } ) ``` ### Response #### Success Response (Promise) - Returns a Promise that resolves with the `ExecutionResult` object upon successful completion of the instruction. ``` -------------------------------- ### Bookmarklet to Load Page-Agent Source: https://github.com/alibaba/page-agent/blob/main/docs/developer-guide.md A JavaScript bookmarklet to dynamically load the Page-Agent IIFE script into the current webpage. It injects a script tag and logs a message upon successful loading. The `t` parameter is a random number to help bypass caching. ```javascript javascript:(function(){var s=document.createElement('script');s.src=`http://localhost:5174/page-agent.demo.js?lang=en-US&t=${Math.random()}`;s.onload=()=>console.log(%27PageAgent ready!%27);document.head.appendChild(s);})(); ``` -------------------------------- ### Execute Task with Page Agent Extension Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Use this to execute a task with the Page Agent Extension. Configure options like API endpoint, model, and callbacks for status and activity changes. The `includeInitialTab` option can be set to `false` to exclude the current tab from the execution context. ```typescript const result = await window.PAGE_AGENT_EXT!.execute( 'Fill in the email field with test@example.com and click Submit', { baseURL: 'https://api.openai.com/v1', apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-5.2', includeInitialTab: false, // Optional: exclude current tab onStatusChange: (status) => console.log(status), onActivity: (activity) => console.log(activity), } ) ``` -------------------------------- ### PageAgent Loading Spinner Styles Source: https://github.com/alibaba/page-agent/blob/main/packages/website/index.html CSS for the PageAgent loading spinner, including layout, background gradients, and a pulsating opacity animation. ```css #sk { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: linear-gradient(135deg, #eff6ff, #f5f3ff); } @media (prefers-color-scheme: dark) { #sk { background: linear-gradient(135deg, #111827, #1f2937); } } .sk-text { font: 400 14px/1 system-ui, sans-serif; color: #94a3b8; animation: skf 2s ease-in-out infinite; } @keyframes skf { 0%, 100% { opacity: 0.6; } 50% { opacity: 0.3; } } ``` -------------------------------- ### Main Namespace Object Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md The main namespace object for interacting with the Page Agent extension's functionalities. ```APIDOC ### `window.PAGE_AGENT_EXT` Main namespace object. ``` -------------------------------- ### Import Core Types for Page Agent Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Import necessary types for agent configuration and results from the `@page-agent/core` package. This is required for defining the `ExecuteConfig` and understanding the return types of agent operations. ```typescript import type { AgentActivity, AgentStatus, ExecutionResult, HistoricalEvent } from '@page-agent/core' ``` -------------------------------- ### Page Agent ExecuteConfig Interface Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Defines the configuration object for executing an agent task. It includes LLM settings, callbacks for status and activity updates, and options for controlling tab scope. ```typescript export interface ExecuteConfig { baseURL: string model: string apiKey?: string // Global system-level instructions for the agent. // Equivalent to AgentConfig.instructions.system. systemInstruction?: string // Include the initial tab where page JS starts. Default: true. includeInitialTab?: boolean // Control all unpinned tabs in the window instead of only the tab group. // When enabled, agent sees and can switch to every non-pinned tab. // Default: false. Experimental. experimentalIncludeAllTabs?: boolean onStatusChange?: (status: AgentStatus) => void onActivity?: (activity: AgentActivity) => void onHistoryUpdate?: (history: HistoricalEvent[]) => void } ``` -------------------------------- ### Page Agent Extension Type Declarations Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md These type declarations are necessary if you are not importing `@page-agent/core`. They define the `ExecuteConfig` interface and augment the global `Window` interface with Page Agent Extension properties. ```typescript import type { AgentActivity, AgentStatus, ExecutionResult, HistoricalEvent } from '@page-agent/core' interface ExecuteConfig { baseURL: string model: string apiKey?: string systemInstruction?: string includeInitialTab?: boolean experimentalIncludeAllTabs?: boolean onStatusChange?: (status: AgentStatus) => void onActivity?: (activity: AgentActivity) => void onHistoryUpdate?: (history: HistoricalEvent[]) => void } declare global { interface Window { PAGE_AGENT_EXT_VERSION?: string PAGE_AGENT_EXT?: { version: string execute: Execute stop: () => void } } } ``` -------------------------------- ### Set Page Agent Extension Auth Token Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Set the authorization token in local storage to allow page JavaScript to call the extension API. This token is obtained from the extension's side panel. ```typescript localStorage.setItem('PageAgentExtUserAuthToken', 'your-token') ``` -------------------------------- ### Wait for Page Agent Extension Injection Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md A utility function to asynchronously wait for the Page Agent extension to be injected into the window object, with a configurable timeout. ```typescript async function waitForExtension(timeout = 1000): Promise { const start = Date.now() while (Date.now() - start < timeout) { if (window.PAGE_AGENT_EXT) return true await new Promise((r) => setTimeout(r, 100)) } return false } ``` -------------------------------- ### AgentActivity Union Type Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Defines the structure for events representing agent activity. This includes thinking, executing tools, and handling errors. ```typescript type AgentActivity = | { type: 'thinking' } | { type: 'executing'; tool: string; input: unknown } | { type: 'executed'; tool: string; input: unknown; output: string; duration: number } | { type: 'retrying'; attempt: number; maxAttempts: number } | { type: 'error'; message: string } ``` -------------------------------- ### Update HTML Lang and Loading Text Source: https://github.com/alibaba/page-agent/blob/main/packages/website/index.html Dynamically sets the HTML document's language attribute based on localStorage or browser settings, and updates loading text accordingly. Listens for storage events to re-apply changes. ```javascript const updateHtmlLang = () => { const lang = localStorage.getItem('i18nextLng') || navigator.language || 'zh-CN' document.documentElement.lang = lang const el = document.getElementById('sk-text') if (el) el.textContent = lang.startsWith('zh') ? '加载中...' : 'Loading...' } updateHtmlLang() window.addEventListener('storage', updateHtmlLang) ``` -------------------------------- ### ExecutionResult Interface Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Defines the structure of the result returned after an agent task completes. Includes success status, data, and the history of events. ```typescript interface ExecutionResult { success: boolean data: string history: HistoricalEvent[] } ``` -------------------------------- ### Page Agent Execute Function Type Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Defines the type for the `execute` function, which takes a task description and an `ExecuteConfig` object, returning a promise that resolves to an `ExecutionResult`. ```typescript export type Execute = (task: string, config: ExecuteConfig) => Promise ``` -------------------------------- ### AgentStatus Enum Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Represents the possible states of an agent during execution. Use this to monitor the agent's lifecycle. ```typescript type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'stopped' ``` -------------------------------- ### PAGE_AGENT_EXT.stop() Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Stops the currently running agent task. This can be used to interrupt an ongoing operation. ```APIDOC #### `PAGE_AGENT_EXT.stop()` Stop the current task. ``` -------------------------------- ### Stop Task Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Stops the currently running task managed by the Page Agent extension. ```APIDOC ## stop ### Description Stops the currently executing task. ### Method Signature `window.PAGE_AGENT_EXT.stop(): void` ### Usage Example ```typescript window.PAGE_AGENT_EXT!.stop() ``` ``` -------------------------------- ### Stop Current Task with Page Agent Extension Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Call this method to immediately stop any currently running task managed by the Page Agent Extension. ```typescript window.PAGE_AGENT_EXT!.stop() ``` -------------------------------- ### HistoricalEvent Union Type Source: https://github.com/alibaba/page-agent/blob/main/packages/extension/docs/extension_api.md Represents a historical record of agent actions and observations. Useful for debugging and auditing agent behavior. ```typescript type HistoricalEvent = | { type: 'step'; stepIndex: number; reflection: AgentReflection; action: Action } | { type: 'observation'; content: string } | { type: 'user_takeover' } | { type: 'retry'; message: string; attempt: number; maxAttempts: number } | { type: 'error'; message: string; rawResponse?: unknown } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.