import type { HumanInterventionReason } from '../../humanIntervention.js'; import type { AccessibilityNode, ComputerState } from './protocol.js'; import { axGivesControlDetail } from './vision/focus.js'; const HUMAN_TEXT = { password: /password|passcode|密码|口令/i, otp: /one[- ]time|verification code|\botp\b|短信验证码|邮件验证码|动态口令/i, captcha: /captcha|verify.{0,12}human|安全验证|人机验证|验证码|滑块|拼图/i, qr_login: /scan.{0,12}(?:code|qr)|扫码登录|二维码登录/i, permission: /permission|allow access|授权|访问权限/i, security_warning: /security warning|安全警告|风险提示|系统保护/i, login: /sign in|log in|登录/i, } as const; function flatten(node: AccessibilityNode | undefined): AccessibilityNode[] { if (!node) return []; return [node, ...(node.children ?? []).flatMap(flatten)]; } export interface ComputerHumanBoundary { reason: HumanInterventionReason; summary: string; target?: { appId?: string; windowId?: string }; /** * How this was established. * * `ax` — read out of the accessibility tree; specific and reliable. * `pixel-only` — inferred without a usable tree. Weaker, and the host must * be able to tell the difference rather than treating both as equal. */ confidence?: 'ax' | 'pixel-only'; } /** * Detects only host-observable boundaries. Protected values and screenshot * pixels are never returned or included in the model-visible summary. * * ⚠️ The accessibility tree is not always there. Measured on this repo: an * Electron app (Claude desktop) exposes its window and three window buttons * and nothing else — no fields, no buttons, no text. Self-drawn and Electron * apps are exactly the target scenario, so a `null` here means "found no * evidence", never "there is no password box". Callers that need to act on * the difference should read `state.accessibility.truncated` as well. */ export function detectComputerHumanBoundary( state: ComputerState, manual?: { humanBoundary?: { reason: string; summary: string; allOf: string[] }[] }, ): ComputerHumanBoundary | null { const nodes = flatten(state.accessibility?.root); const target = { ...(state.activeApp?.id || state.accessibility?.appId ? { appId: state.activeApp?.id ?? state.accessibility?.appId } : {}), ...(state.accessibility?.windowId ? { windowId: state.accessibility.windowId } : {}), }; const ax = (reason: HumanInterventionReason, summary: string): ComputerHumanBoundary => ({ reason, summary, target, confidence: 'ax' }); if (nodes.some((node) => node.protected === true || /secure|password/i.test(node.role))) { return ax('password', '需要你在目标应用中输入密码或安全凭据'); } const text = nodes .map((node) => `${node.role} ${node.name ?? ''}`) .join('\n') .slice(0, 100_000); // ★ 应用自己声明的信号先于通用正则。 // // 内核只认识**跨应用成立**的东西(密码框、验证码、二维码登录…)。有些应用的 // 边界只有它自己知道,那属于说明书的知识,不属于内核 —— 此前这里写死过一段 // `/com\.tencent\.xinWeChat/` 的判断(微信登录小窗不暴露「扫码登录」四个字, // 只能靠「二维码」+「仅传输文件」同时出现来判),那等于「多支持一个应用就要 // 改一次内核」,与「drop 一份说明书即扩展能力」的架构正好相反。现在它住在 // `plugins/computer_use/app/wechat.md` 的 `humanBoundary:` 段里。 // // 放在通用正则**之前**:应用专属判据更精确,通用的更钝,钝的先命中会把 // 精确的那条永远盖住。 for (const declared of manual?.humanBoundary ?? []) { // 空条件 `every` 恒真 —— 会把**任何**界面报成需要人工介入。加载期已经报 error, // 这里再挡一次:一份坏说明书最多是「这条不生效」,绝不能变成「整个应用卡死」。 if (declared.allOf.length === 0 || !declared.reason) continue; const hit = declared.allOf.every((pattern) => { try { return new RegExp(pattern, 'i').test(text); } catch { // 说明书里的正则写坏了 —— 当作不成立,别让一份坏说明书拖垮整个判定。 // (validateManual 会把它报成 issue,作者看得见。) return false; } }); if (hit) return ax(declared.reason as HumanInterventionReason, declared.summary); } if (HUMAN_TEXT.otp.test(text)) return ax('otp', '需要你在目标应用中输入一次性验证码'); if (HUMAN_TEXT.captcha.test(text)) return ax('captcha', '需要你在目标应用中完成人工验证'); if (HUMAN_TEXT.qr_login.test(text)) return ax('qr_login', '需要你扫码完成登录'); if (HUMAN_TEXT.permission.test(text)) return ax('permission', '需要你确认系统或应用权限'); if (HUMAN_TEXT.security_warning.test(text)) return ax('security_warning', '需要你处理系统安全提示'); if (HUMAN_TEXT.login.test(text) && nodes.some((node) => /text.?field|input/i.test(node.role))) { return ax('login', '需要你完成登录'); } return null; } /** 输入过程中的观察,供不依赖无障碍树的兜底判据使用。 */ export interface TypingObservation { /** 模型正在(或即将)输入文本 */ typing: boolean; /** 全屏像素变化占比(0–1)。undefined = 没测,与「测了是 0」不同。 */ changeRatio?: number; /** 焦点控件区域内的变化占比(0–1)。给了 ROI 才有。 */ regionChangeRatio?: number; /** 焦点控件占全屏的面积比例(0–1)。TS 自己就知道,不必让原生再算一遍。 */ focusAreaRatio?: number; } /** 拿不到焦点控件时的整屏阈值。比有 ROI 时高,因为判据更钝。 */ const BLIND_FULLSCREEN_LIMIT = 0.15; /** 变化面积超过焦点控件面积的多少倍才算「控件解释不了」。 */ const AREA_SLACK = 1.5; /** 有 ROI 时的整屏下限:再小的动静都不值得打断人。 */ const MIN_FULLSCREEN_LIMIT = 0.02; /** 判定的三种结局。`no-effect` 不是安全问题,但同样值得如实报给模型。 */ export type PixelVerdict = 'suspicious' | 'no-effect' | 'normal'; /** * 不依赖无障碍树的兜底判据。 * * 存在的理由:`detectComputerHumanBoundary` 的全部判据来自 AX,而 AX 在 * Electron/自绘应用上常常是空的 —— 本仓库实测确认过。把安全关键判定单押在 * 一个已知会失效的通道上,正是 R1 重构纠正过的那个错误,不能再犯第二次。 * * ★ **判据是面积归一化的,不是一个固定的整屏百分比。** * * 在输入框里打字,界面**必然**变化 —— 变的就是那个输入框。老判据是 * 「整屏变化 > 2%」,于是每一次正常输入都可能命中,而真正该命中的 * 「输入框外面冒出了个联想框」反而和它混在一起分不出来。 * * 现在问的是:**这次变化超出了焦点控件本身能解释的范围吗**。控件面积占屏 * 3%,那么 3% 以内的变化完全可以是「字打进去了」;显著超出,才说明控件 * 之外多了东西。ROI 面积比 TS 自己就知道(AX 给了控件矩形),不用原生再算。 * * 这**不能**告诉我们弹的是什么(所以 reason 是笼统的 `blocked`),但足以 * 停下来交给人 —— 而停下来正是这里唯一需要做对的决定。 */ export function detectPixelHumanBoundary( state: ComputerState, observation: TypingObservation, ): ComputerHumanBoundary | null { if (classifyPixelChange(state, observation) !== 'suspicious') return null; return { reason: 'blocked', summary: '输入过程中,焦点控件之外的界面发生了明显变化' + '(可能弹出了联想、补全或对话框),需要你确认当前状态', target: { ...(state.activeApp?.id ? { appId: state.activeApp.id } : {}), }, confidence: 'pixel-only', }; } /** * 像素证据的三分类。分出 `no-effect` 是因为它回答的是另一个问题: * ROI 和整屏**都没动** = 这次按键根本没落地(焦点丢了、应用没响应)。 * 那不是安全问题,但把它当成「一切正常」会让模型接着往下打字,越走越偏。 */ export function classifyPixelChange( state: ComputerState, observation: TypingObservation, ): PixelVerdict { if (!observation.typing) return 'normal'; // 树**真的给得出控件级信息**时,以 AX 判据为准,不用这条更钝的信号去添乱。 // // ⚠️ 这里曾经写成 `state.accessibility && !truncated` —— 那测的是「树存在」, // 不是「树有用」。微信的 AX 树有 5 个节点(纯窗口壳)、未截断,于是这条直接 // 返回 normal,下面整段像素判据(含 no-effect 回执与像素级人工接管)从未运行过。 // 判据统一收敛到 `axGivesControlDetail`,与 shouldProbeChange 共用同一份。 if (axGivesControlDetail(state)) return 'normal'; // 没测就是没测。把「没看」当成「没变」是这套判据里最容易犯的错。 if (observation.changeRatio === undefined) return 'normal'; const full = observation.changeRatio; const region = observation.regionChangeRatio; const area = observation.focusAreaRatio; // 完全没有动静:输入没落地。需要 ROI 那一路也确认,否则「整屏没变」可能 // 只是变化都发生在一个小控件里而被平均掉了。 if (full <= 0.0005 && (region === undefined || region <= 0.0005)) return 'no-effect'; if (area === undefined) { // 拿不到焦点控件(AX 全空)。只能看整屏,且门槛抬高 —— 判据钝了, // 就不该用和精确判据一样的灵敏度去打断人。 return full > BLIND_FULLSCREEN_LIMIT ? 'suspicious' : 'normal'; } const limit = Math.max(MIN_FULLSCREEN_LIMIT, area * AREA_SLACK); return full > limit ? 'suspicious' : 'normal'; }