From 5716966b6d32189ed71f28239802b00b7a0decb2 Mon Sep 17 00:00:00 2001 From: Simon <10131203+gaomeng1900@users.noreply.github.com> Date: Tue, 21 Oct 2025 19:39:06 +0800 Subject: [PATCH] feat: add hooks for step lifecycle --- ROADMAP.md | 1 + src/PageAgent.ts | 4 ++++ src/config/index.ts | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 28e9acf..affde59 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -17,6 +17,7 @@ The development progress and future plans for PageAgent. - [x] **Free evaluation plan?** - [x] **Custom actions and HITL** - [ ] **Hooks and Events** + - [x] **Step lifecycle** - [ ] **Hijacking `page_open` event** - [ ] **Custom knowledge base and instructions** - [ ] **Black/white-list safeguard** diff --git a/src/PageAgent.ts b/src/PageAgent.ts index f49310a..668d649 100644 --- a/src/PageAgent.ts +++ b/src/PageAgent.ts @@ -156,6 +156,8 @@ export class PageAgent extends EventTarget { let step = 0 while (true) { + if (this.config.onBeforeStep) await this.config.onBeforeStep.call(this, step) + console.group(`step: ${step + 1}`) // abort @@ -209,6 +211,8 @@ export class PageAgent extends EventTarget { console.log(chalk.green('Step finished:'), actionName) console.groupEnd() + if (this.config.onAfterStep) await this.config.onAfterStep.call(this, step, this.history) + step++ if (step > MAX_STEPS) { this.#onDone('Step count exceeded maximum limit', false) diff --git a/src/config/index.ts b/src/config/index.ts index 6060efe..3859fde 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -1,3 +1,4 @@ +import type { AgentHistory, PageAgent } from '@/PageAgent' import type { DomConfig } from '@/dom' import type { SupportedLanguage } from '@/i18n' import type { PageAgentTool } from '@/tools' @@ -47,6 +48,11 @@ export interface UIConfig { * } */ customTools?: Record + + // hooks + + onBeforeStep?: (this: PageAgent, stepCnt: number) => Promise | void + onAfterStep?: (this: PageAgent, stepCnt: number, history: AgentHistory[]) => Promise | void } export type PageAgentConfig = LLMConfig & DomConfig & UIConfig