computer-use-client.mjs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /**
  2. * Computer Use SDK —— 模型可见的 `cua` 对象面(只含 computer 部分,不含 browser)。
  3. *
  4. * 设计文档:zcode-cua/docs/refactor-port-specs/2026-09-10-cua-sdk-v3-api.md
  5. *
  6. * 三条原则(文档 §1):
  7. * R1 同名同签 —— 公开方法的名字、位置参数顺序、选项键名、返回类型保持冻结。
  8. * R2 公开面之外的能力先问能不能删;留下的只能出现在可选选项键、尾部可选参数,
  9. * 或 `cua.computer` 逃逸口里。`Target` 上的附加成员数必须为 0。
  10. * R3 安全语义只藏不删 —— state_id 强校验、frame 精确栅格、possibly_sent 防重放、
  11. * controller lease、kill switch 全部保留,改为内部字段或类型化错误。
  12. *
  13. * 两处刻意的语义选择(文档 §5):
  14. * 1. node_repl 的 Worker 每次 `js` 调用都是全新的,`const app` 活不到下一个 cell。
  15. * stateId / frameId / diff 基线由 shared host 的 runtime session 持有,所以下一个
  16. * cell 里 `getApp` 是重新绑定而非重新观察。
  17. * 2. 动作失败抛 ComputerUseError 并带 actionSent —— 不能把动作做成单纯的 Promise<void>,
  18. * 那样会丢掉「可能已下发」的信息;这条语义是事故驱动的,必须保留。
  19. *
  20. * 不融合 Browser Use:这里不存在 browsers / getBrowser / createBrowserTab / getTab;
  21. * `State` 没有 `browsers` 键;`Target` 只被 App 实现,不与 browser 的 Tab 共享类型。
  22. */
  23. import { readFile } from "node:fs/promises";
  24. import { join } from "node:path";
  25. const BRIDGE_SYMBOL = Symbol.for("zcode.node-repl.computer-use-bridge");
  26. /** 存活的工具面(= `cua.computer`)。协议层的事实来源在 zcode-cua/src/tools/manifest.ts。 */
  27. const COMPUTER_METHOD_NAMES = Object.freeze([
  28. "list_apps",
  29. "list_windows",
  30. "get_app_state",
  31. "left_click",
  32. "scroll",
  33. "left_click_drag",
  34. "type",
  35. "set_value",
  36. "select_text",
  37. "key",
  38. "perform_action",
  39. "paste",
  40. "request_access",
  41. "stop_computer_control",
  42. ]);
  43. /**
  44. * 平台面收缩:某些工具在某些平台上**不存在**。事实来源同为 zcode-cua/src/tools/manifest.ts
  45. * 的 TOOL_PLATFORM_EXCLUSIONS —— 那边不注册 handler,这边不挂到 `cua.computer` 上,
  46. * 两侧必须一致,否则模型看得见一个调用即报错的方法,又会去猜替代写法。
  47. *
  48. * 2026-09-16:`open_application` 已在 producer 侧**整体删除**(不再只是 darwin 排除)——
  49. * 启动与激活并入 get_app_state 的透明拉起(见 zcode-cua/src/tools/manifest.ts 的说明),
  50. * 模型面不再有单独的启动/激活原语。于是这张表暂时为空:
  51. * 留着它是因为「按平台收缩」这个机制本身还需要,下一个平台专属工具直接往里加。
  52. */
  53. const PLATFORM_EXCLUDED_METHODS = Object.freeze({});
  54. /** 会改变 UI 的方法。成功即 void,失败抛错;这一集合决定 possibly_sent 的判定路径。 */
  55. const MUTATING_METHODS = new Set([
  56. "left_click",
  57. "scroll",
  58. "left_click_drag",
  59. "type",
  60. "set_value",
  61. "select_text",
  62. "key",
  63. "perform_action",
  64. "paste",
  65. "stop_computer_control",
  66. ]);
  67. // ─────────────────────────────────────────────────────────── 错误
  68. /** broker 错误码 → SDK 错误码。未知码归 INTERNAL,绝不静默成功。 */
  69. const ERROR_CODE_BY_BROKER = Object.freeze({
  70. permission_denied: "PERMISSION_DENIED",
  71. not_authorized: "NOT_AUTHORIZED",
  72. launch_failed: "LAUNCH_FAILED",
  73. invalid_request: "INVALID_APP",
  74. element_unavailable: "ELEMENT_UNAVAILABLE",
  75. not_settable: "NOT_SETTABLE",
  76. not_selectable: "NOT_SELECTABLE",
  77. action_unavailable: "ACTION_UNAVAILABLE",
  78. foreground_required: "FOREGROUND_REQUIRED",
  79. controller_busy: "CONTROLLER_BUSY",
  80. broker_unavailable: "HELPER_UNAVAILABLE",
  81. version_mismatch: "VERSION_MISMATCH",
  82. stale_socket: "HELPER_UNAVAILABLE",
  83. timeout: "TIMEOUT",
  84. unimplemented: "ACTION_UNAVAILABLE",
  85. method_not_found: "INTERNAL",
  86. internal: "INTERNAL",
  87. });
  88. /** 只有这些码在重试同一个动作之前必须先重新观察。 */
  89. const REOBSERVE_CODES = new Set([
  90. "ELEMENT_UNAVAILABLE",
  91. "STALE_STATE",
  92. "STRUCTURED_STATE_UNAVAILABLE",
  93. ]);
  94. const NEVER_RETRY_CODES = new Set([
  95. "CONTROLLER_BUSY",
  96. "CONTROL_STOPPED",
  97. "PERMISSION_DENIED",
  98. "NOT_AUTHORIZED",
  99. "VERSION_MISMATCH",
  100. "ACTION_UNAVAILABLE",
  101. "NOT_SETTABLE",
  102. "NOT_SELECTABLE",
  103. ]);
  104. class ComputerUseError extends Error {
  105. constructor(message, { code, actionSent, dispatchStatus, details } = {}) {
  106. super(message);
  107. this.name = "ComputerUseError";
  108. this.code = code ?? "INTERNAL";
  109. // 默认 false 是**故意**的保守方向:只有在收据明确说下发过时才置 true。
  110. // 反过来(默认 true)会让模型对一个从未下发的动作放弃重试。
  111. this.actionSent = actionSent === true;
  112. if (dispatchStatus) this.dispatchStatus = dispatchStatus;
  113. this.details = Object.freeze({ ...(details ?? {}) });
  114. this.retry = this.actionSent
  115. ? "reobserve"
  116. : NEVER_RETRY_CODES.has(this.code)
  117. ? "never"
  118. : REOBSERVE_CODES.has(this.code)
  119. ? "reobserve"
  120. : "retry";
  121. }
  122. }
  123. function parseJsonRecord(text) {
  124. if (typeof text !== "string") return undefined;
  125. try {
  126. const parsed = JSON.parse(text);
  127. return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
  128. } catch {
  129. return undefined;
  130. }
  131. }
  132. /**
  133. * 同上,但不排除数组。
  134. *
  135. * Bug 原因(2026-09-11 真机):list_apps 的 envelope 是一个**裸 JSON 数组**,而
  136. * inventory() 用 parseJsonRecord 去解析它 —— 那个函数对数组显式返回 undefined,
  137. * 于是紧随其后的 `else if (Array.isArray(parsed))` 是永远进不去的死分支,
  138. * listApps() 恒返回 []。模型据此判定「应用列表是空的,可能需要先初始化/请求权限」,
  139. * 白绕了三个 cell。空数组和「拿不到列表」在这里必须能被区分,所以解析要保真。
  140. */
  141. function parseJsonValue(text) {
  142. if (typeof text !== "string") return undefined;
  143. try {
  144. return JSON.parse(text);
  145. } catch {
  146. return undefined;
  147. }
  148. }
  149. function textBlocks(result) {
  150. const content = Array.isArray(result?.content) ? result.content : [];
  151. return content
  152. .filter((block) => block?.type === "text" && typeof block.text === "string")
  153. .map((block) => block.text);
  154. }
  155. /** 从 MCP envelope 里挖出结构化收据(顶层、structuredContent 或 action_outcome)。 */
  156. function receiptOf(result) {
  157. const candidates = [];
  158. if (result && typeof result === "object") candidates.push(result);
  159. if (result?.structuredContent && typeof result.structuredContent === "object") {
  160. candidates.push(result.structuredContent);
  161. }
  162. for (const text of textBlocks(result)) {
  163. const parsed = parseJsonRecord(text);
  164. if (!parsed) continue;
  165. candidates.push(parsed);
  166. if (parsed.action_outcome && typeof parsed.action_outcome === "object") {
  167. candidates.push(parsed.action_outcome);
  168. }
  169. }
  170. const merged = {};
  171. for (const candidate of candidates) {
  172. for (const key of [
  173. "state_id",
  174. "frame_id",
  175. "action_sent",
  176. "dispatch_status",
  177. "state_sync_status",
  178. "code",
  179. "reason",
  180. "snapshot_mode",
  181. "base_state_id",
  182. ]) {
  183. if (merged[key] === undefined && candidate[key] !== undefined) {
  184. merged[key] = candidate[key];
  185. }
  186. }
  187. }
  188. return merged;
  189. }
  190. /**
  191. * frame_id 的真实位置:官方 CUA 把它放在图片相邻的 `image_ref` 文本块里
  192. * (`{"image_ref":{"frame_id":...}}`),而不是收据顶层。SDK 两处都读,
  193. * 因为 image_ref 才是精确栅格契约的签发载体。
  194. */
  195. function frameIdOf(result) {
  196. const receipt = receiptOf(result);
  197. if (typeof receipt.frame_id === "string") return receipt.frame_id;
  198. for (const text of textBlocks(result)) {
  199. const parsed = parseJsonRecord(text);
  200. const id = parsed?.image_ref?.frame_id;
  201. if (typeof id === "string") return id;
  202. }
  203. return undefined;
  204. }
  205. function brokerErrorCodeOf(result) {
  206. for (const text of textBlocks(result)) {
  207. const parsed = parseJsonRecord(text);
  208. const code = parsed?.code ?? parsed?.error?.code;
  209. if (typeof code === "string") return code;
  210. }
  211. const receipt = receiptOf(result);
  212. return typeof receipt.code === "string" ? receipt.code : undefined;
  213. }
  214. function messageOf(result, fallback) {
  215. const texts = textBlocks(result);
  216. for (const text of texts) {
  217. const parsed = parseJsonRecord(text);
  218. if (typeof parsed?.message === "string" && parsed.message) return parsed.message;
  219. }
  220. const plain = texts.find((text) => text && !parseJsonRecord(text));
  221. return plain ?? texts[0] ?? fallback;
  222. }
  223. /**
  224. * 把工具结果归一成「成功 void / 失败抛错」。
  225. *
  226. * possibly_sent 的映射是这里唯一需要小心的地方(文档 §5.2):v1 把它作为
  227. * isError=false 加一段文本提示,模型经常读漏;v3 变成 reject 且 actionSent=true,
  228. * 迫使模型先观察再决定,而不是盲重试一个可能已经落地的非幂等动作。
  229. */
  230. /**
  231. * Helper 冷启动的 not-ready 信封。
  232. *
  233. * Bug 原因(2026-09-11 真机):Helper 是懒启动的 —— 第一次调用触发拉起,同时工具层
  234. * 返回一个**非 error** 结果,单个文本块装着
  235. * {kind:"CUA_NOT_READY", reasonCode:"broker_not_accepting", retryable:true,
  236. * message:"...is starting up... Retry the same tool call after a brief wait."}
  237. * 这是 producer 刻意设计的机器可读契约(possibly_sent ⇒ retryable=false,绝不重放;
  238. * marker 在途 ⇒ 可重试),目的正是"宿主不必解析错误字符串"。
  239. *
  240. * 而 SDK 此前对它一无所知:appStateOf 只从 JSON 里挑 state_id/app/window/elements,
  241. * not-ready 载荷一个键都不匹配,于是整条信号被丢掉,模型收到的是
  242. * 「missing state_id, elements, app, window」。加上 node_repl 每个 cell 都是全新
  243. * Worker,每次尝试都停在同一刻冷启动上,模型永远走不过去(真机上它据此去 request_access
  244. * 并用 shell 排查环境)。
  245. */
  246. const NOT_READY_KIND = "CUA_NOT_READY";
  247. const NOT_READY_MAX_ATTEMPTS = 6;
  248. const NOT_READY_BACKOFF_MS = [250, 500, 750, 1000, 1500];
  249. function notReadyEnvelopeOf(result) {
  250. if (result?.isError === true) return undefined;
  251. for (const text of textBlocks(result)) {
  252. const parsed = parseJsonRecord(text);
  253. if (parsed?.kind === NOT_READY_KIND) return parsed;
  254. }
  255. return undefined;
  256. }
  257. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  258. function assertOk(methodName, result) {
  259. const receipt = receiptOf(result);
  260. const isError = result?.isError === true;
  261. const dispatch = receipt.dispatch_status;
  262. const actionSent = receipt.action_sent === true;
  263. if (!isError && dispatch !== "possibly_sent") return receipt;
  264. const brokerCode = brokerErrorCodeOf(result);
  265. const code = isError
  266. ? (ERROR_CODE_BY_BROKER[brokerCode] ?? "INTERNAL")
  267. : "TIMEOUT";
  268. throw new ComputerUseError(
  269. messageOf(result, `${methodName} failed`),
  270. {
  271. code,
  272. actionSent: actionSent || dispatch === "possibly_sent",
  273. dispatchStatus: dispatch,
  274. details: { method: methodName, ...(brokerCode ? { brokerCode } : {}) },
  275. },
  276. );
  277. }
  278. // ─────────────────────────────────────────────────────────── 目标绑定
  279. /**
  280. * number → 元素索引,[x,y] → 当前栅格像素。
  281. *
  282. * 索引按**该 app 最新一次观察**解析(2026-09-12:动作形如
  283. * `set_value({app, elementIndex, value})`,索引身份只有 app + index,wire 上不携带
  284. * 「这个索引属于哪次观察」的凭证)。所以这里只发 `{type:"element", index}`,
  285. * 由动作自带的 app_ref 说明作用域;坐标用当前 frameId,模型永远不需要碰 frame_id。
  286. *
  287. * 仍然要求先有一次观察:没有观察就没有索引可言,自动补观察会把「模型以为点 A、
  288. * 实际点到 B」变成静默错误。
  289. */
  290. function bindTarget(binding, target, what) {
  291. if (typeof target === "number") {
  292. if (!Number.isInteger(target) || target < 0) {
  293. throw new ComputerUseError(
  294. `${what} element index must be a non-negative integer (got ${target})`,
  295. { code: "INTERNAL" },
  296. );
  297. }
  298. if (!binding.stateId) {
  299. throw new ComputerUseError(
  300. // Bug 原因(2026-09-12 真机):这里原先把 binding.label 拼进代码位置 ——
  301. // `Call await ${binding.label}.getAXState()`。label 是**显示名**,模型用
  302. // getApp({pid: 2697}) 绑定时它就是 "2697",于是给出的是 `await 2697.getAXState()`
  303. // 这种语法都不合法的代码;绑定中文名时同样如此(`await 地图.getAXState()`)。
  304. // 报错要么给可直接粘贴的代码,要么就用散文描述,不能给一句假代码。
  305. `${what} needs a fresh accessibility state before an element index can be resolved. ` +
  306. `Call getAXState() on the bound app first (the object getApp(...) returned), then act in the same cell.`,
  307. { code: "STALE_STATE", details: { need: "getAXState" } },
  308. );
  309. }
  310. return { type: "element", index: target };
  311. }
  312. if (Array.isArray(target) && target.length === 2) {
  313. const [x, y] = target;
  314. if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0) {
  315. throw new ComputerUseError(
  316. `${what} coordinate must be two non-negative integer pixels of the latest raster (got [${x}, ${y}])`,
  317. { code: "INTERNAL" },
  318. );
  319. }
  320. // 本 cell 没有取过栅格时不再拒绝。
  321. //
  322. // 工具层的坐标目标本来就允许省略 frame_id —— schemas/parseTarget.ts 的
  323. // `CoordinateTarget.frame_id` 注释写着「omitted targets bind inside the current
  324. // transport」,frame-pixel-resolver 的 `bindFramePixelTarget` 也早有 explicit /
  325. // implicit 两条路,implicit 走 `resolveLatestForAction()`(绑该会话最近一次可动作
  326. // 栅格)。所以"必须与截图同 cell"只是这一处 throw 加出来的限制,broker 侧从来不需要。
  327. //
  328. // 代价(真机 2026-09-14):node_repl 每个 cell 都是新 Worker,binding 不跨 cell,于是
  329. // 每个要点坐标的 cell 都得先截一次图。模型照做前先撞一次这个错误、再补截图重来,
  330. // 白花一轮。模型面本来就不需要帧凭证概念:坐标就是"最近一张 app 窗口截图的像素",
  331. // 只要会话已激活就能直接点。
  332. //
  333. // 放宽之后安全性不变:帧过期 / 被替换 / 非可动作,以及 app_ref 与该帧
  334. // 真实 owner 不一致(`frame_dispatch_identity_mismatch`),都仍然 fail-closed;一次栅格
  335. // 都没有过时,broker 会给出「no actionable frame is available in this transport」。
  336. return binding.frameId
  337. ? { type: "coordinate", frame_id: binding.frameId, x, y }
  338. : { type: "coordinate", x, y };
  339. }
  340. throw new ComputerUseError(
  341. `${what} target must be an element index (number) or a raster pixel ([x, y])`,
  342. { code: "INTERNAL" },
  343. );
  344. }
  345. /**
  346. * 一个字符串该当成 bundle id 还是 display name。
  347. *
  348. * Bug 原因(2026-09-11 真机):工具层的 `app_ref` 把**裸字符串一律当成 bundle_id**
  349. * (`schemas/appRef.ts` 的 transform),所以 `getApp("Notes")` 变成
  350. * `{bundle_id:"Notes"}` —— 即使 Notes 正在运行、`list_apps` 也把它的 `name` 报成
  351. * "Notes",依然报「app 未运行且无法后台启动」。而 `{name:"Notes"}` 是通的。
  352. * 模型按 SKILL 的指引传 display name,于是每次都撞在这里。
  353. *
  354. * bundle id 的判据:含点、不含空格和斜杠(`com.apple.Notes`)。其余按 display name。
  355. * 猜错时调用方会用 {@link alternateAppRef} 换字段重试一次,所以判据只影响首选顺序,
  356. * 不影响能不能成。
  357. */
  358. function looksLikeBundleId(target) {
  359. return target.includes(".") && !/[\s/]/u.test(target);
  360. }
  361. function appRefFor(target, windowId) {
  362. const field = looksLikeBundleId(target) ? "bundle_id" : "name";
  363. return { [field]: target, ...(windowId === undefined ? {} : { window_id: windowId }) };
  364. }
  365. function alternateAppRef(target, windowId) {
  366. const field = looksLikeBundleId(target) ? "name" : "bundle_id";
  367. return { [field]: target, ...(windowId === undefined ? {} : { window_id: windowId }) };
  368. }
  369. /** 工具层的「未运行且无法后台启动」是 app 解析失败的信号,不是别的故障。 */
  370. /**
  371. * 只匹配语义核心「target app is not running」,不匹配后半句。
  372. *
  373. * 根因(2026-09-15,ZCodeArena 151 例批次):原本匹配的是
  374. * `target app is not running and could not be launched`,而 producer 的文案早已改成
  375. * `target app is not running, and no installed application matched the ...`
  376. * (zcode-cua 的 nativeAxSource.ts)。一个逗号加改写就让下面的 alternateAppRef 备用查询
  377. * **一次都没执行过** —— 批次里 App 无法解析报错 47 次 / 23 例,模型只发了一次 name 查询就放弃。
  378. * 与 #29 同类:字符串在两个仓库各写一遍,一侧改了另一侧不知道。
  379. *
  380. * 前缀是这条错误的语义核心("目标 app 没在运行"),后半句是随可执行建议演化的部分。
  381. * z-code 侧的 sdk 测试钉住了 producer 的现行文案必须仍被这里命中。
  382. */
  383. function isAppNotFound(result) {
  384. if (!result?.isError) return false;
  385. return textBlocks(result).some((text) =>
  386. /target app is not running/u.test(text),
  387. );
  388. }
  389. const DIRECTIONS = new Set(["up", "down", "left", "right", "u", "d", "l", "r"]);
  390. const LONG_DIRECTION = { u: "up", d: "down", l: "left", r: "right" };
  391. const MOUSE_BUTTONS = { left: "left", right: "right", middle: "middle", l: "left", r: "right", m: "middle" };
  392. // ─────────────────────────────────────────────────────────── 展示
  393. /**
  394. * 观察方法自行展示结果。
  395. *
  396. * v1 把这件事写成 SKILL 里的一条纪律(「每个动作 cell 末尾必须显式
  397. * nodeRepl.write(state.text)」),模型忘记就整段观察丢失。纪律本该由 SDK 承担。
  398. * `{emit:false}` 留给「用代码判断但不想污染上下文」的场合。
  399. */
  400. function emitText(globals, text, options) {
  401. if (options?.emit === false) return;
  402. try {
  403. globals.nodeRepl?.write?.(text);
  404. } catch {
  405. // 展示失败不能让功能调用失败。
  406. }
  407. }
  408. function isFrameAuthorityText(value) {
  409. const parsed = parseJsonRecord(value);
  410. return Boolean(
  411. parsed && Object.keys(parsed).length === 1 && Object.hasOwn(parsed, "image_ref"),
  412. );
  413. }
  414. /**
  415. * 图片与 frame authority 走 host 的 structured sink,文本走 write。
  416. * 成功的纯文本动作不产生任何正文 —— 否则会和观察结果拼成两段输出。
  417. */
  418. function projectToHost(globals, result) {
  419. const sink = globals.nodeRepl?.emitStructuredResult;
  420. if (typeof sink !== "function" || !result || !Array.isArray(result.content)) return;
  421. const media = result.content.filter(
  422. (block) => block?.type === "image" || (block?.type === "text" && isFrameAuthorityText(block.text)),
  423. );
  424. if (media.length > 0) {
  425. // 带图的观察必须**保留**自己的 structuredContent(投影后)。
  426. //
  427. // Bug 根因(2026-09-17 真机,会话 sess_8ec5bb22):这里原先无条件丢弃它,于是
  428. // getAXStateAndScreenshot() 那次的元数据一个字都不显示,模型看到的 `Structured
  429. // content` 是同 cell 里**没有图**的另一次调用 —— 也就是 getApp() 绑定时那次隐藏的
  430. // 全量观察。可观测后果:请求了像素、图也确实附上了,`has_image` 却恒为 false
  431. // (6 次调用全中),而 SKILL 里写着 "has_image: false 只表示这次没要像素",两边对不上。
  432. // 更危险的是 `window` 与 `state_id` 也是探针那次的:探针早于本 cell 的动作执行,
  433. // 弹窗在动作后才出现时,模型读到的是**漂移前**的窗口,据此判断"对话框没出现"。
  434. //
  435. // 丢弃的原意是防元素全表泄漏(见 forDisplay 的注释),但那件事 forDisplay 已经做了,
  436. // 不需要整块丢。这里走同一条投影,所以元素表照样不会外泄。
  437. const { structuredContent: raw, ...rest } = result;
  438. const structured = raw && typeof raw === "object" ? forDisplay(raw) : undefined;
  439. sink({ ...rest, content: media, ...(structured ? { structuredContent: structured } : {}) });
  440. return;
  441. }
  442. if (result.isError === true) {
  443. sink(result);
  444. return;
  445. }
  446. const meta = result._meta && typeof result._meta === "object" ? result._meta : undefined;
  447. const structured =
  448. result.structuredContent && typeof result.structuredContent === "object"
  449. ? result.structuredContent
  450. : undefined;
  451. if (!meta && !structured) return;
  452. sink({
  453. content: [],
  454. ...(structured ? { structuredContent: forDisplay(structured) } : {}),
  455. ...(meta ? { _meta: meta } : {}),
  456. });
  457. }
  458. /**
  459. * 投给宿主的结构化负载:去掉元素全表。
  460. *
  461. * Bug 原因(2026-09-11 真机):观察结果的 `structuredContent` 里带着整棵 AX 树的
  462. * 元素数组,宿主把它挂到 MCP 结果上,agent 再把它序列化进**模型可见**的工具消息。
  463. * 打开 Notes(26 条笔记、180+ 元素)时单次 node_repl 输出 140KB 被迫落盘,模型只能
  464. * 反过来用 shell 去 grep 自己的工具结果。而元素表对模型是纯重复:它读的是同一次
  465. * 观察里已经渲染好的树文本,结构化视图只在 Worker 内部给 SDK 用。
  466. *
  467. * 宿主侧唯一的消费者是工具结果展示面板(core 的 result-display,32KB 上限),
  468. * 所以这里保留能标识状态的小字段,只把 `elements` 换成计数、`text` 丢掉(它已在
  469. * content 里)。非观察类结果(动作收据等)没有 elements,原样透传。
  470. */
  471. function forDisplay(structured) {
  472. if (!Array.isArray(structured.elements)) return structured;
  473. const { elements, text: _text, ...rest } = structured;
  474. return { ...rest, element_count: elements.length };
  475. }
  476. function imageBytesOf(result) {
  477. const content = Array.isArray(result?.content) ? result.content : [];
  478. const image = content.find((block) => block?.type === "image" && typeof block.data === "string");
  479. return image ? Uint8Array.from(Buffer.from(image.data, "base64")) : undefined;
  480. }
  481. /** AppState 的结构化事实来源。缺任何一项都 fail closed,不让模型拿到 undefined 去猜。 */
  482. function appStateOf(methodName, result) {
  483. const structured =
  484. result?.structuredContent && typeof result.structuredContent === "object"
  485. ? result.structuredContent
  486. : {};
  487. const merged = { ...structured };
  488. for (const text of textBlocks(result)) {
  489. const parsed = parseJsonRecord(text);
  490. if (!parsed) continue;
  491. for (const key of ["state_id", "app", "window", "elements", "text", "snapshot_mode", "base_state_id"]) {
  492. if (merged[key] === undefined && parsed[key] !== undefined) merged[key] = parsed[key];
  493. }
  494. }
  495. if (merged.text === undefined) {
  496. const tree = textBlocks(result).find((text) => !parseJsonRecord(text));
  497. if (tree) merged.text = tree;
  498. }
  499. // 诊断性(2026-09-11 真机):这条过去只说「Re-run the bootstrap and observe again」。
  500. // 模型照做了两次、次次失败,然后升级去 request_access 并用 shell 排查环境 —— 而事后
  501. // 从转录本也无法回溯究竟缺了哪个字段,因为结果里只剩这句话。缺什么必须写进消息,
  502. // 否则同一个故障既不可自愈也不可诊断。
  503. const missing = [
  504. typeof merged.state_id !== "string" ? "state_id" : null,
  505. Array.isArray(merged.elements) ? null : "elements",
  506. merged.app ? null : "app",
  507. merged.window ? null : "window",
  508. ].filter(Boolean);
  509. if (missing.length > 0) {
  510. throw new ComputerUseError(
  511. `${methodName} returned no usable accessibility state: missing ${missing.join(", ")}. ` +
  512. "A hidden app with no open window can produce this, and re-observing will not change it. " +
  513. "Check listApps() for the app's state, or ask the user to open a window. " +
  514. "Do not infer a state_id from prose.",
  515. { code: "STRUCTURED_STATE_UNAVAILABLE", details: { method: methodName, missing } },
  516. );
  517. }
  518. return merged;
  519. }
  520. /**
  521. * Producer 随观察附带的**告知性文本块**(`[effect_evidence unchanged]`、
  522. * `[screenshot_blank]` 等),树文本本身除外。
  523. *
  524. * Bug 根因(2026-09-17 真机,会话 sess_8ec5bb22):producer 为「AX 受理了但界面逐字节
  525. * 未变」专门做了一个与控件类型无关的证据位,观察响应里以独立 text block 下发。而
  526. * node_repl 这条链路把它整个丢了:`getAXState()` 只返回 `state.text`(= 树),
  527. * `emitText` 也只写这一段,`projectToHost` 的非 media 分支又把 `content` 清成 `[]`。
  528. * 于是模型对"点了没反应"零感知 —— 该会话里 3 次坐标点击全部静默无效、模型只能靠自己
  529. * diff 两棵树,最终连点 3 次同一条失效路径。
  530. *
  531. * 挂在树文本后面而不是另开通道:模型常写 `{ emit: false }` 再自行过滤,附加在返回值里
  532. * 两条路都覆盖到。同一个做法 getAXStateAndScreenshot 早就在用(`[screenshot unavailable: …]`)。
  533. */
  534. function advisoryTextOf(result, treeText) {
  535. const blocks = textBlocks(result).filter(
  536. (text) => text && text !== treeText && !parseJsonRecord(text) && !isFrameAuthorityText(text),
  537. );
  538. return blocks.length > 0 ? `\n${blocks.join("\n")}` : "";
  539. }
  540. // ─────────────────────────────────────────────────────────── 首用文档
  541. // ─────────────────────────────────────────────────────────── Target
  542. /**
  543. * App / Window 共享的交互面 —— `Target` 的 12 个公开成员,签名冻结。
  544. * 附加成员数为 0(zoom 已在评审中删除);ZCode 的附加能力只出现在选项袋里。
  545. */
  546. function createTarget(ctx, binding) {
  547. const { call, globals } = ctx;
  548. const observe = async (options, includeScreenshot, yieldsTree) => {
  549. // 默认拿 delta(Helper 的 snapshot_mode),显式要整树时转发 `disable_diffing`,
  550. // 工具层再把它翻成 broker 的 `force_full`。字段名必须和 get_app_state 的 schema
  551. // 一致:它是 `.strict()` 的,凭空发明的键会让每一次观察都被 unrecognized_keys
  552. // 打回(2026-09-11 真机就是这么炸的)。
  553. const args = { app_ref: binding.appRef, include_screenshot: includeScreenshot };
  554. // 不变量:delta 只在基线是模型**看过**的树时才允许。
  555. //
  556. // Bug 根因(2026-09-13 真机,会话 sess_04f97297):Helper 的 diff 基线是
  557. // `snapshotCache.get(pid, window)` —— "该 pid+窗口的上一次 capture",不管发起者是谁、
  558. // 模型有没有看见。而 getApp() 绑定时会做一次**全量但不展示**的观察(身份解析、窗口校验、
  559. // 索引基线都要它),那次 capture 就成了基线。于是模型第一次 getAXState() 是对着一棵它
  560. // 从未见过的树做增量:飞书 930 个元素只吐出 8 行 AXMenuItem enabled 抖动,模型只能
  561. // 每次都显式传 disableDiffing 拿整树。node_repl 每个 cell 都是全新 Worker、每个 cell
  562. // 都要重新 getApp,所以这不是"首次观察"的个例,而是**每个 cell 都发生**。
  563. //
  564. // 只截图的观察同样移动了 Helper 的基线却不给树文本,所以它把 treeSeen 清掉 ——
  565. // 规则是「只截图观察之后,再依赖无障碍索引前必须先拿整树」,这里由 SDK 强制执行而非靠模型记住。
  566. if (yieldsTree === true && binding.treeSeen !== true) args.disable_diffing = true;
  567. if (options?.disableDiffing === true) args.disable_diffing = true;
  568. // yieldsTree=false(getScreenshot)不给树文本 —— 上面 binding.treeSeen 的注释里本来就写着
  569. // 「也不能把自己算成基线」。同一个道理对 producer 侧的位移台账成立:没展示给模型的树
  570. // 不能被算作「模型看到过的」,否则索引位移校验变成当前树跟当前树自比(2026-09-15 探针实测)。
  571. if (yieldsTree !== true) args.tree_shown_to_model = false;
  572. const result = await call("get_app_state", args);
  573. assertOk("get_app_state", result);
  574. const state = appStateOf("get_app_state", result);
  575. binding.stateId = state.state_id;
  576. binding.treeSeen = yieldsTree === true;
  577. const frameId = frameIdOf(result);
  578. if (typeof frameId === "string") binding.frameId = frameId;
  579. return { state, result };
  580. };
  581. const act = async (methodName, args) => {
  582. const result = await call(methodName, args);
  583. assertOk(methodName, result);
  584. // 这里原先动作后无条件 `binding.stateId = undefined`,逼下一次索引解析先重新观察。
  585. //
  586. // 为什么去掉(2026-09-12):
  587. // 1. 与我们自己的文档打架。当时参考文档的动作示例就是 click(42) 紧跟 setValue(42),
  588. // 而这条守卫让那种写法必然失败。真机上模型正是照文档写 click(9); setValue(9, ...),
  589. // 然后被拒,白烧两个 cell(一个重新观察、一个重做)。
  590. // 2. 模型面不需要新鲜度凭证:set_value({app, elementIndex, value}) 不带
  591. // stateId/stale/generation 之类的字段;失效应由持有原生元素的一侧被动判定 ——
  592. // 先尝试按特征重取元素,只有重取歧义/失败才报错。
  593. // 3. 这条守卫没有信息支撑:SDK 只知道"发生过动作",不知道 UI 是否变化、也不知道那个
  594. // 元素还在不在。真正知道的是 Helper —— 索引在观察时就已冻结成 native token,
  595. // 元素消失时它本来就 fail-closed。
  596. //
  597. // 所以保留冻结映射 + Helper 侧校验,不再在客户端提前否决。
  598. };
  599. return {
  600. async getAXState(options) {
  601. const { state, result } = await observe(options, false, true);
  602. // producer 的告知性块(effect_evidence / screenshot_blank)必须跟着树一起走,
  603. // 否则这条链路会把它们丢光 —— 见 advisoryTextOf 的根因注释。
  604. const text = `${state.text}${advisoryTextOf(result, state.text)}`;
  605. emitText(globals, text, options);
  606. return text;
  607. },
  608. async getScreenshot(options) {
  609. // yieldsTree=false:只截图不给树文本,所以它不强制整树,也不能把自己算成基线。
  610. const { state, result } = await observe(options, true, false);
  611. const bytes = imageBytesOf(result);
  612. if (!bytes) {
  613. throw new ComputerUseError(
  614. // 措辞纪律(2026-09-11 真机):这里过去写「raise the window and retry」,
  615. // 那是直接教模型抢用户焦点 —— 后台截图本来就能拿到(负坐标副屏窗口实测可用)。
  616. //
  617. // 而真正常见的成因是应用处于 hidden(⌘H):macOS 不渲染隐藏窗口,Helper 的前后
  618. // surface 指纹必然不一致,栅格 fail-closed。此时重试永远不会成功,模型如果只看到
  619. // 一句无信息的 "Screenshot unavailable" 就会绕圈并升级(历史上升级成抢焦点,
  620. // 后来升级成 request_access + shell 排查)。所以把 producer 给出的原因带上,
  621. // 并指回真正可走的 AX 路径 —— 隐藏窗口的 accessibility 完全不受影响。
  622. `Screenshot unavailable for ${binding.label}` +
  623. (state.non_actionable_reason ? ` (${state.non_actionable_reason})` : "") +
  624. (state.screenshot_blank ? " (the captured raster was blank)" : "") +
  625. ". The accessibility tree still works on a hidden or unrendered window: use " +
  626. "getAXState() and act on element indices. Do not activate the app; ask the user " +
  627. "to unhide the window if pixels are genuinely required.",
  628. { code: "ELEMENT_UNAVAILABLE", details: { app: binding.label } },
  629. );
  630. }
  631. return bytes;
  632. },
  633. async getAXStateAndScreenshot(options) {
  634. const { state, result } = await observe(options, true, true);
  635. const screenshot = imageBytesOf(result);
  636. // 静默丢图是本轮最后一条同类缺陷(过去 screenshot===null 时直接 return {state},
  637. // 一句话不给)。真机上模型正是从"没收到图"推断出「截图没有
  638. // 回传(窗口在副显示器上,坐标为负)」,然后去抢用户焦点——它得到的信息量是零,
  639. // 所以只能猜。请求了像素却没拿到,必须说清为什么、以及重试有没有用。
  640. const note =
  641. screenshot || !state.non_actionable_reason
  642. ? ""
  643. : `\n[screenshot unavailable: ${state.non_actionable_reason}]` +
  644. " A hidden or minimized window produces this persistently, so re-observing will not" +
  645. " help. The accessibility tree above is complete — act on element indices. Do not" +
  646. " activate the app.";
  647. const text = `${state.text}${advisoryTextOf(result, state.text)}`;
  648. emitText(globals, `${text}${note}`, options);
  649. return screenshot ? { state: text, screenshot } : { state: text };
  650. },
  651. async paste(text, options) {
  652. if (typeof text !== "string") {
  653. throw new ComputerUseError("paste requires text", { code: "INTERNAL" });
  654. }
  655. await act("paste", {
  656. app_ref: binding.appRef,
  657. text,
  658. format: options?.format ?? "text",
  659. });
  660. },
  661. async click(target, options) {
  662. const bound = bindTarget(binding, target, "click");
  663. const button = options?.mouseButton ? MOUSE_BUTTONS[options.mouseButton] : "left";
  664. if (!button) {
  665. throw new ComputerUseError(
  666. `click mouseButton must be left, right or middle (got ${options.mouseButton})`,
  667. { code: "INTERNAL" },
  668. );
  669. }
  670. await act("left_click", {
  671. target: bound,
  672. // 索引作用域:元素目标不再带 state_id,app_ref 说明"按哪个 app 的最新观察解析"。
  673. // 少了它,多 app 会话里的索引会退到"全局最近一次观察",可能属于另一个 app。
  674. app_ref: binding.appRef,
  675. mouse_button: button,
  676. click_count: options?.clickCount ?? 1,
  677. ...(options?.modifiers ? { modifiers: options.modifiers } : {}),
  678. ...(options?.strategy ? { strategy: options.strategy } : {}),
  679. });
  680. },
  681. async drag(from, to, options) {
  682. await act("left_click_drag", {
  683. from_target: bindTarget(binding, from, "drag from"),
  684. to: bindTarget(binding, to, "drag to"),
  685. app_ref: binding.appRef,
  686. ...(options?.modifiers ? { modifiers: options.modifiers } : {}),
  687. // Bug 原因(2026-10-27):文档 DragOptions 声明了 strategy,broker 的 drag
  688. // handler 也早已按 strategy==="event" 跳过后台中间级走前台 SendInput,但
  689. // 此前 SDK 只透传 modifiers —— 调用方显式选 event 被静默吞成 auto,前台
  690. // 拖拽从 SDK 层不可达。与 click/pressKey/scroll 同形透传。
  691. ...(options?.strategy ? { strategy: options.strategy } : {}),
  692. });
  693. },
  694. async pressKey(key, options) {
  695. if (typeof key !== "string" || !key.trim()) {
  696. throw new ComputerUseError("pressKey requires a key or chord", { code: "INTERNAL" });
  697. }
  698. await act("key", {
  699. text: normalizeKeyChord(key, ctx.platform),
  700. app_ref: binding.appRef,
  701. ...(options?.holdSeconds !== undefined ? { hold_seconds: options.holdSeconds } : {}),
  702. ...(options?.strategy ? { strategy: options.strategy } : {}),
  703. });
  704. },
  705. async scroll(target, direction, pages, options) {
  706. const dir = typeof direction === "string" ? direction.trim().toLowerCase() : "";
  707. if (!DIRECTIONS.has(dir)) {
  708. throw new ComputerUseError(
  709. `scroll direction must be up, down, left or right (got ${direction})`,
  710. { code: "INTERNAL" },
  711. );
  712. }
  713. await act("scroll", {
  714. target: bindTarget(binding, target, "scroll"),
  715. app_ref: binding.appRef,
  716. scroll_direction: LONG_DIRECTION[dir] ?? dir,
  717. scroll_amount: pages === undefined ? 1 : pages,
  718. ...(options?.strategy ? { strategy: options.strategy } : {}),
  719. });
  720. },
  721. async selectText(elementIndex, text, options) {
  722. const bound = bindTarget(binding, elementIndex, "selectText");
  723. // 签名按内容匹配(传要选中的文本)。range 由 SDK 在**已观察到的元素 value** 上本地算出,
  724. // 不需要额外的 broker 往返:value 就在上一次 getAXState 的结构化结果里。
  725. const range = resolveTextRange(binding, elementIndex, text, options);
  726. await act("select_text", { target: bound, app_ref: binding.appRef, text_range: range });
  727. },
  728. async setValue(elementIndex, value) {
  729. if (typeof value !== "string") {
  730. throw new ComputerUseError("setValue requires a string value", { code: "INTERNAL" });
  731. }
  732. await act("set_value", {
  733. target: bindTarget(binding, elementIndex, "setValue"),
  734. app_ref: binding.appRef,
  735. value,
  736. });
  737. },
  738. async typeText(text) {
  739. if (typeof text !== "string") {
  740. throw new ComputerUseError("typeText requires text", { code: "INTERNAL" });
  741. }
  742. await act("type", { text, app_ref: binding.appRef });
  743. },
  744. async performSecondaryAction(elementIndex, action) {
  745. if (typeof action !== "string" || !action.trim()) {
  746. throw new ComputerUseError(
  747. "performSecondaryAction requires an action advertised by the element; do not guess one",
  748. { code: "ACTION_UNAVAILABLE" },
  749. );
  750. }
  751. await act("perform_action", {
  752. target: bindTarget(binding, elementIndex, "performSecondaryAction"),
  753. app_ref: binding.appRef,
  754. action,
  755. });
  756. },
  757. };
  758. }
  759. /**
  760. * 按内容定位 [start, length]。
  761. *
  762. * `prefix` / `suffix` 用来消歧重复匹配;`selectionType` 把选区折叠成光标位置。
  763. * 匹配不唯一时抛 NOT_SELECTABLE 并报候选数 —— 静默取第一个会让模型在错的位置编辑。
  764. */
  765. function resolveTextRange(binding, elementIndex, text, options) {
  766. if (text && typeof text === "object" && Number.isInteger(text.start)) {
  767. return [text.start, text.length ?? 0];
  768. }
  769. if (typeof text !== "string" || text.length === 0) {
  770. throw new ComputerUseError("selectText requires the text to locate", { code: "INTERNAL" });
  771. }
  772. const element = binding.elements?.[elementIndex];
  773. const value = typeof element?.value === "string" ? element.value : undefined;
  774. if (value === undefined) {
  775. throw new ComputerUseError(
  776. `selectText cannot locate text in element ${elementIndex}: the latest accessibility state exposed no value for it. Observe again, or use a range { start, length }.`,
  777. { code: "NOT_SELECTABLE", details: { elementIndex } },
  778. );
  779. }
  780. const needle = `${options?.prefix ?? ""}${text}${options?.suffix ?? ""}`;
  781. const hits = [];
  782. for (let at = value.indexOf(needle); at !== -1; at = value.indexOf(needle, at + 1)) {
  783. hits.push(at);
  784. }
  785. if (hits.length === 0) {
  786. throw new ComputerUseError(
  787. `selectText found no occurrence of the requested text in element ${elementIndex}`,
  788. { code: "NOT_SELECTABLE", details: { elementIndex } },
  789. );
  790. }
  791. if (hits.length > 1) {
  792. throw new ComputerUseError(
  793. `selectText matched ${hits.length} occurrences in element ${elementIndex}; disambiguate with prefix/suffix`,
  794. { code: "NOT_SELECTABLE", details: { elementIndex, matches: hits.length } },
  795. );
  796. }
  797. const start = hits[0] + (options?.prefix?.length ?? 0);
  798. const selectionType = options?.selectionType ?? "text";
  799. if (selectionType === "cursor_before") return [start, 0];
  800. if (selectionType === "cursor_after") return [start + text.length, 0];
  801. return [start, text.length];
  802. }
  803. /**
  804. * 键位别名规范化:接受 xdotool / X keysym 写法(模型先验多是这种写法),
  805. * 输出 ZCode 的内部 token 集合。只做输入侧兼容,不改跨平台修饰键规则
  806. * (macOS cmd,Linux / Windows ctrl)。
  807. */
  808. const KEY_ALIASES = Object.freeze({
  809. return: "return", enter: "return", kp_enter: "return",
  810. control_l: "ctrl", control_r: "ctrl", control: "ctrl", ctrl: "ctrl",
  811. alt_l: "alt", alt_r: "alt", meta_l: "alt", alt: "alt",
  812. shift_l: "shift", shift_r: "shift", shift: "shift",
  813. escape: "esc", esc: "esc",
  814. prior: "pageup", next: "pagedown",
  815. // 曾有 greater: ">"——输出 ">" 从未通过工具层白名单(S2 前后均如此),是端到端
  816. // 死路径,且会让组合契约测试(sdk-key-chord-contract.node-test.mjs)被迫开
  817. // 豁免口,故移除。需要输出 ">" 时应先给工具层 canonical 集补该 token。
  818. period: ".", comma: ",", slash: "/", minus: "-", equal: "=",
  819. });
  820. function normalizeKeyChord(chord, platform) {
  821. return chord
  822. .split("+")
  823. .map((raw) => {
  824. const token = raw.trim();
  825. const lower = token.toLowerCase();
  826. if (lower === "super_l" || lower === "super_r" || lower === "super") {
  827. return platform === "darwin" ? "cmd" : platform === "win32" ? "win" : "super";
  828. }
  829. return KEY_ALIASES[lower] ?? token;
  830. })
  831. .filter(Boolean)
  832. .join("+");
  833. }
  834. // ─────────────────────────────────────────────────────────── 装配
  835. export async function setupComputerUseRuntime({ globals }) {
  836. const bridge = globals[BRIDGE_SYMBOL];
  837. if (!bridge || typeof bridge !== "object" || typeof bridge.call !== "function") {
  838. throw new Error(
  839. "Computer Use runtime bridge is unavailable. Use Computer Use from a ZCode desktop or shared-host session.",
  840. );
  841. }
  842. bridge.assertAvailable?.();
  843. const platform = globals.process?.platform ?? process.platform;
  844. const call = async (methodName, args) => {
  845. // not-ready 是 Helper 冷启动的正常一步,不是失败:payload 明确要求"稍等后重试同一
  846. // 调用"。只在 retryable 为真时重试 —— possibly_sent 的动作绝不重放(见常量注释)。
  847. for (let attempt = 0; ; attempt += 1) {
  848. bridge.assertAvailable?.();
  849. const result = await bridge.call(methodName, args ?? {});
  850. const notReady = notReadyEnvelopeOf(result);
  851. if (!notReady) {
  852. projectToHost(globals, result);
  853. return result;
  854. }
  855. if (notReady.retryable !== true || attempt >= NOT_READY_MAX_ATTEMPTS - 1) {
  856. // 不可重试,或已等到上限:把 producer 自己的话和 reasonCode 交给模型,
  857. // 不要替换成通用句子(那正是今天反复出问题的地方)。
  858. throw new ComputerUseError(
  859. `${methodName}: ${notReady.message ?? "Computer Use is not ready."}`,
  860. {
  861. code: notReady.retryable === true ? "TIMEOUT" : "CONTROLLER_BUSY",
  862. details: {
  863. method: methodName,
  864. reasonCode: notReady.reasonCode,
  865. retryable: notReady.retryable === true,
  866. attempts: attempt + 1,
  867. },
  868. },
  869. );
  870. }
  871. await sleep(NOT_READY_BACKOFF_MS[Math.min(attempt, NOT_READY_BACKOFF_MS.length - 1)]);
  872. }
  873. };
  874. const ctx = { call, globals, platform };
  875. /** 每个绑定目标在 Worker 内的视图;跨 cell 的真身由 shared host 的 session 持有。 */
  876. const createBinding = (label, appRef) => ({
  877. label,
  878. appRef,
  879. stateId: undefined,
  880. frameId: undefined,
  881. elements: undefined,
  882. // delta 的基线是否是模型**看过**的那棵树。见 createTarget 的 observe()。
  883. treeSeen: false,
  884. });
  885. const bindApp = async (target, windowId) => {
  886. let objectRef;
  887. let label = typeof target === "string" ? target : "";
  888. // 也接受工具层那种 app_ref 对象。SKILL 把绑定面和逃逸口并排放着,模型学到
  889. // `{bundle_id: ...}` 之后很自然会把它传给 getApp(2026-09-11 真机就是这样,
  890. // 撞了 "getApp requires an app display name or bundle id")。对象形态没有歧义,
  891. // 直接透传比让它退回去改写更省一次往返。
  892. if (target && typeof target === "object" && !Array.isArray(target)) {
  893. const direct = windowId === undefined ? { ...target } : { ...target, window_id: windowId };
  894. if (
  895. typeof direct.name !== "string" &&
  896. typeof direct.bundle_id !== "string" &&
  897. typeof direct.pid !== "number"
  898. ) {
  899. throw new ComputerUseError(
  900. "getApp needs an app display name, a bundle id, or {name|bundle_id|pid}",
  901. { code: "INVALID_APP" },
  902. );
  903. }
  904. objectRef = direct;
  905. label = String(direct.name ?? direct.bundle_id ?? direct.pid);
  906. } else if (typeof target !== "string" || !target.trim()) {
  907. throw new ComputerUseError(
  908. "getApp needs an app display name, a bundle id, or {name|bundle_id|pid}",
  909. { code: "INVALID_APP" },
  910. );
  911. }
  912. let appRef = objectRef ?? appRefFor(target, windowId);
  913. const binding = createBinding(label, appRef);
  914. const app = createTarget(ctx, binding);
  915. // 绑定即观察:返回前展示该 app 的**全量** AX 树。
  916. let result = await call("get_app_state", {
  917. app_ref: appRef,
  918. include_screenshot: false,
  919. disable_diffing: true,
  920. // 这棵树不展示给模型(下面 981 行那段注释说明为什么),所以它**不能**被算作
  921. // 「模型看到过的树」。不标的后果(2026-09-15 探针实测):索引位移校验拿当前树
  922. // 跟当前树自比,必然一致,静默点错元素的保护完全失效。
  923. tree_shown_to_model: false,
  924. });
  925. if (isAppNotFound(result) && objectRef === undefined) {
  926. // 只有字符串需要猜字段;对象形态是显式的,猜错的是调用方而不是我们。
  927. const alternate = alternateAppRef(target, windowId);
  928. if (alternate) {
  929. appRef = alternate;
  930. binding.appRef = alternate;
  931. result = await call("get_app_state", {
  932. app_ref: alternate,
  933. include_screenshot: false,
  934. disable_diffing: true,
  935. tree_shown_to_model: false,
  936. });
  937. }
  938. }
  939. assertOk("get_app_state", result);
  940. const state = appStateOf("get_app_state", result);
  941. binding.stateId = state.state_id;
  942. binding.elements = state.elements;
  943. // 绑定成功后把 app_ref 收敛成**解析出来的身份**,不再继续拿模型给的原始字符串。
  944. //
  945. // Bug 原因(2026-09-12 真机):模型写 `getApp("地图")`(Maps 的中文本地化名)。观察成功了
  946. // —— capture_app 按名字找不到活动应用会走透明拉起分支,那里的 LaunchServices 查表能把
  947. // "地图" 解成 com.apple.Maps。但同一个 cell 里紧接着的 pressKey 失败:
  948. // press_key_to_app: app_ref did not resolve to a unique live application
  949. // 因为活动应用列表里 Maps 的 name 字段是英文 "Maps",{name:"地图"} 匹配零行,而键盘路径
  950. // 只按活动应用严格匹配。观察路径宽容、输入路径严格,两边就此分叉。
  951. //
  952. // 观察结果里本来就带着已解析的身份(state.app.pid / bundle_id),此前只是没用。收敛之后
  953. // 本地化名、模糊名、大小写差异都只在第一跳解决一次,后续所有路径拿到的都是无歧义身份。
  954. // 两个字段都给:pid 精确(同 cell 内进程不会换),bundle_id 供 broker 侧交叉校验身份。
  955. // window_id 若已绑定必须保留 —— 它决定 macOS 后台键盘的 synthetic-focus session。
  956. const resolvedPid = typeof state.app?.pid === "number" ? state.app.pid : undefined;
  957. const resolvedBundleId =
  958. typeof state.app?.bundle_id === "string" && state.app.bundle_id.trim()
  959. ? state.app.bundle_id
  960. : undefined;
  961. if (resolvedPid !== undefined || resolvedBundleId !== undefined) {
  962. const boundWindowId =
  963. typeof appRef?.window_id === "number" ? { window_id: appRef.window_id } : {};
  964. appRef = {
  965. ...(resolvedPid !== undefined ? { pid: resolvedPid } : {}),
  966. ...(resolvedBundleId !== undefined ? { bundle_id: resolvedBundleId } : {}),
  967. ...boundWindowId,
  968. };
  969. binding.appRef = appRef;
  970. }
  971. // 判据取自**最终的 appRef**,不是位置参数 windowId。
  972. //
  973. // Bug 根因(2026-09-17 复查):这里原先写 `windowId !== undefined`,只认
  974. // getWindow(target, id) 那种位置参数形态。而 `getApp({pid, window_id})` 也能钉窗口
  975. // (objectRef 直接透传,见上面的 direct),走那条路时 windowId 恒为 undefined,
  976. // 于是这道 fail-closed 被整个跳过:Helper 静默降级到最前窗口、只回一句 note,
  977. // 模型在错窗口上继续操作。两种钉法必须同一套校验。
  978. const boundWindow = typeof appRef?.window_id === "number" ? appRef.window_id : windowId;
  979. if (boundWindow !== undefined && state.window?.window_id_fallback === true) {
  980. // 现状会静默降级到最前窗口并只回一句 note,模型极易读漏后在错窗口上继续操作。
  981. throw new ComputerUseError(
  982. `Window ${boundWindow} of ${label} could not be resolved; the Helper fell back to the frontmost window. Call agent.computerUse.computer.list_windows to pick a fresh window_id.`,
  983. { code: "STALE_STATE", details: { app: label, windowId: boundWindow } },
  984. );
  985. }
  986. // getApp 不展示状态(2026-09-13)。它仍然做一次观察 —— 身份解析、窗口校验与索引解析
  987. // 基线都要它 —— 但不再把那棵树写进输出。
  988. //
  989. // 根因:「getApp 自动输出结果」只在 kernel **持久**时划算 —— `const app = await
  990. // cua.getApp(...)` 跨 cell 存活,一个会话只调一次 getApp,那次展示确实省掉一次单独观察。
  991. // ZCode 的 node_repl 每个 cell 都是全新 Worker,绑定不跨 cell,于是**每个 cell 都要重新
  992. // getApp**,那次"顺便展示"就从"一次性省一个往返"变成了"每个 cell 都多一棵注定作废的树"。
  993. //
  994. // 代价不只是 token。真机实测(会话 sess_f14c07fd):8 个 cell 里 5 个吐两棵树,
  995. // 36% 的工具输出(43902/120854 字符)是被同 cell 后续观察直接覆盖的前序树;更糟的是
  996. // 同一个 `[35]` 在一个 cell 的输出里指向两个不同元素(先出现的 79 元素树里是
  997. // `genericelement Yanbao Maquanying Homeland`,后出现的 105 元素树里才是
  998. // `button Tsinghua University`),而**只有最后那棵**是索引解析真正会用的,输出里却
  999. // 没有任何标记说明这件事。读错就点到无关元素,且不会报错 —— 那个索引在旧树里合法。
  1000. //
  1001. // 想看状态就显式 getAXState(),与其它观察方法一致。
  1002. //
  1003. // 结构化元素视图。Target 的公开观察方法只给字符串,但模型写的是代码,单 cell 内
  1004. // 「观察 → 找元素 → 动作」能省一次往返;树被按优先级裁剪(targeting/format.ts 的
  1005. // `indices are sparse` 注记)时,它还是模型拿到隐藏元素索引的唯一途径。因此它已被
  1006. // 提为**文档化成员**(SKILL 的 Keyboard 段 + docs/computer-use.md 的 API 段),
  1007. // 保持 enumerable:false 只是为了不进 Object.keys —— R2 的「Target 附加成员为 0」
  1008. // 说的是冻结的**可枚举**公开面,不是禁止具名逃逸口。
  1009. Object.defineProperty(app, "elements", {
  1010. enumerable: false,
  1011. value: async () => {
  1012. // 与 getScreenshot 不同档(2026-10-25 修正):返回值(含 index 的元素表)
  1013. // 回给了模型所写的 JS——els[3].index 直接进 click 参数,这张表就是模型
  1014. // 选目标的信息来源,构成「模型可见」。2026-09-16 评审按「不 emit」把它
  1015. // 与 bindApp/getScreenshot 一刀切标 false,掩盖了本质差异(那两条的
  1016. // 返回值不含树);false 的真实后果是位移台账只剩更旧的树,模型用
  1017. // elements() 的新鲜索引点击时被拿旧树对照新树,element_index_shifted
  1018. // 假阳性(真位移同时拦不住)。记账后 producer 台账与模型实际所见一致。
  1019. //
  1020. // diff 基线问题不受影响:binding.treeSeen 仍清空(treeSeen 管的是 emit
  1021. // 展示面的整树承诺,与记账正交),下一次 getAXState 照旧强制整树。
  1022. const fresh = appStateOf(
  1023. "get_app_state",
  1024. await call("get_app_state", { app_ref: appRef, tree_shown_to_model: true }),
  1025. );
  1026. binding.stateId = fresh.state_id;
  1027. binding.elements = fresh.elements;
  1028. binding.treeSeen = false;
  1029. return fresh.elements;
  1030. },
  1031. });
  1032. return app;
  1033. };
  1034. const inventory = async (options) => {
  1035. const result = await call("list_apps", {});
  1036. assertOk("list_apps", result);
  1037. const apps = [];
  1038. for (const text of textBlocks(result)) {
  1039. const parsed = parseJsonValue(text);
  1040. if (Array.isArray(parsed?.apps)) apps.push(...parsed.apps);
  1041. else if (Array.isArray(parsed)) apps.push(...parsed);
  1042. }
  1043. const state = { apps };
  1044. emitText(globals, JSON.stringify(state, null, 2), options);
  1045. return state;
  1046. };
  1047. // `cua.computer` —— 平台特定逃逸口,暴露额外的平台相关 computer API。
  1048. // 内容是存活的 14 个工具,入参 schema 逐字保留。
  1049. //
  1050. // 返回值**解封**(2026-09-16):此前原样返回 MCP envelope,于是模型拿到的是
  1051. // `{content:[{type:"text",text:"[...]"}],_meta:{…}}`,还得自己 `JSON.parse(r.content[0].text)`。
  1052. // 真机代价(list_windows):4964 字符里有用载荷只 1723(35%),另外 65% 是信封与
  1053. // `_meta` 里的 app 图标 base64(上限 24KiB ⇒ base64 最坏 ~32KiB)。而 `_meta` 按设计
  1054. // 就是**宿主专用**的(target-app-display 设计文档:host-only、"stripped before handlers
  1055. // observe responses"),projectToHost 已经单独把它送给宿主展示 —— 所以泄漏给模型是
  1056. // 契约违规,不是契约选择。连设计文档自己的示例都写成 `wins[1].window_id`(把它当裸数组),
  1057. // 可见"保留信封"从来不是有人依赖的行为;全仓 grep 也确认零消费者。
  1058. const unwrapEnvelope = (result) => {
  1059. if (result === null || typeof result !== "object") return result;
  1060. if (!Array.isArray(result.content)) return result;
  1061. const textBlocks = result.content.filter(
  1062. (block) => block && block.type === "text" && typeof block.text === "string",
  1063. );
  1064. // 只在"单一 text block"这种明确形态上解封;多块 / 图像等一律原样返回,
  1065. // 避免把一个我们不认识的形状猜成裸值。
  1066. if (textBlocks.length !== 1 || result.content.length !== 1) return result;
  1067. const text = textBlocks[0].text;
  1068. try {
  1069. return JSON.parse(text);
  1070. } catch {
  1071. return text;
  1072. }
  1073. };
  1074. const computer = Object.create(null);
  1075. Object.defineProperty(computer, "target", {
  1076. enumerable: true,
  1077. value: platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux",
  1078. });
  1079. const excluded = new Set(PLATFORM_EXCLUDED_METHODS[platform] ?? []);
  1080. for (const methodName of COMPUTER_METHOD_NAMES) {
  1081. if (excluded.has(methodName)) continue;
  1082. Object.defineProperty(computer, methodName, {
  1083. enumerable: true,
  1084. value: async (args = {}) => unwrapEnvelope(await call(methodName, args)),
  1085. });
  1086. }
  1087. const cua = {
  1088. async getState(options) {
  1089. return await inventory(options);
  1090. },
  1091. async getApp(target) {
  1092. return await bindApp(target);
  1093. },
  1094. async listApps(options) {
  1095. return (await inventory(options)).apps;
  1096. },
  1097. computer: Object.freeze(computer),
  1098. async requestAccess(capabilities) {
  1099. const result = await call("request_access", capabilities ? { capabilities } : {});
  1100. assertOk("request_access", result);
  1101. const texts = textBlocks(result);
  1102. return parseJsonRecord(texts[0]) ?? { ready: true };
  1103. },
  1104. async stop(reason) {
  1105. const result = await call("stop_computer_control", reason ? { reason } : {});
  1106. assertOk("stop_computer_control", result);
  1107. },
  1108. };
  1109. // 未文档化成员:窗口绑定。窗口寻址各平台差异很大(有的平台没有窗口寻址,有的整套
  1110. // 以 Window 对象寻址),ZCode 三平台统一命名,不按平台分裂公开面,
  1111. // 所以窗口寻址留在逃逸口 + 这个未文档化入口。
  1112. Object.defineProperty(cua, "getWindow", {
  1113. enumerable: false,
  1114. value: async (target, windowId) => await bindApp(target, windowId),
  1115. });
  1116. // 入口是 `agent.computerUse`(ZCode 自己的命名空间约定,与 agent.documentation /
  1117. // agent.browsers 并列),不注入裸 `cua` 全局。
  1118. // 平铺的 14 个工具在 `agent.computerUse.computer.*` 下(COMPUTER_METHOD_NAMES)。
  1119. const agent = (globals.agent ??= {});
  1120. agent.computerUse = cua;
  1121. const previousDocumentation = agent.documentation;
  1122. const previousGet =
  1123. previousDocumentation && typeof previousDocumentation.get === "function"
  1124. ? previousDocumentation.get.bind(previousDocumentation)
  1125. : undefined;
  1126. agent.documentation = Object.freeze({
  1127. get: async (name) => {
  1128. // Browser Use 的文档 loader 必须原样转交 —— CUA 只认自己那一个名字。
  1129. if (name !== "computer-use") {
  1130. if (previousGet) return await previousGet(name);
  1131. throw new Error(`Unknown documentation entry: ${name}`);
  1132. }
  1133. if (typeof bridge.documentationRoot !== "string") {
  1134. throw new Error("Computer Use documentation is unavailable");
  1135. }
  1136. return await readFile(join(bridge.documentationRoot, "computer-use.md"), "utf8");
  1137. },
  1138. });
  1139. return cua;
  1140. }
  1141. export { COMPUTER_METHOD_NAMES, PLATFORM_EXCLUDED_METHODS, ComputerUseError, normalizeKeyChord, KEY_ALIASES };