import { randomUUID } from 'node:crypto'; import { HumanInterventionCoordinator, type HumanInterventionCredential, type HumanInterventionEvent, type HumanInterventionIdentity, type HumanInterventionReason, type PendingHumanIntervention, } from '../../humanIntervention.js'; export type BrowserHumanReason = HumanInterventionReason; /** * 控制权状态的**定义已搬进 `src/web/protocol.ts`**(线路协议自持形状), * 这里只 re-export,工具侧既有 import 路径一律不变。 * * 为什么搬:desktop 与 server 都从 `minimal-agent/protocol` 取线路类型, * 若协议反过来 import 这个工具模块,本工具的任何重构都会顺着协议波及两个 * 外部消费方。方向必须是工具依赖协议。`test/kernelPurity.test.ts` 守这条线 * ——它正是靠这条规则把本处揪出来的。 */ // 注意是 import + 再 export 两步:单写 `export type { X } from '...'` 只做 // **再导出**,不会把名字带进本文件的作用域,而下面有五处内部引用要用到它。 import type { BrowserControlState } from '../../web/protocol.js'; export type { BrowserControlState }; export interface BrowserChallenge { reason: Exclude; summary: string; } const CAPTCHA_PATTERNS = [ /captcha/i, /验证码|安全验证|人机验证|完成.{0,8}验证|拖动.{0,12}(滑块|拼图)|滑动.{0,12}(滑块|拼图)/i, /verify\s+(?:you are|that you are)\s+(?:a\s+)?human/i, // Additional patterns: reCAPTCHA / hCaptcha / Turnstile / Cloudflare / etc. /i\s*'?m\s+not\s+a\s+robot/i, /checking\s+your\s+browser/i, /press\s+&?\s*hold|click\s+to\s+verify|verifying\s+you/i, /点击验证|按住滑块|图片验证|行为验证/i, ]; const OTP_PATTERNS = [ /一次性密码|短信验证码|邮件验证码|动态口令|\botp\b|one[- ]time (?:password|code)/i, ]; const PASSWORD_PATTERNS = [ /请输入.{0,12}(?:密码|口令)|(?:密码|口令).{0,12}(?:必填|不能为空)/i, /(?:enter|type).{0,20}(?:password|passcode)|(?:password|passcode).{0,20}(?:required|cannot be empty)/i, ]; const QR_LOGIN_PATTERNS = [ /扫码登录|二维码登录|scan (?:the )?qr|qr code.{0,20}(?:login|sign in)/i, ]; const LOGIN_PATTERNS = [ /请先登录|登录后继续|扫码登录|sign in to continue|log in to continue/i, /please\s+(?:log|sign)\s+in/i, ]; const BLOCK_PATTERNS = [ /操作存在异常|访问请求.{0,8}(暂停|拦截)|请求过于频繁|访问受限|access denied|unusual traffic|temporarily blocked/i, // 403/429 必须落在 HTTP/错误语境里再判风控,避免把「售价 $429」「forbidden fruit」这类正常正文误判成拦截。 /rate\s+limit(?:ed)?|too\s+many\s+requests|\b403\s+forbidden\b|http[^\n]{0,10}\b(?:403|429)\b|\b(?:error|status)\s*(?:code)?\s*[::]?\s*(?:403|429)\b/i, /被封禁|风控拦截|系统异常/i, ]; const PERMISSION_PATTERNS = [ /需要授权|请求权限|permission required|allow access/i, ]; const SECURITY_WARNING_PATTERNS = [ /安全警告|风险提示|security warning|untrusted (?:application|site|publisher)/i, ]; /** Classifies only explicit page signals. It never attempts to solve or bypass a challenge. */ export function detectBrowserChallenge(text: string): BrowserChallenge | null { const normalized = text.replace(/\s+/g, ' ').slice(0, 200_000); if (OTP_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'otp', summary: '页面需要人工输入一次性验证码' }; if (CAPTCHA_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'captcha', summary: '页面需要人工完成安全验证' }; if (QR_LOGIN_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'qr_login', summary: '页面需要人工扫码登录' }; if (PASSWORD_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'password', summary: '页面需要人工输入密码' }; if (LOGIN_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'login', summary: '页面需要人工登录' }; if (BLOCK_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'blocked', summary: '网站已暂停或拦截当前访问' }; if (SECURITY_WARNING_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'security_warning', summary: '页面需要人工处理安全警告' }; if (PERMISSION_PATTERNS.some((pattern) => pattern.test(normalized))) return { reason: 'permission', summary: '页面需要人工确认权限' }; return null; } type HumanWaiter = { interventionId: string; }; /** * 判定「持有者已经死了」的阈值。 * * 取值有依据,不是拍脑袋:单次动作的 `timeout` 在 zod schema 里是 `.max(300_000)`, * 语义是**整个序列**(前置探测 + 动作 + 收尾重探)的总时长。所以任何合法的 running * 都有 300s 的硬上界,取 2× 作阈值 —— 合法长动作绝不会被误接管,而泄漏的锁在一个 * 动作周期后自动可用,不再是「本进程剩余生命周期内浏览器永久不可用」。 * * ⚠️ 改小之前先确认 webbrowser.ts 里 preTimer 与 runSequence 各自的计时器在最长路径上 * 不会叠加;`browserControl.test.ts` 用假时钟锁住了这个不变量的行为面。 */ export const DEFAULT_STALE_AFTER_MS = 600_000; export interface StaleTakeover { previousRunId?: string; previousAction?: string; heldMs: number; } export class BrowserControlCoordinator { private state: BrowserControlState = { owner: 'none', status: 'idle' }; private listeners = new Set<(state: BrowserControlState) => void>(); private activeIdentity: HumanInterventionIdentity | null = null; private activeIntervention: PendingHumanIntervention | null = null; private readonly interventions = new HumanInterventionCoordinator(); private readonly defaultOwnerId: string; private readonly defaultConversationKey: string; private readonly staleAfterMs: number; private readonly now: () => number; private readonly onStaleTakeover: (info: StaleTakeover) => void; /** 进入 running 的时刻;由 setState 统一维护,所以 resume 之后也会重新计时。 */ private runningSince = 0; constructor( input: { ownerId?: string; conversationKey?: string; /** 注入时钟:让「超过阈值」在测试里用假时钟验证,而不是真等 10 分钟。 */ now?: () => number; staleAfterMs?: number; onStaleTakeover?: (info: StaleTakeover) => void; } = {}, ) { this.defaultOwnerId = input.ownerId ?? 'local-owner'; this.defaultConversationKey = input.conversationKey ?? 'browser:default'; this.now = input.now ?? (() => Date.now()); this.staleAfterMs = input.staleAfterMs ?? DEFAULT_STALE_AFTER_MS; // 接管**绝不能静默**:不留痕的话,「这把锁曾经泄漏过」就再也查不到了, // 而下一次排查会从一个已经自愈的现场开始 —— 那比报错更难查。 this.onStaleTakeover = input.onStaleTakeover ?? ((info) => { process.stderr.write( `[browser] 上一个持有者(runId=${info.previousRunId ?? '?'}` + `${info.previousAction ? `, action=${info.previousAction}` : ''})` + `已持锁 ${Math.round(info.heldMs / 1000)}s,超过 ${Math.round(this.staleAfterMs / 1000)}s 判为泄漏,已接管。\n`, ); }); } getState(): BrowserControlState { return this.state; } subscribe(listener: (state: BrowserControlState) => void): () => void { this.listeners.add(listener); listener(this.state); return () => this.listeners.delete(listener); } subscribeInterventions( listener: (event: HumanInterventionEvent) => void, ): () => void { return this.interventions.subscribe(listener); } beginAgent(input: { runId: string; conversationKey?: string; action?: string; }): void { if (this.state.status === 'waiting_human') { if (this.state.runId === input.runId) return; throw new Error('浏览器正在等待另一个任务的人工处理'); } if (this.state.status === 'running' && this.state.runId !== input.runId) { const heldMs = this.now() - this.runningSince; if (heldMs < this.staleAfterMs) { // 带上持锁者身份与已持有时长:这把锁是进程级单例,一旦泄漏,后续每次调用都撞 // 同一句话,而"另一个会话"是谁、卡在哪个动作上、卡了多久,现场早就没了。 // 时长尤其关键 —— 它把「真并发」和「已泄漏」在报错里一眼分开。 throw new Error( `浏览器正在执行另一个会话的原子操作(持有者 runId=${this.state.runId ?? '?'}` + `${this.state.action ? `, action=${this.state.action}` : ''}` + `${this.activeIdentity?.conversationKey ? `, conversation=${this.activeIdentity.conversationKey}` : ''}` + `, 已持有 ${Math.round(heldMs / 1000)}s)`, ); } // 超过任何合法动作的上界 —— 持有者的 finally 没能跑(进程被外部掐断、 // finally 自身抛错、或将来某条还没被想到的路径)。不接管的话,这个进程里的 // 浏览器就永久不可用了。接管并留痕,让「失败一次」不再等于「彻底报废」。 this.onStaleTakeover({ previousRunId: this.state.runId, previousAction: this.state.action, heldMs, }); } this.activeIdentity = { ownerId: this.defaultOwnerId, conversationKey: input.conversationKey ?? this.defaultConversationKey, runId: input.runId, }; this.setState({ owner: 'agent', status: 'running', ...input }); } finishAgent(runId: string): void { if (this.state.status === 'running' && this.state.runId === runId) { this.activeIdentity = null; this.setState({ owner: 'none', status: 'idle' }); } } requestHuman( reason: BrowserHumanReason, input?: { runId?: string; conversationKey?: string; ownerId?: string; summary?: string; }, ): string { if (this.state.status === 'waiting_human') { if (!input?.runId || this.state.runId === input.runId) return this.state.resumeToken; throw new Error('另一个浏览器任务正在等待人工处理'); } const running = this.state.status === 'running' ? this.state : null; const identity: HumanInterventionIdentity = { ownerId: input?.ownerId ?? this.activeIdentity?.ownerId ?? this.defaultOwnerId, conversationKey: input?.conversationKey ?? this.activeIdentity?.conversationKey ?? running?.conversationKey ?? this.defaultConversationKey, runId: input?.runId ?? this.activeIdentity?.runId ?? running?.runId ?? randomUUID(), }; const intervention = this.interventions.request({ ...identity, surface: 'browser', reason, sanitizedSummary: input?.summary ?? summaryForReason(reason), }); this.activeIdentity = identity; this.activeIntervention = intervention; this.setState({ owner: 'user', status: 'waiting_human', runId: identity.runId, conversationKey: identity.conversationKey, reason, interventionId: intervention.id, resumeToken: intervention.resumeToken, ownerId: identity.ownerId, }); return intervention.resumeToken; } takeInteractive(input?: { runId?: string; conversationKey?: string }): void { if (this.activeIntervention && this.activeIdentity) { this.interventions.cancel( this.credential(this.activeIntervention, this.activeIdentity), ); } this.activeIntervention = null; this.activeIdentity = null; this.setState({ owner: 'user', status: 'interactive', runId: input?.runId, conversationKey: input?.conversationKey, }); } resume(token?: string): boolean { if ( this.state.status !== 'waiting_human' || !token || !this.activeIntervention || !this.activeIdentity ) return false; const previous = this.state; const ok = this.interventions.resume( this.credential(this.activeIntervention, this.activeIdentity, token), ); if (!ok) return false; this.activeIntervention = null; this.setState({ owner: 'agent', status: 'running', runId: previous.runId, conversationKey: previous.conversationKey, action: '正在检查人工操作结果', }); return true; } resumeIntervention(credential: HumanInterventionCredential): boolean { if ( this.state.status !== 'waiting_human' || !this.activeIntervention || !this.activeIdentity ) return false; const previous = this.state; if (!this.interventions.resume(credential)) return false; this.activeIntervention = null; this.activeIdentity = null; this.setState({ owner: 'agent', status: 'running', runId: previous.runId, conversationKey: previous.conversationKey, action: '正在检查人工操作结果', }); return true; } stop(token?: string): boolean { if (this.state.status === 'waiting_human') { if (!token || !this.activeIntervention || !this.activeIdentity) return false; const ok = this.interventions.cancel( this.credential(this.activeIntervention, this.activeIdentity, token), ); if (!ok) return false; } this.activeIntervention = null; this.activeIdentity = null; this.setState({ owner: 'user', status: 'interactive' }); return true; } cancelIntervention(credential: HumanInterventionCredential): boolean { if ( this.state.status !== 'waiting_human' || !this.activeIntervention || !this.activeIdentity ) return false; if (!this.interventions.cancel(credential)) return false; this.activeIntervention = null; this.activeIdentity = null; this.setState({ owner: 'user', status: 'interactive' }); return true; } waitForHuman(signal?: AbortSignal): Promise<'resumed' | 'stopped'> { if (this.state.status !== 'waiting_human') return Promise.resolve('resumed'); const intervention = this.activeIntervention; if (!intervention) return Promise.resolve('stopped'); const waiter: HumanWaiter = { interventionId: intervention.id }; return this.interventions .wait(waiter.interventionId, signal) .then((resolution) => resolution.status === 'resumed' ? 'resumed' : 'stopped', ); } private setState(state: BrowserControlState): void { // 所有进入 running 的路径都在这里重新计时(beginAgent 之外,还有 resume / // resumeIntervention 从人工处理回到 agent 手里)。⚠️ 少了这一条,人工处理 // 花掉的时间会被算进持锁时长 —— 用户认真填了十分钟验证码,恢复的瞬间就被判成 // 「泄漏」让别人接管,正好惩罚了最该被保护的那条路径。 if (state.status === 'running') this.runningSince = this.now(); this.state = state; for (const listener of this.listeners) { try { listener(state); } catch { // Observers are telemetry/UI extensions; control state must remain authoritative. } } } private credential( intervention: PendingHumanIntervention, identity: HumanInterventionIdentity, resumeToken = intervention.resumeToken, ): HumanInterventionCredential { return { id: intervention.id, resumeToken, ownerId: identity.ownerId, conversationKey: identity.conversationKey, runId: identity.runId, }; } } function summaryForReason(reason: BrowserHumanReason): string { switch (reason) { case 'captcha': return '页面需要人工完成安全验证'; case 'otp': return '页面需要人工输入一次性验证码'; case 'password': return '页面需要人工输入密码'; case 'qr_login': return '页面需要人工扫码登录'; case 'login': return '页面需要人工登录'; case 'permission': return '页面需要人工确认权限'; case 'security_warning': return '页面需要人工处理安全警告'; case 'blocked': return '网站已暂停或拦截当前访问'; case 'manual': return '用户已接管浏览器'; } }