/** * ============================================================ * observationImages.ts —— 把原生观测变成模型看得懂的一组图 * ------------------------------------------------------------ * 职责边界(架构总纲「Rust 出像素,TS 做判断」的落点): * - 原生侧只出**裸像素**(低频彩色环里的 RGB 帧),不编码、不组装、不判断 * - 本模块负责差分、注意力遮罩、编码、落盘、配说明 * * 为什么帧要落盘而不是直接塞 data URL:`ImageInputSpec.source` 走的是既有的 * 多模态管线(`multimodal.ts`),它接受路径、读盘、base64 内联进请求体。 * * ⚠️ **那条管线不做任何缩放。** `ImageInputSpec.maxLongSidePixel` 只是透传给 * provider 的提示字段(`image_url.max_long_side_pixel`),发出去的仍是原文件 * 字节。所以**尺寸必须在本模块内定死** —— 交给管线的每一张图都得是已经缩过的。 * 这一条曾被违反过一次,代价是一次 observe 打爆上下文(见 downscaleForModel)。 * * 文件写在系统临时目录并带 TTL 清理 —— 屏幕帧是隐私敏感数据,不进工作目录、 * 不长留磁盘。 * ============================================================ */ import { mkdir, readFile, readdir, rm, stat, writeFile, } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { ImageInputSpec } from '../../types.js'; import { REPLAY_LONG_SIDE, buildFrameSequence, estimateImageTokens, } from './vision/imaging.js'; import { buildTimeline, pickEventAnchors } from './vision/frames.js'; import { cloneImage, crop, drawActionMarker, drawBadge, drawRect, fitLongSide, resizeRgba, } from './vision/raster.js'; /** * 元素框与编号徽标的颜色,以及徽标字号。 * * 刻意**不同于**动作十字的颜色:一个是"这些是可点的控件",一个是"我刚才点了这里", * 混成一种颜色模型会把两件事读成一件。 */ const ELEMENT_BOX_COLOR: [number, number, number] = [0, 132, 255]; const ELEMENT_BADGE_SCALE = 2; /** `drawBadge` 的位图字形几何,用来算徽标占多少像素(与 raster.ts 保持一致)。 */ const BADGE_GLYPH_W = 5; const BADGE_GLYPH_H = 7; const BADGE_PADDING = 2; /** * 算标注是否放得下时假定的图片尺寸。 * * 真实尺寸要解码完才知道,而筛选发生在解码之前。用预算上限对应的典型尺寸做保守 * 估计即可:估小了只会少画几个(安全),估大了才会画出读不清的(危险)。 */ const DEFAULT_OVERLAY_IMAGE_SIZE = { width: 1371, height: 771 }; import { decodePng, encodePng, type RgbaImage } from './vision/png.js'; import { recordComputerUseCall } from './telemetryLog.js'; import { generateAxElementSummary, type AxInteractiveElement, } from './axSnap.js'; import type { ComputerUseActionMarker, ComputerState, ComputerUseImageReference, ComputerUseRect, ComputerUseSequenceFrame, } from './protocol.js'; /** 帧文件目录。与原生侧的截图目录并列,同样只放临时数据。 */ export const FRAME_DIR = join(tmpdir(), 'kakadeai-computer-use-frames'); /** 帧文件保留时长。SPEC §4.3 的截图磁盘 TTL(10分钟)。 */ const FRAME_TTL_MS = 600_000; /** 帧文件最大数量(额外保护,超过后删除最旧的)。 */ const FRAME_MAX_COUNT = 200; /** Compatibility export; runtime defaults now come from ConfigService. */ export const DEFAULT_OBSERVE_FRAMES = 1; /** * Ordinary observations always expose one current frame. Replay remains the * explicit API for inspecting a timeline without inflating every model turn. */ export function resolveObservationFrames( _requested: number | undefined, _configured: number, ): number { return 1; } export interface ObservationImages { images: ImageInputSpec[]; /** 随图给模型的说明。帧数是变量,文案按实际帧数生成。 */ note: string; /** 文本摘要,进 tool result 的正文(比图便宜 20 倍)。 */ summary: string[]; estimatedTokens: number; /** AX元素短id→真实id映射,用于处理LLM用@1/@2引用元素 */ axIdMap?: Map; } /** * 组装一次观测要发给模型的图。 * * ★ 对齐 UI-TARS:永远只给全屏截图,不给裁剪图。 * 裁剪图会造成"坐标错觉"——模型在裁剪图内定位,却被要求输出整屏坐标,容易算错偏移。 * 截图统一按 MAX_PIXELS (~100万像素) 收进预算(`downscaleForModel`),坐标直接对应。 */ export async function buildObservationImages( state: ComputerState, actionMarker?: ComputerUseActionMarker, magnify?: ComputerUseRect, ): Promise { const started = performance.now(); try { return await assembleObservationImages(state, actionMarker, magnify); } finally { await recordComputerUseCall({ cmd: 'image_prepare', ms: performance.now() - started }); } } async function assembleObservationImages( state: ComputerState, actionMarker?: ComputerUseActionMarker, magnify?: ComputerUseRect, ): Promise { const sequence = state.sequence ?? []; // History is supplemental: only the current full screenshot is a coordinate surface. if (state.screenshot) { const hasMarker = actionMarker !== undefined; // ★ 编号必须来自**同一个** summary:图上画的 ③ 和文字清单里的 [@3] 必须永远是 // 同一个元素。所以先算 summary,再把它选中的那批元素交给绘图,而不是让绘图 // 自己再筛一遍——两处各筛各的,迟早会错开,而错开的表现是模型点了别的控件。 const axSummary = generateAxElementSummary(state); const { image, scaledSize } = await downscaleForModel( state.screenshot.path, state.screenshot.mime, actionMarker, buildElementOverlays(axSummary?.shown, state), ); const origW = state.screenshot.width; const origH = state.screenshot.height; const imgW = scaledSize?.width ?? origW; const imgH = scaledSize?.height ?? origH; state.screenshot.presentation = { frameId: state.screenshot.sha256 ?? state.revision, width: imgW, height: imgH, scaleX: imgW / origW, scaleY: imgH / origH, displayId: state.screenshot.displayId, }; // ⚠️ **如实告诉模型这张图的精度极限。** // // 此前只说「图片尺寸 1371×771」,没说这意味着什么 —— 模型于是不知道自己看不清, // 看到一团模糊就按**最像的那个**猜,而且猜得毫不犹豫。 // // 实测事故(真机 trace + 截图为证):任务是「给王磊发消息」,微信当时停在**王鹏** // 的会话上。5120×2880 缩到 1371×771 是 3.7 倍,聊天标题那 30 设备像素的字在图上 // 只剩约 8 像素 —— 把那块裁出来放大 6 倍看,第二个字完全糊成一团,「鹏」和「磊」 // 无法区分。模型据此认定「已经在王磊的会话上了」,跳过整个搜索步骤,直接打字发送, // **消息发给了王鹏**,然后报告「已成功给王磊发送消息」。 // // 这不是模型能力问题:那张图里**物理上就不含**区分这两个字所需的信息。 // 能修的是让它知道这一点,并知道 magnify 能拿到原生分辨率。 const shrink = origW > 0 && imgW > 0 ? origW / imgW : 1; // 可用区(扣掉菜单栏与 Dock)换算成 0-1000 比例坐标。拿不到就整段不说 —— // 说不出准确数字时保持沉默,好过给一个编的。 const display = state.displays?.find((d) => d.primary) ?? state.displays?.[0]; const visible = display?.visibleBounds; const bounds = display?.logicalBounds; const usable = visible && bounds && bounds.height > 0 ? { top: Math.round(((visible.y - bounds.y) / bounds.height) * 1000), bottom: Math.round( ((visible.y - bounds.y + visible.height) / bounds.height) * 1000, ), centerY: Math.round( ((visible.y - bounds.y + visible.height / 2) / bounds.height) * 1000, ), } : undefined; const noteLines: string[] = [ '【截图说明】', `当前定位帧:${state.screenshot.presentation.frameId};显示器:${state.screenshot.displayId ?? '主屏'};像素坐标基准 ${imgW}×${imgH}。`, shrink >= 1.05 ? `图片尺寸:${imgW}×${imgH}(原生 ${origW}×${origH} 等比缩小到像素预算内)` : `图片尺寸:${imgW}×${imgH}(**与屏幕 1:1,没有缩放**,界面上多大的字这里就是多大)`, ...(shrink >= 1.5 ? [ `⚠️ 这张图比原生屏幕**缩小了 ${shrink.toFixed(1)} 倍**:界面上正常大小的文字,` + `在这张图上只有约 ${Math.max(1, Math.round(30 / shrink))} 像素高。`, ' **这个尺寸下汉字无法逐字分辨** —— 只差一笔的两个字看起来会完全一样。', ' 凡是需要**逐字确认**的内容 —— 人名、联系人、金额、验证码、文件名、账号 ——', ' 一律先用 `magnify`(返回该区域的原生分辨率裁剪)看清楚再下结论。', ' ⛔ 看着模糊的字「觉得像」就当成确认 —— 这是本工具造成过真实事故的错误。', ] : []), '', // ⚠️ **可用区 ≠ 整屏。** 顶部菜单栏和底部 Dock 永远盖在应用上面, // 可点区域比屏幕小一圈,而且**中心是偏上的**。 // 本机实测(1920×1080):菜单栏 30pt、Dock 94pt → 可用区 1920×956, // 中心在 y=470‰ 而不是 500‰。按整屏中心摆窗口,底部 62pt 会塞进 Dock 底下—— // 被压住的往往正是输入框或提交按钮,坐标点得到、实际点不着。 ...(usable ? [ `⚠️ 可用区(能放窗口、能点到的范围)= y 从 ${usable.top} 到 ${usable.bottom}(0-1000 比例):`, ` 顶部 0~${usable.top} 是菜单栏、底部 ${usable.bottom}~1000 是 Dock,都盖在应用上面。`, ` **可用区中心是 (500, ${usable.centerY}),不是 (500, 500)。**`, ' 窗口有一部分在这个范围外时,用 `window` 的 `center` 操作把它摆回来。', '', ] : []), '⛔⛔⛔ 坐标系统(非常重要,不要搞错!):', '- 坐标是 0-1000 的**全屏比例坐标**,不是像素坐标!', '- x=0 是最左边,x=1000 是最右边;y=0 是最上边,y=1000 是最下边', `- 图片宽度 ${imgW} 像素对应 x=1000,图片高度 ${imgH} 像素对应 y=1000`, '', '★ 强制要求:所有点击必须用 bbox 框选(x/y 左上角 + x2/y2 右下角)', '- 不需要精确框!大致框住目标按钮/条目即可,系统自动点中心点', '- 换算方法:目测目标左/右/上/下边缘分别在屏幕宽度/高度的百分之多少,×1000 就是坐标', '', // ⚠️ hover **不属于**这张清单。它是一次「验证」,不是一种「定位方式」。 // 早先它被排在这份「必须按顺序尝试」的第 2 位,模型于是对**每一次** // click 都先 hover 一轮 —— 实测一次任务里第 4/5 步是同一个 bbox, // 白烧 20.1s 的 LLM 往返(工具本身只用 1.4s)。 // 清单只列定位方式;hover 单独说,并且写清「什么时候才值得多花一轮」。 '定位方式优先级(按可用性从高到低选一种):', ' 1. textTarget 文字定位(最准,完全绕过坐标误差)', ' 2. elementId 精准点击(从下方AX元素列表用 @id 引用)', ' 3. bbox 坐标点击(自绘 / Electron 类应用无障碍树为空,只能用这个;坐标越靠近0/500/1000越稳)', '', '★ 什么时候先 hover 再 click:', ' hover 会多花一整轮往返(通常 10~20 秒),**只在下面两种情况下才值得**:', ' · 这一步不可逆或代价高(发送、提交、删除、支付、关窗);', ' · 上一次点击的红色十字明显偏了,需要先确认位置再点。', ' 其余情况(点列表条目、点输入框、点标签页…)**直接 click**,', ' 点错了从截图看得出来,重点一次比每次都 hover 便宜得多。', ]; if (hasMarker) { noteLines.push(''); noteLines.push('🎯 红色十字标记你上次点击的位置。如果偏了,请根据偏移调整本次坐标。'); } // ★ AX元素摘要:原生应用可交互元素列表,给LLM用elementId精准点击 if (axSummary) { noteLines.push(axSummary.noteText); if (axSummary.shown.length > 0) { noteLines.push( `🔢 上面这些元素已经**在截图上画了同号的方框和编号徽标**(图上的 N = 清单里的 @N)。` + `看图找到目标的编号,直接 elementId:"@N" 点击,不用估坐标。`, ); } } // ── 放大镜:从**原始分辨率**帧上裁一块放大,专供读小字 ────────────── const glass = magnify ? await buildMagnifier(state.screenshot, magnify) : null; if (glass) { noteLines.push(''); noteLines.push( `🔍 第 2 张是**放大镜**:全屏比例区域 (${Math.round(magnify!.x)},${Math.round(magnify!.y)})` + `-(${Math.round(magnify!.x + magnify!.width)},${Math.round(magnify!.y + magnify!.height)})` + ` 从原始 ${origW}×${origH} 帧上裁出后放大到 ${glass.width}×${glass.height}。`, ); noteLines.push( '⛔ 放大镜**只能用来看清文字/数字**。所有坐标一律以第 1 张全屏图为准 ——' + '放大镜里的位置换算回全屏是错的,不要用它定位点击目标。', ); } const history = sequence.length >= 2 ? await assembleSequence(sequence) : null; if (history) noteLines.push('后附历史帧仅供观察过程,不可用于像素定位。所有点击坐标以第 1 张当前全屏截图为准。'); return { images: [...(glass ? [image, glass.image] : [image]), ...(history?.images ?? [])], note: noteLines.join('\n'), summary: [ `屏幕 ${origW}×${origH} → 模型输入 ${imgW}×${imgH},坐标 0-1000 直接对应`, ...(glass ? [`🔍 放大镜已附(${glass.width}×${glass.height}),仅供读字不供定位`] : []), '优先 activate_app / textTarget / elementId,坐标最后考虑', ], estimatedTokens: estimateImageTokens({ width: imgW, height: imgH }) + (glass?.estimatedTokens ?? 0) + (history?.estimatedTokens ?? 0), axIdMap: axSummary?.idMap, }; } return null; } /** * 把原生截图**在本地缩放**后再交给模型。 * * ★ 这里曾经直接把 `screencapture` 的原始文件路径交出去,只在 * `ImageInputSpec` 上挂一个 `maxLongSidePixel: 1400`。那个字段**不做任何本地 * 缩放** —— 它只是透传给 provider 的一个提示(`image_url.max_long_side_pixel`), * 而我们仍然把原文件整个 base64 塞进请求体。 * * 后果实测:这台机器的原生截图是 3840×2160 / 3.25MB,base64 后 **4.33MB 字符**, * 一次 observe 就把请求打成 `context window exceeds limit`。而本地缩到 720p 之后 * 是 525KB(**6 倍差距**)—— 帧序列那条路一直是这么做的,只有这条单张兜底路 * 是裸的。又一次「一条路封装完整、另一条路是空的」。 * * `maxLongSidePixel` 因此不再用于这里:一个看起来像在缩放、实际不缩放的参数, * 比没有更危险。 */ function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function readFileWithRetry( sourcePath: string, maxRetries: number = 2, retryDelayMs: number = 100, ): Promise { for (let attempt = 0; attempt <= maxRetries; attempt++) { const raw = await readFile(sourcePath).catch(() => null); if (raw && raw.length > 0) return raw; if (attempt < maxRetries) { await delay(retryDelayMs); } } return null; } async function decodePngWithRetry( raw: Buffer, maxRetries: number = 2, ): Promise | null> { for (let attempt = 0; attempt <= maxRetries; attempt++) { try { return decodePng(raw); } catch { if (attempt < maxRetries) { await delay(50); } } } return null; } /** * 解码截图为 RgbaImage。 * * **只认 PNG,且这是有意的**:唯一的像素来源是 Rust 的 cu-helperd,它的 * `capture-full` 出 PNG、快循环出裸灰度帧,不产 JPEG。此处曾经有一条 Jimp 的 * JPEG/WebP 分支,那是为已移除的 nut-js transport(输出 q78 JPEG)配的; * 随它一起删掉,`vision/png.ts` 的零依赖编解码重新自足——这也是绿色版 * 「零原生 node 模块」得以成立的前提之一。 * * 若将来真需要 JPEG(省磁盘/IO;注意模型侧按**像素**计费,token 成本不变), * 应由 Rust 侧编码后连同 mime 一起送来,**不要**再引入 JS 图像库。 */ async function decodeImageWithRetry( raw: Buffer, mime: ComputerUseImageReference['mime'] | undefined, maxRetries: number = 2, ): Promise { if (mime !== undefined && mime !== 'image/png') return null; if (mime === undefined && !isPngBuffer(raw)) return null; return decodePngWithRetry(raw, maxRetries); } function isPngBuffer(buf: Buffer): boolean { return ( buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 ); } /** 只读 IHDR 拿尺寸,不解码像素(PNG 的宽高就在固定偏移 16/20)。 */ function readPngDimensionsQuick(buf: Buffer): { width: number; height: number } | null { if (!isPngBuffer(buf) || buf.length < 24) return null; const width = buf.readUInt32BE(16); const height = buf.readUInt32BE(20); return width > 0 && height > 0 ? { width, height } : null; } /** * 送给模型的截图像素预算。 * * 值取 1920×1080 —— 这**不是**随手放大,是与 * `macos.rs::ensure_model_friendly_resolution` 配套的一半: * 那边把桌面切成 1920×1080 的 1:1 模式,这边的预算正好装得下,于是 * **整条链上零缩放**,界面上多大的字送到模型眼里就是多大。 * * 旧值是 1350*28*28 ≈ 106 万(对齐 UI-TARS)。在 5120×2880 的 Retina 桌面上 * 它意味着缩 3.7 倍:24 像素的字只剩 6~8 像素,**汉字无法逐字分辨**。 * 实测因此发生过发错人事故(把「王鹏」的会话当成「王磊」的,见那个函数的注释)。 * * 代价诚实说:单张图约 2.8k token,比旧值的 1.4k 翻倍。但它换掉的是 * 「看不清 → 放大镜再来一轮」这种整轮 LLM 往返(实测 10~20 秒、外加一张图), * 以及看不清时直接猜错的风险。净赚。 * * ⚠️ 仍然是**防线**而不是目标尺寸:桌面若因为任何原因不是 1080p(外接屏、 * 用户手动改回去、切换失败),这里照旧把图压进预算,不让大图打爆上下文。 */ const MAX_PIXELS = 1920 * 1080; /** * 模型**实际看到**的那张图有多大。 * * ⚠️ 这是一条必须单一出处的规则。任何「把模型给的像素坐标换算回屏幕」的地方,分母都 * 只能是这个值 —— 不能是 `state.screenshot.width`(那是 daemon 的原始截图尺寸)。 * * 两者在 Retina 上差得很远:5K 屏原始截图 5120×2880,压进预算后模型看到的是 1371×771, * **相差 3.73 倍**。用错分母的后果不是「稍微偏一点」,是每一次点击都朝左上角偏出去 * 近四倍距离 —— 在多窗口叠放的桌面上,这通常意味着点到了目标窗口后面的另一个应用。 * * 缩放规则与 `downscaleForModel` 里的实际缩放**必须逐字一致**,所以那里也改成调它。 */ export function modelFacingImageSize( sourceWidth: number, sourceHeight: number, ): { width: number; height: number } { if (sourceWidth <= 0 || sourceHeight <= 0) { return { width: sourceWidth, height: sourceHeight }; } if (sourceWidth * sourceHeight <= MAX_PIXELS) { return { width: sourceWidth, height: sourceHeight }; } const factor = Math.sqrt(MAX_PIXELS / (sourceWidth * sourceHeight)); return { width: Math.floor(sourceWidth * factor), height: Math.floor(sourceHeight * factor), }; } /** 一个要画到图上的元素标注:矩形按屏幕比例 0–1 表示,与图片实际像素解耦。 */ interface ElementOverlay { /** 徽标数字,等于文字清单里的 @N。 */ index: number; /** 0–1 的屏幕比例矩形。 */ left: number; top: number; right: number; bottom: number; } /** * 面积超过整屏这个比例的元素不画。 * * AX 树里 `AXGroup` / `AXScrollArea` 这类容器也满足"可交互"的判据,但给整个窗口 * 画一个框加一个编号没有任何定位价值,只会盖住真正的控件。 */ const MAX_OVERLAY_AREA_RATIO = 0.25; /** * 把 AX 元素(逻辑点)换算成屏幕比例矩形。 * * `frame` 与 `display.logicalBounds` 是同一坐标空间(都是逻辑点),所以先减去 * 显示器原点再除以显示器尺寸就得到比例;比例再乘图片像素尺寸即可落到图上—— * 这样不管图被缩放到多大都不用改。 */ function buildElementOverlays( shown: AxInteractiveElement[] | undefined, state: ComputerState, imageSize: { width: number; height: number } = DEFAULT_OVERLAY_IMAGE_SIZE, ): ElementOverlay[] { if (!shown?.length) return []; const display = state.displays.find((d) => d.primary) ?? state.displays[0]; if (!display || display.logicalBounds.width <= 0 || display.logicalBounds.height <= 0) { return []; } const { x: ox, y: oy, width: sw, height: sh } = display.logicalBounds; // 徽标在图上占多大(比例)。约束是**徽标之间不许叠**,不是「元素必须装得下徽标」—— // 后者试过,是错的:元素排序是面积从小到大(小按钮更可能是目标),而"装得下"恰好 // 把小的全筛掉,18 个里只剩 1 个能画。两条规则互相打架。 // // 真正要防的是**读不出来**:实拍时 Finder 文件列表里十几个单元格上下只差几像素, // 徽标层层叠住,数字互相盖住谁也认不出,还糊住了内容。所以徽标允许溢出元素框 // (SoM 的常规做法),但一旦会和已放置的徽标重叠就跳过——密集列表里只标第一个, // 稀疏界面上全都能标。 const badgeW = BADGE_GLYPH_W * ELEMENT_BADGE_SCALE + BADGE_PADDING * 2 * ELEMENT_BADGE_SCALE; const badgeH = BADGE_GLYPH_H * ELEMENT_BADGE_SCALE + BADGE_PADDING * 2 * ELEMENT_BADGE_SCALE; const minW = badgeW / Math.max(1, imageSize.width); const minH = badgeH / Math.max(1, imageSize.height); const overlays: ElementOverlay[] = []; for (let i = 0; i < shown.length; i += 1) { const frame = shown[i].frame; const left = (frame.x - ox) / sw; const top = (frame.y - oy) / sh; const right = (frame.x + frame.width - ox) / sw; const bottom = (frame.y + frame.height - oy) / sh; // 完全在屏幕外的不画;容器类的不画;装不下徽标的不画。 // 编号仍然按原顺序,**不重排** —— 编号必须和文字清单一一对应,跳过一个就让 // 后面全体错位。图上缺号是安全的(模型仍可用清单里的 @N),编号错位不是。 if (right <= 0 || bottom <= 0 || left >= 1 || top >= 1) continue; if ((right - left) * (bottom - top) > MAX_OVERLAY_AREA_RATIO) continue; // 徽标之间不许重叠:两个数字叠在一起等于两个都读不出来。先来先得, // 顺序即优先级(extractInteractiveElements 已按「聚焦 > 启用 > 面积小」排过)。 const collides = overlays.some( (placed) => left < placed.left + minW && left + minW > placed.left && top < placed.top + minH && top + minH > placed.top, ); if (collides) continue; overlays.push({ index: i + 1, left, top, right, bottom }); } return overlays; } /** * 只给测试用的内部导出。 * * `buildElementOverlays` 是纯函数(输入 AX 元素 + 显示器几何,输出比例矩形), * 编号一致性这条不变量只能在这一层断言 —— 画到图上之后就只剩像素了。 */ export const __testing = { buildElementOverlays, MAX_OVERLAY_AREA_RATIO, }; /** * 放大镜:从**原始分辨率**截图上裁一块,放大后单独作为一张图给模型。 * * ⚠️ 为什么必须从原始帧裁,而不是从模型那张图上裁 —— 这是实测逼出来的: * 微信读书的页码("35 | 116")在 5120×2880 原图上约 20px 高,压进模型预算 * (1371×771)后只剩约 5px。把那张图放大 8 倍看到的是一团马赛克 —— * **信息在降采样那一步就被物理销毁了,任何提示词都救不回来。** * 此前模型报的页码全是猜的(报「85/116」时恰好蒙对,也报错过)。 * * ⚠️ 为什么不直接把全屏图给得更大:模型侧按像素计费,全屏提分辨率是每次观测都付 * 的固定成本;而小字只在少数步骤需要读。放大镜是按需付费的那一档。 * * ⚠️ 坐标错觉的防线:放大镜**始终是第 2 张**,全屏图永远是第 1 张且不受影响, * note 里明写「放大镜只许读字、不许定位」。这与「永不返回裁剪图」那条铁律 * 不冲突 —— 那条禁的是**用裁剪图替代全屏图**,这里是叠加,不是替代。 */ async function buildMagnifier( screenshot: ComputerUseImageReference, rect: ComputerUseRect, ): Promise< { image: ImageInputSpec; width: number; height: number; estimatedTokens: number } | null > { const raw = await readFileWithRetry(screenshot.path, 2, 100); if (!raw) return null; const decoded = await decodeImageWithRetry(raw, screenshot.mime, 2); if (!decoded) return null; // 0–1000 相对坐标 → 原始帧像素。分母是**原始尺寸**,不是模型输入尺寸: // 这里裁的就是原始帧,用错分母会裁到别处(且不会报错,只会安静地裁错)。 const px = { x: (rect.x / 1000) * decoded.width, y: (rect.y / 1000) * decoded.height, width: Math.max(1, (rect.width / 1000) * decoded.width), height: Math.max(1, (rect.height / 1000) * decoded.height), }; const patch = crop(decoded, px); if (patch.width < 2 || patch.height < 2) return null; // 放大到长边 ~900px(够读清 5px 的字),同时受 MAX_PIXELS 兜底。 const factor = Math.min( MAGNIFIER_LONG_SIDE / Math.max(patch.width, patch.height), Math.sqrt(MAX_PIXELS / (patch.width * patch.height)), ); const scaled = factor > 1.01 ? resizeRgba( patch.data, patch.width, patch.height, Math.round(patch.width * factor), Math.round(patch.height * factor), ) : patch; await mkdir(FRAME_DIR, { recursive: true, mode: 0o700 }).catch(() => {}); const encoded = encodePng(scaled, { channels: 3, level: 6 }); const path = join(FRAME_DIR, `glass-${Date.now()}-${process.pid}.png`); await writeFile(path, encoded, { mode: 0o600 }); return { image: { source: path, detail: 'high' }, width: scaled.width, height: scaled.height, // 与全屏图同一套估法:按像素数折算(~28×28 一个 token)。 estimatedTokens: Math.ceil((scaled.width * scaled.height) / (28 * 28)), }; } /** 放大镜输出的长边目标像素。够把 5px 的字撑到 ~40px(人眼与模型都能读)。 */ const MAGNIFIER_LONG_SIDE = 900; async function downscaleForModel( sourcePath: string, mime: ComputerUseImageReference['mime'] | undefined, actionMarker?: ComputerUseActionMarker, overlays: ElementOverlay[] = [], ): Promise<{ image: ImageInputSpec; scaledSize: { width: number; height: number } | null; sourceSize: { width: number; height: number }; }> { // 快速路径:不需要画十字标记、且原图尺寸已在预算内时,直接返回原文件, // 零拷贝零编码。判据从「是 JPEG」改成「尺寸读得出且在预算内」—— // 前者绑的是已移除的 nut-js(它输出预缩放好的 JPEG),后者才是真正的条件。 const raw = await readFileWithRetry(sourcePath, 2, 100); if (!raw) return { image: { source: sourcePath, detail: 'default' }, scaledSize: null, sourceSize: { width: 0, height: 0 }, }; // 只读文件头拿尺寸,不解码全图 let sourceWidth = 0, sourceHeight = 0; const dims = readPngDimensionsQuick(raw); if (dims) { sourceWidth = dims.width; sourceHeight = dims.height; } // 有标注要画就不能走零拷贝快路径 —— 快路径直接把原文件交出去,画不上任何东西。 const needsDrawing = actionMarker !== undefined || overlays.length > 0; if (!needsDrawing && sourceWidth > 0 && sourceWidth * sourceHeight <= MAX_PIXELS) { return { image: { source: sourcePath, detail: 'high' }, scaledSize: { width: sourceWidth, height: sourceHeight }, sourceSize: { width: sourceWidth, height: sourceHeight }, }; } // 需要处理:解码 → [安全缩放] → 画十字 → 编码 PNG const decoded = await decodeImageWithRetry(raw, mime, 2); if (!decoded) { return { image: { source: sourcePath, detail: 'default' }, scaledSize: sourceWidth > 0 ? { width: sourceWidth, height: sourceHeight } : null, sourceSize: { width: sourceWidth, height: sourceHeight }, }; } sourceWidth = decoded.width; sourceHeight = decoded.height; await mkdir(FRAME_DIR, { recursive: true, mode: 0o700 }).catch(() => {}); await pruneStaleFrames(); // ★ 安全防线:如果图片超过 MAX_PIXELS,先缩放到预算内(防御性编程,防止其他transport输出大图) let processed: RgbaImage = decoded; // 缩放规则走 modelFacingImageSize(单一出处):像素坐标换算的分母必须与这里 // 算出来的尺寸逐字一致,两处各写一遍迟早会错开,而错开的表现是每次点击都偏。 const target = modelFacingImageSize(sourceWidth, sourceHeight); if (target.width !== sourceWidth || target.height !== sourceHeight) { processed = resizeRgba(decoded.data, decoded.width, decoded.height, target.width, target.height); sourceWidth = target.width; sourceHeight = target.height; } // ★ 元素编号标注(Set-of-Marks)先画,动作十字后画 —— 十字标的是"我刚点了哪", // 必须压在最上层,不能被某个方框盖住。 if (overlays.length > 0) { if (processed === decoded) { processed = cloneImage(decoded); } for (const overlay of overlays) { const x = Math.round(overlay.left * processed.width); const y = Math.round(overlay.top * processed.height); const width = Math.max(2, Math.round((overlay.right - overlay.left) * processed.width)); const height = Math.max(2, Math.round((overlay.bottom - overlay.top) * processed.height)); drawRect(processed, { x, y, width, height }, ELEMENT_BOX_COLOR, 1); // 徽标画在框内左上角:画在框外会跑到相邻控件身上,模型就分不清编号属于谁。 drawBadge(processed, x + 1, y + 1, overlay.index, ELEMENT_BOX_COLOR, ELEMENT_BADGE_SCALE); } } // 画标记 if (actionMarker?.x !== undefined && actionMarker?.y !== undefined) { if (processed === decoded) { processed = cloneImage(decoded); } const mx = (actionMarker.x / 1000) * processed.width; const my = (actionMarker.y / 1000) * processed.height; drawActionMarker(processed, mx, my, 0, 14, 2); } const encoded = encodePng(processed, { channels: 3, level: 6 }); const path = join(FRAME_DIR, `shot-${Date.now()}-${process.pid}.png`); await writeFile(path, encoded, { mode: 0o600 }); return { image: { source: path, detail: 'high' }, scaledSize: { width: sourceWidth, height: sourceHeight }, sourceSize: { width: sourceWidth, height: sourceHeight }, }; } /** * 把 `replay` 返回的裸灰度帧变成模型能看的少量图。 * * ★ 不接这条路的后果是灾难性的,而且它曾经真的没接:`replay` 已经暴露给模型, * 守护进程返回 30 帧 480×270 灰度的 base64,而 TS 侧不解码 —— 于是 * **约 520 万字符(≈130 万 token)的 base64 直接进上下文**。不是不好用, * 是一次调用就把上下文炸穿。 * * 所以这里做三件事: * ① 用**事件锚定**从帧序列里挑最有信息量的 4 帧 —— 界面变化是突发的, * 等间隔采样会花 30 倍的钱买 4 帧的信息量 * ② 缩到 `REPLAY_LONG_SIDE`(683)—— 回放回答「发生了什么」而非「写的什么」 * ③ 编码成灰度 PNG 落盘,走既有的多模态管线 */ export async function buildReplayImages( frames: ReplayFrame[], ): Promise { const decoded = frames.flatMap((frame) => { if (!frame.grayBase64 || frame.width <= 0 || frame.height <= 0) return []; const gray = Buffer.from(frame.grayBase64, 'base64'); if (gray.length !== frame.width * frame.height) return []; return [ { t: frame.capturedAtMs, gray: new Uint8Array(gray), width: frame.width, height: frame.height, }, ]; }); if (decoded.length === 0) return null; const { width, height } = decoded[0]!; // 尺寸不一致的帧无法两两差分,直接排除,不拿坏数据算时间线。 const usable = decoded.filter( (f) => f.width === width && f.height === height, ); const timeline = buildTimeline(usable, width, height); const anchors = pickEventAnchors(usable, timeline, { max: REPLAY_FRAMES }); await mkdir(FRAME_DIR, { recursive: true, mode: 0o700 }).catch(() => {}); await pruneStaleFrames(); const stamp = `${Date.now()}-${process.pid}-${crypto.randomUUID()}`; const images: ImageInputSpec[] = []; const summary: string[] = [ `回放 ${anchors.length} 帧(从 ${usable.length} 帧里事件锚定挑出)`, ]; let estimatedTokens = 0; for (const [index, anchor] of anchors.entries()) { const frame = usable[anchor.index]!; const scaled = fitLongSide( grayToRgba(frame.gray, width, height), REPLAY_LONG_SIDE, ); // 回放帧用低压缩级别的 PNG:回放回答「发生了什么」不是「写的什么」, // level 3 换编码速度(注释原本写「质量 75 的 JPEG」,与代码不符,已订正) const png = encodePng(scaled, { channels: 3, level: 3 }); const path = join(FRAME_DIR, `replay-${stamp}-${index + 1}.png`); await writeFile(path, png, { mode: 0o600 }); images.push({ source: path, detail: 'low' }); estimatedTokens += estimateImageTokens(scaled); const offset = Math.round((frame.t - usable[0]!.t) / 100) / 10; summary.push(`第 ${index + 1} 帧:${anchor.label}(+${offset}s)`); } return { images, note: [ `以上 ${anchors.length} 张是**灰度回放帧**,按时间正序,从刚才那几秒里挑出信息量最大的时刻`, '(动作前 / 首次变化 / 变化峰值 / 稳定后)。它回答「刚才发生了什么」,', '**不是**用来读文字的 —— 分辨率和颜色都已为此牺牲。要看清内容请用 observe。', ].join('\n'), summary, estimatedTokens, }; } export interface ReplayFrame { capturedAtMs: number; width: number; height: number; grayBase64?: string; } /** 回放最多给几帧。事件锚定的四个语义位各一帧。 */ const REPLAY_FRAMES = 4; function grayToRgba( gray: Uint8Array, width: number, height: number, ): RgbaImage { const data = new Uint8Array(width * height * 4); for (let i = 0, p = 0; p < gray.length; p += 1, i += 4) { const v = gray[p]!; data[i] = v; data[i + 1] = v; data[i + 2] = v; data[i + 3] = 255; } return { width, height, data }; } async function assembleSequence( frames: ComputerUseSequenceFrame[], ): Promise { const decoded = frames.flatMap((frame) => { const image = rgbToRgba(frame); return image ? [{ t: frame.capturedAtMs, image }] : []; }); if (decoded.length === 0) return null; const sequence = buildFrameSequence({ frames: decoded }); if (sequence.frames.length === 0) return null; await mkdir(FRAME_DIR, { recursive: true, mode: 0o700 }).catch(() => {}); await pruneStaleFrames(); const stamp = `${Date.now()}-${process.pid}`; const images: ImageInputSpec[] = []; let estimatedTokens = 0; for (const frame of sequence.frames) { // 帧序列一次给多张,用低压缩级别 PNG 控制编码耗时 // (注释原本写「使用 JPEG(质量 80)」,与代码不符,已订正) const png = encodePng(frame.image, { channels: 3, level: 3 }); const path = join(FRAME_DIR, `seq-${stamp}-${frame.index}.png`); await writeFile(path, png, { mode: 0o600 }); images.push({ source: path, detail: 'default' }); estimatedTokens += estimateImageTokens(frame.image); } return { images, note: sequence.note, summary: sequence.summary, estimatedTokens, }; } /** 裸 RGB → RGBA。载荷长度与声明尺寸不符时返回 null,不拿坏数据组图。 */ function rgbToRgba(frame: ComputerUseSequenceFrame): RgbaImage | null { const rgb = Buffer.from(frame.rgbBase64, 'base64'); const expected = frame.width * frame.height * 3; if (rgb.length !== expected) return null; const data = new Uint8Array(frame.width * frame.height * 4); for (let src = 0, dst = 0; src < rgb.length; src += 3, dst += 4) { data[dst] = rgb[src]!; data[dst + 1] = rgb[src + 1]!; data[dst + 2] = rgb[src + 2]!; data[dst + 3] = 255; } return { width: frame.width, height: frame.height, data }; } /** * 清掉过期帧文件。 * * 每次组装时顺手做,而不是靠退出时清理:进程可能被 kill、可能崩溃, * 而「退出时才清」的策略在这两种情况下都留下满磁盘的屏幕截图。 * * 双重保护: * 1. TTL:删除超过10分钟的文件(默认值,对齐内核规范) * 2. LRU数量限制:如果剩余文件超过200个,删除最旧的 */ export async function pruneStaleFrames(ttlMs: number = FRAME_TTL_MS, maxCount: number = FRAME_MAX_COUNT): Promise { try { await mkdir(FRAME_DIR, { recursive: true, mode: 0o700 }).catch(() => {}); const entries = await readdir(FRAME_DIR).catch(() => [] as string[]); const fileStats: Array<{ path: string; mtime: number }> = []; for (const name of entries) { const path = join(FRAME_DIR, name); const info = await stat(path).catch(() => null); if (info?.isFile()) { fileStats.push({ path, mtime: info.mtimeMs }); } else if (!info) { // 文件已不存在或无权限,尝试删除 await rm(path, { force: true }).catch(() => {}); } } const now = Date.now(); // 1. 删除TTL过期文件 const expired = fileStats.filter((f) => now - f.mtime > ttlMs); await Promise.all(expired.map((f) => rm(f.path, { force: true }).catch(() => {}))); // 2. LRU:剩余文件按mtime升序,超过maxCount时删除最旧的 const remaining = fileStats .filter((f) => now - f.mtime <= ttlMs) .sort((a, b) => a.mtime - b.mtime); if (remaining.length > maxCount) { const toDelete = remaining.slice(0, remaining.length - maxCount); await Promise.all(toDelete.map((f) => rm(f.path, { force: true }).catch(() => {}))); } } catch { // 清理失败不影响主功能 } }