import { execFileSync, spawn } from 'node:child_process'; import { createHash, createHmac, randomUUID } from 'node:crypto'; import { existsSync, unlinkSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { createConnection } from 'node:net'; import { homedir } from 'node:os'; import { delimiter, dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { ensureMacPermissions } from './accessibilityPermission.js'; import { COMPUTER_USE_PROTOCOL_VERSION, type ComputerState, type ComputerUseDisplay, type ComputerUseImageReference, type ComputerUseInputStatus, type ComputerUseRect, type ComputerUseRequest, type ComputerUseResponse, type ComputerUseRunContext, type ComputerUseSequenceFrame, isMutatingComputerUseAction, } from './protocol.js'; import { FOCUS_CHANGE, type FocusExpectation, type FocusSnapshot, axGivesControlDetail, axFocusIsConcreteControl, classifyFocusChange, deriveFocusSnapshot, } from './vision/focus.js'; function delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } /** * 判断是否是截图相关的可重试错误 */ function isScreenshotRetryableError(error: ComputerUseResponse['error']): boolean { return error?.retryable === true && error.code === 'capture_transient'; } export interface ComputerUseTransport { request( request: ComputerUseRequest, signal?: AbortSignal, ): Promise; /** Stops every helper-owned input lease, including runs owned by another host. */ emergencyStopAll?(signal?: AbortSignal): Promise; inputStatus?( context: ComputerUseRunContext, acknowledge?: boolean, signal?: AbortSignal, ): Promise; close?(): Promise; } export interface ComputerUseServiceOptions { transport?: ComputerUseTransport; helperPath?: string; stateDir?: string; } function executableName(): string { return process.platform === 'win32' ? 'cu-helperd.exe' : 'cu-helperd'; } function platformDir(): string { return `${process.arch}-${process.platform}`; } /** * 包根:本文件在 `src/tools/computeruse/`,上溯三级。 * * 不能用 `process.cwd()` —— 那是**用户的工作目录**,不是包所在位置。dev 场景 * 两者恰好重合所以看不出问题,npm 安装后(cwd = 用户项目)必然找不到。 * 同一个坑在技能侧解对过一次,内核这边曾解错。 */ const PACKAGE_ROOT = resolve( fileURLToPath(import.meta.url), '..', '..', '..', '..', ); export function findComputerUseHelper( explicit = process.env.MINIMAL_AGENT_COMPUTER_USE_HELPER, ): string | null { const relative = join( 'vendor', 'computer-use', platformDir(), executableName(), ); const candidates = [ explicit, // 包内 vendor/:dev 与 npm 安装 join(PACKAGE_ROOT, relative), // exe 同级:绿色版(compile 后 import.meta.url 是虚拟路径,只能靠 execPath) process.execPath ? join(dirname(process.execPath), relative) : undefined, ].filter((value): value is string => !!value); for (const candidate of candidates) { const resolved = resolve(candidate); if (existsSync(resolved)) return resolved; } for (const dir of (process.env.PATH ?? '').split(delimiter)) { const candidate = join(dir, executableName()); if (existsSync(candidate)) return candidate; } return null; } /** * Computer Use 的本机状态目录:配对令牌、socket、审计与遥测都落在这里。 * * 单一出处。这段跨平台路径逻辑曾经在 `cli/computerUse.ts` 里有第二份拷贝, * 两份各自演进就会让「审计写在哪」和「审计从哪读」悄悄分叉。 */ export function computerUseStateDir(): string { if (process.env.KAKADEAI_CU_HOME) return resolve(process.env.KAKADEAI_CU_HOME); if (process.platform === 'darwin') return join( homedir(), 'Library', 'Application Support', 'KakadeAI', 'computer-use', ); if (process.platform === 'win32') return join( process.env.LOCALAPPDATA ?? homedir(), 'KakadeAI', 'computer-use', ); return join( process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'kakadeai', 'computer-use', ); } /** * 本进程的「宿主身份」—— 决定守护进程能拿到哪些系统权限的那个 App。 * * macOS 的 TCC 不认发起请求的二进制,认的是 **responsible process**:进程被创建时从 * 父进程继承、并且**在 daemonize 之后依然保留**的那个 App 身份。守护进程正是被我们 * spawn 出来的,所以它这辈子的权限由「谁第一个拉起它」决定,之后再也不会变。 * * 往上找到第一个 `.app` 包就是答案。找不到(比如从纯终端跑)就退回可执行文件路径 —— * 那种情况下 TCC 认的确实是那个可执行文件所属的终端 App,桶分开了也依然正确。 */ function responsibleHostIdentity(): string { if (process.platform !== 'darwin') return 'default'; try { let pid = process.pid; for (let depth = 0; depth < 12 && pid > 1; depth += 1) { // macOS 的 `comm` 给的是完整可执行路径(与 Linux 的截断行为不同)。 const line = execFileSync('ps', ['-o', 'ppid=,comm=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], }).trim(); const parsed = /^(\d+)\s+(.+)$/.exec(line); if (!parsed) break; const bundle = /^(.*?\.app)\/Contents\/MacOS\//.exec(parsed[2]); if (bundle) return bundle[1]; pid = Number(parsed[1]); } } catch { // ps 不可用时不猜:退回共享桶,行为与分桶前一致。 } return process.execPath; } let cachedHostTag: string | null = null; /** * 守护进程的**运行时**状态目录(socket / 配对令牌 / 锁 / 审计),按宿主身份分桶。 * * ⚠️ 为什么必须分桶(真实事故):这些文件此前全机唯一,于是守护进程被**所有宿主共享**。 * 谁先拉起它,谁的 TCC 授权就决定了之后**所有**客户端的命运 —— 而它是 `ppid=1` 的常驻 * 进程,这个身份一旦定下就再不会变。实测后果:某次从 Claude Code 里跑了一遍端到端验证, * 拉起的守护进程带着 `com.anthropic.claude-code` 的身份常驻;此后用户从自己的 Desktop * App 发起的每一次截图都被 TCC 拒绝 —— App 自己的授权是好的,但请求根本没走它的身份。 * 重启 App 也无效(守护进程不跟着 App 死),排查耗掉数小时,期间先后错怪了 cdhash、 * 用户的授权设置和我们自己的改动。 * * 分桶之后各宿主各起各的守护进程,天然隔离,**不需要任何人去杀别人的进程** —— 那个方向 * (启动时清理全部实例)会把并发宿主的正在进行的动作从中间掐断,是更糟的解法。 * * 遥测与授权记录仍写在共享根目录下,不受影响;审计由守护进程写在各自桶内, * 读取方 `readRecentComputerUseAudit` 负责跨桶汇总。 */ export function computerUseHostStateDir(): string { if (!cachedHostTag) { cachedHostTag = createHash('sha256') .update(responsibleHostIdentity()) .digest('hex') .slice(0, 12); } return join(computerUseStateDir(), 'hosts', cachedHostTag); } type NativeRequest = Record; interface NativeWireResponse { protocolVersion: number; requestId: string; response: | { Ok: unknown } | { Err: { code: string; message: string; retryable?: boolean; details?: unknown; }; }; } type NativeErrorCode = NonNullable['code']; type JsonRecord = Record; function isRecord(value: unknown): value is JsonRecord { return !!value && typeof value === 'object' && !Array.isArray(value); } function contextKey( context: Pick, ): string { return `${context.ownerId}\0${context.conversationKey}\0${context.runId}`; } /** 熔断指纹只需要「动作 + 目标」这几个字段,不必是完整请求。 */ export interface ComputerUseActionIdentity { action: ComputerUseRequest['action']; appId?: string; elementId?: string; key?: string; x?: number; y?: number; windowOperation?: string; } /** * 动作指纹 = 「同一件事」的判据。 * * 粒度是刻意的:**同一个动作打同一个目标**才算重试。换目标说明模型在尝试 * 别的路子,那正是我们希望它做的,不该继续累加;而反复戳同一个坐标正是 * 「原地打转」的典型形状。 * * 坐标取整到 10(相对坐标 0–1000):模型重试时常有 1–2 的抖动,不取整会让 * 每次都算「新目标」,熔断永远数不到 3。 */ export function actionFingerprint(input: ComputerUseActionIdentity): string { const target = input.elementId ?? (input.x !== undefined && input.y !== undefined ? `${Math.round(input.x / 10)},${Math.round(input.y / 10)}` : (input.key ?? input.windowOperation ?? '')); return `${input.action}\0${input.appId ?? ''}\0${target}`; } function numberAt(value: unknown, fallback = 0): number { return typeof value === 'number' && Number.isFinite(value) ? value : fallback; } function stringAt(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; } async function validateStateImage( state: ComputerState, ): Promise | undefined> { const image = state.screenshot; if (!image) return undefined; // 只接受 PNG。 // // 这里曾经也收 JPEG(nut-js transport 输出 q78 JPEG 省体积),但那条分支把这道 // 校验**架空**了:PNG 分支从 IHDR 读**文件里的真实宽高**再与声明值比对, // JPEG 分支却直接 `width = image.width`,于是下面「声明元数据必须与文件相符」 // 变成拿声明值和自己比,恒真。nut-js 移除后 JPEG 来源消失,这道校验重新是真的。 if (image.mime !== 'image/png') { return { code: 'invalid_image', message: `Computer Use 当前只接受经过验证的 PNG 截图,收到 ${image.mime}`, retryable: false, }; } try { const bytes = await readFile(image.path); // PNG签名: 137 80 78 71 13 10 26 10 const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); if (bytes.length < 24 || !bytes.subarray(0, 8).equals(pngSignature)) { throw new Error('PNG signature or IHDR is missing'); } const width = bytes.readUInt32BE(16); const height = bytes.readUInt32BE(20); const digest = createHash('sha256').update(bytes).digest('hex'); if ( width !== image.width || height !== image.height || (image.byteLength !== undefined && image.byteLength !== bytes.length) || (image.sha256 !== undefined && image.sha256 !== digest) ) { throw new Error('declared image metadata does not match the file'); } return undefined; } catch (error) { return { code: 'invalid_image', message: `Computer Use 截图校验失败:${(error as Error).message}`, retryable: false, }; } } function normalizeRect(value: unknown) { if (!isRecord(value)) return undefined; const width = numberAt(value.width); const height = numberAt(value.height); if (width <= 0 || height <= 0) return undefined; return { x: numberAt(value.x), y: numberAt(value.y), width, height }; } function normalizeDisplay(value: unknown): ComputerUseDisplay | undefined { if (!isRecord(value)) return undefined; const id = stringAt(value.id); const logicalBounds = normalizeRect(value.logicalBounds); if (!id || !logicalBounds) return undefined; return { id, ...(stringAt(value.name) ? { name: stringAt(value.name) } : {}), logicalBounds, ...(normalizeRect(value.visibleBounds) ? { visibleBounds: normalizeRect(value.visibleBounds)! } : {}), physicalWidth: numberAt(value.pixelWidth ?? value.physicalWidth), physicalHeight: numberAt(value.pixelHeight ?? value.physicalHeight), scaleFactor: numberAt(value.scaleFactor, 1), primary: value.primary === true, }; } /** * Ceiling on any accessibility value we forward. A single node should never be * able to push an unbounded blob (a whole document body, a log pane) into the * model's context. */ const MAX_AX_VALUE_CHARS = 256; /** Decode only the response shapes that the versioned Rust protocol owns. */ export function normalizeNativeComputerState( data: unknown, ): ComputerState | undefined { if (!isRecord(data)) return undefined; if (data.type === 'verified_action' && isRecord(data.observation)) { return normalizeNativeComputerState({ ...data.observation, type: 'observe' }); } // 数据已经是裸 ComputerState 形状(未包在 verified_action 里)时直接用。 // 形状容错,不绑定任何具体 transport。 if ( !data.type && typeof data.revision === 'string' && Array.isArray(data.displays) && isRecord(data.screenshot) ) { // 已经是归一化后的ComputerState,验证必要字段后直接返回 const displays = Array.isArray(data.displays) ? data.displays .map(normalizeDisplay) .filter((d): d is ComputerUseDisplay => !!d) : []; if (displays.length === 0) return undefined; const state = data as unknown as ComputerState; // 确保screenshot有expiresAt if (state.screenshot && !state.screenshot.expiresAt) { state.screenshot.expiresAt = Date.now() + 5 * 60_000; } return state; } if (data.type !== 'observe') return undefined; const revision = stringAt(data.revision) ?? 'native-observation'; const displays = Array.isArray(data.displays) ? data.displays .map(normalizeDisplay) .filter((display): display is ComputerUseDisplay => !!display) : []; const activeRaw = isRecord(data.activeApp) ? data.activeApp : undefined; const activeApp = activeRaw && stringAt(activeRaw.id) && stringAt(activeRaw.name) ? { id: stringAt(activeRaw.id)!, name: stringAt(activeRaw.name)!, ...(typeof activeRaw.pid === 'number' ? { pid: activeRaw.pid } : {}), } : undefined; const windows = Array.isArray(data.windows) ? data.windows.flatMap((value) => { if (!isRecord(value)) return []; const id = stringAt(value.id); const appId = stringAt(value.appId); const bounds = normalizeRect(value.bounds); return id && appId && bounds ? [ { id, appId, ...(stringAt(value.title) ? { title: stringAt(value.title) } : {}), bounds, ...(typeof value.minimized === 'boolean' ? { minimized: value.minimized } : {}), // 守护进程一直在发 focused,类型里也一直声明着,只有这里漏抄—— // 于是「哪个是主窗口」退化成「列表里第一个」。微信的第一个窗口是 // 一块 678pt 宽的辅助面板,主窗口 2560pt 排在它后面,结果模型每次 // 点对了都被警告「点到窗口外面去了」,还会按错窗口重算 region 坐标。 ...(typeof value.focused === 'boolean' ? { focused: value.focused } : {}), }, ] : []; }) : []; const sequence = normalizeSequence(data.sequence); const rawAccessibility = isRecord(data.accessibility) ? data.accessibility : undefined; const nodes = rawAccessibility && Array.isArray(rawAccessibility.nodes) ? rawAccessibility.nodes : []; const screenshotRaw = isRecord(data.screenshot) ? data.screenshot : undefined; const screenshot = screenshotRaw && stringAt(screenshotRaw.path) && stringAt(screenshotRaw.mime) ? { path: stringAt(screenshotRaw.path)!, mime: stringAt( screenshotRaw.mime, ) as ComputerUseImageReference['mime'], width: numberAt(screenshotRaw.width), height: numberAt(screenshotRaw.height), byteLength: numberAt(screenshotRaw.byteLen), ...(stringAt(screenshotRaw.sha256) ? { sha256: stringAt(screenshotRaw.sha256) } : {}), ...(stringAt(screenshotRaw.displayId) ? { displayId: stringAt(screenshotRaw.displayId) } : {}), revision, // Native frames live in a protected temporary directory and are short-lived. expiresAt: Date.now() + 5 * 60_000, } : undefined; return { revision, epoch: numberAt(data.epoch), displays, ...(activeApp ? { activeApp } : {}), windows, ...(rawAccessibility ? { accessibility: { appId: activeApp?.id ?? '', root: { elementId: stringAt(rawAccessibility.revision) ?? 'native-root', role: 'application', children: nodes.filter(isRecord).map((node) => ({ elementId: stringAt(node.elementId) ?? 'unknown', role: stringAt(node.role) ?? 'unknown', ...(stringAt(node.subrole) ? { subrole: stringAt(node.subrole) } : {}), ...(stringAt(node.name) ? { name: stringAt(node.name) } : {}), // A secure control's contents never travel, whatever the driver // sent. The macOS driver declines to read AXValue at all, but this // is the last layer before the model's context, and "the producer // promised not to" is not an access control. Windows UIA and any // future driver get the same treatment for free. ...(node.protected !== true && stringAt(node.value) ? { value: stringAt(node.value)!.slice(0, MAX_AX_VALUE_CHARS), } : {}), // `protected` drives the human-handoff boundary. Dropping it here // would leave the detector reading an always-safe-looking tree, // which is indistinguishable from having no detector at all. ...(node.protected === true ? { protected: true } : {}), ...(normalizeRect(node.bounds) ? { bounds: normalizeRect(node.bounds) } : {}), enabled: node.enabled !== false, focused: node.focused === true, actions: Array.isArray(node.actions) ? node.actions.filter( (action): action is string => typeof action === 'string', ) : [], })), }, // A truncated or permission-denied walk must never look like a clean // "no controls here" reading. ...(rawAccessibility.truncated === true ? { truncated: true } : {}), }, } : {}), ...(screenshot ? { screenshot } : {}), changedRegions: Array.isArray(data.changedRegions) ? data.changedRegions .map(normalizeRect) .filter( (rect): rect is NonNullable> => !!rect, ) : [], ...(sequence.length > 0 ? { sequence } : {}), backend: 'native', }; } /** 解出低频彩色帧序列。尺寸与载荷长度对不上的帧直接丢弃,不拿坏数据组图。 */ function normalizeSequence(value: unknown): ComputerUseSequenceFrame[] { if (!Array.isArray(value)) return []; return value.flatMap((raw) => { if (!isRecord(raw)) return []; const width = numberAt(raw.width); const height = numberAt(raw.height); const rgbBase64 = stringAt(raw.rgbBase64); if (width <= 0 || height <= 0 || !rgbBase64) return []; return [ { capturedAtMs: numberAt(raw.capturedAtMs), width, height, rgbBase64, }, ]; }); } function mapRelativePoint( value: number | undefined, origin: number, size: number, ): number | undefined { if (value === undefined) return undefined; return origin + (value / 1000) * size; } /** Automatic post-action observation uses a short readiness window, not a completion gate. * Explicit settle/wait calls retain their own timeout for genuinely slow transitions. */ export function settlePolicy(action: ComputerUseRequest['action']): { quietMs: number; timeoutMs: number; } { switch (action) { case 'activate_app': case 'window': case 'file_drop': return { quietMs: 150, timeoutMs: 700 }; case 'scroll': case 'drag': case 'pointer_up': return { quietMs: 100, timeoutMs: 400 }; case 'type': case 'key': case 'hotkey': return { quietMs: 80, timeoutMs: 300 }; default: return { quietMs: 100, timeoutMs: 400 }; } } function actionExpectedToChangeScreen(action: ComputerUseRequest['action']): boolean { return [ 'click', 'double_click', 'right_click', 'middle_click', 'drag', 'scroll', 'pointer_up', 'type', 'key', 'hotkey', 'window', 'file_drop', ].includes(action); } /** * 效果**局部**的动作:预期变化只发生在目标控件那一小块。 * * 对这些动作,「全屏变化率升高」不构成动作生效的证据 —— 屏幕上任何别的东西在动都会 * 让它升高。点击/滚动/窗口操作不在此列:它们的效果通常是结构性的、覆盖大片区域。 */ function actionEffectIsLocal(action: ComputerUseRequest['action']): boolean { return ['type', 'key', 'hotkey'].includes(action); } /** * 遍历类动作:「没动」的正确解读是**到边界了**,不是动作失败。 * * 静止也可能是瞬时动作已经完成;不得据此判输入失败。 */ const TRAVERSAL_ACTIONS = new Set(['scroll', 'key']); /** 界面变化率低于这个值就认为「屏幕没动」。 */ const CHANGE_RATIO_THRESHOLD = 0.001; export interface ActionVerificationInput { action: ComputerUseRequest['action']; /** `activate_app` 的目标应用;其它动作留空。 */ expectedAppId?: string; actualAppId?: string; /** 守护进程测得的 ROI / 全屏变化率;测不出来时**缺席**(不是 0)。 */ regionChangeRatio?: unknown; changeRatio?: unknown; /** * 动作**前后**画面差异 —— 与上面两个回答的是不同问题。 * * 上面两个来自动作后的采样窗口(「画面还在不在动」);这个是动作前的基线对 * 动作后的画面(「内容相对之前有没有移动」)。只有它能回答遍历到没到边界: * 翻页是瞬时的、没有动画,上面两个测出 0 属于正常,说明不了任何事。 */ movedRatio?: unknown; beforeRevision?: string; afterRevision: string; settled: boolean; } export interface ActionVerdict { status: 'passed' | 'failed' | 'inconclusive'; reason: string; changed: boolean; /** 三档证据强度,便于测试和排障时看清判定依据。 */ evidence: 'moved' | 'still' | 'unmeasured'; /** 实际采信的变化率(两路取最强);未测得时 undefined。 */ measuredChangeRatio?: number; } /** * 判定一次动作「是否真的落到了界面上」。 * * 抽成纯函数是为了能被单测钉死——这段逻辑没有守卫的那段时间里,它漏掉了一次 * **所有键鼠输入 100% 静默失效**的事故(守护进程把每个事件的类型字段写坏了, * 系统全部丢弃,屏幕纹丝不动),而它一路判 passed。 * * 主判据是变化率,**不是** revision。revision 的 hash 里含整屏截图的 sha256, * 屏幕上任何一处像素动一下都会让它变——菜单栏时钟跳秒就够了。这里曾经写成 * `changeRatio >= 0.001 || afterRevision !== beforeRevision` * 的那条 `||`,等于让任何一次背景噪声替动作作证,于是那次事故里这道防线一次都没响。 * * 现在按证据强度分三档,revision 降级为只在「压根没测到」时才动用的弱信号: * · moved —— 测到了且超阈值:动作确实在屏幕上留下了痕迹 * · still —— 测到了但没超阈值:这是**确定性的**「什么都没发生」,直接判失败 * · unmeasured —— 探测本身降级了(守护进程测不出来时字段缺席):最多给 inconclusive, * 不能拿 revision 变没变来冒充「通过」 */ export function gradeActionVerification( input: ActionVerificationInput, ): ActionVerdict { const finiteRatio = (value: unknown): number | undefined => typeof value === 'number' && Number.isFinite(value) ? value : undefined; // These ratios measure post-action motion, not whether the requested result was achieved. // Keep ROI separate from fullscreen noise. Zero is a valid measurement, not a failure. const roiRatio = finiteRatio(input.regionChangeRatio); const fullRatio = finiteRatio(input.changeRatio); const measuredChangeRatio = roiRatio ?? fullRatio; /** 这次判定的证据来自哪一路 —— 决定它有多硬。 */ const scope: 'roi' | 'fullscreen' | 'none' = roiRatio !== undefined ? 'roi' : fullRatio !== undefined ? 'fullscreen' : 'none'; const evidence: ActionVerdict['evidence'] = measuredChangeRatio === undefined ? 'unmeasured' : measuredChangeRatio >= CHANGE_RATIO_THRESHOLD ? 'moved' : 'still'; const expectsVisualChange = actionExpectedToChangeScreen(input.action); const revisionChanged = input.afterRevision !== input.beforeRevision; const changed = (finiteRatio(input.movedRatio) ?? 0) >= CHANGE_RATIO_THRESHOLD || evidence === 'moved' || (evidence === 'unmeasured' && revisionChanged); const activatedExpectedApp = input.action !== 'activate_app' || !input.expectedAppId || input.actualAppId === input.expectedAppId; const withRatio = (verdict: ActionVerdict): ActionVerdict => measuredChangeRatio === undefined ? verdict : { ...verdict, measuredChangeRatio }; if (!activatedExpectedApp) { return withRatio({ status: 'failed', reason: `动作后前台应用不是目标 ${input.expectedAppId ?? ''}。`, changed, evidence, }); } // ⚠️ 遍历类动作「没动」= **到边界了**,那是信息,不是失败。 // // 判成 failed 会连锁出两个恶果:`ok` 变 false(一次正常的「已经翻到头」被当成动作出错), // 而 `repeat` 半路遇到 `!next.ok` 会直接 break —— 到底的那一下反而被当成故障中止。 // 边界该由 `isAtScrollEdge` 读同一个比率去回答,措辞也该是「翻到头了」。 if (expectsVisualChange && evidence === 'still' && TRAVERSAL_ACTIONS.has(input.action)) { // 遍历类动作「没动」不是失败 —— 到边界时本来就不动。 // 有 movedRatio(动作前后差分)才敢说到底了;只有 settle 那两个比率时, // 0 可能只是「翻页是瞬时的、没有动画」,说明不了任何事。 const moved = finiteRatio(input.movedRatio); const atEdge = moved !== undefined && moved < CHANGE_RATIO_THRESHOLD; return withRatio({ status: 'inconclusive', reason: atEdge ? '动作已发出,但**动作前后画面完全相同** —— 已经翻到边界(到顶/到底),' + '同方向再翻不会有新内容。' : `动作已发出,但这次测量**回答不了它有没有生效**(变化率 ` + `${(measuredChangeRatio ?? 0).toFixed(4)})。这个指标测的是「画面还在不在动」,` + `而翻页是瞬时的、没有动画,测到 0 属于正常 —— **不代表已经翻到头**。` + `请对照最新画面自行确认内容有没有前进。`, changed, evidence, }); } if (expectsVisualChange && evidence === 'still') { return withRatio({ status: 'inconclusive', reason: '动作已发出,动作后画面静止不代表执行失败。请依据返回的最新截图确认目标结果,不要仅因此重复输入或点击。', changed, evidence, }); } // 文字录入类动作的效果是**局部**的(输入框里多几个字符)。只有全屏这一路证据时, // 「屏幕动了」完全可能是别处在动 —— 那不构成「字打进去了」的证明。据实报不确定, // 而不是把它算作通过:模型据此会去核对,而不是带着一个假的成功往下走。 // // 只收窄到文字录入,不一刀切到所有动作:点击/滚动的效果通常是结构性的,全屏证据 // 对它们仍然成立,无差别改成不确定只会制造噪声。 if (expectsVisualChange && evidence === 'moved' && scope === 'fullscreen' && actionEffectIsLocal(input.action)) { return withRatio({ status: 'inconclusive', reason: '只测到全屏有变化,没有目标区域的证据 —— 无法确认这次输入真的落进了目标控件' + '(屏幕别处的动静也会让全屏变化率升高)。请对照最新截图确认内容是否已经出现,' + '没出现就重新定位输入框后再输入。', changed, evidence, }); } if (expectsVisualChange && evidence === 'unmeasured') { return withRatio( revisionChanged ? { status: 'inconclusive', reason: '动作已发出;请直接核对返回的新截图中的目标结果,无需重复 observe 或重复执行。', changed, evidence, } : { status: 'inconclusive', reason: '没有足够的视觉变化证据;请检查返回的截图,不能据此判定动作失败或重复执行。', changed, evidence, }, ); } if (!input.settled) { return withRatio({ status: 'inconclusive', reason: '已取得动作后状态,但稳态或变化证据不足。', changed, evidence, }); } return withRatio({ status: 'passed', reason: '动作后状态已重新观测并通过稳态检查;这不是任务成功证明,请核对返回画面中的目标结果。', changed, evidence, }); } class ComputerUseClientError extends Error { constructor( readonly code: NativeErrorCode, message: string, ) { super(message); this.name = 'ComputerUseClientError'; } } function nativeContext(context: ComputerUseRunContext): Record { return { ownerId: context.ownerId, conversationKey: context.conversationKey, runId: context.runId, }; } function target(request: ComputerUseRequest): Record { if (request.elementId) { if (!request.expectedRevision) { throw new ComputerUseClientError( 'invalid_request', '使用 elementId 时必须提供 expectedRevision', ); } return { kind: 'element', elementId: request.elementId, revision: request.expectedRevision, }; } if ( !request.displayId || request.x === undefined || request.y === undefined ) { throw new ComputerUseClientError( 'invalid_request', '坐标动作必须提供 displayId、x 和 y', ); } return { kind: 'point', displayId: request.displayId, point: { x: request.x, y: request.y }, }; } function nativeAction(request: ComputerUseRequest): Record { switch (request.action) { case 'click': case 'double_click': case 'right_click': case 'middle_click': return { kind: 'click', target: target(request), button: request.action === 'right_click' ? 'right' : request.action === 'middle_click' ? 'middle' : 'left', count: request.action === 'double_click' ? 2 : 1, }; case 'hover': return { kind: 'hover', target: target(request) }; case 'pointer_down': case 'pointer_move': case 'pointer_up': if (request.x === undefined || request.y === undefined) { throw new ComputerUseClientError( 'invalid_request', `${request.action} 必须提供 x 和 y`, ); } return { kind: 'pointer', phase: request.action.slice('pointer_'.length), point: { x: request.x, y: request.y }, buttons: request.action === 'pointer_up' ? 0 : 1, }; case 'drag': if ( request.toX === undefined || request.toY === undefined || !request.displayId ) { throw new ComputerUseClientError( 'invalid_request', 'drag 必须提供 displayId、toX 和 toY', ); } return { kind: 'drag', from: target(request), to: request.elementId ? { kind: 'point', displayId: request.displayId, point: { x: request.toX, y: request.toY }, } : target({ ...request, x: request.toX, y: request.toY }), durationMs: request.timeoutMs ?? 500, }; case 'scroll': { let deltaX = request.dx ?? 0; let deltaY = request.dy ?? 0; if (request.direction) { const scrollAmount = 500; switch (request.direction) { case 'up': deltaY = -scrollAmount; break; case 'down': deltaY = scrollAmount; break; case 'left': deltaX = -scrollAmount; break; case 'right': deltaX = scrollAmount; break; } } // ⚠️ **坐标必须传下去。** // // 这里以前只发 deltaX/deltaY,x/y 被静默丢弃 —— 而工具描述一直写着 // 「x/y 指向要滚动的区域中心」。macOS 的滚轮事件不携带位置,投递给**当前光标 // 所在**的视图,于是滚轮实际落在上一次点击留下的地方。 // // 实测抓到:任务要滚聊天记录,模型规规矩矩给了聊天区中心的坐标,连滚三次 —— // 右侧聊天记录一行没动,左侧(上一次点过的)会话列表滚了一大截。三次都报成功, // 因为全屏确实变了。工具承诺了实现没做的事,模型无从察觉。 // // 坐标此刻已被 mapRelativeCoordinates 换算过(scroll 在 needsPoint 名单里), // 直接复用 target() 构造,与其它指针动作走同一条路。 const at = request.elementId || (request.displayId && request.x !== undefined && request.y !== undefined) ? target(request) : undefined; return { kind: 'scroll', deltaX, deltaY, ...(at ? { at } : {}), }; } case 'type': if (request.text === undefined) throw new ComputerUseClientError( 'invalid_request', 'type 必须提供 text', ); return { kind: 'type_text', text: request.text, replaceSelection: false }; case 'key': if (!request.key) throw new ComputerUseClientError('invalid_request', 'key 必须提供 key'); return { kind: 'key', key: request.key, modifiers: request.modifiers ?? [] }; case 'hotkey': { if (!request.key) throw new ComputerUseClientError('invalid_request', 'hotkey 必须提供 key(格式:command+c, command+shift+g)'); const parts = request.key.split('+'); const mainKey = parts.pop()!; const modifiers = parts; return { kind: 'key', key: mainKey, modifiers }; } case 'clipboard_read': return { kind: 'clipboard_read' }; case 'clipboard_write': if (request.text === undefined) { throw new ComputerUseClientError( 'invalid_request', 'clipboard_write 必须提供 text', ); } return { kind: 'clipboard_write', text: request.text }; case 'grab_region_to_clipboard': if (!request.rect) { throw new ComputerUseClientError( 'invalid_request', 'grab_region_to_clipboard 必须提供 rect', ); } return { kind: 'grab_region_to_clipboard', rect: request.rect }; case 'activate_app': if (!request.appId) throw new ComputerUseClientError( 'invalid_request', 'activate_app 必须提供 appId', ); return { kind: 'activate_app', appId: request.appId }; case 'window': { if (!request.windowId) throw new ComputerUseClientError( 'invalid_request', 'window 必须提供 windowId', ); const op = request.windowOperation ?? 'focus'; if (op === 'move_resize' && !request.rect) { throw new ComputerUseClientError( 'invalid_request', 'window move_resize 必须提供 rect', ); } return { kind: 'window', windowId: request.windowId, // Rust's WindowOperation is externally tagged: unit variants are bare // strings, the struct variant carries its payload. // `center` 是 struct variant(带 force 字段),与 move_resize 一样不能 // 序列化成裸字符串 —— 那样 Rust 侧反序列化会直接失败。 operation: op === 'move_resize' ? { move_resize: { bounds: request.rect } } : op === 'center' ? { center: { force: request.force === true } } : op, }; } case 'file_drop': if (!request.filePaths?.length) { throw new ComputerUseClientError( 'invalid_request', 'file_drop 必须提供至少一个文件路径', ); } return { kind: 'file_drop', paths: request.filePaths, // Optional on purpose: with no drop target the paste lands in whatever // already has focus, which is often what the caller wants. Synthesising // a (0,0) target instead would click the corner of the screen. ...(request.elementId || (request.displayId && request.x !== undefined) ? { target: target(request) } : {}), method: request.dropMethod ?? 'paste', }; default: throw new ComputerUseClientError( 'unsupported', `${request.action} 尚未映射到原生动作协议`, ); } } /** * 这次输入动作要不要顺手测一下界面变化率。 * * @internal 判据依赖上一次观测,见下。 * * 判断留在 TS 而不是守护进程,因为它依赖一件只有宿主知道的事:**上一次观测 * 的无障碍树到底可不可用**。 * * 两个条件同时成立才探测: * ① 动作是 `type` —— 这条判据要回答的是「**打字**过程中冒出了联想框/补全/ * 确认框吗」。曾经把 `key` 也算进来,那是错的:回车导航、Cmd+Tab 切应用、 * 翻页快捷键都会让整屏大面积变化,于是每一次正常的键盘操作都被判成 * 「弹出了可疑东西」并停下来找人。按键的意图千差万别,用同一条像素判据 * 去套必然误报。 * ② 上次观测的 AX 树是 `truncated` —— 树好用的时候有更准的 AX 判据 * (`detectComputerHumanBoundary`),不必用像素这条更钝的信号添乱 * * 于是探测那 ~400ms 只花在真正瞎的应用上(微信、Electron 系),而这恰好是 * 唯一需要它的地方。AX 树正常的应用零额外成本。 */ /** * 效果可以由「目标区域动没动」回答的动作。 * * ⚠️ 这里原先只有 `type`,理由(见下方历史注释)是:点击/滚动引起的变化本来就是预期 * 结果,拿变化率去判「是不是出意外了」必然满屏误报。**那个理由本身没错,但它混同了 * 两个不同的问题**: * · 「有没有出意外」—— 确实只对打字有意义,这一路的消费方是 `classifyPixelChange`, * 它自己用 `typing` 门禁挡住了非输入动作(humanBoundary.ts:148),不受本表影响; * · 「**动作到底生效了没有**」—— 对滚动/点击同样成立,而且语义明确: * 目标区域没动 = 没滚动 = 到边界了 / 没点中。 * * 后者恰恰是整条反馈链路的地基,而它此前从未被测量过。实测代价:`repeat` 的边界自动停 * 是死代码、type 恒判 inconclusive(诚实文案退化成恒定误报)、「滚动没生效」的提示恒不 * 触发、点击零命中反馈 —— 模型只能盲操作 + 肉眼看截图。 */ const PROBE_CHANGE_ACTIONS = new Set(['type', 'scroll', 'key']); /** * ⛔ **点击类动作不在上表里,这是实测定下来的边界,别再加回去。** * * 关键在于 `probe_change_ratio` 测的**不是**「动作前 vs 动作后的差异」,而是 * `settle_timeline(region, 120, 400)` —— 在动作之后的一个窗口里**逐帧对比相邻采样**, * 回答的是「画面还在不在动」。 * * 于是三类动作的契合度完全不同: * · `type` —— 逐字上屏的重绘落在窗口内 ✅ * · `scroll` / `key`(翻页) —— 滚动持续到窗口内;到边界时纹丝不动,0 正是「到底了」✅ * · `click` —— 重绘往往在采样开始前就结束了,**动作成功也测出 0** ❌ * * 一次把 click 加进来的实测代价:10 步里 7 步被判 `verification_failed: * 动作后界面变化率仅 0.0000`,而那些点击在截图上明明生效了。原注释担心的 * 「拿变化率判点击必然误报」是对的,只是理由要说准 —— 不是「变化本来就是预期结果」, * 是**这个测量根本回答不了点击那个问题**。 */ /** * 要不要让守护进程顺带做一次像素变化探测。 * * 探测每次要几百毫秒,所以判据要窄 —— 但要窄在**对的维度**上: * * ① **动作**:见 `PROBE_CHANGE_ACTIONS`。 * * ② **只在 AX 给不出控件级信息时**。有真实 AX 树的应用,焦点变化、控件角色这些信号 * 比像素准得多且几乎免费(见 `humanBoundary.ts::detectComputerHumanBoundary`), * 再花几百毫秒去数像素纯属把成本外溢给正常应用。像素是自绘 / Electron * 这类"AX 树只是个窗口壳"的应用**唯一剩下**的手段,探测该留给它们。 * * 这个参数此前是 `_observation`(收下却从不读),于是判据退化成 * 「凡输入类动作一律探测」——死参数照例是 bug 的强信号。 */ function shouldProbeChange( action: ComputerUseRequest['action'], observation: ComputerState | undefined, ): boolean { if (!PROBE_CHANGE_ACTIONS.has(action)) return false; return !axGivesControlDetail(observation); } /** * 探测用的 ROI:上一次观测里焦点控件的矩形(逻辑点)。 * * 拿不到就返回 undefined,守护进程退回整屏测量 —— 那仍然可用,只是判据更钝 * (见 `humanBoundary.ts::detectPixelHumanBoundary` 里的面积归一化)。 * * **不经相对坐标换算**:AX 给的 bounds 本来就是逻辑点,再换算一次会得到一块 * 完全不相干的区域,而且不会报错——只会安静地测错地方。 */ /** 回落 ROI 的边长,占显示器短边的比例。够罩住一个输入框,又不至于把半屏噪声收进来。 */ const FALLBACK_PROBE_SPAN = 0.12; /** * 这次动作的「目标区域」——用来回答「动作有没有落到目标上」。 * * 首选 AX 焦点控件的矩形。**但自绘应用给不出它**:微信的 AX 树整棵只有 5 个节点、 * `focusLevel` 恒为 1(只有窗口壳),于是 ROI 永远缺席,判定只能退到全屏 —— 而全屏 * 在聊天软件上几乎恒有动静,等于没有判定。这不是边缘情况,是这类应用的常态。 * * 所以拿不到 AX 时用**刚刚点击的那个位置**兜底:对「点输入框 → 打字」这个最常见的 * 序列,点击点就是文字将要出现的地方,围绕它取一小块就是正确的观察窗口。 * * `point` 是 0–1000 相对坐标(模型的坐标系),这里换算成逻辑点 —— 与 AX 矩形同一 * 空间,因为守护进程按逻辑点解释 probeRegion(见调用处注释:ROI 不能再过一次 * mapRelativeCoordinates)。 */ export function probeRegionFor( observation: ComputerState | undefined, point?: { x: number; y: number }, action?: ComputerUseRequest['action'], ): ComputerUseRect | undefined { if (!observation) return undefined; // ⚠️ **只在焦点节点确实是个控件时才信它的矩形。** // // 与 `shouldProbeChange` 共用同一个判据不是为了省代码 —— 「要不要测」和「测哪里」 // 必须对「这个 AX 焦点算不算数」给出同一个答案,否则会出现最坏的组合: // 判定去测了,却测在一块永远不变的地方,于是**言之凿凿地报「没有变化」**。 // // 实测:微信读书报 `AXGroup · caret(51,97)` —— 窗口左上角的退化包装节点。 // ROI 落在那个角上,右箭头把书从 32/106 翻到 34/106(整页正文全换), // movedRatio 依旧是 0。模型收到的是一条**证据确凿的错误结论**。 if (axFocusIsConcreteControl(observation)) { const caret = deriveFocusSnapshot(observation)?.caret; if (caret) return caret; } // ⚠️ **遍历类动作不吃「上次点击位置」这个兜底。** // 指针落点之所以能当 ROI,靠的是「点输入框 → 在那里打字」这条因果链。 // `key: right` / `scroll` 没有这条链:上一次点击可能是十几步之前为了打开这本书, // 围着那个陈旧的点取一小块,测的还是一块不相干的区域 —— 又一次「测了个寂寞」。 // 这类动作的效果本来就是整页/整个视口的,退回整屏才是正确的观察窗口。 if (action && TRAVERSAL_ACTIONS.has(action)) return undefined; // 容器焦点 + 没有指针落点 → 返回 undefined,守护进程退回**整屏**测量。 if (!point) return undefined; const display = observation.displays?.find((candidate) => candidate.primary) ?? observation.displays?.[0]; const bounds = display?.logicalBounds; if (!bounds || bounds.width <= 0 || bounds.height <= 0) return undefined; const span = Math.min(bounds.width, bounds.height) * FALLBACK_PROBE_SPAN; const centerX = bounds.x + (point.x / 1000) * bounds.width; const centerY = bounds.y + (point.y / 1000) * bounds.height; // 夹回显示器内:越界的矩形在采样侧要么被拒、要么退化成全屏,两种都会让 ROI 白设。 const x = Math.max(bounds.x, Math.min(centerX - span / 2, bounds.x + bounds.width - span)); const y = Math.max(bounds.y, Math.min(centerY - span / 2, bounds.y + bounds.height - span)); return { x, y, width: span, height: span }; } export function toNativeComputerUseRequest( request: ComputerUseRequest & { _internalObserve?: boolean }, ): NativeRequest { const context = nativeContext(request.context); if (request.action === 'status') return { type: 'hello', supported: { min: 1, max: 1 } }; if (request.action === 'permissions') return { type: 'permissions' }; if (request.action === 'observe') { return { type: 'observe', context, includeScreenshot: true, ...(request._internalObserve ? { internal: true } : {}), ...(request.frames && request.frames > 1 ? { frames: request.frames } : {}), ...(request.rect ? { rect: request.rect } : {}), }; } // Host diagnostics use a metadata-only observation. It intentionally stays // outside the model-visible action list until the native app inventory has // a stable, cross-platform contract. if (request.action === 'list_apps') { return { type: 'observe', context, includeScreenshot: false, internal: true, }; } // 30 帧是**守护进程侧**的上限,不是给模型的图数 —— TS 侧会用事件锚定挑出 // 4 帧再编码(见 observationImages::buildReplayImages)。要多要少都在这里定, // 别在模型那边定。 if (request.action === 'replay') return { type: 'replay', context, maxFrames: 30 }; if (request.action === 'settle') { return { type: 'settle', context, expectedEpoch: request.expectedEpoch ?? 0, quietMs: request.quietMs ?? 300, timeoutMs: request.timeoutMs ?? 3_000, region: request.rect ?? null, }; } if (request._verifiedAction) { if (request.expectedEpoch === undefined) { throw new ComputerUseClientError( 'invalid_request', `${request.action} 前必须 observe 并提供 expectedEpoch`, ); } if (!request.context.grantId?.trim()) { throw new ComputerUseClientError( 'grant_required', `${request.action} 必须携带有效 grantId`, ); } return { type: 'execute_verified_action', context, grantId: request.context.grantId, expectedEpoch: request.expectedEpoch, action: nativeAction(request), ...(request.probeChange ? { probeChange: true } : {}), ...(request.probeRegion ? { probeRegion: request.probeRegion } : {}), quietMs: request._verifiedAction.quietMs, timeoutMs: request._verifiedAction.timeoutMs, ...(request._verifiedAction.region ? { settleRegion: request._verifiedAction.region } : {}), }; } if (request.action === 'stop' || request.action === 'emergency_stop') { return { type: 'emergency_stop', context, reason: request.action }; } // activate_app 通过 bundleId 工作,不依赖之前的屏幕观测状态, // 不需要 expectedEpoch(默认传 0 即可)。用户刚打开 app 时也不可能先 observe。 if (request.action === 'activate_app') { return { type: 'action', context, grantId: request.context.grantId ?? '', expectedEpoch: request.expectedEpoch ?? 0, action: nativeAction(request), ...(request.probeChange ? { probeChange: true } : {}), }; } if ( [ 'select_text', 'secondary_action', 'wait_stable', 'wait_for_element', 'wait_for_text', 'wait_for_window', 'takeover', 'resume', ].includes(request.action) ) { throw new ComputerUseClientError( 'unsupported', `${request.action} 尚未实现原生 Wire 请求`, ); } if (request.expectedEpoch === undefined) { throw new ComputerUseClientError( 'invalid_request', `${request.action} 前必须 observe 并提供 expectedEpoch`, ); } if (!request.context.grantId?.trim()) { throw new ComputerUseClientError( 'grant_required', `${request.action} 必须携带有效 grantId`, ); } return { type: 'action', context, grantId: request.context.grantId ?? '', expectedEpoch: request.expectedEpoch, action: nativeAction(request), ...(request.probeChange ? { probeChange: true } : {}), }; } export function createSignedComputerUseWire(input: { request: ComputerUseRequest; token: Uint8Array; nonce: string; timestampMs: number; }): { protocolVersion: number; requestId: string; auth: { nonce: string; timestampMs: number; macHex: string }; request: NativeRequest; } { return createSignedNativeWire({ nativeRequest: toNativeComputerUseRequest(input.request), requestId: input.request.requestId, token: input.token, nonce: input.nonce, timestampMs: input.timestampMs, }); } function createSignedNativeWire(input: { nativeRequest: NativeRequest; requestId: string; token: Uint8Array; nonce: string; timestampMs: number; }): { protocolVersion: number; requestId: string; auth: { nonce: string; timestampMs: number; macHex: string }; request: NativeRequest; } { const payloadHash = createHash('sha256') .update(JSON.stringify(input.nativeRequest)) .digest('hex'); const signing = `${COMPUTER_USE_PROTOCOL_VERSION}\n${input.requestId}\n${input.timestampMs}\n${input.nonce}\n${payloadHash}`; return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId: input.requestId, auth: { nonce: input.nonce, timestampMs: input.timestampMs, macHex: createHmac('sha256', input.token).update(signing).digest('hex'), }, request: input.nativeRequest, }; } /** * 是否是「连不上守护进程」而非业务失败。 * * 只有这一类值得清掉陈旧 socket 重试;业务错误重试没有意义,而且对写操作 * 来说重试可能造成重复动作。 */ function isConnectionFailure(error: unknown): boolean { const code = (error as NodeJS.ErrnoException | undefined)?.code; return ( code === 'ECONNREFUSED' || code === 'ENOENT' || code === 'EPIPE' || code === 'ECONNRESET' ); } function mapErrorCode( code: string, ): NonNullable['code'] { const map: Record['code']> = { unsupported: 'unsupported', permission_denied: 'permission_denied', capture_transient: 'capture_transient', invalid_request: 'invalid_request', protocol_mismatch: 'protocol_mismatch', stale_epoch: 'stale_state', run_not_found: 'stale_state', // 与 stale_state 分开:「应用没启动」重新观测也不会让它出现, // 建议模型「再试一次」是错的指引。 target_not_found: 'target_not_found', input_lease_unavailable: 'lease_conflict', human_input_detected: 'human_input_detected', emergency_stopped: 'cancelled', ipc_failure: 'unavailable', authentication_failed: 'permission_denied', nonce_replay: 'permission_denied', request_expired: 'invalid_request', }; return map[code] ?? 'internal'; } class NativeDaemonTransport implements ComputerUseTransport { private startPromise: Promise | null = null; private daemonProcess: ReturnType | null = null; private permissionPrompted = false; constructor( private readonly helperPath: string, private readonly stateDir: string, ) {} /** Kill the daemon if running. Called on dispose. */ private killDaemon(): void { if (this.daemonProcess) { try { this.daemonProcess.kill(); } catch { // already dead } this.daemonProcess = null; } } /** 一次完整往返:确保守护进程在跑 → 读配对 token → 签名 → 发送。 */ private async exchange( request: ComputerUseRequest & { _internalObserve?: boolean }, signal: AbortSignal | undefined, restart: boolean, ): Promise { await this.ensureDaemon(signal, restart); const token = await readFile(join(this.stateDir, 'pairing.token')); const wire = createSignedComputerUseWire({ request, token, nonce: randomUUID(), timestampMs: Date.now(), }); return this.sendWire(wire, signal); } async request( request: ComputerUseRequest & { _internalObserve?: boolean; }, signal?: AbortSignal, ): Promise { try { const response = await this.exchange(request, signal, false) // 连不上就当作「守护进程死了但 socket 文件还在」,清掉重启再试一次。 // 只重试连接失败,不重试业务错误 —— 后者重试没有意义且可能重复动作。 .catch(async (error: unknown) => { if (signal?.aborted || !isConnectionFailure(error)) throw error; return this.exchange(request, signal, true); }); if ('Err' in response.response) { const errorCode = mapErrorCode(response.response.Err.code); return { protocolVersion: response.protocolVersion, requestId: response.requestId, ok: false, error: { code: errorCode, message: response.response.Err.message, retryable: response.response.Err.retryable === true, details: isRecord(response.response.Err.details) ? response.response.Err.details : undefined, }, }; } const data = response.response.Ok; return { protocolVersion: response.protocolVersion, requestId: response.requestId, ok: true, // `data` is kept for the protocol normalizer and diagnostics. Do not // stringify a whole native observation into `content`: the tool layer // already emits a compact state summary plus one image. Repeating the // AX tree and screenshot metadata here costs thousands of tokens per // action and makes a CLI run appear to stall between mouse events. data, }; } catch (error) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId: request.requestId, ok: false, error: { code: signal?.aborted ? 'cancelled' : error instanceof ComputerUseClientError ? error.code : 'unavailable', message: (error as Error).message, }, }; } } async emergencyStopAll(signal?: AbortSignal): Promise { const requestId = randomUUID(); try { await this.ensureDaemon(signal); const token = await readFile(join(this.stateDir, 'pairing.token')); const wire = createSignedNativeWire({ nativeRequest: { type: 'emergency_stop', context: null, reason: 'desktop_global_hotkey', }, requestId, token, nonce: randomUUID(), timestampMs: Date.now(), }); const response = await this.sendWire(wire, signal); if ('Err' in response.response) { return { protocolVersion: response.protocolVersion, requestId: response.requestId, ok: false, error: { code: mapErrorCode(response.response.Err.code), message: response.response.Err.message, }, }; } return { protocolVersion: response.protocolVersion, requestId: response.requestId, ok: true, content: JSON.stringify(response.response.Ok), data: response.response.Ok, }; } catch (error) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: { code: signal?.aborted ? 'cancelled' : 'unavailable', message: (error as Error).message, }, }; } } async inputStatus( context: ComputerUseRunContext, acknowledge = false, signal?: AbortSignal, ): Promise { const requestId = randomUUID(); const send = async (restart: boolean): Promise => { await this.ensureDaemon(signal, restart); const token = await readFile(join(this.stateDir, 'pairing.token')); const wire = createSignedNativeWire({ nativeRequest: { type: 'input_status', context, acknowledge }, requestId, token, nonce: randomUUID(), timestampMs: Date.now(), }); return this.sendWire(wire, signal); }; const response = await send(false).catch(async (error: unknown) => { if (signal?.aborted || !isConnectionFailure(error)) throw error; return send(true); }); if ('Err' in response.response) { throw new ComputerUseClientError( mapErrorCode(response.response.Err.code), response.response.Err.message, ); } const value = response.response.Ok; const envelope = isRecord(value) && isRecord(value.InputStatus) ? value.InputStatus : value; if (!isRecord(envelope)) { throw new ComputerUseClientError('protocol_mismatch', 'Helper 未返回有效的输入接管状态'); } return { context: { ownerId: context.ownerId, conversationKey: context.conversationKey, runId: context.runId, }, detected: envelope.detected === true, ...(stringAt(envelope.inputType) ? { inputType: stringAt(envelope.inputType) as ComputerUseInputStatus['inputType'] } : {}), ...(numberAt(envelope.detectedAtMs) > 0 ? { detectedAtMs: numberAt(envelope.detectedAtMs) } : {}), }; } private endpoint(): string { if (process.platform === 'win32') { return `\\\\.\\pipe\\kakadeai-cu-helperd-${process.env.USERNAME ?? 'user'}`; } return join(this.stateDir, 'cu-helperd.sock'); } /** * 主动调用 permissions 接口: * 1. 触发 cu-helperd 内部的 macOS 系统权限弹窗(首次 not determined 时) * 2. 获取当前权限状态 * 3. 如果权限缺失,自动打开系统设置页面并打印醒目引导 * * 设计参考:UI-TARS ensurePermissions() + openSystemPreferences() */ private async probePermissions(): Promise { try { // 等待一小会确保 daemon 完成初始化并写入 pairing.token await delay(300); // ⚠️ **必须按 Buffer 读,不能加 'utf8'。** 配对令牌是 32 字节随机数,不是文本: // 按 utf8 解码会把非法字节替换成 U+FFFD,算出来的 HMAC 与 `exchange()`(一直是 // 按 Buffer 读的)完全不同。后果不是「偶尔失败」,是这个自检**从来没有成功过一次** —— // 它每次都收到 authentication_failed,而下面的 parsePermissionResponse 把错误信封 // 当成「字段缺失」,于是无条件判定两个权限都没授权,打印一整屏权限引导。 // 用户因此被反复引去检查根本没问题的系统设置,而真正的故障在别处。 const token = await readFile(join(this.stateDir, 'pairing.token')); const nonce = randomUUID(); const timestampMs = Date.now(); const nativeRequest = { type: 'permissions' }; const payloadHash = createHash('sha256') .update(JSON.stringify(nativeRequest)) .digest('hex'); const requestId = randomUUID(); const signing = `${COMPUTER_USE_PROTOCOL_VERSION}\n${requestId}\n${timestampMs}\n${nonce}\n${payloadHash}`; const wire = { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, auth: { nonce, timestampMs, macHex: createHmac('sha256', token).update(signing).digest('hex'), }, request: nativeRequest, }; // 等待权限响应 const resp = await this.sendWire(wire); // 检查权限状态,缺失则自动打开系统设置并显示引导 ensureMacPermissions(resp); } catch { // 权限探测失败不影响主流程(可能是daemon还没完全就绪),静默忽略 } } /** * 确保守护进程在跑。 * * `force` 用于**陈旧 socket 恢复**:unix domain socket 是文件,守护进程被 * kill 或崩溃时不会被清理,于是 `existsSync` 恒为 true、永远不重启,而 * 连接必然失败 —— 每一次后续请求都失败,直到有人手工删掉那个文件。 * 一个需要人工介入才能恢复的失败模式不能算产品级。 */ private async ensureDaemon( signal?: AbortSignal, force = false, ): Promise { if (force) { this.startPromise = null; // 先移除陈旧 socket,否则守护进程 bind 时会撞上它 if (process.platform !== 'win32') { try { unlinkSync(this.endpoint()); } catch { // 已经不在了,或者没权限 —— 两种情况下继续尝试启动都是对的 } } } else if (existsSync(this.endpoint())) { return; } if (!this.startPromise) { this.startPromise = new Promise((resolveStart, reject) => { const child = spawn(this.helperPath, [], { // 不要设置 detached: true —— detached 会调用 setsid() 创建新 session, // 导致 macOS TCC 无法通过进程继承链找到 responsible application(.app), // 权限弹窗就只能显示 "cu-helperd" 而不是 "KakadeAI"。 // 保持子进程在父进程的 session 内,TCC 能正确关联到 KakadeAI.app。 stdio: 'ignore', windowsHide: true, env: { ...process.env, KAKADEAI_CU_HOME: this.stateDir }, }); this.daemonProcess = child; child.once('error', reject); child.once('exit', () => { // 守护进程退出时清理引用,下次请求会自动重启 this.daemonProcess = null; this.startPromise = null; }); // unref() 让子进程不阻止父进程事件循环退出,但不改变进程组归属。 // 父进程退出时子进程会收到 SIGHUP 自然消亡,避免孤儿进程。 child.unref(); const startedAt = Date.now(); const poll = (): void => { if (signal?.aborted) return reject(new DOMException('aborted', 'AbortError')); if (existsSync(this.endpoint()) || process.platform === 'win32') { return resolveStart(); } if (Date.now() - startedAt > 5_000) return reject(new Error('cu-helperd 启动超时')); setTimeout(poll, 50); }; poll(); }).finally(() => { this.startPromise = null; }); } await this.startPromise; // Daemon 启动成功后,主动检查 macOS 权限并引导用户授权。 // 设计参考 UI-TARS ensurePermissions(): // 1. 触发 cu-helperd 内部的系统原生弹窗(首次 not determined 时) // 2. 获取当前权限状态 // 3. 权限缺失时自动打开系统设置页面 + 打印醒目引导 if (!this.permissionPrompted && process.platform === 'darwin') { this.permissionPrompted = true; // 后台异步执行,不阻塞主流程 this.probePermissions().catch(() => { // 权限检查失败不影响主流程 }); } } private sendWire( wire: object, signal?: AbortSignal, ): Promise { return new Promise((resolveResponse, reject) => { const socket = createConnection(this.endpoint()); let buffer = ''; const cleanup = (): void => signal?.removeEventListener('abort', abort); const abort = (): void => { socket.destroy(); cleanup(); reject(new DOMException('aborted', 'AbortError')); }; signal?.addEventListener('abort', abort, { once: true }); socket.setEncoding('utf8'); socket.once('connect', () => socket.write(`${JSON.stringify(wire)}\n`)); socket.on('data', (chunk) => { buffer += chunk; const newline = buffer.indexOf('\n'); if (newline < 0) return; cleanup(); socket.end(); try { resolveResponse( JSON.parse(buffer.slice(0, newline)) as NativeWireResponse, ); } catch (error) { reject(error); } }); socket.once('error', (error) => { cleanup(); reject(error); }); }); } } export class ComputerUseService { private readonly transport: ComputerUseTransport | null; private readonly observations = new Map(); /** * 动作发生时那次观测。动作会让 `observations` 里的条目作废(坐标不能再用), * 但动作**之后**的像素兜底判定需要知道当时的 AX 可用性与前台应用。 * 分开存放是为了让「不能用于坐标」这件事在类型/命名上就说清楚。 */ private readonly actedObservations = new Map(); /** 上一次观测派生的焦点快照。跨动作存活,用于跨进程打断检测。 */ private readonly focusSnapshots = new Map(); /** 本运行内已经注入过完整说明书摘要的应用。 */ private readonly injectedManuals = new Map>(); /** * 上一个动作对「焦点应该落到哪」的预期。**一次性**:下一次观测取用后即清除。 * * 不清除的话,一次 `activate_app` 会永久豁免这个运行里后续所有的前台抢占 * 检测 —— 那就把 C2 这条信号变成了摆设。 */ private readonly pendingExpectations = new Map(); /** * 最近一次观测返回的AX元素短id→真实id映射。 * 用于支持LLM用@1/@2这种简短引用点击元素。 */ private readonly axIdMaps = new Map>(); /** * 每个 run 最近一次**指针动作**落在哪(0–1000 相对坐标)。 * * `type` / `key` 自身不带坐标,但它们的效果几乎总是出现在上一次点击的位置 —— * 「点输入框 → 打字」。AX 给不出焦点控件时(自绘应用的常态),这就是唯一能把 * 判定收敛到局部的信息,没有它就只能退到全屏,而全屏在聊天软件上等于没有判定。 */ private readonly lastPointerPoints = new Map(); /** * 连续失败熔断状态,**按运行 + 动作指纹**隔离。 * * 曾经它住在全机唯一的 `telemetry.jsonl` 里,有三个问题,每一个都足够致命: * ① 没有隔离 —— 会话 A 连续失败会把会话 B 的写操作一起熔断 * ② 读改写整文件 + 时间戳临时文件名 —— 并发调用会互相覆盖、丢记录 * ③ 计数不分动作 —— 一次成功的 observe 就清零,于是 * 「失败 → observe → 失败 → observe …」这个最常见的打转模式 * 可以无限绕过熔断 * * 现在状态在内存里、按 `contextKey + 指纹` 分桶:同一个失败动作反复重试才 * 累加,换目标重置,**该指纹的一次成功**才清零。磁盘遥测退回纯观测职责。 */ private readonly failureStreaks = new Map< string, { fingerprint: string; count: number } >(); constructor(options: ComputerUseServiceOptions = {}) { // 平台门放在这里,而不是各宿主各判一次。 // // Windows 只有协议桩、没有 UI Automation 驱动,而 `ensureDaemon` 的 // win32 分支还不等命名管道出现就直接 resolve —— 走进去必然连接失败, // 报出来的是含糊的 `unavailable`。宁可在入口就明说「这个平台还不支持」。 // Unit tests use injected transports for behavior and an explicit helper // path for the one native contract test. Auto-discovering the user's real // daemon would turn unrelated tests into permission/UI integration tests // and write into the user's machine state. const nativeAutoDiscoveryEnabled = process.env.NODE_ENV !== 'test' || options.helperPath !== undefined; const supported = options.transport !== undefined || (process.platform === 'darwin' && nativeAutoDiscoveryEnabled); // Transport 只有一条:Rust 的 cu-helperd(`NativeDaemonTransport`),CLI 与 Desktop 共用。 // // 这里曾经并存第二条 `NutJsNodeTransport`(CLI 默认走它,在主进程内用 // `@computer-use/nut-js` 直接操作键鼠)。它被整条移除,理由按影响从大到小: // ① 它带进 3 个原生 `.node` 二进制,`bun --compile` 在**打包期**就要解析, // 于是绿色版(装 U 盘卖的免安装单文件夹)在 win-x64 直接编译失败。 // 平台判断和 try/catch 都救不了——那是运行时的事,打包器不看。 // ② 同一能力两套实现。已核实 Rust 侧 `Action`(13 变体) + `Request`(10 变体) // 覆盖了 nut-js 那条通路的全部动作,并且**独有** ExecuteVerifiedAction / // InputStatus / probe_change —— 移除不丢能力。 // ③ 它顺带架空了两道校验:截图完整性校验的 JPEG 分支拿声明值和自己比(见 // `verifyScreenshot`),动作验证的 nut-js 分支无条件合成 `settled: true`。 // 代价是真实的、已单独补偿:nut-js 的唯一优势是「权限授给终端、免给 daemon 单独授权」, // 改走 daemon 后由 `accessibilityPermission.ts` 的授权引导承接。 let transport: ComputerUseTransport | null = options.transport ?? null; if (!transport && supported) { const helperPath = options.helperPath ?? findComputerUseHelper(); if (helperPath) { transport = new NativeDaemonTransport( helperPath, // 守护进程的运行时状态按**宿主身份**分桶,不再全机共用一个 socket。 // 理由见 computerUseHostStateDir 的注释(跨宿主共享曾导致 TCC 身份污染)。 options.stateDir ?? computerUseHostStateDir(), ); } } this.transport = transport; } available(): boolean { return this.transport !== null; } /** 当前平台是否有可用的原生驱动(而不是「只有协议定义」)。 */ static platformSupported(): boolean { return process.platform === 'darwin'; } /** * 最近一次成功观测。 * * 给「这个动作在当前应用里是不是不可逆」这类查询用 —— 判定需要知道前台是 * 哪个应用,而那是观测的产物。放在这里而不是塞进 `ToolCallContext`:服务 * 本来就是「我们上次看到了什么」的所有者,不必让内核也记一份。 */ lastObservation( context: Pick< ComputerUseRunContext, 'ownerId' | 'conversationKey' | 'runId' >, ): ComputerState | undefined { return this.observations.get(contextKey(context)); } /** * 动作发生时那次观测(动作已让它对坐标无效,但对「当时是什么状况」仍有效)。 * * 仅供动作后的安全判定使用 —— 像素人工接管兜底要知道当时 AX 树可不可用、 * 前台是哪个应用。**不要**拿它做坐标换算:那是它被作废的原因。 */ observationAtAction( context: Pick< ComputerUseRunContext, 'ownerId' | 'conversationKey' | 'runId' >, ): ComputerState | undefined { return this.actedObservations.get(contextKey(context)); } /** * 本运行内是否**首次**要注入某份说明书的完整摘要;调用即登记。 * * 完整摘要约 1–2k token,每次观测都发一遍是纯浪费;但只发一次又不够 —— * 所以策略是「首次全量、之后一行提醒 + 路径」。状态住在服务里而不是工具里, * 因为服务本来就是「这个运行看到过什么」的所有者(观测、焦点快照都在这)。 */ shouldInjectFullManual( context: Pick< ComputerUseRunContext, 'ownerId' | 'conversationKey' | 'runId' >, manualName: string, ): boolean { const key = contextKey(context); let injected = this.injectedManuals.get(key); if (!injected) { injected = new Set(); this.injectedManuals.set(key, injected); } if (injected.has(manualName)) return false; injected.add(manualName); return true; } /** * 这次动作**这个具体目标**已经连续失败几次了。 * * 同步、无 IO:熔断判定在每个写类动作前都要跑一次,不能是一次文件读。 */ consecutiveFailuresFor( context: Pick< ComputerUseRunContext, 'ownerId' | 'conversationKey' | 'runId' >, input: ComputerUseActionIdentity, ): number { const streak = this.failureStreaks.get(contextKey(context)); if (!streak) return 0; return streak.fingerprint === actionFingerprint(input) ? streak.count : 0; } /** * 登记一次动作结局。 * * 只认写类动作:观测失败不该熔断写操作(模型正需要用观测看清自己卡在哪), * 观测成功也不该清零写操作的计数(那正是绕过熔断的老路子)。 */ recordActionOutcome( context: Pick< ComputerUseRunContext, 'ownerId' | 'conversationKey' | 'runId' >, input: ComputerUseActionIdentity, ok: boolean, ): void { if (!isMutatingComputerUseAction(input.action)) return; const key = contextKey(context); const fingerprint = actionFingerprint(input); if (ok) { // 只清掉这个指纹的计数。别的目标还卡着就该继续卡着。 const streak = this.failureStreaks.get(key); if (streak?.fingerprint === fingerprint) this.failureStreaks.delete(key); return; } const streak = this.failureStreaks.get(key); this.failureStreaks.set( key, streak?.fingerprint === fingerprint ? { fingerprint, count: streak.count + 1 } : { fingerprint, count: 1 }, ); } async emergencyStopAll(signal?: AbortSignal): Promise { const requestId = randomUUID(); if (!this.transport?.emergencyStopAll) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: { code: 'unavailable', message: '当前 Computer Use 服务不支持全局急停', }, }; } const response = await this.transport.emergencyStopAll(signal); this.observations.clear(); return response; } async inputStatus( context: ComputerUseRunContext, acknowledge = false, signal?: AbortSignal, ): Promise { if (!this.transport?.inputStatus) { return { context, detected: false }; } return this.transport.inputStatus(context, acknowledge, signal); } async request( context: ComputerUseRunContext, input: Omit< ComputerUseRequest, 'protocolVersion' | 'requestId' | 'context' >, signal?: AbortSignal, options?: { internalObserve?: boolean }, ): Promise { const requestId = randomUUID(); if (!this.transport) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: ComputerUseService.platformSupported() ? { code: 'unavailable', message: 'Computer Use 原生服务未安装或不可用', hint: '请安装当前平台的 cu-helperd,或在 Desktop 设置中检查 Computer Use 诊断。', } : { code: 'unsupported', message: `Computer Use 目前只支持 macOS,当前平台是 ${process.platform}`, hint: 'Windows 的 UI Automation 驱动尚未实现;请改用其它方式完成这一步,不要重试。', }, }; } // Internal observations (UI refresh, intervention inspect, diagnostics) go straight // through without coordinate mapping (no observation to map against) and without // updating the model-visible observation cache or focus state. They do not advance // the daemon-side epoch either (the native `internal: true` flag handles that). if (options?.internalObserve && input.action === 'observe') { const response = await this.transport.request( { ...input, protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, context, _internalObserve: true, } as ComputerUseRequest & { _internalObserve?: boolean }, signal, ); if (response.protocolVersion !== COMPUTER_USE_PROTOCOL_VERSION) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: { code: 'protocol_mismatch', message: `Computer Use 协议不兼容:客户端 ${COMPUTER_USE_PROTOCOL_VERSION},Helper ${response.protocolVersion}`, }, }; } const state = response.ok ? normalizeNativeComputerState(response.data) : undefined; if (state) { const imageError = await validateStateImage(state); if (imageError) return { ...response, ok: false, error: imageError }; return { ...response, state, ...(state.screenshot ? { images: [state.screenshot] } : {}), }; } return response; } const observation = this.observations.get(contextKey(context)); const ctxKey = contextKey(context); const mappedInput = this.mapRelativeCoordinates(input, observation, ctxKey); if ('error' in mappedInput) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: mappedInput.error, }; } // 记住指针落点,供后续 type/key 的 ROI 回落使用(见 probeRegionFor)。 const pointerPoint = input.x !== undefined && input.y !== undefined ? { x: input.x2 !== undefined ? (input.x + input.x2) / 2 : input.x, y: input.y2 !== undefined ? (input.y + input.y2) / 2 : input.y, } : undefined; if (pointerPoint) this.lastPointerPoints.set(ctxKey, pointerPoint); // Only a request that will actually reach the helper may establish a // focus expectation. Invalid coordinates must not leave a stale // expectation that suppresses the next real focus-change signal. // ★ 对齐 UI-TARS:永远全屏截图,不裁剪。observe 带 rect 参数时, // rect 仅用于 grab_region_to_clipboard/window 操作,不用于裁剪返回给模型的图片。 // 裁剪图会造成"坐标错觉",模型在裁剪图内看到目标却需要输出整屏坐标,容易算错。 const helperInput = mappedInput.input.action === 'observe' && mappedInput.input.rect ? { ...mappedInput.input, rect: undefined } : mappedInput.input; this.rememberExpectation(context, helperInput, observation); const probeRegion = probeRegionFor( observation, this.lastPointerPoints.get(ctxKey), helperInput.action, ); // ⚠️ `activate_app` 的 epoch 守卫**必须用当前 epoch**,不能用 0。 // // 这里的注释(见 toNativeComputerUseRequest 里 activate_app 那支)一直写着 // 「不需要 expectedEpoch,默认传 0 即可」—— 但守护进程做的是**严格相等比较** // (service.rs::`actual != expected`),0 不是通配符。于是那句话只在 // 「本 run 还没 observe 过」时碰巧成立。 // // 实测代价:模型走「observe → activate_app」这个最自然的流程时, // observe 把 epoch 推到 1,activate_app 带着 0 过去 → `stale_state`。 // 而 activate_app 靠 bundleId 工作、根本不依赖屏幕状态,这道守卫对它没有意义 —— // 所以取当前 epoch,语义上等于「不做新鲜度检查」。 const currentEpoch = this.lastObservation(context)?.epoch; const epochFixed = helperInput.action === 'activate_app' && currentEpoch !== undefined ? { ...helperInput, expectedEpoch: currentEpoch } : helperInput; const requestPayload = { ...epochFixed, // 探测参数在坐标换算**之后**注入:ROI 来自 AX,本来就是逻辑点, // 混进 mapRelativeCoordinates 会被当成 0–1000 相对值再换算一次。 // Verified actions already settle and capture a fresh frame. Do not add two // serial pixel-probe windows before that observation. Explicit probes remain available. ...(!helperInput._verifiedAction && shouldProbeChange(helperInput.action, observation) ? { probeChange: true, ...(probeRegion ? { probeRegion } : {}) } : {}), protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, context, }; // 截图请求(observe)失败时自动重试最多2次 const maxScreenshotRetries = helperInput.action === 'observe' ? 2 : 0; let response: ComputerUseResponse; let retries = 0; while (true) { response = await this.transport.request(requestPayload, signal); if (response.ok || retries >= maxScreenshotRetries || !isScreenshotRetryableError(response.error)) { break; } retries++; await delay(100); } if (response.protocolVersion !== COMPUTER_USE_PROTOCOL_VERSION) { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId, ok: false, error: { code: 'protocol_mismatch', message: `Computer Use 协议不兼容:客户端 ${COMPUTER_USE_PROTOCOL_VERSION},Helper ${response.protocolVersion}`, }, }; } const state = response.ok ? normalizeNativeComputerState(response.data) : undefined; if (state) { const imageError = await validateStateImage(state); if (imageError) return { ...response, ok: false, error: imageError }; const key = contextKey(context); this.observations.set(key, state); // 焦点变化要跨「观测被作废」而存活,所以单独存一份。 const focus = deriveFocusSnapshot(state); const previous = this.focusSnapshots.get(key); if (focus) this.focusSnapshots.set(key, focus); // 取用并清除上一个动作留下的预期(一次性,见 pendingExpectations)。 const expectation = this.pendingExpectations.get(key); this.pendingExpectations.delete(key); const focusChange = classifyFocusChange(previous, focus, expectation); return { ...response, state, ...(focus ? { focus } : {}), ...(focusChange !== FOCUS_CHANGE.NONE ? { focusChange } : {}), ...(state.screenshot ? { images: [state.screenshot] } : {}), }; } if ( response.ok && input.action !== 'observe' && input.action !== 'replay' ) { // Every successful input invalidates the observation on the daemon. Do // the same locally so a stale normalized display cannot be reused. // // 但**移到 lastActedObservation**而不是直接丢掉:动作之后的像素兜底判定 // (detectPixelHumanBoundary)需要「动作发生时那次观测」的 AX 可用性和 // 前台应用。丢掉它,那条判定就永远拿不到 state 而静默失效 —— 这正是本轮 // 差点复刻的老毛病:接线看着通了,实际那一端是空的。 // 语义上它**不能**再被当成有效观测用于坐标换算,所以换了个名字存放。 const key = contextKey(context); const invalidated = this.observations.get(key); if (invalidated) this.actedObservations.set(key, invalidated); this.observations.delete(key); } return response; } async executeVerifiedAction( context: ComputerUseRunContext, input: Omit< ComputerUseRequest, 'protocolVersion' | 'requestId' | 'context' >, signal?: AbortSignal, ): Promise { let before = this.observations.get(contextKey(context)); // Pointer down/move/up and press are intermediate gesture steps. // Holding a lease through an intermediate post-observe would break capture, // so only the final up/release is eligible for the verified transaction. if (['pointer_down', 'pointer_move', 'press'].includes(input.action)) { return this.request(context, input, signal); } // An explicit epoch is a reference to a particular observation. If that // observation is no longer in this process, silently taking a new one does // not make the old coordinates valid again. Reject before touching the OS; // the caller must observe and re-locate. `activate_app` is the exception: // it identifies its target by app id and is specifically allowed to // bootstrap a fresh run. if (!before && input.expectedEpoch !== undefined && input.action !== 'activate_app') { return { protocolVersion: COMPUTER_USE_PROTOCOL_VERSION, requestId: randomUUID(), ok: false, error: { code: 'stale_state', message: 'expectedEpoch 对应的本地观测已失效;请重新 observe 并定位后再操作。', retryable: false, }, }; } // The verified transaction always starts from a canonical observation. // This also makes activate_app usable from a fresh run without inventing // epoch 0 as if it represented a real screen state. if (!before) { const observed = await this.request(context, { action: 'observe' }, signal); if (!observed.ok || !observed.state) return observed; before = observed.state; } const policy = settlePolicy(input.action); const actionResponse = await this.request( context, { ...input, expectedEpoch: input.expectedEpoch ?? before.epoch, _verifiedAction: { quietMs: policy.quietMs, timeoutMs: policy.timeoutMs, ...(input.rect ? { region: input.rect } : {}), }, }, signal, ); if (!actionResponse.ok || !isMutatingComputerUseAction(input.action)) { return actionResponse; } const verifiedData = isRecord(actionResponse.data) && actionResponse.data.type === 'verified_action' ? actionResponse.data : undefined; const actionData = verifiedData && isRecord(verifiedData.action) ? verifiedData.action : undefined; const settleData = verifiedData && isRecord(verifiedData.settle) ? verifiedData.settle : undefined; // 动作后观察必须完整,否则不认「操作成功」。 // // 这里曾有一条 nut-js 兼容旁路:`isNutJsTransport = !verifiedData && state`, // 它既绕过下面这道守卫,又**无条件合成 `settled: true`** —— 稳态检查在那条 // 通路上是假的。nut-js 移除后旁路一并删掉,契约恢复为「没有完整的 // verified_action 就是验证失败」。 if (!verifiedData || !actionResponse.state || !actionData || !settleData) { return { ...actionResponse, ok: false, error: { code: 'verification_failed', message: '原生动作未返回完整的动作后观察结果,不能确认操作成功。', retryable: false, }, }; } const postState = actionResponse.state; const settle = { settled: settleData.settled === true, stableMs: numberAt(settleData.stableMs), observedEpoch: numberAt(settleData.observedEpoch), ...(stringAt(settleData.reason) ? { reason: stringAt(settleData.reason) } : {}), }; const graded = gradeActionVerification({ action: input.action, expectedAppId: input.appId, actualAppId: postState.activeApp?.id, regionChangeRatio: actionData.regionChangeRatio, changeRatio: actionData.changeRatio, movedRatio: actionData.movedRatio, beforeRevision: before?.revision, afterRevision: postState.revision, settled: settle.settled, }); const status = graded.status; const verification = { status, reason: graded.reason, ...(before?.revision ? { beforeRevision: before.revision } : {}), afterRevision: postState.revision, changed: graded.changed, } as const; // ★ 对齐 UI-TARS:actionMarker 标记实际点击位置(bbox中心点),不是左上角 // 坐标不会隐式吸附到附近 AX 元素。 let markerX = input.x; let markerY = input.y; if (input.x !== undefined && input.y !== undefined && input.x2 !== undefined && input.y2 !== undefined) { markerX = (input.x + input.x2) / 2; markerY = (input.y + input.y2) / 2; } return { ...actionResponse, ok: status !== 'failed', postState, beforeState: before, verification, settle, actionMarker: { action: input.action, ...(input.displayId ? { displayId: input.displayId } : {}), ...(markerX !== undefined ? { x: markerX } : {}), ...(markerY !== undefined ? { y: markerY } : {}), ...(before?.revision ? { beforeRevision: before.revision } : {}), afterRevision: postState.revision, }, ...(status === 'failed' ? { error: { code: 'verification_failed' as const, message: verification.reason, retryable: false, }, } : {}), }; } /** * ★ AX吸附:更新最近一次观测的短id->真实id映射。 * 由 computeruse.ts 在 buildObservationImages 后调用。 */ updateAxIdMap(context: ComputerUseRunContext, idMap: Map | undefined): void { const key = contextKey(context); if (idMap && idMap.size > 0) { this.axIdMaps.set(key, idMap); } else { this.axIdMaps.delete(key); } } /** * Internal observation for UI refresh, intervention inspect, diagnostics. * Returns a fresh screenshot/AX snapshot but does NOT advance the model-visible * epoch or update the observation cache. Safe to call from polling/UI code without * causing stale_epoch errors for the model's action sequence. */ async observeInternal( context: ComputerUseRunContext, signal?: AbortSignal, ): Promise { return this.request(context, { action: 'observe' }, signal, { internalObserve: true, }); } /** * 记下这个动作对「焦点应该落到哪」的预期,供下一次观测判定用。 * * 这条修的是一个必然发生的误判:agent 自己执行 `activate_app` 之后, * 下一次观测看到前台进程变了,于是判成 `other-process`「别的程序抢了前台」 * 并触发人工介入 —— 一次由 agent 主动发起的正常切换被当成事故。 * 只要工作流里有一步切应用,接下来就必然卡住。 * * 观测类动作不记预期:它们不改变焦点,记了反而会覆盖掉上一个动作的预期。 */ private rememberExpectation( context: ComputerUseRunContext, input: Omit< ComputerUseRequest, 'protocolVersion' | 'requestId' | 'context' >, observation: ComputerState | undefined, ): void { if (!isMutatingComputerUseAction(input.action)) return; const key = contextKey(context); if (input.action === 'activate_app' && input.appId) { this.pendingExpectations.set(key, { expectAppId: input.appId }); return; } if ( input.action === 'window' && input.windowId && (input.windowOperation === 'focus' || input.windowOperation === undefined) ) { this.pendingExpectations.set(key, { expectWindowId: input.windowId }); return; } // 其余动作预期**留在原地**:点一下、打个字不该让前台换应用。 // 记下当前前台是谁,这样「点击后前台变了」仍然是可检出的异常。 const current = input.appId ?? observation?.activeApp?.id ?? observation?.activeApp?.name; if (current) this.pendingExpectations.set(key, { expectAppId: current }); } /** * 把模型给的 0–1000 相对坐标换算成守护进程要的逻辑点。 * * 点和会改变系统状态的矩形都要换算。`observe { rect }` 是例外:它是 * 本地模型图像裁剪,不会进入原生输入线路,因此无需也不能依赖旧显示器快照。 */ private mapRelativeCoordinates( input: Omit< ComputerUseRequest, 'protocolVersion' | 'requestId' | 'context' >, observation: ComputerState | undefined, contextKey: string, ): | { input: Omit< ComputerUseRequest, 'protocolVersion' | 'requestId' | 'context' >; } | { error: NonNullable } { // ★ AX短id→真实id转换:如果elementId是@1/@2这种短引用,从map里取真实id if (input.elementId && input.elementId.startsWith('@')) { const idMap = this.axIdMaps.get(contextKey); const realId = idMap?.get(input.elementId); if (realId) { input = { ...input, elementId: realId }; } } const needsPoint = [ 'click', 'double_click', 'right_click', 'middle_click', 'hover', 'pointer_down', 'pointer_move', 'pointer_up', 'drag', 'scroll', ].includes(input.action); const needsRect = input.rect !== undefined && ['grab_region_to_clipboard', 'window'].includes(input.action); const hasObserveRect = input.action === 'observe' && input.rect !== undefined; if ((!needsPoint || input.elementId) && !needsRect && !hasObserveRect) return { input }; const coordinates = [input.x, input.y, input.x2, input.y2, input.toX, input.toY].filter( (value): value is number => value !== undefined, ); if (coordinates.some((value) => !Number.isFinite(value) || value < 0 || value > 1000)) { return { error: { code: 'invalid_coordinates', message: '坐标必须是0–1000范围内的有限相对值;请重新观察并定位目标。', retryable: false, }, }; } // ★ 对齐 UI-TARS bbox 支持:如果提供了 x2/y2(框选右下角),自动取中心点 // 这样模型只需要"框住"目标而不用精确点中一个像素,容错率大大提高 // ★ 容错:如果模型只输出单点 x/y 没提供 x2/y2,自动补上默认大小的 bbox // 中心点保持为输入的 x/y 不变,避免点击位置偏移 const DEFAULT_BBOX_SIZE = 40; // 0-1000 坐标中,默认 bbox 大小为 40×40(约 40-50 像素) let centerX: number | undefined = input.x; let centerY: number | undefined = input.y; if (input.x !== undefined && input.y !== undefined) { if (input.x2 !== undefined && input.y2 !== undefined) { centerX = (input.x + input.x2) / 2; centerY = (input.y + input.y2) / 2; } else { // 单点兜底:保持中心点为 (x,y),自动补上 x2/y2 const halfSize = DEFAULT_BBOX_SIZE / 2; const cx = input.x; const cy = input.y; input.x = Math.max(0, cx - halfSize); input.y = Math.max(0, cy - halfSize); input.x2 = Math.min(1000, cx + halfSize); input.y2 = Math.min(1000, cy + halfSize); centerX = cx; centerY = cy; } } if ( (needsRect || hasObserveRect) && input.rect && (!Number.isFinite(input.rect.x) || !Number.isFinite(input.rect.y) || !Number.isFinite(input.rect.width) || !Number.isFinite(input.rect.height) || input.rect.x < 0 || input.rect.y < 0 || input.rect.width <= 0 || input.rect.height <= 0 || input.rect.x + input.rect.width > 1000 || input.rect.y + input.rect.height > 1000) ) { return { error: { code: 'invalid_coordinates', message: '矩形必须完整位于0–1000相对坐标范围内;请缩小或重新定位区域。', retryable: false, }, }; } // ★ 对齐 UI-TARS:observe 永远返回全屏截图(不裁剪),不需要映射坐标。 // rect 参数仅用于 grab_region_to_clipboard 和 window 操作。 if (hasObserveRect) return { input }; // 矩形动作不必指定 displayId —— 它们作用在被观测的那块屏上。 // 点动作未指定时自动填充主显示器 id(单屏场景模型无需知道 display id)。 const display = input.displayId ? observation?.displays.find( (candidate) => candidate.id === input.displayId, ) : observation?.displays[0]; if (!display) { return { error: { code: 'stale_state', message: '坐标操作前必须先 observe;当前观察已失效或显示器已变化。', }, }; } const { logicalBounds } = display; // Explicit coordinates are authoritative. AX semantics require an explicit elementId; // a nearby container must never silently move the requested point to its center. if ( needsPoint && (centerX === undefined || centerY === undefined) && !needsRect ) { return { input }; } const mapX = (value: number | undefined): number | undefined => { const mapped = mapRelativePoint(value, logicalBounds.x, logicalBounds.width); return mapped === undefined ? undefined : Math.min(mapped, logicalBounds.x + logicalBounds.width - 0.001); }; const mapY = (value: number | undefined): number | undefined => { const mapped = mapRelativePoint(value, logicalBounds.y, logicalBounds.height); return mapped === undefined ? undefined : Math.min(mapped, logicalBounds.y + logicalBounds.height - 0.001); }; return { input: { ...input, // Auto-fill displayId for point actions when model didn't specify one // (single-display setups don't require the model to know the display id). ...(needsPoint && !input.elementId && !input.displayId ? { displayId: display.id } : {}), ...(needsPoint && !input.elementId ? { x: mapX(centerX), y: mapY(centerY), toX: mapX(input.toX), toY: mapY(input.toY), } : {}), ...(needsRect ? { rect: mapRelativeRect(input.rect!, logicalBounds) } : {}), }, }; } } /** 0–1000 相对矩形 → 逻辑点矩形。宽高至少 1 点,避免退化成不可见区域。 */ function mapRelativeRect( rect: NonNullable, bounds: ComputerUseDisplay['logicalBounds'], ): NonNullable { return { x: bounds.x + (rect.x / 1000) * bounds.width, y: bounds.y + (rect.y / 1000) * bounds.height, width: Math.max(1, (rect.width / 1000) * bounds.width), height: Math.max(1, (rect.height / 1000) * bounds.height), }; } export function anonymousOwnerId(): string { return createHash('sha256') .update(`${homedir()}\0${process.getuid?.() ?? 'windows'}`) .digest('hex') .slice(0, 24); } export const computerUseService = new ComputerUseService();