Compare commits

...

35 Commits

Author SHA1 Message Date
Simon 299a5b2075 chore(version): bump version to 1.0.0 2026-01-22 15:38:21 +08:00
Simon 785a2d194e chore(version): bump version to 1.0.0-beta.5 2026-01-22 15:17:19 +08:00
Simon 391e70dca4 feat: update historical event types 2026-01-22 15:16:15 +08:00
Simon 3ffcd6482d refactor: rename AgentStep to AgentStepEventErrorEvent to AgentErrorEvent 2026-01-22 14:59:35 +08:00
Simon 0cd04db40f fix: rebuild lock 2026-01-22 14:12:37 +08:00
Simon 23f1818503 docs: update README for clarity and integration details 2026-01-21 20:15:33 +08:00
Simon 5fdb49fecb fix(sync-version): update version check to use pkgJson.version 2026-01-21 19:20:23 +08:00
Simon fe1893a382 fix: rebuild lock 2026-01-21 19:04:26 +08:00
Simon 8c1c1ed9fe fix: correct prettier extension recommendation 2026-01-21 19:01:27 +08:00
Simon 6cbb4e99c4 chore(version): bump version to 1.0.0-beta.4 2026-01-21 18:55:07 +08:00
Simon 34ce56b446 feat(PageController): make sure page is indexed before calling actions on elements 2026-01-21 18:54:17 +08:00
Simon 23ec4602c2 feat: export types from './types' in PageAgentCore 2026-01-21 17:26:31 +08:00
Simon 536e5076da chore(version): bump version to 1.0.0-beta.3 2026-01-21 17:00:08 +08:00
Simon 81807e17ca feat: add stepIndex to history events 2026-01-21 16:59:22 +08:00
Simon 6944bedf85 chore: correct formatting in markdown 2026-01-21 01:30:27 +08:00
Simon 897b919044 chore(version): bump version to 1.0.0-beta.2 2026-01-21 01:23:42 +08:00
Simon 3a3bb0e58c fix: use spaces for JSON formatting in version sync script 2026-01-21 01:23:07 +08:00
Simon bc7ccf47ff fix: handle version in sync script 2026-01-21 01:15:58 +08:00
Simon c781eba986 feat: fixed version in CDN URL 2026-01-21 01:08:19 +08:00
Simon efe131660a fix: demo not showing panel; docs updated 2026-01-21 00:44:09 +08:00
Simon 22516dec74 feat: unify InvokeError; add rawResponse to historical ErrorEvent 2026-01-20 20:16:34 +08:00
Simon 1f8953c450 feat: add llm rawResponse to history 2026-01-20 19:56:40 +08:00
Simon d6a57f3e20 chore: merge .gitignore from feat/ext 2026-01-20 19:53:52 +08:00
Simon e0027f99c4 Merge pull request #121 from alibaba/dependabot/npm_and_yarn/development-dependencies-0b42ca76aa
chore(deps-dev): bump the development-dependencies group with 6 updates
2026-01-20 14:14:40 +08:00
Simon b234868bc1 Merge pull request #120 from alibaba/dependabot/npm_and_yarn/production-dependencies-f96e18e569
chore(deps): bump the production-dependencies group with 2 updates
2026-01-20 14:13:47 +08:00
dependabot[bot] 10ae34a677 chore(deps-dev): bump the development-dependencies group with 6 updates
Bumps the development-dependencies group with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.0.7` | `25.0.9` |
| [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/HEAD/packages/plugins/eslint-plugin-react-dom) | `2.5.7` | `2.7.2` |
| [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/HEAD/packages/plugins/eslint-plugin-react-x) | `2.5.7` | `2.7.2` |
| [prettier](https://github.com/prettier/prettier) | `3.7.4` | `3.8.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.53.0` | `8.53.1` |
| [react-i18next](https://github.com/i18next/react-i18next) | `16.5.2` | `16.5.3` |


Updates `@types/node` from 25.0.7 to 25.0.9
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `eslint-plugin-react-dom` from 2.5.7 to 2.7.2
- [Release notes](https://github.com/Rel1cx/eslint-react/releases)
- [Changelog](https://github.com/Rel1cx/eslint-react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Rel1cx/eslint-react/commits/v2.7.2/packages/plugins/eslint-plugin-react-dom)

Updates `eslint-plugin-react-x` from 2.5.7 to 2.7.2
- [Release notes](https://github.com/Rel1cx/eslint-react/releases)
- [Changelog](https://github.com/Rel1cx/eslint-react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Rel1cx/eslint-react/commits/v2.7.2/packages/plugins/eslint-plugin-react-x)

Updates `prettier` from 3.7.4 to 3.8.0
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.7.4...3.8.0)

Updates `typescript-eslint` from 8.53.0 to 8.53.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.53.1/packages/typescript-eslint)

Updates `react-i18next` from 16.5.2 to 16.5.3
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v16.5.2...v16.5.3)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.0.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development-dependencies
- dependency-name: eslint-plugin-react-dom
  dependency-version: 2.7.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: development-dependencies
- dependency-name: eslint-plugin-react-x
  dependency-version: 2.7.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: development-dependencies
- dependency-name: prettier
  dependency-version: 3.8.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: development-dependencies
- dependency-name: typescript-eslint
  dependency-version: 8.53.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development-dependencies
- dependency-name: react-i18next
  dependency-version: 16.5.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-20 06:11:50 +00:00
dependabot[bot] 2fb01b7315 chore(deps): bump the production-dependencies group with 2 updates
Bumps the production-dependencies group with 2 updates: [motion](https://github.com/motiondivision/motion) and [simple-icons](https://github.com/simple-icons/simple-icons).


Updates `motion` from 12.26.1 to 12.27.1
- [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md)
- [Commits](https://github.com/motiondivision/motion/compare/v12.26.1...v12.27.1)

Updates `simple-icons` from 16.5.0 to 16.6.0
- [Release notes](https://github.com/simple-icons/simple-icons/releases)
- [Commits](https://github.com/simple-icons/simple-icons/compare/16.5.0...16.6.0)

---
updated-dependencies:
- dependency-name: motion
  dependency-version: 12.27.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production-dependencies
- dependency-name: simple-icons
  dependency-version: 16.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-20 06:11:18 +00:00
Simon 5c80f2b002 chore: prettier json indentation 2026-01-20 14:08:42 +08:00
Simon 28c128645e chore(version): bump version to 1.0.0-beta.1 2026-01-19 20:51:37 +08:00
Simon 250cb47e44 fix: wait time second not ms 2026-01-19 20:50:50 +08:00
Simon f83a4174cc chore(version): bump version to 1.0.0-beta.0 2026-01-19 20:39:57 +08:00
Simon 334512210d feat: improve lifecycle hooks API; wait a little after url change 2026-01-19 20:39:03 +08:00
Simon 3df71788ff docs: update package descriptions 2026-01-19 20:14:40 +08:00
Simon 60450ea7be chore: export tool from PageAgent package 2026-01-19 20:12:46 +08:00
Simon 80c93bd668 feat: expose maxSteps config 2026-01-19 20:11:53 +08:00
33 changed files with 9000 additions and 8780 deletions
+7 -3
View File
@@ -25,11 +25,15 @@ dist-ssr
*.sw?
.qoder
#
# env files
.env
.env.*
# Copied files for npm publish (generated by prepublishOnly)
packages/page-agent/README.md
packages/page-agent/README-zh.md
packages/page-agent/LICENSE
packages/page-agent/LICENSE
# extension
.output
.wxt
+1 -1
View File
@@ -1,3 +1,3 @@
{
"recommendations": ["dbaeumer.vscode-eslint", "prettier.prettier-vscode"]
"recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
}
+1
View File
@@ -6,6 +6,7 @@
"HITL",
"innerhtml",
"llms",
"npmmirror",
"onwarn",
"opensource",
"qwen",
+17 -31
View File
@@ -31,8 +31,8 @@ Simple monorepo solution: TypeScript references + Vite aliases. Update tsconfig
```
packages/
├── page-agent/ # npm: "page-agent" ⭐ MAIN (with Panel UI + IIFE builds)
├── core/ # npm: "@page-agent/core" (headless, no UI)
├── core/ # npm: "@page-agent/core" ⭐ Core agent logic (headless)
├── page-agent/ # npm: "page-agent" entry class (with UI + controller + demo builds)
├── website/ # @page-agent/website (private)
├── llms/ # @page-agent/llms
├── page-controller/ # @page-agent/page-controller
@@ -72,45 +72,31 @@ const pageInfo = await this.pageController.getPageInfo()
3. **LLM Processing**: AI returns action plans (page-agent)
4. **Indexed Operations**: PageAgent calls PageController by element index
### IIFE Builds (`packages/page-agent/dist/iife/`)
Two IIFE builds for script tag usage:
| Build | File | Description |
| ----- | -------------------- | -------------------------------- |
| Demo | `page-agent.demo.js` | Auto-init with built-in test API |
| Full | `page-agent.js` | Exposes `PageAgent` class only |
Demo build supports query params (e.g., `?model=gpt-4&lang=en-US`).
Build with `npm run build:iife --workspace=page-agent`.
## Key Files Reference
### Page Agent (`packages/page-agent/`)
| File | Description |
| ----------------------- | -------------------------------------------- |
| `src/PageAgent.ts` | ⭐ Main class with UI, extends PageAgentCore |
| `src/entry-iife.ts` | IIFE entry (exposes PageAgent class) |
| `src/entry-iife-demo.ts`| IIFE demo entry (auto-init with demo API) |
| File | Description |
| ------------------ | -------------------------------------------- |
| `src/PageAgent.ts` | ⭐ Main class with UI, extends PageAgentCore |
| `src/demo.ts` | IIFE demo entry (auto-init with demo API) |
### Core (`packages/core/`)
| File | Description |
| ----------------------- | ------------------------------------------- |
| `src/PageAgentCore.ts` | ⭐ Core agent class without UI |
| `src/tools/` | Tool definitions calling PageController |
| `src/config/` | Configuration types and constants |
| `src/prompts/` | System prompt templates |
| File | Description |
| ---------------------- | --------------------------------------- |
| `src/PageAgentCore.ts` | ⭐ Core agent class without UI |
| `src/tools/` | Tool definitions calling PageController |
| `src/config/` | Configuration types and constants |
| `src/prompts/` | System prompt templates |
### LLMs (`packages/llms/`)
| File | Description |
| ---------------------------- | ------------------------------------- |
| `src/index.ts` | ⭐ LLM class with retry logic |
| `src/types.ts` | MacroToolInput, AgentBrain, LLMConfig |
| `src/OpenAILenientClient.ts` | OpenAI-compatible client |
| File | Description |
| --------------------- | ------------------------------------- |
| `src/index.ts` | ⭐ LLM class with retry logic |
| `src/types.ts` | MacroToolInput, AgentBrain, LLMConfig |
| `src/OpenAIClient.ts` | OpenAI-compatible client |
### Page Controller (`packages/page-controller/`)
+94
View File
@@ -0,0 +1,94 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2026-01-19
### 🎉 First Stable Release
PageAgent is now ready for production use. The API is stable and breaking changes will follow semantic versioning.
### Features
#### Core
- **PageAgent** - Main entry class with built-in UI Panel
- **PageAgentCore** - Headless agent class for custom UI or programmatic use
- **DOM Analysis** - Text-based DOM extraction with high-intensity dehydration
- **LLM Support** - Works with OpenAI, Claude, DeepSeek, Qwen, and other OpenAI-compatible APIs
- **Tool System** - Built-in tools for click, input, scroll, select, and more
- **Custom Tools** - Extend agent capabilities with your own tools (experimental)
- **Lifecycle Hooks** - Hook into agent execution (experimental)
- **Instructions System** - System-level and page-level instructions to guide agent behavior
- **Data Masking** - Transform page content before sending to LLM
#### Page Controller
- **Element Interactions** - Click, input text, select options, scroll
- **Visual Mask** - Blocks user interaction during automation
- **DOM Tree Extraction** - Efficient page structure extraction for LLM consumption
#### UI
- **Interactive Panel** - Real-time task progress and agent thinking display
- **Ask User Tool** - Agent can ask users for clarification
- **i18n Support** - English and Chinese localization
### Configuration
```typescript
interface PageAgentConfig {
// LLM Configuration (required)
baseURL: string
apiKey: string
model: string
temperature?: number
maxRetries?: number
customFetch?: typeof fetch
// Agent Configuration
language?: 'en-US' | 'zh-CN'
maxSteps?: number // default: 20
customTools?: Record<string, PageAgentTool> // experimental
instructions?: InstructionsConfig
transformPageContent?: (content: string) => string | Promise<string>
experimentalScriptExecutionTool?: boolean // default: false
// Lifecycle Hooks (experimental)
onBeforeTask?: (agent, result) => void
onAfterTask?: (agent, result) => void
onBeforeStep?: (agent, stepCount) => void
onAfterStep?: (agent, history) => void
onDispose?: (agent, reason?) => void
// Page Controller Configuration
enableMask?: boolean // default: true
viewportExpansion?: number
interactiveBlacklist?: Element[]
interactiveWhitelist?: Element[]
}
```
### Packages
| Package | Description |
| ----------------------------- | ---------------------------------- |
| `page-agent` | Main entry with UI Panel |
| `@page-agent/core` | Core agent logic without UI |
| `@page-agent/llms` | LLM client with retry logic |
| `@page-agent/page-controller` | DOM operations and visual feedback |
| `@page-agent/ui` | Panel and i18n |
### Known Limitations
- Single-page application only (cannot navigate across pages)
- No visual recognition (relies on DOM structure)
- Limited interaction support (no hover, drag-drop, canvas operations)
- See [Limitations](https://alibaba.github.io/page-agent/#/docs/introduction/limitations) for details
### Acknowledgments
This project builds upon the excellent work of [browser-use](https://github.com/browser-use/browser-use). DOM processing components and prompts are adapted from browser-use (MIT License).
+2 -2
View File
@@ -69,10 +69,10 @@ members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][https://www.contributor-covenant.org], version 1.4,
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
----
---
> Chinese Version
> 《阿里巴巴开源行为准则》
+2 -2
View File
@@ -122,13 +122,13 @@ npm start
- Start and serve a local `iife` script
```bash
npm run dev:iife # Serving IIFE with auto rebuild at http://localhost:5174/page-agent.js
npm run dev:demo # Serving IIFE with auto rebuild at http://localhost:5174/page-agent.demo.js
```
- Add a new bookmark
```javascript
javascript:(function(){var s=document.createElement('script');s.src=`http://localhost:5174/page-agent.js?t=${Math.random()}`;s.onload=()=>console.log(%27PageAgent ready!%27);document.head.appendChild(s);})();
javascript:(function(){var s=document.createElement('script');s.src=`http://localhost:5174/page-agent.demo.js?t=${Math.random()}`;s.onload=()=>console.log(%27PageAgent ready!%27);document.head.appendChild(s);})();
```
- Click the bookmark on any page to load Page-Agent
+18 -20
View File
@@ -20,34 +20,38 @@
## ✨ Features
- **🎯 轻松集成**
- 无需 Python,无需无头浏览器,无需浏览器插件。纯页面内脚本。
- **🔐 端侧运行**
- **🧠 HTML 脱水**
- **💬 自然语言接口**
- **🎨 HITL 交互界面**
## 🗺️ Roadmap
以及 😉
👉 [**Roadmap**](https://github.com/alibaba/page-agent/issues/96)
- **🧪 实验性的 Chrome 扩展,支持跨页面控制** - `-b feat/ext`
👉 [**🗺️ Roadmap**](https://github.com/alibaba/page-agent/issues/96)
## 🚀 快速开始
### 快速体验 (With Testing LLM)
### 一行代码集成
最快的体验方式
通过我们免费的 Demo LLM 快速体验 PageAgent
```html
<script
src="https://registry.npmmirror.com/@page-agent/cdn/latest/files/dist/page-agent.demo.js"
src="https://registry.npmmirror.com/page-agent/1.0.0/files/dist/iife/page-agent.demo.js"
crossorigin="true"
></script>
```
> ⚠️ **仅用于技术评估。** Demo 模型有速率限制和使用限制,生产环境请使用 NPM 方式
> - **⚠️ 仅用于技术评估。** Demo LLM 有速率和使用限制,可能随时变更
> - **🌷 建议使用自己的 LLM API。**
| 镜像 | URL |
| ------ | ----------------------------------------------------------------------------------- |
| Global | https://cdn.jsdelivr.net/npm/page-agent/dist/iife/page-agent.demo.js |
| China | https://registry.npmmirror.com/page-agent/latest/files/dist/iife/page-agent.demo.js |
| 镜像 | URL |
| ------ | ----------------------------------------------------------------------------------------- |
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.0.0/dist/iife/page-agent.demo.js |
| China | https://registry.npmmirror.com/page-agent/1.0.0/files/dist/iife/page-agent.demo.js |
### NPM 安装
@@ -76,8 +80,8 @@ PageAgent adopts a simplified monorepo structure:
```
packages/
├── page-agent/ # AI agent and demo(npm: page-agent)
├── core/ # Agent core logic without UI(npm: @page-agent/core)
├── core/ # ** Core agent logic without UI(npm: @page-agent/core) **
├── page-agent/ # Exported agent and demo(npm: page-agent)
├── llms/ # LLM 客户端 (npm: @page-agent/llms)
├── page-controller/ # DOM 操作 & 蒙层 & 模拟鼠标 (npm: @page-agent/page-controller)
├── ui/ # 面板 & i18n (npm: @page-agent/ui)
@@ -86,15 +90,9 @@ packages/
## 🤝 贡献
欢迎社区贡献!以下是参与方式:
欢迎社区贡献!请参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 了解环境配置和本地开发说明。
1. Fork 并 clone。`git clone https://github.com/alibaba/page-agent.git && cd page-agent`
2. 安装依赖: `npm install`
3. 启动开发: `npm start`
更多详情请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。
请在贡献前阅读我们的[行为准则](CODE_OF_CONDUCT.md)。
请在贡献前阅读[行为准则](CODE_OF_CONDUCT.md)。
## 👏 致谢
+19 -21
View File
@@ -19,35 +19,39 @@ The GUI Agent Living in Your Webpage. Control web interfaces with natural langua
## ✨ Features
- **🎯 Easy Integration** - Transform your webpage into an agent with a single script tag.
- **🎯 Easy Integration**
- No python. No headless browser. No browser extension. Just in-page scripts.
- **🔐 Client-Side Processing**
- **🧠 DOM Extraction**
- **💬 Natural Language Interface**
- **🎨 UI with Human in the loop**
## 🗺️ Roadmap
And 😉
👉 [**Roadmap**](https://github.com/alibaba/page-agent/issues/96)
- **🧪 `cross-page` control with an experimental chrome extension** - `-b feat/ext`
👉 [**🗺️ Roadmap**](https://github.com/alibaba/page-agent/issues/96)
## 🚀 Quick Start
### Quick Try (With Testing LLM)
### One-line integration
Fastest way to try PageAgent:
Fastest way to try PageAgent with our free Demo LLM:
```html
<script
src="https://cdn.jsdelivr.net/npm/page-agent/dist/iife/page-agent.demo.js"
src="https://cdn.jsdelivr.net/npm/page-agent@1.0.0/dist/iife/page-agent.demo.js"
crossorigin="true"
></script>
```
> ⚠️ **For technical evaluation only.** Demo model has rate limits and usage restrictions. Use NPM for production.
> - **⚠️ For technical evaluation only.** Demo LLM has rate limits and usage restrictions. May change without notice.
> - **🌷 Bring your own LLM API.**
| Mirrors | URL |
| ------- | ----------------------------------------------------------------------------------- |
| Global | https://cdn.jsdelivr.net/npm/page-agent/dist/iife/page-agent.demo.js |
| China | https://registry.npmmirror.com/page-agent/latest/files/dist/iife/page-agent.demo.js |
| Mirrors | URL |
| ------- | ----------------------------------------------------------------------------------------- |
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.0.0/dist/iife/page-agent.demo.js |
| China | https://registry.npmmirror.com/page-agent/1.0.0/files/dist/iife/page-agent.demo.js |
### NPM Installation
@@ -74,8 +78,8 @@ PageAgent adopts a simplified monorepo structure:
```
packages/
├── page-agent/ # AI agent and demo(npm: page-agent)
├── core/ # Agent core logic without UI(npm: @page-agent/core)
├── core/ # ** Core agent logic without UI(npm: @page-agent/core) **
├── page-agent/ # Exported agent and demo(npm: page-agent)
├── llms/ # LLM client (npm: @page-agent/llms)
├── page-controller/ # DOM operations & Visual Mask (npm: @page-agent/page-controller)
├── ui/ # Panel & i18n (npm: @page-agent/ui)
@@ -84,15 +88,9 @@ packages/
## 🤝 Contributing
We welcome contributions from the community! Here's how to get started:
We welcome contributions from the community! Follow our instructions in [CONTRIBUTING.md](CONTRIBUTING.md) for environment setup and local development.
1. Fork and clone. `git clone https://github.com/alibaba/page-agent.git && cd page-agent`
2. Install dependencies: `npm install`
3. Start development: `npm start`
More details in [CONTRIBUTING.md](CONTRIBUTING.md).
Please read our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.
Please read [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.
## 👏 Acknowledgments
+8207 -8221
View File
File diff suppressed because it is too large Load Diff
+121 -121
View File
@@ -1,123 +1,123 @@
{
"name": "root",
"private": true,
"version": "0.3.0",
"type": "module",
"workspaces": [
"packages/page-controller",
"packages/ui",
"packages/llms",
"packages/core",
"packages/page-agent",
"packages/website"
],
"description": "AI-powered UI agent for web applications",
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"engines": {
"node": ">=20.0.0",
"npm": ">=10.0.0"
},
"scripts": {
"cleanup": "rm -rf packages/*/dist",
"start": "npm run dev --workspace=@page-agent/website",
"build:website": "npm run build:website --workspace=@page-agent/website",
"build:libs": "npm run build --workspaces --if-present",
"build": "npm run build:libs && npm run build:website",
"dev:iife": "npm run dev:iife --workspace=page-agent",
"version": "node scripts/sync-version.js",
"lint": "eslint .",
"prepare": "husky"
},
"devDependencies": {
"@commitlint/cli": "^20.3.1",
"@commitlint/config-conventional": "^20.3.1",
"@eslint/js": "^9.39.2",
"@microsoft/api-extractor": "^7.55.2",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/node": "^25.0.7",
"concurrently": "^9.2.1",
"dotenv": "^17.2.3",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-dom": "^2.5.7",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.26",
"eslint-plugin-react-x": "^2.5.7",
"globals": "^17.0.0",
"husky": "^9.1.7",
"lint-staged": "^16.2.4",
"prettier": "^3.7.4",
"typescript": "^5.9.3",
"typescript-eslint": "^8.53.0",
"unplugin-dts": "^1.0.0-beta.6",
"vite": "^7.3.1",
"vite-plugin-css-injected-by-js": "^3.5.2"
},
"overrides": {
"typescript": "^5.9.3"
},
"lint-staged": {
"*.{js,ts,cjs,cts,mjs,mts}": [
"npx prettier --write --ignore-unknown",
"npx eslint --quiet"
],
"*.{jsx,tsx}": [
"npx prettier --write --ignore-unknown",
"npx eslint --quiet"
],
"*.css": [
"npx prettier --write --ignore-unknown"
]
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
],
"rules": {
"subject-case": [
0,
"never"
]
}
},
"prettier": {
"singleQuote": true,
"semi": false,
"useTabs": true,
"printWidth": 100,
"trailingComma": "es5",
"plugins": [
"@trivago/prettier-plugin-sort-imports"
],
"importOrder": [
"<THIRD_PARTY_MODULES>",
"^(@/).*(?<!css)$",
"^[./].*(?<!css)$",
".css$"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true,
"overrides": [
{
"files": "*.md",
"options": {
"useTabs": false,
"tabWidth": 4
}
},
{
"files": "*.json",
"options": {
"useTabs": false,
"tabWidth": 4
}
}
]
}
"name": "root",
"private": true,
"version": "1.0.0",
"type": "module",
"workspaces": [
"packages/page-controller",
"packages/ui",
"packages/llms",
"packages/core",
"packages/page-agent",
"packages/website"
],
"description": "AI-powered UI agent for web applications",
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"engines": {
"node": ">=20.0.0",
"npm": ">=10.0.0"
},
"scripts": {
"cleanup": "rm -rf packages/*/dist",
"start": "npm run dev --workspace=@page-agent/website",
"build:website": "npm run build:website --workspace=@page-agent/website",
"build:libs": "npm run build --workspaces --if-present",
"build": "npm run build:libs && npm run build:website",
"dev:demo": "npm run dev:demo --workspace=page-agent",
"version": "node scripts/sync-version.js",
"lint": "eslint .",
"prepare": "husky"
},
"devDependencies": {
"@commitlint/cli": "^20.3.1",
"@commitlint/config-conventional": "^20.3.1",
"@eslint/js": "^9.39.2",
"@microsoft/api-extractor": "^7.55.2",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/node": "^25.0.9",
"concurrently": "^9.2.1",
"dotenv": "^17.2.3",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-dom": "^2.7.2",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.26",
"eslint-plugin-react-x": "^2.7.2",
"globals": "^17.0.0",
"husky": "^9.1.7",
"lint-staged": "^16.2.4",
"prettier": "^3.8.0",
"typescript": "^5.9.3",
"typescript-eslint": "^8.53.1",
"unplugin-dts": "^1.0.0-beta.6",
"vite": "^7.3.1",
"vite-plugin-css-injected-by-js": "^3.5.2"
},
"overrides": {
"typescript": "^5.9.3"
},
"lint-staged": {
"*.{js,ts,cjs,cts,mjs,mts}": [
"npx prettier --write --ignore-unknown",
"npx eslint --quiet"
],
"*.{jsx,tsx}": [
"npx prettier --write --ignore-unknown",
"npx eslint --quiet"
],
"*.css": [
"npx prettier --write --ignore-unknown"
]
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
],
"rules": {
"subject-case": [
0,
"never"
]
}
},
"prettier": {
"singleQuote": true,
"semi": false,
"useTabs": true,
"printWidth": 100,
"trailingComma": "es5",
"plugins": [
"@trivago/prettier-plugin-sort-imports"
],
"importOrder": [
"<THIRD_PARTY_MODULES>",
"^(@/).*(?<!css)$",
"^[./].*(?<!css)$",
".css$"
],
"importOrderSeparation": true,
"importOrderSortSpecifiers": true,
"overrides": [
{
"files": "*.md",
"options": {
"useTabs": false,
"tabWidth": 4
}
},
{
"files": "*.json",
"options": {
"useTabs": false,
"tabWidth": 4
}
}
]
}
}
+49 -49
View File
@@ -1,51 +1,51 @@
{
"name": "@page-agent/core",
"private": false,
"version": "0.3.0",
"type": "module",
"main": "./dist/esm/page-agent-core.js",
"module": "./dist/esm/page-agent-core.js",
"types": "./dist/esm/PageAgentCore.d.ts",
"exports": {
".": {
"types": "./dist/esm/PageAgentCore.d.ts",
"import": "./dist/esm/page-agent-core.js",
"default": "./dist/esm/page-agent-core.js"
}
},
"files": [
"dist/"
],
"description": "GUI agent for web applications - add intelligent automation to any webpage with a single script",
"keywords": [
"ai",
"automation",
"ui-agent",
"GUI-agent",
"browser-automation",
"web-agent",
"llm",
"dom-interaction",
"web-automation",
"GUI-simulation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"dev:iife": "concurrently \"vite build --config vite.iife.config.js --watch\" \"npx serve dist/iife -p 5174\"",
"prepublishOnly": "node -e \"const fs=require('fs');['README.md','LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['README.md','LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5",
"@page-agent/llms": "0.3.0",
"@page-agent/page-controller": "0.3.0"
}
"name": "@page-agent/core",
"private": false,
"version": "1.0.0",
"type": "module",
"main": "./dist/esm/page-agent-core.js",
"module": "./dist/esm/page-agent-core.js",
"types": "./dist/esm/PageAgentCore.d.ts",
"exports": {
".": {
"types": "./dist/esm/PageAgentCore.d.ts",
"import": "./dist/esm/page-agent-core.js",
"default": "./dist/esm/page-agent-core.js"
}
},
"files": [
"dist/"
],
"description": "GUI agent for web applications - add intelligent automation to any webpage with a single script",
"keywords": [
"ai",
"automation",
"ui-agent",
"GUI-agent",
"browser-automation",
"web-agent",
"llm",
"dom-interaction",
"web-automation",
"GUI-simulation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"dev:iife": "concurrently \"vite build --config vite.iife.config.js --watch\" \"npx serve dist/iife -p 5174\"",
"prepublishOnly": "node -e \"const fs=require('fs');['README.md','LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['README.md','LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5",
"@page-agent/llms": "1.0.0",
"@page-agent/page-controller": "1.0.0"
}
}
+30 -26
View File
@@ -2,30 +2,31 @@
* Copyright (C) 2025 Alibaba Group Holding Limited
* All rights reserved.
*/
import { LLM, type Tool } from '@page-agent/llms'
import { InvokeError, LLM, type Tool } from '@page-agent/llms'
import type { PageController } from '@page-agent/page-controller'
import chalk from 'chalk'
import zod from 'zod'
import { type PageAgentConfig } from './config'
import { MAX_STEPS } from './config/constants'
import { DEFAULT_MAX_STEPS } from './config/constants'
import SYSTEM_PROMPT from './prompts/system_prompt.md?raw'
import { tools } from './tools'
import {
AgentActivity,
AgentReflection,
AgentStatus,
AgentStep,
AgentStepEvent,
ExecutionResult,
HistoricalEvent,
MacroToolInput,
MacroToolResult,
} from './types'
import { normalizeResponse, trimLines, uid } from './utils'
import { normalizeResponse, trimLines, uid, waitFor } from './utils'
import { assert } from './utils/assert'
export { type PageAgentConfig }
export { tool, type PageAgentTool } from './tools'
export type * from './types'
/**
* AI agent for browser DOM automation.
@@ -49,7 +50,7 @@ export { tool, type PageAgentTool } from './tools'
* - Types: thinking, executing, executed, retrying, error
*/
export class PageAgentCore extends EventTarget {
config: PageAgentConfig
config: PageAgentConfig & { maxSteps: number }
id = uid()
tools: typeof tools
disposed = false
@@ -86,7 +87,8 @@ export class PageAgentCore extends EventTarget {
constructor(config: PageAgentConfig & { pageController: PageController }) {
super()
this.config = config
this.config = { ...config, maxSteps: config.maxSteps || DEFAULT_MAX_STEPS }
this.#llm = new LLM(this.config)
this.tools = new Map(tools)
this.pageController = config.pageController
@@ -97,8 +99,7 @@ export class PageAgentCore extends EventTarget {
this.emitActivity({ type: 'retrying', attempt, maxAttempts })
// Also push to history for panel rendering
this.history.push({
type: 'error',
errorType: 'retry',
type: 'retry',
message: `LLM retry attempt ${attempt} of ${maxAttempts}`,
attempt,
maxAttempts,
@@ -106,14 +107,14 @@ export class PageAgentCore extends EventTarget {
this.#emitHistoryChange()
})
this.#llm.addEventListener('error', (e) => {
const { error } = (e as CustomEvent).detail
const error = (e as CustomEvent).detail.error as Error | InvokeError
const message = String(error)
this.emitActivity({ type: 'error', message })
// Also push to history for panel rendering
this.history.push({
type: 'error',
errorType: 'error',
message,
rawResponse: (error as InvokeError).rawResponse,
})
this.#emitHistoryChange()
})
@@ -183,12 +184,12 @@ export class PageAgentCore extends EventTarget {
this.tools.delete('ask_user')
}
const onBeforeStep = this.config.onBeforeStep || (() => void 0)
const onAfterStep = this.config.onAfterStep || (() => void 0)
const onBeforeTask = this.config.onBeforeTask || (() => void 0)
const onAfterTask = this.config.onAfterTask || (() => void 0)
const onBeforeStep = this.config.onBeforeStep
const onAfterStep = this.config.onAfterStep
const onBeforeTask = this.config.onBeforeTask
const onAfterTask = this.config.onAfterTask
await onBeforeTask.call(this)
await onBeforeTask?.(this)
// Show mask
await this.pageController.showMask()
@@ -214,7 +215,7 @@ export class PageAgentCore extends EventTarget {
while (true) {
await this.#generateObservations(step)
await onBeforeStep.call(this, step)
await onBeforeStep?.(this, step)
console.group(`step: ${step}`)
@@ -253,7 +254,7 @@ export class PageAgentCore extends EventTarget {
next_goal: input.next_goal,
}
const actionName = Object.keys(input.action)[0]
const action: AgentStep['action'] = {
const action: AgentStepEvent['action'] = {
name: actionName,
input: input.action[actionName],
output: output,
@@ -261,26 +262,28 @@ export class PageAgentCore extends EventTarget {
this.history.push({
type: 'step',
stepIndex: step,
reflection,
action,
usage: result.usage,
} as AgentStep)
rawResponse: result.rawResponse,
} as AgentStepEvent)
this.#emitHistoryChange()
console.log(chalk.green('Step finished:'), actionName)
console.groupEnd()
await onAfterStep.call(this, this.history)
await onAfterStep?.(this, this.history)
step++
if (step > MAX_STEPS) {
if (step > this.config.maxSteps) {
this.#onDone('Step count exceeded maximum limit', false)
const result: ExecutionResult = {
success: false,
data: 'Step count exceeded maximum limit',
history: this.history,
}
await onAfterTask.call(this, result)
await onAfterTask?.(this, result)
return result
}
if (actionName === 'done') {
@@ -293,7 +296,7 @@ export class PageAgentCore extends EventTarget {
data: text,
history: this.history,
}
await onAfterTask.call(this, result)
await onAfterTask?.(this, result)
return result
}
}
@@ -307,7 +310,7 @@ export class PageAgentCore extends EventTarget {
data: errorMessage,
history: this.history,
}
await onAfterTask.call(this, result)
await onAfterTask?.(this, result)
return result
}
}
@@ -472,10 +475,11 @@ export class PageAgentCore extends EventTarget {
if (currentURL !== this.states.lastURL) {
this.pushObservation(`Page navigated to → ${currentURL}`)
this.states.lastURL = currentURL
await waitFor(0.5) // wait for page to stabilize
}
// Warn about remaining steps
const remaining = MAX_STEPS - stepCount
const remaining = this.config.maxSteps - stepCount
if (remaining === 5) {
this.pushObservation(
`⚠️ Only ${remaining} steps remaining. Consider wrapping up or calling done with partial results.`
@@ -505,7 +509,7 @@ export class PageAgentCore extends EventTarget {
${this.task}
</user_request>
<step_info>
Step ${stepCount + 1} of ${MAX_STEPS} max possible steps
Step ${stepCount + 1} of ${this.config.maxSteps} max possible steps
Current date and time: ${new Date().toISOString()}
</step_info>
</agent_state>
@@ -583,6 +587,6 @@ export class PageAgentCore extends EventTarget {
// Emit dispose event for UI cleanup
this.dispatchEvent(new Event('dispose'))
this.config.onDispose?.call(this, reason)
this.config.onDispose?.(this, reason)
}
}
+1 -2
View File
@@ -1,2 +1 @@
// Agent-specific constants (LLM constants moved to @page-agent/llms)
export const MAX_STEPS = 20
export const DEFAULT_MAX_STEPS = 20
+50 -27
View File
@@ -1,5 +1,5 @@
import type { LLMConfig } from '@page-agent/llms'
import type { PageController, PageControllerConfig } from '@page-agent/page-controller'
import type { PageControllerConfig } from '@page-agent/page-controller'
import type { PageAgentCore } from '../PageAgentCore'
import type { PageAgentTool } from '../tools'
@@ -14,6 +14,12 @@ export interface AgentConfig {
// theme?: 'light' | 'dark'
language?: SupportedLanguage
/**
* Maximum number of steps the agent can take per task.
* @default 20
*/
maxSteps?: number
/**
* Custom tools to extend PageAgent capabilities
* @experimental
@@ -63,20 +69,52 @@ export interface AgentConfig {
getPageInstructions?: (url: string) => string | undefined | null
}
// lifecycle hooks
// @todo: use event instead of hooks
// @todo: remove `this` binding, pass agent as explicit parameter instead
onBeforeStep?: (this: PageAgentCore, stepCnt: number) => Promise<void> | void
onAfterStep?: (this: PageAgentCore, history: HistoricalEvent[]) => Promise<void> | void
onBeforeTask?: (this: PageAgentCore) => Promise<void> | void
onAfterTask?: (this: PageAgentCore, result: ExecutionResult) => Promise<void> | void
/**
* Lifecycle hooks for task execution.
* @experimental API may change in future versions.
*
* All hooks receive the agent instance as first parameter.
*/
/**
* @note this hook can block the disposal process
* @todo remove `this` binding, pass agent as explicit parameter instead
* Called before each step execution.
* @experimental
* @param agent - The PageAgentCore instance
* @param stepCount - Current step number (0-indexed)
*/
onDispose?: (this: PageAgentCore, reason?: string) => void
onBeforeStep?: (agent: PageAgentCore, stepCount: number) => Promise<void> | void
/**
* Called after each step execution.
* @experimental
* @param agent - The PageAgentCore instance
* @param history - Current history of events
*/
onAfterStep?: (agent: PageAgentCore, history: HistoricalEvent[]) => Promise<void> | void
/**
* Called before task execution starts.
* @experimental
* @param agent - The PageAgentCore instance
*/
onBeforeTask?: (agent: PageAgentCore) => Promise<void> | void
/**
* Called after task execution completes (success or failure).
* @experimental
* @param agent - The PageAgentCore instance
* @param result - The execution result
*/
onAfterTask?: (agent: PageAgentCore, result: ExecutionResult) => Promise<void> | void
/**
* Called when the agent is disposed.
* @experimental
* @note This hook can block the disposal process if it's async.
* @param agent - The PageAgentCore instance
* @param reason - Optional reason for disposal
*/
onDispose?: (agent: PageAgentCore, reason?: string) => void
// page behavior hooks
@@ -103,21 +141,6 @@ export interface AgentConfig {
* }
*/
transformPageContent?: (content: string) => Promise<string> | string
/**
* TODO: @unimplemented
* hook when action causes a new page to be opened
* @note PageAgent will try to detect new pages and decide if it's caused by an action. But not very reliable.
* @todo remove `this` binding, pass agent as explicit parameter instead
*/
// onNewPageOpen?: (this: PageAgent, url: string) => Promise<void> | void
/**
* TODO: @unimplemented
* try to navigate to a new page instead of opening a new tab/window.
* @note will unload the current page when a action tries to open a new page. so that things keep in the same tab/window.
*/
// experimentalPreventNewPage?: boolean
}
export type PageAgentConfig = LLMConfig & AgentConfig & PageControllerConfig
+24 -8
View File
@@ -33,8 +33,9 @@ export interface MacroToolResult {
/**
* A single agent step with reflection and action
*/
export interface AgentStep {
export interface AgentStepEvent {
type: 'step'
stepIndex: number
reflection: Partial<AgentReflection>
action: {
name: string
@@ -48,6 +49,8 @@ export interface AgentStep {
cachedTokens?: number
reasoningTokens?: number
}
/** Raw LLM response for debugging */
rawResponse?: unknown
}
/**
@@ -66,20 +69,33 @@ export interface UserTakeoverEvent {
}
/**
* Error event (retry or error from LLM)
* Retry event - LLM call is being retried
*/
export interface ErrorEvent {
type: 'error'
errorType: 'retry' | 'error'
export interface RetryEvent {
type: 'retry'
message: string
attempt?: number
maxAttempts?: number
attempt: number
maxAttempts: number
}
/**
* Error event - fatal error from LLM or execution
*/
export interface AgentErrorEvent {
type: 'error'
message: string
rawResponse?: unknown
}
/**
* Union type for all history events
*/
export type HistoricalEvent = AgentStep | ObservationEvent | UserTakeoverEvent | ErrorEvent
export type HistoricalEvent =
| AgentStepEvent
| ObservationEvent
| UserTakeoverEvent
| RetryEvent
| AgentErrorEvent
/**
* Agent execution status
+41 -41
View File
@@ -1,43 +1,43 @@
{
"name": "@page-agent/llms",
"version": "0.3.0",
"type": "module",
"main": "./dist/lib/page-agent-llms.js",
"module": "./dist/lib/page-agent-llms.js",
"types": "./dist/lib/index.d.ts",
"exports": {
".": {
"types": "./dist/lib/index.d.ts",
"import": "./dist/lib/page-agent-llms.js",
"default": "./dist/lib/page-agent-llms.js"
}
},
"files": [
"dist/"
],
"description": "LLM client with reflection-before-action mental model for page-agent",
"keywords": [
"page-agent",
"llm",
"openai",
"tool-calling",
"agent"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/llms"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5"
}
"name": "@page-agent/llms",
"version": "1.0.0",
"type": "module",
"main": "./dist/lib/page-agent-llms.js",
"module": "./dist/lib/page-agent-llms.js",
"types": "./dist/lib/index.d.ts",
"exports": {
".": {
"types": "./dist/lib/index.d.ts",
"import": "./dist/lib/page-agent-llms.js",
"default": "./dist/lib/page-agent-llms.js"
}
},
"files": [
"dist/"
],
"description": "LLM client with reflection-before-action mental model for page-agent",
"keywords": [
"page-agent",
"llm",
"openai",
"tool-calling",
"agent"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/llms"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5"
}
}
+24 -9
View File
@@ -107,14 +107,23 @@ export class OpenAIClient implements LLMClient {
case 'length':
throw new InvokeError(
InvokeErrorType.CONTEXT_LENGTH,
'Response truncated: max tokens reached'
'Response truncated: max tokens reached',
undefined,
data
)
case 'content_filter':
throw new InvokeError(InvokeErrorType.CONTENT_FILTER, 'Content filtered by safety system')
throw new InvokeError(
InvokeErrorType.CONTENT_FILTER,
'Content filtered by safety system',
undefined,
data
)
default:
throw new InvokeError(
InvokeErrorType.UNKNOWN,
`Unexpected finish_reason: ${choice.finish_reason}`
`Unexpected finish_reason: ${choice.finish_reason}`,
undefined,
data
)
}
@@ -128,7 +137,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.NO_TOOL_CALL,
'No tool call found in response',
normalizedData
undefined,
data
)
}
@@ -137,7 +147,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.UNKNOWN,
`Tool "${toolCallName}" not found in tools`,
normalizedData
undefined,
data
)
}
@@ -147,7 +158,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.INVALID_TOOL_ARGS,
'No tool call arguments found',
normalizedData
undefined,
data
)
}
@@ -158,7 +170,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.INVALID_TOOL_ARGS,
'Failed to parse tool arguments as JSON',
error
error,
data
)
}
@@ -169,7 +182,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.INVALID_TOOL_ARGS,
'Tool arguments validation failed',
validation.error
validation.error,
data
)
}
const toolInput = validation.data
@@ -182,7 +196,8 @@ export class OpenAIClient implements LLMClient {
throw new InvokeError(
InvokeErrorType.TOOL_EXECUTION_ERROR,
`Tool execution failed: ${(e as Error).message}`,
e
e,
data
)
}
+5 -1
View File
@@ -25,14 +25,18 @@ export class InvokeError extends Error {
type: InvokeErrorType
retryable: boolean
statusCode?: number
/* raw error (provided if this error is caused by another error) */
rawError?: unknown
/* raw response from the API (provided if this error is caused by an API calling) */
rawResponse?: unknown
constructor(type: InvokeErrorType, message: string, rawError?: unknown) {
constructor(type: InvokeErrorType, message: string, rawError?: unknown, rawResponse?: unknown) {
super(message)
this.name = 'InvokeError'
this.type = type
this.retryable = this.isRetryable(type)
this.rawError = rawError
this.rawResponse = rawResponse
}
private isRetryable(type: InvokeErrorType): boolean {
+1 -1
View File
@@ -3,7 +3,7 @@ import { DEFAULT_TEMPERATURE, LLM_MAX_RETRIES } from './constants'
import { InvokeError } from './errors'
import type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool } from './types'
export type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool }
export type { InvokeError, InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool }
export function parseLLMConfig(config: LLMConfig): Required<LLMConfig> {
// Runtime validation as defensive programming (types already guarantee these)
+52 -52
View File
@@ -1,54 +1,54 @@
{
"name": "page-agent",
"private": false,
"version": "0.3.0",
"type": "module",
"main": "./dist/esm/page-agent.js",
"module": "./dist/esm/page-agent.js",
"types": "./dist/esm/PageAgent.d.ts",
"exports": {
".": {
"types": "./dist/esm/PageAgent.d.ts",
"import": "./dist/esm/page-agent.js",
"default": "./dist/esm/page-agent.js"
}
},
"files": [
"dist/"
],
"description": "GUI agent for web applications - add intelligent automation to any webpage with a single script",
"keywords": [
"ai",
"automation",
"ui-agent",
"GUI-agent",
"browser-automation",
"web-agent",
"llm",
"dom-interaction",
"web-automation",
"GUI-simulation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build && npm run build:demo",
"build:demo": "vite build --config vite.iife.config.js",
"dev:demo": "concurrently \"vite build --config vite.iife.config.js --watch\" \"npx serve dist/iife -p 5174\"",
"prepublishOnly": "node -e \"const fs=require('fs');['README.md','LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['README.md','LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5",
"@page-agent/llms": "0.3.0",
"@page-agent/page-controller": "0.3.0",
"@page-agent/core": "0.3.0",
"@page-agent/ui": "0.3.0"
}
"name": "page-agent",
"private": false,
"version": "1.0.0",
"type": "module",
"main": "./dist/esm/page-agent.js",
"module": "./dist/esm/page-agent.js",
"types": "./dist/esm/PageAgent.d.ts",
"exports": {
".": {
"types": "./dist/esm/PageAgent.d.ts",
"import": "./dist/esm/page-agent.js",
"default": "./dist/esm/page-agent.js"
}
},
"files": [
"dist/"
],
"description": "GUI agent for web applications - add intelligent automation to any webpage with a single script",
"keywords": [
"ai",
"automation",
"ui-agent",
"GUI-agent",
"browser-automation",
"web-agent",
"llm",
"dom-interaction",
"web-automation",
"GUI-simulation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build && npm run build:demo",
"build:demo": "vite build --config vite.iife.config.js",
"dev:demo": "concurrently \"vite build --config vite.iife.config.js --watch\" \"npx serve dist/iife -p 5174\"",
"prepublishOnly": "node -e \"const fs=require('fs');['README.md','LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['README.md','LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"chalk": "^5.6.2",
"zod": "^4.3.5",
"@page-agent/llms": "1.0.0",
"@page-agent/page-controller": "1.0.0",
"@page-agent/core": "1.0.0",
"@page-agent/ui": "1.0.0"
}
}
+3 -2
View File
@@ -2,11 +2,12 @@
* Copyright (C) 2025 Alibaba Group Holding Limited
* All rights reserved.
*/
import { type PageAgentConfig, PageAgentCore } from '@page-agent/core'
import { type PageAgentConfig, PageAgentCore, type PageAgentTool, tool } from '@page-agent/core'
import { PageController } from '@page-agent/page-controller'
import { Panel } from '@page-agent/ui'
export type { PageAgentConfig }
export type { PageAgentConfig, PageAgentTool }
export { tool }
export class PageAgent extends PageAgentCore {
panel: Panel
+1
View File
@@ -41,6 +41,7 @@ setTimeout(() => {
// Create agent
window.pageAgent = new PageAgent(config)
window.pageAgent.panel.show()
console.log('🚀 page-agent.js initialized with config:', window.pageAgent.config)
})
+39 -39
View File
@@ -1,41 +1,41 @@
{
"name": "@page-agent/page-controller",
"version": "0.3.0",
"type": "module",
"main": "./dist/lib/page-controller.js",
"module": "./dist/lib/page-controller.js",
"types": "./dist/lib/PageController.d.ts",
"exports": {
".": {
"types": "./dist/lib/PageController.d.ts",
"import": "./dist/lib/page-controller.js",
"default": "./dist/lib/page-controller.js"
}
},
"files": [
"dist/"
],
"description": "Page controller for page-agent - DOM operations and element interactions",
"keywords": [
"page-agent",
"dom",
"browser-automation",
"web-automation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/page-controller"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"ai-motion": "^0.4.8"
}
"name": "@page-agent/page-controller",
"version": "1.0.0",
"type": "module",
"main": "./dist/lib/page-controller.js",
"module": "./dist/lib/page-controller.js",
"types": "./dist/lib/PageController.d.ts",
"exports": {
".": {
"types": "./dist/lib/PageController.d.ts",
"import": "./dist/lib/page-controller.js",
"default": "./dist/lib/page-controller.js"
}
},
"files": [
"dist/"
],
"description": "Page controller for page-agent - DOM operations and element interactions",
"keywords": [
"page-agent",
"dom",
"browser-automation",
"web-automation"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/page-controller"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
},
"dependencies": {
"ai-motion": "^0.4.8"
}
}
@@ -80,6 +80,9 @@ export class PageController extends EventTarget {
/** last time the tree was updated */
private lastTimeUpdate = 0
/** Whether the tree has been indexed at least once */
private isIndexed = false
/** Visual mask overlay for blocking user interaction during automation */
private mask: InstanceType<typeof import('./mask/SimulatorMask').SimulatorMask> | null = null
private maskReady: Promise<void> | null = null
@@ -196,6 +199,9 @@ export class PageController extends EventTarget {
this.elementTextMap.clear()
this.elementTextMap = dom.getElementTextMap(this.simplifiedHTML)
// Mark as indexed - now element actions are allowed
this.isIndexed = true
// Restore mask blocking
if (this.mask) {
this.mask.wrapper.style.pointerEvents = 'auto'
@@ -215,11 +221,22 @@ export class PageController extends EventTarget {
// ======= Element Actions =======
/**
* Ensure the tree has been indexed before any index-based operation.
* Throws if updateTree() hasn't been called yet.
*/
private assertIndexed(): void {
if (!this.isIndexed) {
throw new Error('DOM tree not indexed. Can not perform actions on elements.')
}
}
/**
* Click element by index
*/
async clickElement(index: number): Promise<ActionResult> {
try {
this.assertIndexed()
const element = getElementByIndex(this.selectorMap, index)
const elemText = this.elementTextMap.get(index)
await clickElement(element)
@@ -249,6 +266,7 @@ export class PageController extends EventTarget {
*/
async inputText(index: number, text: string): Promise<ActionResult> {
try {
this.assertIndexed()
const element = getElementByIndex(this.selectorMap, index)
const elemText = this.elementTextMap.get(index)
await inputTextElement(element, text)
@@ -270,6 +288,7 @@ export class PageController extends EventTarget {
*/
async selectOption(index: number, optionText: string): Promise<ActionResult> {
try {
this.assertIndexed()
const element = getElementByIndex(this.selectorMap, index)
const elemText = this.elementTextMap.get(index)
await selectOptionElement(element as HTMLSelectElement, optionText)
@@ -298,6 +317,8 @@ export class PageController extends EventTarget {
try {
const { down, numPages, pixels, index } = options
this.assertIndexed()
const scrollAmount = pixels ?? numPages * (down ? 1 : -1) * window.innerHeight
const element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null
@@ -327,6 +348,8 @@ export class PageController extends EventTarget {
try {
const { right, pixels, index } = options
this.assertIndexed()
const scrollAmount = pixels * (right ? 1 : -1)
const element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null
@@ -394,6 +417,7 @@ export class PageController extends EventTarget {
this.selectorMap.clear()
this.elementTextMap.clear()
this.simplifiedHTML = '<EMPTY>'
this.isIndexed = false
this.mask?.dispose()
this.mask = null
}
+36 -36
View File
@@ -1,38 +1,38 @@
{
"name": "@page-agent/ui",
"version": "0.3.0",
"type": "module",
"main": "./dist/lib/page-agent-ui.js",
"module": "./dist/lib/page-agent-ui.js",
"types": "./dist/lib/index.d.ts",
"exports": {
".": {
"types": "./dist/lib/index.d.ts",
"import": "./dist/lib/page-agent-ui.js",
"default": "./dist/lib/page-agent-ui.js"
}
},
"files": [
"dist/"
],
"description": "UI components for page-agent - Panel and i18n",
"keywords": [
"page-agent",
"ui",
"panel",
"i18n"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/ui"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
}
"name": "@page-agent/ui",
"version": "1.0.0",
"type": "module",
"main": "./dist/lib/page-agent-ui.js",
"module": "./dist/lib/page-agent-ui.js",
"types": "./dist/lib/index.d.ts",
"exports": {
".": {
"types": "./dist/lib/index.d.ts",
"import": "./dist/lib/page-agent-ui.js",
"default": "./dist/lib/page-agent-ui.js"
}
},
"files": [
"dist/"
],
"description": "UI components for page-agent - Panel and i18n",
"keywords": [
"page-agent",
"ui",
"panel",
"i18n"
],
"author": "Simon<gaomeng1900>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alibaba/page-agent.git",
"directory": "packages/ui"
},
"homepage": "https://alibaba.github.io/page-agent/",
"scripts": {
"build": "vite build",
"prepublishOnly": "node -e \"const fs=require('fs');['LICENSE'].forEach(f=>fs.copyFileSync('../../'+f,f))\"",
"postpublish": "node -e \"['LICENSE'].forEach(f=>{try{require('fs').unlinkSync(f)}catch{}})\""
}
}
+18 -9
View File
@@ -563,9 +563,8 @@ export class Panel {
// 2. Render each history event
const history = this.#agent.history
for (let i = 0; i < history.length; i++) {
const event = history[i]
items.push(...this.#createHistoryCards(event, i + 1))
for (const event of history) {
items.push(...this.#createHistoryCards(event))
}
this.#historySection.innerHTML = items.join('')
@@ -577,14 +576,17 @@ export class Panel {
}
/** Create cards for a history event */
#createHistoryCards(event: PanelAgentAdapter['history'][number], stepNumber: number): string[] {
#createHistoryCards(event: PanelAgentAdapter['history'][number]): string[] {
const cards: string[] = []
const time = formatTime(this.#config.language ?? 'en-US')
const meta = this.#i18n.t('ui.panel.step', {
number: stepNumber.toString(),
time,
duration: '',
})
const meta =
event.type === 'step' && event.stepIndex !== undefined
? this.#i18n.t('ui.panel.step', {
number: (event.stepIndex + 1).toString(),
time,
duration: '',
})
: time
if (event.type === 'step') {
// Reflection card
@@ -606,6 +608,13 @@ export class Panel {
)
} else if (event.type === 'user_takeover') {
cards.push(createCard({ icon: '👤', content: 'User takeover', meta, type: 'input' }))
} else if (event.type === 'retry') {
const retryInfo = `${event.message || 'Retrying'} (${event.attempt}/${event.maxAttempts})`
cards.push(createCard({ icon: '🔄', content: retryInfo, meta, type: 'observation' }))
} else if (event.type === 'error') {
cards.push(
createCard({ icon: '❌', content: event.message || 'Error', meta, type: 'observation' })
)
}
return cards
+7 -1
View File
@@ -33,7 +33,8 @@ export interface PanelAgentAdapter extends EventTarget {
/** History of agent events */
readonly history: readonly {
type: 'step' | 'observation' | 'user_takeover' | 'error'
type: 'step' | 'observation' | 'user_takeover' | 'retry' | 'error'
stepIndex?: number
/** For 'step' type */
reflection?: {
evaluation_previous_goal?: string
@@ -48,6 +49,11 @@ export interface PanelAgentAdapter extends EventTarget {
}
/** For 'observation' type */
content?: string
/** For 'retry' type */
attempt?: number
maxAttempts?: number
/** For 'retry' and 'error' types */
message?: string
}[]
/** Current task being executed */
+40 -40
View File
@@ -1,42 +1,42 @@
{
"name": "@page-agent/website",
"private": true,
"version": "0.3.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build:website": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"@types/react": "^19.2.8",
"@types/react-dom": "^19.2.1",
"@vitejs/plugin-react-swc": "^4.1.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-i18next": "^16.5.2",
"tailwindcss": "^4.1.14",
"tw-animate-css": "^1.4.0",
"wouter": "^3.9.0"
},
"dependencies": {
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tooltip": "^1.2.8",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"motion": "^12.26.1",
"next-themes": "^0.4.6",
"rough-notation": "^0.5.1",
"simple-icons": "^16.5.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0"
}
"name": "@page-agent/website",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build:website": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"@types/react": "^19.2.8",
"@types/react-dom": "^19.2.1",
"@vitejs/plugin-react-swc": "^4.1.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-i18next": "^16.5.3",
"tailwindcss": "^4.1.14",
"tw-animate-css": "^1.4.0",
"wouter": "^3.9.0"
},
"dependencies": {
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tooltip": "^1.2.8",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"motion": "^12.27.1",
"next-themes": "^0.4.6",
"rough-notation": "^0.5.1",
"simple-icons": "^16.6.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0"
}
}
+3 -2
View File
@@ -1,7 +1,8 @@
// Demo build (auto-init with demo LLM, for quick testing)
export const CDN_DEMO_URL = 'https://cdn.jsdelivr.net/npm/page-agent/dist/iife/page-agent.demo.js'
export const CDN_DEMO_URL =
'https://cdn.jsdelivr.net/npm/page-agent@1.0.0/dist/iife/page-agent.demo.js'
export const CDN_DEMO_CN_URL =
'https://registry.npmmirror.com/page-agent/latest/files/dist/iife/page-agent.demo.js'
'https://registry.npmmirror.com/page-agent/1.0.0/files/dist/iife/page-agent.demo.js'
// Demo LLM for website testing
export const DEMO_MODEL = 'PAGE-AGENT-FREE-TESTING-RANDOM'
@@ -105,8 +105,8 @@ const result = await agent.execute('Fill in the form with test data')`}
type: 'string',
required: true,
description: isZh
? '模型名称(如 gpt-4o, claude-3.5-sonnet'
: 'Model name (e.g., gpt-4o, claude-3.5-sonnet)',
? '模型名称(如 gpt-5.2, anthropic/claude-4.5-haiku'
: 'Model name (e.g., gpt-5.2, anthropic/claude-4.5-haiku)',
},
{
name: 'temperature',
@@ -149,6 +149,12 @@ const result = await agent.execute('Fill in the form with test data')`}
defaultValue: "'en-US'",
description: isZh ? 'Agent 输出语言' : 'Agent output language',
},
{
name: 'maxSteps',
type: 'number',
defaultValue: '20',
description: isZh ? '每个任务的最大步骤数' : 'Maximum number of steps per task',
},
{
name: 'customTools',
type: 'Record<string, PageAgentTool | null>',
@@ -207,35 +213,48 @@ const result = await agent.execute('Fill in the form with test data')`}
{/* Lifecycle Hooks */}
<section className="mb-10">
<h2 className="text-2xl font-semibold mb-4">{isZh ? '生命周期钩子' : 'Lifecycle Hooks'}</h2>
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4">
<p className="text-amber-800 dark:text-amber-200 text-sm">
<strong> {isZh ? '警告' : 'Warning'}:</strong>{' '}
{isZh
? '这些接口高度实验性,可能在未来版本中发生变化。建议优先使用事件系统(Events)来监听 Agent 状态。'
: 'These APIs are highly experimental and may change in future versions. Prefer using the Events system for monitoring agent state.'}
</p>
</div>
<p className="text-gray-600 dark:text-gray-400 mb-4">
{isZh
? '所有生命周期钩子都接收 agent 实例作为第一个参数,便于在回调中访问 Agent 状态和方法。'
: 'All lifecycle hooks receive the agent instance as first parameter, making it easy to access agent state and methods in callbacks.'}
</p>
<APIReference
properties={[
{
name: 'onBeforeStep',
type: '(stepCnt: number) => void | Promise<void>',
type: '(agent: PageAgentCore, stepCount: number) => void | Promise<void>',
description: isZh ? '每个步骤执行前调用' : 'Called before each step execution',
status: 'experimental',
},
{
name: 'onAfterStep',
type: '(history: HistoricalEvent[]) => void | Promise<void>',
type: '(agent: PageAgentCore, history: HistoricalEvent[]) => void | Promise<void>',
description: isZh ? '每个步骤执行后调用' : 'Called after each step execution',
status: 'experimental',
},
{
name: 'onBeforeTask',
type: '() => void | Promise<void>',
type: '(agent: PageAgentCore) => void | Promise<void>',
description: isZh ? '任务开始前调用' : 'Called before task starts',
status: 'experimental',
},
{
name: 'onAfterTask',
type: '(result: ExecutionResult) => void | Promise<void>',
type: '(agent: PageAgentCore, result: ExecutionResult) => void | Promise<void>',
description: isZh ? '任务结束后调用' : 'Called after task ends',
status: 'experimental',
},
{
name: 'onDispose',
type: '(reason?: string) => void',
type: '(agent: PageAgentCore, reason?: string) => void',
description: isZh ? 'Agent 销毁时调用' : 'Called when agent is disposed',
status: 'experimental',
},
@@ -53,7 +53,7 @@ const agent = new PageAgent({
// LLM Configuration (required)
baseURL: 'https://api.openai.com/v1',
apiKey: 'your-api-key',
model: 'gpt-4o',
model: 'gpt-5.2',
// Optional settings
language: 'en-US',
+36 -5
View File
@@ -9,6 +9,7 @@
import chalk from 'chalk'
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'fs'
import { dirname, join } from 'path'
import { exit } from 'process'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
@@ -17,17 +18,23 @@ const rootDir = join(__dirname, '..')
// Parse arguments
const versionArg = process.argv[2]
if (!versionArg) {
console.log(chalk.yellow('⚠️ No version specified.\n'))
exit(1)
}
// Read root package.json
const rootPkgPath = join(rootDir, 'package.json')
const rootPkg = JSON.parse(readFileSync(rootPkgPath, 'utf-8'))
const newVersion = versionArg || rootPkg.version
const oldVersion = rootPkg.version
const newVersion = versionArg
console.log(chalk.cyan.bold('\n📦 Syncing version\n'))
// Update root package.json if new version specified
if (versionArg) {
rootPkg.version = newVersion
writeFileSync(rootPkgPath, JSON.stringify(rootPkg, null, '\t') + '\n')
writeFileSync(rootPkgPath, JSON.stringify(rootPkg, null, ' ') + '\n')
console.log(chalk.green('✓') + ` ${chalk.bold('root')}${chalk.yellow(newVersion)}`)
} else {
console.log(chalk.dim(' root:') + ` ${chalk.yellow(newVersion)} ${chalk.dim('(source)')}`)
@@ -69,11 +76,10 @@ for (const pkg of packages) {
if (!existsSync(pkgPath)) continue
const pkgJson = JSON.parse(readFileSync(pkgPath, 'utf-8'))
const oldVersion = pkgJson.version
let pkgChanged = false
// Update package version
if (oldVersion !== newVersion) {
if (pkgJson.version !== newVersion) {
pkgJson.version = newVersion
pkgChanged = true
}
@@ -88,7 +94,7 @@ for (const pkg of packages) {
continue
}
writeFileSync(pkgPath, JSON.stringify(pkgJson, null, '\t') + '\n')
writeFileSync(pkgPath, JSON.stringify(pkgJson, null, ' ') + '\n')
console.log(
chalk.green('✓') +
` ${chalk.bold(pkgJson.name)}: ${chalk.dim(oldVersion)}${chalk.yellow(newVersion)}`
@@ -96,6 +102,31 @@ for (const pkg of packages) {
hasChanges = true
}
// Update CDN URLs in documentation and source files
const CDN_DEMO_URL_OLD = `https://cdn.jsdelivr.net/npm/page-agent@${oldVersion}/dist/iife/page-agent.demo.js`
const CDN_DEMO_URL_NEW = `https://cdn.jsdelivr.net/npm/page-agent@${newVersion}/dist/iife/page-agent.demo.js`
const CDN_DEMO_CN_URL_OLD = `https://registry.npmmirror.com/page-agent/${oldVersion}/files/dist/iife/page-agent.demo.js`
const CDN_DEMO_CN_URL_NEW = `https://registry.npmmirror.com/page-agent/${newVersion}/files/dist/iife/page-agent.demo.js`
const filesToUpdateCdn = ['README.md', 'README-zh.md', 'packages/website/src/constants.ts']
for (const relPath of filesToUpdateCdn) {
const filePath = join(rootDir, relPath)
if (!existsSync(filePath)) continue
let content = readFileSync(filePath, 'utf-8')
const original = content
content = content.replaceAll(CDN_DEMO_URL_OLD, CDN_DEMO_URL_NEW)
content = content.replaceAll(CDN_DEMO_CN_URL_OLD, CDN_DEMO_CN_URL_NEW)
if (content !== original) {
writeFileSync(filePath, content)
console.log(chalk.green('✓') + ` ${chalk.bold(relPath)}: CDN URLs updated`)
hasChanges = true
}
}
console.log(chalk.green.bold(`\n✓ Version synced: ${newVersion}\n`))
// Show git commands hint