|
| 1 | +import type { Snapshot, StepHookContext } from '../types'; |
| 2 | +import type { PermissionPolicy } from '../browser'; |
| 3 | +import type { AgentRuntime } from '../agent-runtime'; |
| 4 | +import type { LLMProvider } from '../llm-provider'; |
| 5 | +import { RuntimeAgent } from '../runtime-agent'; |
| 6 | +import type { RuntimeStep } from '../runtime-agent'; |
| 7 | +import type { CaptchaOptions } from '../captcha/types'; |
| 8 | +import type { CaptchaHandler } from '../captcha/types'; |
| 9 | + |
| 10 | +export interface PermissionRecoveryConfig { |
| 11 | + enabled?: boolean; |
| 12 | + maxRestarts?: number; |
| 13 | + autoGrant?: string[]; |
| 14 | + geolocation?: Record<string, any> | null; |
| 15 | + origin?: string | null; |
| 16 | +} |
| 17 | + |
| 18 | +export interface VisionFallbackConfig { |
| 19 | + enabled?: boolean; |
| 20 | + maxVisionCalls?: number; |
| 21 | + triggerRequiresVision?: boolean; |
| 22 | + triggerRepeatedNoop?: boolean; |
| 23 | + triggerCanvasOrLowActionables?: boolean; |
| 24 | +} |
| 25 | + |
| 26 | +export interface CaptchaConfig { |
| 27 | + policy?: 'abort' | 'callback'; |
| 28 | + // Interface-only: SDK does not ship captcha solvers. Users provide a handler/callback. |
| 29 | + handler?: CaptchaHandler | null; |
| 30 | + timeoutMs?: number | null; |
| 31 | + pollMs?: number | null; |
| 32 | + minConfidence?: number; |
| 33 | +} |
| 34 | + |
| 35 | +export interface PredicateBrowserAgentConfig { |
| 36 | + // Permissions |
| 37 | + permissionStartup?: PermissionPolicy | null; |
| 38 | + permissionRecovery?: PermissionRecoveryConfig | null; |
| 39 | + |
| 40 | + // Vision fallback |
| 41 | + vision?: VisionFallbackConfig; |
| 42 | + |
| 43 | + // CAPTCHA handling |
| 44 | + captcha?: CaptchaConfig; |
| 45 | + |
| 46 | + // Prompt / token controls |
| 47 | + historyLastN?: number; // 0 disables LLM-facing step history |
| 48 | + |
| 49 | + // Compact prompt customization |
| 50 | + // builder(taskGoal, stepGoal, domContext, snapshot, historySummary) -> {systemPrompt, userPrompt} |
| 51 | + compactPromptBuilder?: ( |
| 52 | + taskGoal: string, |
| 53 | + stepGoal: string, |
| 54 | + domContext: string, |
| 55 | + snap: Snapshot, |
| 56 | + historySummary: string |
| 57 | + ) => { systemPrompt: string; userPrompt: string }; |
| 58 | + |
| 59 | + compactPromptPostprocessor?: (domContext: string) => string; |
| 60 | +} |
| 61 | + |
| 62 | +function historySummary(items: string[]): string { |
| 63 | + if (!items.length) return ''; |
| 64 | + return items.map(s => `- ${s}`).join('\n'); |
| 65 | +} |
| 66 | + |
| 67 | +function applyCaptchaConfigToRuntime(runtime: AgentRuntime, cfg: CaptchaConfig | undefined): void { |
| 68 | + if (!cfg) return; |
| 69 | + |
| 70 | + const policy = (cfg.policy ?? 'abort').toLowerCase() as 'abort' | 'callback'; |
| 71 | + if (policy === 'abort') { |
| 72 | + runtime.setCaptchaOptions({ |
| 73 | + policy: 'abort', |
| 74 | + minConfidence: cfg.minConfidence ?? 0.7, |
| 75 | + } satisfies CaptchaOptions); |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + const pollMs = cfg.pollMs ?? 1_000; |
| 80 | + const timeoutMs = cfg.timeoutMs ?? 120_000; |
| 81 | + const minConfidence = cfg.minConfidence ?? 0.7; |
| 82 | + |
| 83 | + const handler = cfg.handler ?? null; |
| 84 | + if (!handler) { |
| 85 | + throw new Error( |
| 86 | + 'captcha.handler is required when captcha.policy="callback". ' + |
| 87 | + 'Provide a handler callback (e.g. human handoff or your external system).' |
| 88 | + ); |
| 89 | + } |
| 90 | + |
| 91 | + runtime.setCaptchaOptions({ |
| 92 | + policy: 'callback', |
| 93 | + handler, |
| 94 | + timeoutMs, |
| 95 | + pollMs, |
| 96 | + minConfidence, |
| 97 | + } satisfies CaptchaOptions); |
| 98 | +} |
| 99 | + |
| 100 | +export type StepOutcome = { stepGoal: string; ok: boolean }; |
| 101 | + |
| 102 | +export class PredicateBrowserAgent { |
| 103 | + readonly runtime: AgentRuntime; |
| 104 | + readonly executor: LLMProvider; |
| 105 | + readonly visionExecutor?: LLMProvider; |
| 106 | + readonly visionVerifier?: LLMProvider; |
| 107 | + readonly config: PredicateBrowserAgentConfig; |
| 108 | + |
| 109 | + private history: string[] = []; |
| 110 | + private visionCallsUsed = 0; |
| 111 | + private runner: RuntimeAgent; |
| 112 | + |
| 113 | + constructor(opts: { |
| 114 | + runtime: AgentRuntime; |
| 115 | + executor: LLMProvider; |
| 116 | + visionExecutor?: LLMProvider; |
| 117 | + visionVerifier?: LLMProvider; |
| 118 | + config?: PredicateBrowserAgentConfig; |
| 119 | + }) { |
| 120 | + this.runtime = opts.runtime; |
| 121 | + this.executor = opts.executor; |
| 122 | + this.visionExecutor = opts.visionExecutor; |
| 123 | + this.visionVerifier = opts.visionVerifier; |
| 124 | + this.config = { |
| 125 | + permissionStartup: null, |
| 126 | + permissionRecovery: null, |
| 127 | + vision: { enabled: false, maxVisionCalls: 0 }, |
| 128 | + captcha: { policy: 'abort', handler: null }, |
| 129 | + historyLastN: 0, |
| 130 | + ...(opts.config ?? {}), |
| 131 | + }; |
| 132 | + |
| 133 | + applyCaptchaConfigToRuntime(this.runtime, this.config.captcha); |
| 134 | + |
| 135 | + this.runner = new RuntimeAgent({ |
| 136 | + runtime: this.runtime, |
| 137 | + executor: this.executor, |
| 138 | + visionExecutor: this.visionExecutor, |
| 139 | + visionVerifier: this.visionVerifier, |
| 140 | + structuredPromptBuilder: this.config.compactPromptBuilder, |
| 141 | + domContextPostprocessor: this.config.compactPromptPostprocessor, |
| 142 | + historySummaryProvider: () => { |
| 143 | + const n = Math.max(0, this.config.historyLastN ?? 0); |
| 144 | + if (n <= 0) return ''; |
| 145 | + const slice = this.history.slice(Math.max(0, this.history.length - n)); |
| 146 | + return historySummary(slice); |
| 147 | + }, |
| 148 | + } as any); |
| 149 | + } |
| 150 | + |
| 151 | + private recordHistory(stepGoal: string, ok: boolean) { |
| 152 | + const n = Math.max(0, this.config.historyLastN ?? 0); |
| 153 | + if (n <= 0) return; |
| 154 | + this.history.push(`${stepGoal} -> ${ok ? 'ok' : 'fail'}`); |
| 155 | + if (this.history.length > n) { |
| 156 | + this.history = this.history.slice(this.history.length - n); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + async step(opts: { |
| 161 | + taskGoal: string; |
| 162 | + step: RuntimeStep; |
| 163 | + onStepStart?: (ctx: StepHookContext) => void | Promise<void>; |
| 164 | + onStepEnd?: (ctx: StepHookContext) => void | Promise<void>; |
| 165 | + }): Promise<StepOutcome> { |
| 166 | + let step = opts.step; |
| 167 | + |
| 168 | + const maxVisionCalls = Math.max(0, this.config.vision?.maxVisionCalls ?? 0); |
| 169 | + if ( |
| 170 | + this.config.vision?.enabled && |
| 171 | + maxVisionCalls > 0 && |
| 172 | + this.visionCallsUsed >= maxVisionCalls |
| 173 | + ) { |
| 174 | + step = { ...step, visionExecutorEnabled: false, maxVisionExecutorAttempts: 0 }; |
| 175 | + } |
| 176 | + |
| 177 | + const ok = await this.runner.runStep({ |
| 178 | + taskGoal: opts.taskGoal, |
| 179 | + step, |
| 180 | + onStepStart: opts.onStepStart, |
| 181 | + onStepEnd: opts.onStepEnd, |
| 182 | + }); |
| 183 | + |
| 184 | + this.recordHistory(step.goal, ok); |
| 185 | + return { stepGoal: step.goal, ok }; |
| 186 | + } |
| 187 | + |
| 188 | + async run(opts: { |
| 189 | + taskGoal: string; |
| 190 | + steps: RuntimeStep[]; |
| 191 | + onStepStart?: (ctx: StepHookContext) => void | Promise<void>; |
| 192 | + onStepEnd?: (ctx: StepHookContext) => void | Promise<void>; |
| 193 | + stopOnFailure?: boolean; |
| 194 | + }): Promise<boolean> { |
| 195 | + const stopOnFailure = opts.stopOnFailure ?? true; |
| 196 | + for (const step of opts.steps) { |
| 197 | + const out = await this.step({ |
| 198 | + taskGoal: opts.taskGoal, |
| 199 | + step, |
| 200 | + onStepStart: opts.onStepStart, |
| 201 | + onStepEnd: opts.onStepEnd, |
| 202 | + }); |
| 203 | + if (stopOnFailure && !out.ok) return false; |
| 204 | + } |
| 205 | + return true; |
| 206 | + } |
| 207 | +} |
0 commit comments