@coolkiller007/my-page-agent 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -6,13 +6,13 @@ declare interface ActionResult {
6
6
  }
7
7
 
8
8
  /**
9
- * Agent activity - transient state for immediate UI feedback.
9
+ * Agent 活动 - 用于即时 UI 反馈的瞬态状态。
10
10
  *
11
- * Unlike historical events (which are persisted), activities are ephemeral
12
- * and represent "what the agent is doing right now". UI components should
13
- * listen to 'activity' events to show real-time feedback.
11
+ * 与历史事件(被持久化)不同,活动是短暂的,
12
+ * 表示"Agent 此刻正在做什么"UI 组件应监听
13
+ * 'activity' 事件以显示实时反馈。
14
14
  *
15
- * Note: There is no 'idle' activity - absence of activity events means idle.
15
+ * 注:没有 'idle' 活动 —— 没有活动事件即表示空闲。
16
16
  */
17
17
  export declare type AgentActivity = {
18
18
  type: 'thinking';
@@ -38,18 +38,23 @@ export declare type AgentActivity = {
38
38
  declare interface AgentConfig extends LLMConfig {
39
39
  language?: SupportedLanguage;
40
40
  /**
41
- * Maximum number of steps the agent can take per task.
41
+ * 每个任务中 Agent 可以执行的最大步数。
42
42
  * @default 40
43
43
  */
44
44
  maxSteps?: number;
45
45
  /**
46
- * Custom tools to extend PageAgent capabilities
46
+ * 拼装 LLM 提示词时,最近保留完整详情的历史步数;更早的步骤会被压缩成一行。
47
+ * @default 15
48
+ */
49
+ historyWindow?: number;
50
+ /**
51
+ * 用于扩展 PageAgent 能力的自定义工具
47
52
  * @experimental
48
- * @note You can also override or remove internal tools by using the same name.
53
+ * @note 你也可以通过使用相同名称来覆盖或移除内部工具。
49
54
  * @see AgentTool
50
55
  *
51
56
  * @example
52
- * // override internal tool
57
+ * // 覆盖内部工具
53
58
  * import { z } from 'zod/v4'
54
59
  * import { tool } from '@coolkiller007/my-page-agent'
55
60
  * const customTools = {
@@ -67,112 +72,112 @@ declare interface AgentConfig extends LLMConfig {
67
72
  * }
68
73
  *
69
74
  * @example
70
- * // remove internal tool
75
+ * // 移除内部工具
71
76
  * const customTools = {
72
- * ask_user: null // never ask user questions
77
+ * ask_user: null // 永远不要向用户提问
73
78
  * }
74
79
  */
75
80
  customTools?: Record<string, AgentTool | null>;
76
81
  /**
77
- * Instructions to guide the agent's behavior
82
+ * 用于引导 Agent 行为的指令
78
83
  */
79
84
  instructions?: {
80
85
  /**
81
- * Global system-level instructions, applied to all tasks
86
+ * 全局系统级指令,应用于所有任务
82
87
  */
83
88
  system?: string;
84
89
  /**
85
- * Dynamic page-level instructions callback
86
- * Called before each step to get instructions for the current page
87
- * @param url - Current page URL (window.location.href)
88
- * @returns Instructions string, or undefined/null to skip
90
+ * 动态的页面级指令回调
91
+ * 每一步前调用,以获取当前页面的指令
92
+ * @param url - 当前页面 URLwindow.location.href
93
+ * @returns 指令字符串,或返回 undefined/null 以跳过
89
94
  */
90
95
  getPageInstructions?: (url: string) => string | undefined | null;
91
96
  };
92
97
  /**
93
- * Lifecycle hooks for task execution.
94
- * @experimental API may change in future versions.
98
+ * 任务执行的生命周期钩子。
99
+ * @experimental API 在未来版本中可能变化。
95
100
  *
96
- * All hooks receive the agent instance as first parameter.
101
+ * 所有钩子都接收 Agent 实例作为第一个参数。
97
102
  */
98
103
  /**
99
- * Called before each step execution.
104
+ * 每一步执行前调用。
100
105
  * @experimental
101
- * @param agent - The AgentRuntime instance
102
- * @param stepCount - Current step number (0-indexed)
106
+ * @param agent - AgentRuntime 实例
107
+ * @param stepCount - 当前步骤序号(从 0 开始)
103
108
  */
104
109
  onBeforeStep?: (agent: AgentRuntime, stepCount: number) => Promise<void> | void;
105
110
  /**
106
- * Called after each step execution.
111
+ * 每一步执行后调用。
107
112
  * @experimental
108
- * @param agent - The AgentRuntime instance
109
- * @param history - Current history of events
113
+ * @param agent - AgentRuntime 实例
114
+ * @param history - 当前的事件历史
110
115
  */
111
116
  onAfterStep?: (agent: AgentRuntime, history: HistoricalEvent[]) => Promise<void> | void;
112
117
  /**
113
- * Called before task execution starts.
118
+ * 任务执行开始前调用。
114
119
  * @experimental
115
- * @param agent - The AgentRuntime instance
120
+ * @param agent - AgentRuntime 实例
116
121
  */
117
122
  onBeforeTask?: (agent: AgentRuntime) => Promise<void> | void;
118
123
  /**
119
- * Called after task execution completes (success or failure).
124
+ * 任务执行完成(成功或失败)后调用。
120
125
  * @experimental
121
- * @param agent - The AgentRuntime instance
122
- * @param result - The execution result
126
+ * @param agent - AgentRuntime 实例
127
+ * @param result - 执行结果
123
128
  */
124
129
  onAfterTask?: (agent: AgentRuntime, result: ExecutionResult) => Promise<void> | void;
125
130
  /**
126
- * Called when the agent is disposed.
131
+ * Agent 被销毁时调用。
127
132
  * @experimental
128
- * @note This hook can block the disposal process if it's async.
129
- * @param agent - The AgentRuntime instance
130
- * @param reason - Optional reason for disposal
133
+ * @note 若该钩子是异步的,它可能会阻塞销毁流程。
134
+ * @param agent - AgentRuntime 实例
135
+ * @param reason - 可选的销毁原因
131
136
  */
132
137
  onDispose?: (agent: AgentRuntime, reason?: string) => void;
133
138
  /**
134
139
  * @experimental
135
- * Enable the experimental script execution tool that allows executing generated JavaScript code on the page.
136
- * @note Can cause unpredictable side effects.
137
- * @note May bypass some safe guards and data-masking mechanisms.
140
+ * 启用实验性的脚本执行工具,允许在页面上执行生成的 JavaScript 代码。
141
+ * @note 可能产生不可预测的副作用。
142
+ * @note 可能绕过某些安全防护和数据遮蔽机制。
138
143
  */
139
144
  experimentalScriptExecutionTool?: boolean;
140
145
  /**
141
146
  * @experimental
142
- * Fetch /llms.txt from current site origin and include as context.
143
- * Only fetched once per origin per task.
147
+ * 从当前站点源拉取 /llms.txt 并作为上下文包含进来。
148
+ * 每个源每个任务只拉取一次。
144
149
  * @default false
145
150
  */
146
151
  experimentalLlmsTxt?: boolean;
147
152
  /**
148
- * Transform page content before sending to LLM.
149
- * Called after DOM extraction and simplification, before LLM invocation.
150
- * Use cases: inspect extraction results, modify page info, mask sensitive data.
153
+ * 在发送给 LLM 之前转换页面内容。
154
+ * DOM 提取和简化之后、调用 LLM 之前调用。
155
+ * 使用场景:检查提取结果、修改页面信息、遮蔽敏感数据。
151
156
  *
152
- * @param content - Simplified page content that will be sent to LLM
153
- * @returns Transformed content
157
+ * @param content - 将被发送给 LLM 的简化页面内容
158
+ * @returns 转换后的内容
154
159
  *
155
160
  * @example
156
- * // Mask phone numbers
161
+ * // 遮蔽手机号
157
162
  * transformPageContent: async (content) => {
158
163
  * return content.replace(/1[3-9]\d{9}/g, '***********')
159
164
  * }
160
165
  */
161
166
  transformPageContent?: (content: string) => Promise<string> | string;
162
167
  /**
163
- * Completely override the default system prompt.
164
- * @experimental Use with caution - incorrect prompts may break agent behavior.
168
+ * 完全覆盖默认的系统提示词。
169
+ * @experimental 谨慎使用 - 错误的提示词可能破坏 Agent 行为。
165
170
  */
166
171
  customSystemPrompt?: string;
167
172
  /**
168
- * Delay between steps in seconds.
173
+ * 步骤之间的延迟(秒)。
169
174
  * @default 0.4
170
175
  */
171
176
  stepDelay?: number;
172
177
  }
173
178
 
174
179
  /**
175
- * Error event - fatal error from LLM or execution
180
+ * 错误事件 - 来自 LLM 或执行的致命错误
176
181
  */
177
182
  declare interface AgentErrorEvent {
178
183
  type: 'error';
@@ -181,12 +186,12 @@ declare interface AgentErrorEvent {
181
186
  }
182
187
 
183
188
  /**
184
- * Agent reflection state - the reflection-before-action model
189
+ * Agent 反思状态 - 行动前先反思的模型
185
190
  *
186
- * Every tool call must first reflect on:
187
- * - evaluation_previous_goal: How well did the previous action achieve its goal?
188
- * - memory: Key information to remember for future steps
189
- * - next_goal: What should be accomplished in the next action?
191
+ * 每次工具调用都必须先反思:
192
+ * - evaluation_previous_goal: 上一个动作在多大程度上实现了其目标?
193
+ * - memory: 需要在未来步骤中记住的关键信息
194
+ * - next_goal: 下一个动作应该完成什么?
190
195
  */
191
196
  declare interface AgentReflection {
192
197
  evaluation_previous_goal: string;
@@ -195,75 +200,83 @@ declare interface AgentReflection {
195
200
  }
196
201
 
197
202
  /**
198
- * AI agent for browser automation.
203
+ * 用于浏览器自动化的 AI 智能体。
199
204
  *
200
205
  * @remarks
201
- * ## Re-act Agent Loop
202
- * - step
203
- * - observe (gather information about current environment and context)
204
- * - think (LLM calling)
205
- * - reflection (evaluate history, generate memory, short-term planning)
206
- * - action (give the action to approach the next goal)
207
- * - act (execute the action)
208
- * - loop
206
+ * ## 反应式 Agent 循环
207
+ * - 步骤
208
+ * - 观察(收集当前环境与上下文信息)
209
+ * - 思考(调用 LLM
210
+ * - 反思(评估历史、生成记忆、短期规划)
211
+ * - 行动(给出接近下一个目标的动作)
212
+ * - 执行(执行动作)
213
+ * - 循环
209
214
  *
210
- * ## Event System
211
- * - `statuschange` - Agent status transitions (idle → running → completed/error/stopped)
212
- * - `historychange` - History events updated (persistent, part of agent memory)
213
- * - `activity` - Real-time activity feedback (transient, for UI only)
214
- * - `dispose` - Agent cleanup triggered
215
+ * ## 事件系统
216
+ * - `statuschange` - Agent 状态变更(idle → running → completed/error/stopped
217
+ * - `historychange` - 历史事件更新(持久化,属于 Agent 记忆的一部分)
218
+ * - `activity` - 实时活动反馈(瞬态,仅用于 UI
219
+ * - `dispose` - 触发 Agent 清理
215
220
  *
216
- * ## Information Streams
217
- * 1. **History Events** (`history` array)
218
- * - Persistent event stream that forms agent's memory
219
- * - Included in LLM context across steps
220
- * - Types: steps, observations, user takeovers, llm errors
221
+ * ## 信息流
222
+ * 1. **历史事件**(`history` 数组)
223
+ * - 构成 Agent 记忆的持久事件流
224
+ * - 跨步骤包含在 LLM 上下文中
225
+ * - 类型:步骤、观察、用户接管、LLM 错误
221
226
  *
222
- * 2. **Activity Events** (via `activity` event)
223
- * - Transient UI feedback during task execution
224
- * - NOT included in LLM context
225
- * - Types: thinking, executing, executed, retrying, error
227
+ * 2. **活动事件**(通过 `activity` 事件)
228
+ * - 任务执行期间的瞬时 UI 反馈
229
+ * - 不包含在 LLM 上下文中
230
+ * - 类型:thinkingexecutingexecutedretryingerror
226
231
  */
227
232
  declare class AgentRuntime extends EventTarget {
228
233
  #private;
234
+ /** Agent 唯一 ID */
229
235
  readonly id: string;
236
+ /** 合并后的 Agent 配置(含最大步数上限) */
230
237
  readonly config: AgentRuntimeConfig & {
231
238
  maxSteps: number;
239
+ historyWindow: number;
232
240
  };
241
+ /** 内部工具集合(按工具名索引) */
233
242
  readonly tools: typeof tools;
234
- /** BrowserController for DOM operations */
243
+ /** 用于 DOM 操作的 BrowserController */
235
244
  readonly browserController: BrowserController;
245
+ /** 当前任务描述 */
236
246
  task: string;
247
+ /** 当前任务 ID */
237
248
  taskId: string;
238
- /** History events */
249
+ /** 历史事件 */
239
250
  history: HistoricalEvent[];
240
- /** Whether this agent has been disposed */
251
+ /** Agent 是否已被销毁 */
241
252
  disposed: boolean;
242
253
  /**
243
- * Called when the agent needs to ask the user questions.
244
- * If unset, the `ask_user` tool will be disabled.
245
- * Implementations should reject the promise when `signal` aborts.
254
+ * Agent 需要向用户提问时调用。
255
+ * 若未设置,`ask_user` 工具将被禁用。
256
+ * 实现应在 `signal` 中止时 reject Promise。
246
257
  * @example onAskUser: (q) => window.prompt(q) || ''
247
258
  */
248
259
  onAskUser?: (question: string, options?: {
249
260
  signal: AbortSignal;
250
261
  }) => Promise<string>;
262
+ /** 构造函数:初始化配置、LLM、工具集,并注册重试事件监听与注入自定义工具 */
251
263
  constructor(config: AgentRuntimeConfig);
252
- /** Get current agent status */
264
+ /** 获取当前 Agent 状态 */
253
265
  get status(): AgentStatus;
254
- /** Result of the most recent run, or `null` before the first run completes. */
266
+ /** 最近一次运行的结果,首次运行完成前为 `null`。 */
255
267
  get lastResult(): ExecutionResult | null;
256
268
  /* Excluded from this release type: pushObservation */
257
269
  /**
258
- * Stop the current task and wait until the run has fully settled (including lifecycle hooks).
259
- * @note never await .stop() in a lifecycle hook.
270
+ * 停止当前任务,并等待运行完全结束(包括生命周期钩子)。
271
+ * @note 切勿在生命周期钩子中 await .stop()
260
272
  */
261
273
  stop(): Promise<void>;
262
274
  /**
263
- * external errors (pre-checks/config/hooks) will threw;
264
- * agent errors will be caught and added to history, and return a failed result
275
+ * 外部错误(前置检查/配置/钩子)会直接抛出;
276
+ * Agent 内部错误会被捕获并加入历史,同时返回失败结果
265
277
  */
266
278
  execute(task: string): Promise<ExecutionResult>;
279
+ /** 销毁 Agent:中止任务、释放浏览器控制器,并触发 dispose 事件(一次性) */
267
280
  dispose(): void;
268
281
  }
269
282
 
@@ -272,12 +285,12 @@ declare type AgentRuntimeConfig = AgentConfig & {
272
285
  };
273
286
 
274
287
  /**
275
- * Agent lifecycle status.
288
+ * Agent 生命周期状态。
276
289
  */
277
290
  export declare type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'stopped';
278
291
 
279
292
  /**
280
- * A single agent step with reflection and action
293
+ * 带反思和动作的单个 Agent 步骤
281
294
  */
282
295
  declare interface AgentStepEvent {
283
296
  type: 'step';
@@ -295,14 +308,14 @@ declare interface AgentStepEvent {
295
308
  cachedTokens?: number;
296
309
  reasoningTokens?: number;
297
310
  };
298
- /** Raw LLM response for debugging */
311
+ /** 原始 LLM 响应(用于调试) */
299
312
  rawResponse?: unknown;
300
- /** Raw LLM request for debugging */
313
+ /** 原始 LLM 请求(用于调试) */
301
314
  rawRequest?: unknown;
302
315
  }
303
316
 
304
317
  /**
305
- * Internal tool definition that has access to PageAgent `this` context
318
+ * 内部工具定义,可访问 PageAgent `this` 上下文
306
319
  */
307
320
  declare interface AgentTool<TParams = any> {
308
321
  description: string;
@@ -311,84 +324,86 @@ declare interface AgentTool<TParams = any> {
311
324
  }
312
325
 
313
326
  /**
314
- * BrowserController manages DOM state and element interactions.
315
- * It provides async methods for all DOM operations, keeping state isolated.
327
+ * BrowserController 管理 DOM 状态和元素交互。
328
+ * 它为所有 DOM 操作提供异步方法,并保持状态隔离。
316
329
  *
317
330
  * @lifecycle
318
- * - beforeUpdate: Emitted before the DOM tree is updated.
319
- * - afterUpdate: Emitted after the DOM tree is updated.
331
+ * - beforeUpdate: DOM 树更新之前触发。
332
+ * - afterUpdate: DOM 树更新之后触发。
320
333
  */
321
334
  declare class BrowserController extends EventTarget {
322
335
  private config;
323
- /** Corresponds to eval_page in browser-use */
336
+ /** 对应 browser-use 中的 eval_page */
324
337
  private flatTree;
325
338
  /**
326
- * All highlighted index-mapped interactive elements
327
- * Corresponds to DOMState.selector_map in browser-use
339
+ * 所有已索引的高亮交互元素
340
+ * 对应 browser-use 中的 DOMState.selector_map
328
341
  */
329
342
  private selectorMap;
330
- /** Index -> element text description mapping */
343
+ /** 索引 -> 元素文本描述映射 */
331
344
  private elementTextMap;
332
345
  /**
333
- * Simplified HTML for LLM consumption.
334
- * Corresponds to clickable_elements_to_string in browser-use
346
+ * LLM 消费的简化 HTML。
347
+ * 对应 browser-use 中的 clickable_elements_to_string
335
348
  */
336
349
  private simplifiedHTML;
337
- /** last time the tree was updated */
350
+ /** 树最后一次更新的时间 */
338
351
  private lastTimeUpdate;
339
- /** Whether the tree has been indexed at least once */
352
+ /** 树是否至少被索引过一次 */
340
353
  private isIndexed;
341
- /** Visual mask overlay for blocking user interaction during automation */
354
+ /** 用于在自动化期间阻止用户交互的视觉遮罩层 */
342
355
  private mask;
356
+ /** mask 异步初始化完成的 Promise,用于在调用前等待初始化完成 */
343
357
  private maskReady;
358
+ /** 是否已释放资源 */
344
359
  private disposed;
345
360
  constructor(config?: BrowserControllerConfig);
346
361
  /**
347
- * Initialize mask asynchronously (dynamic import to avoid CSS loading in Node)
362
+ * 异步初始化遮罩层(动态导入以避免在 Node 中加载 CSS
348
363
  */
349
364
  initMask(): void;
350
365
  /**
351
- * Get current page URL
366
+ * 获取当前页面 URL
352
367
  */
353
368
  getCurrentUrl(): Promise<string>;
354
369
  /**
355
- * Get last tree update timestamp
370
+ * 获取树最后一次更新的时间戳
356
371
  */
357
372
  getLastUpdateTime(): Promise<number>;
358
373
  /**
359
- * Get structured browser state for LLM consumption.
360
- * Automatically calls updateTree() to refresh the DOM state.
374
+ * 获取供 LLM 消费的结构化浏览器状态。
375
+ * 自动调用 updateTree() 刷新 DOM 状态。
361
376
  */
362
377
  getBrowserState(): Promise<BrowserState>;
363
378
  /**
364
- * Update DOM tree, returns simplified HTML for LLM.
365
- * This is the main method to refresh the page state.
366
- * Automatically bypasses mask during DOM extraction if enabled.
379
+ * 更新 DOM 树,返回供 LLM 使用的简化 HTML
380
+ * 这是刷新页面状态的主要方法。
381
+ * 若已启用遮罩,DOM 提取期间会自动绕过遮罩。
367
382
  */
368
383
  updateTree(): Promise<string>;
369
384
  /**
370
- * Clean up all element highlights
385
+ * 清理所有元素高亮
371
386
  */
372
387
  cleanUpHighlights(): Promise<void>;
373
388
  /**
374
- * Ensure the tree has been indexed before any index-based operation.
375
- * Throws if updateTree() hasn't been called yet.
389
+ * 在任何基于索引的操作之前确保树已被索引。
390
+ * 若尚未调用 updateTree() 则抛出异常。
376
391
  */
377
392
  private assertIndexed;
378
393
  /**
379
- * Click element by index
394
+ * 根据索引点击元素
380
395
  */
381
396
  clickElement(index: number): Promise<ActionResult>;
382
397
  /**
383
- * Input text into element by index
398
+ * 根据索引向元素输入文本
384
399
  */
385
400
  inputText(index: number, text: string): Promise<ActionResult>;
386
401
  /**
387
- * Select dropdown option by index and option text
402
+ * 根据索引和选项文本在下拉框中选中选项
388
403
  */
389
404
  selectOption(index: number, optionText: string): Promise<ActionResult>;
390
405
  /**
391
- * Scroll vertically
406
+ * 垂直滚动
392
407
  */
393
408
  scroll(options: {
394
409
  down: boolean;
@@ -397,7 +412,7 @@ declare class BrowserController extends EventTarget {
397
412
  index?: number;
398
413
  }): Promise<ActionResult>;
399
414
  /**
400
- * Scroll horizontally
415
+ * 水平滚动
401
416
  */
402
417
  scrollHorizontally(options: {
403
418
  right: boolean;
@@ -405,51 +420,55 @@ declare class BrowserController extends EventTarget {
405
420
  index?: number;
406
421
  }): Promise<ActionResult>;
407
422
  /**
408
- * Execute arbitrary JavaScript on the page.
409
- * The optional `signal` is exposed to the script scope so cooperative code
410
- * can abort promptly when the task is stopped.
423
+ * 在页面上执行任意 JavaScript
424
+ * 可选的 `signal` 会暴露到脚本作用域中,使协作代码能在任务被中止时及时退出。
411
425
  */
412
426
  executeJavascript(script: string, signal?: AbortSignal): Promise<ActionResult>;
413
427
  /**
414
- * Show the visual mask overlay.
415
- * Only works after mask is setup.
428
+ * 显示视觉遮罩层。
429
+ * 仅在遮罩初始化完成后可用。
416
430
  */
417
431
  showMask(): Promise<void>;
418
432
  /**
419
- * Hide the visual mask overlay.
420
- * Only works after mask is setup.
433
+ * 隐藏视觉遮罩层。
434
+ * 仅在遮罩初始化完成后可用。
421
435
  */
422
436
  hideMask(): Promise<void>;
423
437
  /**
424
- * Dispose and clean up resources
438
+ * 释放资源并清理
425
439
  */
426
440
  dispose(): void;
427
441
  }
428
442
 
429
443
  /**
430
- * Configuration for BrowserController
444
+ * BrowserController 的配置
431
445
  */
432
446
  declare interface BrowserControllerConfig extends dom.DomConfig {
433
- /** Enable visual mask overlay during operations (default: false) */
447
+ /** 操作期间启用视觉遮罩层(默认:false */
434
448
  enableMask?: boolean;
435
449
  }
436
450
 
437
451
  /**
438
- * Structured browser state for LLM consumption
452
+ * LLM 使用的结构化浏览器状态
439
453
  */
440
454
  declare interface BrowserState {
441
455
  url: string;
442
456
  title: string;
443
- /** Page info + scroll position hint (e.g. "Page info: 1920x1080px...\n[Start of page]") */
457
+ /** 页面信息 + 滚动位置提示(例如 "Page info: 1920x1080px...\n[Start of page]" */
444
458
  header: string;
445
- /** Simplified HTML of interactive elements */
459
+ /** 可交互元素的简化 HTML */
446
460
  content: string;
447
- /** Page footer hint (e.g. "... 300 pixels below ..." or "[End of page]") */
461
+ /** 页面底部提示(例如 "... 300 pixels below ..." "[End of page]" */
448
462
  footer: string;
449
463
  }
450
464
 
451
465
  declare function cleanUpHighlights(): void;
452
466
 
467
+ /**
468
+ * 创建智能体实例的快捷函数,内部直接实例化 MyPageAgent。
469
+ * @param config 智能体的配置对象
470
+ * @returns 创建好的 MyPageAgent 实例
471
+ */
453
472
  export declare function createAgent(config: MyPageAgentConfig): MyPageAgent;
454
473
 
455
474
  declare namespace dom {
@@ -474,8 +493,8 @@ declare interface DomConfig {
474
493
  highlightOpacity?: number;
475
494
  highlightLabelOpacity?: number;
476
495
  /**
477
- * Preserve semantic landmark tags in dehydrated output even if not interactive
478
- * @note maybe confusing for LLM combining with page scrolling, use with caution
496
+ * 即使不可交互,也保留脱水输出中的语义化地标标签
497
+ * @note 结合页面滚动时可能让 LLM 感到困惑,请谨慎使用
479
498
  **/
480
499
  keepSemanticTags?: boolean;
481
500
  }
@@ -497,6 +516,7 @@ declare interface ElementDomNode {
497
516
  [key: string]: unknown;
498
517
  }
499
518
 
519
+ /** 任务执行结果 */
500
520
  export declare interface ExecutionResult {
501
521
  success: boolean;
502
522
  data: string;
@@ -542,9 +562,9 @@ declare function getFlatTree(config: DomConfig): FlatDomTree;
542
562
  declare function getSelectorMap(flatTree: FlatDomTree): Map<number, InteractiveElementDomNode>;
543
563
 
544
564
  /**
545
- * Union type for all history events
565
+ * 所有历史事件的联合类型
546
566
  */
547
- export declare type HistoricalEvent = AgentStepEvent | ObservationEvent | UserTakeoverEvent | RetryEvent | AgentErrorEvent;
567
+ export declare type HistoricalEvent = AgentStepEvent | ObservationEvent | UserTakeoverEvent | TaskStartEvent | RetryEvent | AgentErrorEvent;
548
568
 
549
569
  declare interface InteractiveElementDomNode {
550
570
  tagName: string;
@@ -564,38 +584,39 @@ declare interface InteractiveElementDomNode {
564
584
  }
565
585
 
566
586
  /**
567
- * LLM configuration
587
+ * LLM 配置
568
588
  */
569
589
  declare interface LLMConfig {
570
590
  baseURL: string;
571
591
  model: string;
572
592
  apiKey?: string;
573
593
  /**
574
- * @deprecated No longer a standard parameter; many models reject it outright.
575
- * Use `transformRequestBody` to set it only for models you've verified.
594
+ * @deprecated 已不再是标准参数,许多模型会直接拒绝该参数。
595
+ * 请使用 `transformRequestBody` 仅为已验证支持的模型设置该参数。
576
596
  */
577
597
  temperature?: number;
578
598
  maxRetries?: number;
579
599
  /**
580
- * Transform the final request body before sending it to the provider.
581
- * Use this to implement provider-specific request tweaks such as caching hints or custom flags.
600
+ * 在发送给服务商之前转换最终的请求体。
601
+ * 用于实现特定服务商的请求定制,例如缓存提示或自定义标记。
582
602
  *
583
- * Return a new object, or mutate the input object and return undefined.
603
+ * 返回一个新对象,或就地修改输入对象并返回 undefined
584
604
  */
585
605
  transformRequestBody?: (requestBody: Record<string, unknown>) => Record<string, unknown> | undefined;
586
606
  /**
587
- * remove the tool_choice field from the request.
588
- * @note fix "Invalid tool_choice type: 'object'" for some LLMs.
607
+ * 从请求中移除 tool_choice 字段。
608
+ * @note 修复部分 LLM 报出的 "Invalid tool_choice type: 'object'" 错误。
589
609
  */
590
610
  disableNamedToolChoice?: boolean;
591
611
  /**
592
- * Custom fetch function for LLM API requests.
593
- * Use this to customize headers, credentials, proxy, etc.
594
- * The response should follow OpenAI API format.
612
+ * 用于 LLM API 请求的自定义 fetch 函数。
613
+ * 可用于自定义请求头、凭据、代理等。
614
+ * 返回的响应应符合 OpenAI API 格式。
595
615
  */
596
616
  customFetch?: typeof globalThis.fetch;
597
617
  }
598
618
 
619
+ /** 语言包集合:键为语言代码,值为对应翻译表 */
599
620
  declare const locales: {
600
621
  readonly 'en-US': {
601
622
  readonly ui: {
@@ -687,15 +708,21 @@ declare const locales: {
687
708
  };
688
709
  };
689
710
 
711
+ /**
712
+ * 完整页面智能体:组合了 AgentRuntime、BrowserController 与 UI
713
+ */
690
714
  export declare class MyPageAgent extends AgentRuntime {
715
+ /** UI 实例(用于用户交互与反馈) */
691
716
  readonly ui: UI;
717
+ /** 构造函数:创建浏览器控制器、父类运行时与 UI 实例 */
692
718
  constructor(config: MyPageAgentConfig);
693
719
  }
694
720
 
721
+ /** MyPageAgent 的配置:Agent 配置 + 浏览器控制器配置 + UI 配置(语言除外) */
695
722
  export declare type MyPageAgentConfig = Omit<AgentConfig, 'experimentalScriptExecutionTool'> & BrowserControllerConfig & Omit<UIConfig, 'language'>;
696
723
 
697
724
  /**
698
- * Persistent observation event (stays in memory)
725
+ * 持久观察事件(保留在记忆中)
699
726
  */
700
727
  declare interface ObservationEvent {
701
728
  type: 'observation';
@@ -705,7 +732,7 @@ declare interface ObservationEvent {
705
732
  declare function resolveViewportExpansion(viewportExpansion?: number): number;
706
733
 
707
734
  /**
708
- * Retry event - LLM call is being retried
735
+ * 重试事件 - LLM 调用正在重试
709
736
  */
710
737
  declare interface RetryEvent {
711
738
  type: 'retry';
@@ -714,11 +741,22 @@ declare interface RetryEvent {
714
741
  maxAttempts: number;
715
742
  }
716
743
 
717
- /** Supported UI languages */
744
+ /** 支持的 UI 语言 */
718
745
  declare type SupportedLanguage = 'en-US' | 'zh-CN';
719
746
 
747
+ /** 受支持的语言代码类型 */
720
748
  declare type SupportedLanguage_2 = keyof typeof locales;
721
749
 
750
+ /**
751
+ * 任务开始事件 - 标记一个新任务的起点
752
+ * @note history 数组跨任务持久保留(不再在每次 execute 时清空),
753
+ * 该事件用于在历史记录中分隔不同任务,UI 据此渲染各自的任务卡片。
754
+ */
755
+ declare interface TaskStartEvent {
756
+ type: 'task_start';
757
+ task: string;
758
+ }
759
+
722
760
  declare interface TextDomNode {
723
761
  type: 'TEXT_NODE';
724
762
  text: string;
@@ -726,19 +764,20 @@ declare interface TextDomNode {
726
764
  [key: string]: unknown;
727
765
  }
728
766
 
767
+ /** 创建一个工具定义(直接透传 options) */
729
768
  export declare function tool<TParams>(options: AgentTool<TParams>): AgentTool<TParams>;
730
769
 
731
770
  /**
732
- * Per-invocation context passed to every tool execution.
733
- * Tools MUST honor `signal` to support cooperative cancellation.
771
+ * 每次工具调用都会传入的上下文。
772
+ * 工具必须遵守 `signal` 以支持协作式取消。
734
773
  */
735
774
  declare interface ToolContext {
736
775
  signal: AbortSignal;
737
776
  }
738
777
 
739
778
  /**
740
- * Internal tools for PageAgent.
741
- * Note: Using any to allow different parameter types for each tool
779
+ * PageAgent 的内部工具。
780
+ * 注:使用 any 以允许每个工具拥有不同的参数类型
742
781
  */
743
782
  declare const tools: Map<string, AgentTool<any>>;
744
783
 
@@ -761,110 +800,118 @@ declare interface TreeNode {
761
800
  }
762
801
 
763
802
  /**
764
- * Agent control UI
803
+ * Agent 控制 UI
765
804
  *
766
- * Architecture:
767
- * - History list: renders directly from agent.history (historical events)
768
- * - Header bar: shows activity events (transient state) and agent status
805
+ * 架构:
806
+ * - 历史列表:直接从 agent.history 渲染(历史事件)
807
+ * - 头部栏:展示活动事件(瞬时状态)和 agent 状态
769
808
  *
770
- * This separation ensures data consistency - history is the single source of truth
771
- * for what has been done, while activity shows what is happening now.
809
+ * 这种分离保证了数据一致性 - 历史是已完成内容的唯一数据源,
810
+ * 而活动状态展示的是当前正在发生的事情。
772
811
  */
773
812
  declare class UI {
774
813
  #private;
814
+ /** 获取 UI 的根容器元素 */
775
815
  get wrapper(): HTMLElement;
776
816
  /**
777
- * Create a UI bound to an agent
778
- * @param agent - Agent instance that implements UIAdapter
779
- * @param config - Optional UI configuration
817
+ * 创建绑定到某个 agent UI
818
+ * @param agent - 实现 UIAdapter Agent 实例
819
+ * @param config - 可选的 UI 配置
780
820
  */
781
821
  constructor(agent: UIAdapter, config?: UIConfig);
822
+ /** 显示 UI(淡入 + 平移效果) */
782
823
  show(): void;
824
+ /** 隐藏 UI(淡出 + 下移效果) */
783
825
  hide(): void;
826
+ /** 重置 UI 状态(拒绝挂起问题、清空状态文本、收起历史并显示输入框) */
784
827
  reset(): void;
828
+ /** 展开历史弹窗(公开方法) */
785
829
  expand(): void;
830
+ /** 收起历史弹窗(公开方法) */
786
831
  collapse(): void;
787
832
  /**
788
- * Dispose UI and clean up event listeners
833
+ * 销毁 UI 并清理事件监听器
789
834
  */
790
835
  dispose(): void;
791
836
  }
792
837
 
793
838
  /**
794
- * Minimal interface that UI expects from an agent.
795
- * UI does not depend on PageAgent directly - it only requires this interface.
796
- * This enables decoupling and allows any agent implementation to work with UI.
839
+ * UI agent 的最简接口要求。
840
+ * UI 不直接依赖 PageAgent - 只需实现该接口即可。
841
+ * 这样实现了解耦,任何 agent 实现都能与 UI 配合使用。
797
842
  *
798
- * Events:
799
- * - 'statuschange': Agent status changed
800
- * - 'historychange': Historical events updated (persisted)
801
- * - 'activity': Transient activity for immediate UI feedback (thinking/executing/etc)
802
- * - 'dispose': Agent is being disposed
843
+ * 事件:
844
+ * - 'statuschange':agent 状态发生变化
845
+ * - 'historychange':历史事件更新(已持久化)
846
+ * - 'activity':供 UI 即时反馈的瞬时活动(思考/执行等)
847
+ * - 'dispose':agent 正在被销毁
803
848
  */
804
849
  declare interface UIAdapter extends EventTarget {
805
- /** Current agent status */
850
+ /** 当前 agent 状态 */
806
851
  readonly status: 'idle' | 'running' | 'completed' | 'error' | 'stopped';
807
- /** Result of the most recent run, or `null` before the first run completes */
852
+ /** 最近一次运行的结果,首次运行完成前为 `null` */
808
853
  readonly lastResult: {
809
854
  success: boolean;
810
855
  } | null;
811
- /** History of agent events */
856
+ /** agent 事件历史 */
812
857
  readonly history: readonly {
813
- type: 'step' | 'observation' | 'user_takeover' | 'retry' | 'error';
858
+ type: 'step' | 'observation' | 'user_takeover' | 'task_start' | 'retry' | 'error';
814
859
  stepIndex?: number;
815
- /** For 'step' type */
860
+ /** 仅用于 'step' 类型 */
816
861
  reflection?: {
817
862
  evaluation_previous_goal?: string;
818
863
  memory?: string;
819
864
  next_goal?: string;
820
865
  };
821
- /** For 'step' type */
866
+ /** 仅用于 'step' 类型 */
822
867
  action?: {
823
868
  name: string;
824
869
  input: unknown;
825
870
  output: string;
826
871
  };
827
- /** For 'observation' type */
872
+ /** 仅用于 'observation' 类型 */
828
873
  content?: string;
829
- /** For 'retry' type */
874
+ /** 仅用于 'task_start' 类型 */
875
+ task?: string;
876
+ /** 仅用于 'retry' 类型 */
830
877
  attempt?: number;
831
878
  maxAttempts?: number;
832
- /** For 'retry' and 'error' types */
879
+ /** 仅用于 'retry' 'error' 类型 */
833
880
  message?: string;
834
881
  }[];
835
- /** Current task being executed */
882
+ /** 当前正在执行的任务 */
836
883
  readonly task: string;
837
884
  /**
838
- * Called when the agent needs to ask the user questions.
839
- * If unset, the `ask_user` tool will be disabled.
840
- * UI will set this to handle user questions via its UI.
841
- * The optional `signal` aborts when the task is stopped or disposed.
885
+ * agent 需要向用户提问时调用。
886
+ * 如果未设置,`ask_user` 工具将被禁用。
887
+ * UI 会设置该回调以便通过自身的界面处理用户提问。
888
+ * 可选参数 `signal` 在任务被停止或销毁时触发中止。
842
889
  */
843
890
  onAskUser?: (question: string, options?: {
844
891
  signal: AbortSignal;
845
892
  }) => Promise<string>;
846
- /** Execute a task */
893
+ /** 执行一个任务 */
847
894
  execute(task: string): Promise<unknown>;
848
- /** Stop the current task (agent remains reusable) */
895
+ /** 停止当前任务(agent 仍可复用) */
849
896
  stop(): Promise<void>;
850
- /** Dispose the agent (terminal, cannot be reused) */
897
+ /** 销毁 agent(终态,不可复用) */
851
898
  dispose(): void;
852
899
  }
853
900
 
854
901
  /**
855
- * UI configuration
902
+ * UI 配置
856
903
  */
857
904
  declare interface UIConfig {
858
905
  language?: SupportedLanguage_2;
859
906
  /**
860
- * Whether to prompt for next task after task completion
907
+ * 任务完成后是否提示输入下一个任务
861
908
  * @default true
862
909
  */
863
910
  promptForNextTask?: boolean;
864
911
  }
865
912
 
866
913
  /**
867
- * User takeover event
914
+ * 用户接管事件
868
915
  */
869
916
  declare interface UserTakeoverEvent {
870
917
  type: 'user_takeover';