computer-use-client.mjs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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, options) {
  419. const sink = globals.nodeRepl?.emitStructuredResult;
  420. if (typeof sink !== "function" || !result || !Array.isArray(result.content)) return;
  421. const raw = result.structuredContent;
  422. const structured = raw && typeof raw === "object" ? forDisplay(raw) : undefined;
  423. // 元数据曾只留在结构化字段,模型读取 content 时也需要它,并保持与本次截图一致。
  424. const metadataContent =
  425. options?.emit !== false && structured
  426. ? [{ type: "text", text: JSON.stringify(structured) }]
  427. : [];
  428. const media =
  429. options?.emit === false
  430. ? []
  431. : result.content.filter(
  432. (block) =>
  433. block?.type === "image" || (block?.type === "text" && isFrameAuthorityText(block.text)),
  434. );
  435. if (media.length > 0) {
  436. const { structuredContent: _raw, ...rest } = result;
  437. sink({
  438. ...rest,
  439. content: [...media, ...metadataContent],
  440. ...(structured ? { structuredContent: structured } : {}),
  441. });
  442. return;
  443. }
  444. if (result.isError === true) {
  445. sink(result);
  446. return;
  447. }
  448. const meta = result._meta && typeof result._meta === "object" ? result._meta : undefined;
  449. if (!meta && !structured) return;
  450. sink({
  451. content: metadataContent,
  452. ...(structured ? { structuredContent: structured } : {}),
  453. ...(meta ? { _meta: meta } : {}),
  454. });
  455. }
  456. /**
  457. * 投给宿主的结构化负载:去掉元素全表。
  458. *
  459. * Bug 原因(2026-09-11 真机):观察结果的 `structuredContent` 里带着整棵 AX 树的
  460. * 元素数组,宿主把它挂到 MCP 结果上,agent 再把它序列化进**模型可见**的工具消息。
  461. * 打开 Notes(26 条笔记、180+ 元素)时单次 node_repl 输出 140KB 被迫落盘,模型只能
  462. * 反过来用 shell 去 grep 自己的工具结果。而元素表对模型是纯重复:它读的是同一次
  463. * 观察里已经渲染好的树文本,结构化视图只在 Worker 内部给 SDK 用。
  464. *
  465. * 宿主侧唯一的消费者是工具结果展示面板(core 的 result-display,32KB 上限),
  466. * 所以这里保留能标识状态的小字段,只把 `elements` 换成计数、`text` 丢掉(它已在
  467. * content 里)。非观察类结果(动作收据等)没有 elements,原样透传。
  468. */
  469. function forDisplay(structured) {
  470. if (!Array.isArray(structured.elements)) return structured;
  471. const { elements, text: _text, ...rest } = structured;
  472. return { ...rest, element_count: elements.length };
  473. }
  474. function imageBytesOf(result) {
  475. const content = Array.isArray(result?.content) ? result.content : [];
  476. const image = content.find((block) => block?.type === "image" && typeof block.data === "string");
  477. return image ? Uint8Array.from(Buffer.from(image.data, "base64")) : undefined;
  478. }
  479. /** AppState 的结构化事实来源。缺任何一项都 fail closed,不让模型拿到 undefined 去猜。 */
  480. function appStateOf(methodName, result) {
  481. const structured =
  482. result?.structuredContent && typeof result.structuredContent === "object"
  483. ? result.structuredContent
  484. : {};
  485. const merged = { ...structured };
  486. for (const text of textBlocks(result)) {
  487. const parsed = parseJsonRecord(text);
  488. if (!parsed) continue;
  489. for (const key of ["state_id", "app", "window", "elements", "text", "snapshot_mode", "base_state_id"]) {
  490. if (merged[key] === undefined && parsed[key] !== undefined) merged[key] = parsed[key];
  491. }
  492. }
  493. if (merged.text === undefined) {
  494. const tree = textBlocks(result).find((text) => !parseJsonRecord(text));
  495. if (tree) merged.text = tree;
  496. }
  497. // 诊断性(2026-09-11 真机):这条过去只说「Re-run the bootstrap and observe again」。
  498. // 模型照做了两次、次次失败,然后升级去 request_access 并用 shell 排查环境 —— 而事后
  499. // 从转录本也无法回溯究竟缺了哪个字段,因为结果里只剩这句话。缺什么必须写进消息,
  500. // 否则同一个故障既不可自愈也不可诊断。
  501. const missing = [
  502. typeof merged.state_id !== "string" ? "state_id" : null,
  503. Array.isArray(merged.elements) ? null : "elements",
  504. merged.app ? null : "app",
  505. merged.window ? null : "window",
  506. ].filter(Boolean);
  507. if (missing.length > 0) {
  508. throw new ComputerUseError(
  509. `${methodName} returned no usable accessibility state: missing ${missing.join(", ")}. ` +
  510. "A hidden app with no open window can produce this, and re-observing will not change it. " +
  511. "Check listApps() for the app's state, or ask the user to open a window. " +
  512. "Do not infer a state_id from prose.",
  513. { code: "STRUCTURED_STATE_UNAVAILABLE", details: { method: methodName, missing } },
  514. );
  515. }
  516. return merged;
  517. }
  518. /**
  519. * Producer 随观察附带的**告知性文本块**(`[effect_evidence unchanged]`、
  520. * `[screenshot_blank]` 等),树文本本身除外。
  521. *
  522. * Bug 根因(2026-09-17 真机,会话 sess_8ec5bb22):producer 为「AX 受理了但界面逐字节
  523. * 未变」专门做了一个与控件类型无关的证据位,观察响应里以独立 text block 下发。而
  524. * node_repl 这条链路把它整个丢了:`getAXState()` 只返回 `state.text`(= 树),
  525. * `emitText` 也只写这一段,`projectToHost` 的非 media 分支又把 `content` 清成 `[]`。
  526. * 于是模型对"点了没反应"零感知 —— 该会话里 3 次坐标点击全部静默无效、模型只能靠自己
  527. * diff 两棵树,最终连点 3 次同一条失效路径。
  528. *
  529. * 挂在树文本后面而不是另开通道:模型常写 `{ emit: false }` 再自行过滤,附加在返回值里
  530. * 两条路都覆盖到。同一个做法 getAXStateAndScreenshot 早就在用(`[screenshot unavailable: …]`)。
  531. */
  532. function advisoryTextOf(result, treeText) {
  533. const blocks = textBlocks(result).filter(
  534. (text) => text && text !== treeText && !parseJsonRecord(text) && !isFrameAuthorityText(text),
  535. );
  536. return blocks.length > 0 ? `\n${blocks.join("\n")}` : "";
  537. }
  538. // ─────────────────────────────────────────────────────────── 首用文档
  539. // ─────────────────────────────────────────────────────────── Target
  540. /**
  541. * App / Window 共享的交互面 —— `Target` 的 12 个公开成员,签名冻结。
  542. * 附加成员数为 0(zoom 已在评审中删除);ZCode 的附加能力只出现在选项袋里。
  543. */
  544. function createTarget(ctx, binding) {
  545. const { call, globals } = ctx;
  546. const observe = async (options, includeScreenshot, yieldsTree) => {
  547. // 默认拿 delta(Helper 的 snapshot_mode),显式要整树时转发 `disable_diffing`,
  548. // 工具层再把它翻成 broker 的 `force_full`。字段名必须和 get_app_state 的 schema
  549. // 一致:它是 `.strict()` 的,凭空发明的键会让每一次观察都被 unrecognized_keys
  550. // 打回(2026-09-11 真机就是这么炸的)。
  551. const args = { app_ref: binding.appRef, include_screenshot: includeScreenshot };
  552. // 不变量:delta 只在基线是模型**看过**的树时才允许。
  553. //
  554. // Bug 根因(2026-09-13 真机,会话 sess_04f97297):Helper 的 diff 基线是
  555. // `snapshotCache.get(pid, window)` —— "该 pid+窗口的上一次 capture",不管发起者是谁、
  556. // 模型有没有看见。而 getApp() 绑定时会做一次**全量但不展示**的观察(身份解析、窗口校验、
  557. // 索引基线都要它),那次 capture 就成了基线。于是模型第一次 getAXState() 是对着一棵它
  558. // 从未见过的树做增量:飞书 930 个元素只吐出 8 行 AXMenuItem enabled 抖动,模型只能
  559. // 每次都显式传 disableDiffing 拿整树。node_repl 每个 cell 都是全新 Worker、每个 cell
  560. // 都要重新 getApp,所以这不是"首次观察"的个例,而是**每个 cell 都发生**。
  561. //
  562. // 只截图的观察同样移动了 Helper 的基线却不给树文本,所以它把 treeSeen 清掉 ——
  563. // 规则是「只截图观察之后,再依赖无障碍索引前必须先拿整树」,这里由 SDK 强制执行而非靠模型记住。
  564. if (yieldsTree === true && binding.treeSeen !== true) args.disable_diffing = true;
  565. if (options?.disableDiffing === true) args.disable_diffing = true;
  566. // yieldsTree=false(getScreenshot)不给树文本 —— 上面 binding.treeSeen 的注释里本来就写着
  567. // 「也不能把自己算成基线」。同一个道理对 producer 侧的位移台账成立:没展示给模型的树
  568. // 不能被算作「模型看到过的」,否则索引位移校验变成当前树跟当前树自比(2026-09-15 探针实测)。
  569. if (yieldsTree !== true) args.tree_shown_to_model = false;
  570. const result = await call("get_app_state", args, options);
  571. assertOk("get_app_state", result);
  572. const state = appStateOf("get_app_state", result);
  573. binding.stateId = state.state_id;
  574. binding.treeSeen = yieldsTree === true;
  575. const frameId = frameIdOf(result);
  576. if (typeof frameId === "string") binding.frameId = frameId;
  577. return { state, result };
  578. };
  579. const act = async (methodName, args) => {
  580. const result = await call(methodName, args);
  581. assertOk(methodName, result);
  582. // 这里原先动作后无条件 `binding.stateId = undefined`,逼下一次索引解析先重新观察。
  583. //
  584. // 为什么去掉(2026-09-12):
  585. // 1. 与我们自己的文档打架。当时参考文档的动作示例就是 click(42) 紧跟 setValue(42),
  586. // 而这条守卫让那种写法必然失败。真机上模型正是照文档写 click(9); setValue(9, ...),
  587. // 然后被拒,白烧两个 cell(一个重新观察、一个重做)。
  588. // 2. 模型面不需要新鲜度凭证:set_value({app, elementIndex, value}) 不带
  589. // stateId/stale/generation 之类的字段;失效应由持有原生元素的一侧被动判定 ——
  590. // 先尝试按特征重取元素,只有重取歧义/失败才报错。
  591. // 3. 这条守卫没有信息支撑:SDK 只知道"发生过动作",不知道 UI 是否变化、也不知道那个
  592. // 元素还在不在。真正知道的是 Helper —— 索引在观察时就已冻结成 native token,
  593. // 元素消失时它本来就 fail-closed。
  594. //
  595. // 所以保留冻结映射 + Helper 侧校验,不再在客户端提前否决。
  596. };
  597. return {
  598. async getAXState(options) {
  599. const { state, result } = await observe(options, false, true);
  600. // producer 的告知性块(effect_evidence / screenshot_blank)必须跟着树一起走,
  601. // 否则这条链路会把它们丢光 —— 见 advisoryTextOf 的根因注释。
  602. const text = `${state.text}${advisoryTextOf(result, state.text)}`;
  603. emitText(globals, text, options);
  604. return text;
  605. },
  606. async getScreenshot(options) {
  607. // yieldsTree=false:只截图不给树文本,所以它不强制整树,也不能把自己算成基线。
  608. const { state, result } = await observe(options, true, false);
  609. const bytes = imageBytesOf(result);
  610. if (!bytes) {
  611. throw new ComputerUseError(
  612. // 措辞纪律(2026-09-11 真机):这里过去写「raise the window and retry」,
  613. // 那是直接教模型抢用户焦点 —— 后台截图本来就能拿到(负坐标副屏窗口实测可用)。
  614. //
  615. // 而真正常见的成因是应用处于 hidden(⌘H):macOS 不渲染隐藏窗口,Helper 的前后
  616. // surface 指纹必然不一致,栅格 fail-closed。此时重试永远不会成功,模型如果只看到
  617. // 一句无信息的 "Screenshot unavailable" 就会绕圈并升级(历史上升级成抢焦点,
  618. // 后来升级成 request_access + shell 排查)。所以把 producer 给出的原因带上,
  619. // 并指回真正可走的 AX 路径 —— 隐藏窗口的 accessibility 完全不受影响。
  620. `Screenshot unavailable for ${binding.label}` +
  621. (state.non_actionable_reason ? ` (${state.non_actionable_reason})` : "") +
  622. (state.screenshot_blank ? " (the captured raster was blank)" : "") +
  623. ". The accessibility tree still works on a hidden or unrendered window: use " +
  624. "getAXState() and act on element indices. Do not activate the app; ask the user " +
  625. "to unhide the window if pixels are genuinely required.",
  626. { code: "ELEMENT_UNAVAILABLE", details: { app: binding.label } },
  627. );
  628. }
  629. return bytes;
  630. },
  631. async getAXStateAndScreenshot(options) {
  632. const { state, result } = await observe(options, true, true);
  633. const screenshot = imageBytesOf(result);
  634. // 静默丢图是本轮最后一条同类缺陷(过去 screenshot===null 时直接 return {state},
  635. // 一句话不给)。真机上模型正是从"没收到图"推断出「截图没有
  636. // 回传(窗口在副显示器上,坐标为负)」,然后去抢用户焦点——它得到的信息量是零,
  637. // 所以只能猜。请求了像素却没拿到,必须说清为什么、以及重试有没有用。
  638. const note =
  639. screenshot || !state.non_actionable_reason
  640. ? ""
  641. : `\n[screenshot unavailable: ${state.non_actionable_reason}]` +
  642. " A hidden or minimized window produces this persistently, so re-observing will not" +
  643. " help. The accessibility tree above is complete — act on element indices. Do not" +
  644. " activate the app.";
  645. const text = `${state.text}${advisoryTextOf(result, state.text)}`;
  646. emitText(globals, `${text}${note}`, options);
  647. return screenshot ? { state: text, screenshot } : { state: text };
  648. },
  649. async paste(text, options) {
  650. if (typeof text !== "string") {
  651. throw new ComputerUseError("paste requires text", { code: "INTERNAL" });
  652. }
  653. await act("paste", {
  654. app_ref: binding.appRef,
  655. text,
  656. format: options?.format ?? "text",
  657. });
  658. },
  659. async click(target, options) {
  660. const bound = bindTarget(binding, target, "click");
  661. const button = options?.mouseButton ? MOUSE_BUTTONS[options.mouseButton] : "left";
  662. if (!button) {
  663. throw new ComputerUseError(
  664. `click mouseButton must be left, right or middle (got ${options.mouseButton})`,
  665. { code: "INTERNAL" },
  666. );
  667. }
  668. await act("left_click", {
  669. target: bound,
  670. // 索引作用域:元素目标不再带 state_id,app_ref 说明"按哪个 app 的最新观察解析"。
  671. // 少了它,多 app 会话里的索引会退到"全局最近一次观察",可能属于另一个 app。
  672. app_ref: binding.appRef,
  673. mouse_button: button,
  674. click_count: options?.clickCount ?? 1,
  675. ...(options?.modifiers ? { modifiers: options.modifiers } : {}),
  676. ...(options?.strategy ? { strategy: options.strategy } : {}),
  677. });
  678. },
  679. async drag(from, to, options) {
  680. await act("left_click_drag", {
  681. from_target: bindTarget(binding, from, "drag from"),
  682. to: bindTarget(binding, to, "drag to"),
  683. app_ref: binding.appRef,
  684. ...(options?.modifiers ? { modifiers: options.modifiers } : {}),
  685. // Bug 原因(2026-10-27):文档 DragOptions 声明了 strategy,broker 的 drag
  686. // handler 也早已按 strategy==="event" 跳过后台中间级走前台 SendInput,但
  687. // 此前 SDK 只透传 modifiers —— 调用方显式选 event 被静默吞成 auto,前台
  688. // 拖拽从 SDK 层不可达。与 click/pressKey/scroll 同形透传。
  689. ...(options?.strategy ? { strategy: options.strategy } : {}),
  690. });
  691. },
  692. async pressKey(key, options) {
  693. if (typeof key !== "string" || !key.trim()) {
  694. throw new ComputerUseError("pressKey requires a key or chord", { code: "INTERNAL" });
  695. }
  696. await act("key", {
  697. text: normalizeKeyChord(key, ctx.platform),
  698. app_ref: binding.appRef,
  699. ...(options?.holdSeconds !== undefined ? { hold_seconds: options.holdSeconds } : {}),
  700. ...(options?.strategy ? { strategy: options.strategy } : {}),
  701. });
  702. },
  703. async scroll(target, direction, pages, options) {
  704. const dir = typeof direction === "string" ? direction.trim().toLowerCase() : "";
  705. if (!DIRECTIONS.has(dir)) {
  706. throw new ComputerUseError(
  707. `scroll direction must be up, down, left or right (got ${direction})`,
  708. { code: "INTERNAL" },
  709. );
  710. }
  711. await act("scroll", {
  712. target: bindTarget(binding, target, "scroll"),
  713. app_ref: binding.appRef,
  714. scroll_direction: LONG_DIRECTION[dir] ?? dir,
  715. scroll_amount: pages === undefined ? 1 : pages,
  716. ...(options?.strategy ? { strategy: options.strategy } : {}),
  717. });
  718. },
  719. async selectText(elementIndex, text, options) {
  720. const bound = bindTarget(binding, elementIndex, "selectText");
  721. // 签名按内容匹配(传要选中的文本)。range 由 SDK 在**已观察到的元素 value** 上本地算出,
  722. // 不需要额外的 broker 往返:value 就在上一次 getAXState 的结构化结果里。
  723. const range = resolveTextRange(binding, elementIndex, text, options);
  724. await act("select_text", { target: bound, app_ref: binding.appRef, text_range: range });
  725. },
  726. async setValue(elementIndex, value) {
  727. if (typeof value !== "string") {
  728. throw new ComputerUseError("setValue requires a string value", { code: "INTERNAL" });
  729. }
  730. await act("set_value", {
  731. target: bindTarget(binding, elementIndex, "setValue"),
  732. app_ref: binding.appRef,
  733. value,
  734. });
  735. },
  736. async typeText(text) {
  737. if (typeof text !== "string") {
  738. throw new ComputerUseError("typeText requires text", { code: "INTERNAL" });
  739. }
  740. await act("type", { text, app_ref: binding.appRef });
  741. },
  742. async performSecondaryAction(elementIndex, action) {
  743. if (typeof action !== "string" || !action.trim()) {
  744. throw new ComputerUseError(
  745. "performSecondaryAction requires an action advertised by the element; do not guess one",
  746. { code: "ACTION_UNAVAILABLE" },
  747. );
  748. }
  749. await act("perform_action", {
  750. target: bindTarget(binding, elementIndex, "performSecondaryAction"),
  751. app_ref: binding.appRef,
  752. action,
  753. });
  754. },
  755. };
  756. }
  757. /**
  758. * 按内容定位 [start, length]。
  759. *
  760. * `prefix` / `suffix` 用来消歧重复匹配;`selectionType` 把选区折叠成光标位置。
  761. * 匹配不唯一时抛 NOT_SELECTABLE 并报候选数 —— 静默取第一个会让模型在错的位置编辑。
  762. */
  763. function resolveTextRange(binding, elementIndex, text, options) {
  764. if (text && typeof text === "object" && Number.isInteger(text.start)) {
  765. return [text.start, text.length ?? 0];
  766. }
  767. if (typeof text !== "string" || text.length === 0) {
  768. throw new ComputerUseError("selectText requires the text to locate", { code: "INTERNAL" });
  769. }
  770. const element = binding.elements?.[elementIndex];
  771. const value = typeof element?.value === "string" ? element.value : undefined;
  772. if (value === undefined) {
  773. throw new ComputerUseError(
  774. `selectText cannot locate text in element ${elementIndex}: the latest accessibility state exposed no value for it. Observe again, or use a range { start, length }.`,
  775. { code: "NOT_SELECTABLE", details: { elementIndex } },
  776. );
  777. }
  778. const needle = `${options?.prefix ?? ""}${text}${options?.suffix ?? ""}`;
  779. const hits = [];
  780. for (let at = value.indexOf(needle); at !== -1; at = value.indexOf(needle, at + 1)) {
  781. hits.push(at);
  782. }
  783. if (hits.length === 0) {
  784. throw new ComputerUseError(
  785. `selectText found no occurrence of the requested text in element ${elementIndex}`,
  786. { code: "NOT_SELECTABLE", details: { elementIndex } },
  787. );
  788. }
  789. if (hits.length > 1) {
  790. throw new ComputerUseError(
  791. `selectText matched ${hits.length} occurrences in element ${elementIndex}; disambiguate with prefix/suffix`,
  792. { code: "NOT_SELECTABLE", details: { elementIndex, matches: hits.length } },
  793. );
  794. }
  795. const start = hits[0] + (options?.prefix?.length ?? 0);
  796. const selectionType = options?.selectionType ?? "text";
  797. if (selectionType === "cursor_before") return [start, 0];
  798. if (selectionType === "cursor_after") return [start + text.length, 0];
  799. return [start, text.length];
  800. }
  801. /**
  802. * 键位别名规范化:接受 xdotool / X keysym 写法(模型先验多是这种写法),
  803. * 输出 ZCode 的内部 token 集合。只做输入侧兼容,不改跨平台修饰键规则
  804. * (macOS cmd,Linux / Windows ctrl)。
  805. */
  806. const KEY_ALIASES = Object.freeze({
  807. return: "return", enter: "return", kp_enter: "return",
  808. control_l: "ctrl", control_r: "ctrl", control: "ctrl", ctrl: "ctrl",
  809. alt_l: "alt", alt_r: "alt", meta_l: "alt", alt: "alt",
  810. shift_l: "shift", shift_r: "shift", shift: "shift",
  811. escape: "esc", esc: "esc",
  812. prior: "pageup", next: "pagedown",
  813. // 曾有 greater: ">"——输出 ">" 从未通过工具层白名单(S2 前后均如此),是端到端
  814. // 死路径,且会让组合契约测试(sdk-key-chord-contract.node-test.mjs)被迫开
  815. // 豁免口,故移除。需要输出 ">" 时应先给工具层 canonical 集补该 token。
  816. period: ".", comma: ",", slash: "/", minus: "-", equal: "=",
  817. });
  818. function normalizeKeyChord(chord, platform) {
  819. return chord
  820. .split("+")
  821. .map((raw) => {
  822. const token = raw.trim();
  823. const lower = token.toLowerCase();
  824. if (lower === "super_l" || lower === "super_r" || lower === "super") {
  825. return platform === "darwin" ? "cmd" : platform === "win32" ? "win" : "super";
  826. }
  827. return KEY_ALIASES[lower] ?? token;
  828. })
  829. .filter(Boolean)
  830. .join("+");
  831. }
  832. // ─────────────────────────────────────────────────────────── 装配
  833. export async function setupComputerUseRuntime({ globals }) {
  834. const bridge = globals[BRIDGE_SYMBOL];
  835. if (!bridge || typeof bridge !== "object" || typeof bridge.call !== "function") {
  836. throw new Error(
  837. "Computer Use runtime bridge is unavailable. Use Computer Use from a ZCode desktop or shared-host session.",
  838. );
  839. }
  840. bridge.assertAvailable?.();
  841. const platform = globals.process?.platform ?? process.platform;
  842. const call = async (methodName, args, options) => {
  843. // not-ready 是 Helper 冷启动的正常一步,不是失败:payload 明确要求"稍等后重试同一
  844. // 调用"。只在 retryable 为真时重试 —— possibly_sent 的动作绝不重放(见常量注释)。
  845. for (let attempt = 0; ; attempt += 1) {
  846. bridge.assertAvailable?.();
  847. const result = await bridge.call(methodName, args ?? {});
  848. const notReady = notReadyEnvelopeOf(result);
  849. if (!notReady) {
  850. // 展示由 SDK 的 emit 控制,不能用 producer 的索引记账标志推断。
  851. projectToHost(globals, result, options);
  852. return result;
  853. }
  854. if (notReady.retryable !== true || attempt >= NOT_READY_MAX_ATTEMPTS - 1) {
  855. // 不可重试,或已等到上限:把 producer 自己的话和 reasonCode 交给模型,
  856. // 不要替换成通用句子(那正是今天反复出问题的地方)。
  857. throw new ComputerUseError(
  858. `${methodName}: ${notReady.message ?? "Computer Use is not ready."}`,
  859. {
  860. code: notReady.retryable === true ? "TIMEOUT" : "CONTROLLER_BUSY",
  861. details: {
  862. method: methodName,
  863. reasonCode: notReady.reasonCode,
  864. retryable: notReady.retryable === true,
  865. attempts: attempt + 1,
  866. },
  867. },
  868. );
  869. }
  870. await sleep(NOT_READY_BACKOFF_MS[Math.min(attempt, NOT_READY_BACKOFF_MS.length - 1)]);
  871. }
  872. };
  873. const ctx = { call, globals, platform };
  874. /** 每个绑定目标在 Worker 内的视图;跨 cell 的真身由 shared host 的 session 持有。 */
  875. const createBinding = (label, appRef) => ({
  876. label,
  877. appRef,
  878. stateId: undefined,
  879. frameId: undefined,
  880. elements: undefined,
  881. // delta 的基线是否是模型**看过**的那棵树。见 createTarget 的 observe()。
  882. treeSeen: false,
  883. });
  884. const bindApp = async (target, windowId) => {
  885. let objectRef;
  886. let label = typeof target === "string" ? target : "";
  887. // 也接受工具层那种 app_ref 对象。SKILL 把绑定面和逃逸口并排放着,模型学到
  888. // `{bundle_id: ...}` 之后很自然会把它传给 getApp(2026-09-11 真机就是这样,
  889. // 撞了 "getApp requires an app display name or bundle id")。对象形态没有歧义,
  890. // 直接透传比让它退回去改写更省一次往返。
  891. if (target && typeof target === "object" && !Array.isArray(target)) {
  892. const direct = windowId === undefined ? { ...target } : { ...target, window_id: windowId };
  893. if (
  894. typeof direct.name !== "string" &&
  895. typeof direct.bundle_id !== "string" &&
  896. typeof direct.pid !== "number"
  897. ) {
  898. throw new ComputerUseError(
  899. "getApp needs an app display name, a bundle id, or {name|bundle_id|pid}",
  900. { code: "INVALID_APP" },
  901. );
  902. }
  903. objectRef = direct;
  904. label = String(direct.name ?? direct.bundle_id ?? direct.pid);
  905. } else if (typeof target !== "string" || !target.trim()) {
  906. throw new ComputerUseError(
  907. "getApp needs an app display name, a bundle id, or {name|bundle_id|pid}",
  908. { code: "INVALID_APP" },
  909. );
  910. }
  911. let appRef = objectRef ?? appRefFor(target, windowId);
  912. const binding = createBinding(label, appRef);
  913. const app = createTarget(ctx, binding);
  914. // 绑定时只解析身份,观察结果留在宿主通道。
  915. let result = await call("get_app_state", {
  916. app_ref: appRef,
  917. include_screenshot: false,
  918. disable_diffing: true,
  919. // 这棵树不展示给模型(下面 981 行那段注释说明为什么),所以它**不能**被算作
  920. // 「模型看到过的树」。不标的后果(2026-09-15 探针实测):索引位移校验拿当前树
  921. // 跟当前树自比,必然一致,静默点错元素的保护完全失效。
  922. tree_shown_to_model: false,
  923. }, { emit: false });
  924. if (isAppNotFound(result) && objectRef === undefined) {
  925. // 只有字符串需要猜字段;对象形态是显式的,猜错的是调用方而不是我们。
  926. const alternate = alternateAppRef(target, windowId);
  927. if (alternate) {
  928. appRef = alternate;
  929. binding.appRef = alternate;
  930. result = await call("get_app_state", {
  931. app_ref: alternate,
  932. include_screenshot: false,
  933. disable_diffing: true,
  934. tree_shown_to_model: false,
  935. }, { emit: false });
  936. }
  937. }
  938. assertOk("get_app_state", result);
  939. const state = appStateOf("get_app_state", result);
  940. binding.stateId = state.state_id;
  941. binding.elements = state.elements;
  942. // 绑定成功后把 app_ref 收敛成**解析出来的身份**,不再继续拿模型给的原始字符串。
  943. //
  944. // Bug 原因(2026-09-12 真机):模型写 `getApp("地图")`(Maps 的中文本地化名)。观察成功了
  945. // —— capture_app 按名字找不到活动应用会走透明拉起分支,那里的 LaunchServices 查表能把
  946. // "地图" 解成 com.apple.Maps。但同一个 cell 里紧接着的 pressKey 失败:
  947. // press_key_to_app: app_ref did not resolve to a unique live application
  948. // 因为活动应用列表里 Maps 的 name 字段是英文 "Maps",{name:"地图"} 匹配零行,而键盘路径
  949. // 只按活动应用严格匹配。观察路径宽容、输入路径严格,两边就此分叉。
  950. //
  951. // 观察结果里本来就带着已解析的身份(state.app.pid / bundle_id),此前只是没用。收敛之后
  952. // 本地化名、模糊名、大小写差异都只在第一跳解决一次,后续所有路径拿到的都是无歧义身份。
  953. // 两个字段都给:pid 精确(同 cell 内进程不会换),bundle_id 供 broker 侧交叉校验身份。
  954. // window_id 若已绑定必须保留 —— 它决定 macOS 后台键盘的 synthetic-focus session。
  955. const resolvedPid = typeof state.app?.pid === "number" ? state.app.pid : undefined;
  956. const resolvedBundleId =
  957. typeof state.app?.bundle_id === "string" && state.app.bundle_id.trim()
  958. ? state.app.bundle_id
  959. : undefined;
  960. if (resolvedPid !== undefined || resolvedBundleId !== undefined) {
  961. const boundWindowId =
  962. typeof appRef?.window_id === "number" ? { window_id: appRef.window_id } : {};
  963. appRef = {
  964. ...(resolvedPid !== undefined ? { pid: resolvedPid } : {}),
  965. ...(resolvedBundleId !== undefined ? { bundle_id: resolvedBundleId } : {}),
  966. ...boundWindowId,
  967. };
  968. binding.appRef = appRef;
  969. }
  970. // 判据取自**最终的 appRef**,不是位置参数 windowId。
  971. //
  972. // Bug 根因(2026-09-17 复查):这里原先写 `windowId !== undefined`,只认
  973. // getWindow(target, id) 那种位置参数形态。而 `getApp({pid, window_id})` 也能钉窗口
  974. // (objectRef 直接透传,见上面的 direct),走那条路时 windowId 恒为 undefined,
  975. // 于是这道 fail-closed 被整个跳过:Helper 静默降级到最前窗口、只回一句 note,
  976. // 模型在错窗口上继续操作。两种钉法必须同一套校验。
  977. const boundWindow = typeof appRef?.window_id === "number" ? appRef.window_id : windowId;
  978. if (boundWindow !== undefined && state.window?.window_id_fallback === true) {
  979. // 现状会静默降级到最前窗口并只回一句 note,模型极易读漏后在错窗口上继续操作。
  980. throw new ComputerUseError(
  981. `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.`,
  982. { code: "STALE_STATE", details: { app: label, windowId: boundWindow } },
  983. );
  984. }
  985. // getApp 不展示状态(2026-09-13)。它仍然做一次观察 —— 身份解析、窗口校验与索引解析
  986. // 基线都要它 —— 但不再把那棵树写进输出。
  987. //
  988. // 根因:「getApp 自动输出结果」只在 kernel **持久**时划算 —— `const app = await
  989. // cua.getApp(...)` 跨 cell 存活,一个会话只调一次 getApp,那次展示确实省掉一次单独观察。
  990. // ZCode 的 node_repl 每个 cell 都是全新 Worker,绑定不跨 cell,于是**每个 cell 都要重新
  991. // getApp**,那次"顺便展示"就从"一次性省一个往返"变成了"每个 cell 都多一棵注定作废的树"。
  992. //
  993. // 代价不只是 token。真机实测(会话 sess_f14c07fd):8 个 cell 里 5 个吐两棵树,
  994. // 36% 的工具输出(43902/120854 字符)是被同 cell 后续观察直接覆盖的前序树;更糟的是
  995. // 同一个 `[35]` 在一个 cell 的输出里指向两个不同元素(先出现的 79 元素树里是
  996. // `genericelement Yanbao Maquanying Homeland`,后出现的 105 元素树里才是
  997. // `button Tsinghua University`),而**只有最后那棵**是索引解析真正会用的,输出里却
  998. // 没有任何标记说明这件事。读错就点到无关元素,且不会报错 —— 那个索引在旧树里合法。
  999. //
  1000. // 想看状态就显式 getAXState(),与其它观察方法一致。
  1001. //
  1002. // 结构化元素视图。Target 的公开观察方法只给字符串,但模型写的是代码,单 cell 内
  1003. // 「观察 → 找元素 → 动作」能省一次往返;树被按优先级裁剪(targeting/format.ts 的
  1004. // `indices are sparse` 注记)时,它还是模型拿到隐藏元素索引的唯一途径。因此它已被
  1005. // 提为**文档化成员**(SKILL 的 Keyboard 段 + docs/computer-use.md 的 API 段),
  1006. // 保持 enumerable:false 只是为了不进 Object.keys —— R2 的「Target 附加成员为 0」
  1007. // 说的是冻结的**可枚举**公开面,不是禁止具名逃逸口。
  1008. Object.defineProperty(app, "elements", {
  1009. enumerable: false,
  1010. value: async () => {
  1011. // 与 getScreenshot 不同档(2026-10-25 修正):返回值(含 index 的元素表)
  1012. // 回给了模型所写的 JS——els[3].index 直接进 click 参数,这张表就是模型
  1013. // 选目标的信息来源,构成「模型可见」。2026-09-16 评审按「不 emit」把它
  1014. // 与 bindApp/getScreenshot 一刀切标 false,掩盖了本质差异(那两条的
  1015. // 返回值不含树);false 的真实后果是位移台账只剩更旧的树,模型用
  1016. // elements() 的新鲜索引点击时被拿旧树对照新树,element_index_shifted
  1017. // 假阳性(真位移同时拦不住)。记账后 producer 台账与模型实际所见一致。
  1018. //
  1019. // diff 基线问题不受影响:binding.treeSeen 仍清空(treeSeen 管的是 emit
  1020. // 展示面的整树承诺,与记账正交),下一次 getAXState 照旧强制整树。
  1021. const fresh = appStateOf(
  1022. "get_app_state",
  1023. await call("get_app_state", { app_ref: appRef, tree_shown_to_model: true }, { emit: false }),
  1024. );
  1025. binding.stateId = fresh.state_id;
  1026. binding.elements = fresh.elements;
  1027. binding.treeSeen = false;
  1028. return fresh.elements;
  1029. },
  1030. });
  1031. return app;
  1032. };
  1033. const inventory = async (options) => {
  1034. const result = await call("list_apps", {}, options);
  1035. assertOk("list_apps", result);
  1036. const apps = [];
  1037. for (const text of textBlocks(result)) {
  1038. const parsed = parseJsonValue(text);
  1039. if (Array.isArray(parsed?.apps)) apps.push(...parsed.apps);
  1040. else if (Array.isArray(parsed)) apps.push(...parsed);
  1041. }
  1042. const state = { apps };
  1043. emitText(globals, JSON.stringify(state, null, 2), options);
  1044. return state;
  1045. };
  1046. // `cua.computer` —— 平台特定逃逸口,暴露额外的平台相关 computer API。
  1047. // 内容是存活的 14 个工具,入参 schema 逐字保留。
  1048. //
  1049. // 返回值**解封**(2026-09-16):此前原样返回 MCP envelope,于是模型拿到的是
  1050. // `{content:[{type:"text",text:"[...]"}],_meta:{…}}`,还得自己 `JSON.parse(r.content[0].text)`。
  1051. // 真机代价(list_windows):4964 字符里有用载荷只 1723(35%),另外 65% 是信封与
  1052. // `_meta` 里的 app 图标 base64(上限 24KiB ⇒ base64 最坏 ~32KiB)。而 `_meta` 按设计
  1053. // 就是**宿主专用**的(target-app-display 设计文档:host-only、"stripped before handlers
  1054. // observe responses"),projectToHost 已经单独把它送给宿主展示 —— 所以泄漏给模型是
  1055. // 契约违规,不是契约选择。连设计文档自己的示例都写成 `wins[1].window_id`(把它当裸数组),
  1056. // 可见"保留信封"从来不是有人依赖的行为;全仓 grep 也确认零消费者。
  1057. const unwrapEnvelope = (result) => {
  1058. if (result === null || typeof result !== "object") return result;
  1059. if (!Array.isArray(result.content)) return result;
  1060. // 新增的紧凑元数据副本已由宿主展示,解封时排除它以保持单载荷调用的返回类型。
  1061. const metadataText =
  1062. result.structuredContent && JSON.stringify(forDisplay(result.structuredContent));
  1063. const content =
  1064. result.content.length > 1 && typeof metadataText === "string"
  1065. ? result.content.filter((block) => block?.type !== "text" || block.text !== metadataText)
  1066. : result.content;
  1067. const textBlocks = content.filter(
  1068. (block) => block && block.type === "text" && typeof block.text === "string",
  1069. );
  1070. // 只在"单一 text block"这种明确形态上解封;多块 / 图像等一律原样返回,
  1071. // 避免把一个我们不认识的形状猜成裸值。
  1072. if (textBlocks.length !== 1 || content.length !== 1) return result;
  1073. const text = textBlocks[0].text;
  1074. try {
  1075. return JSON.parse(text);
  1076. } catch {
  1077. return text;
  1078. }
  1079. };
  1080. const computer = Object.create(null);
  1081. Object.defineProperty(computer, "target", {
  1082. enumerable: true,
  1083. value: platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux",
  1084. });
  1085. const excluded = new Set(PLATFORM_EXCLUDED_METHODS[platform] ?? []);
  1086. for (const methodName of COMPUTER_METHOD_NAMES) {
  1087. if (excluded.has(methodName)) continue;
  1088. Object.defineProperty(computer, methodName, {
  1089. enumerable: true,
  1090. value: async (args = {}) => unwrapEnvelope(await call(methodName, args)),
  1091. });
  1092. }
  1093. const cua = {
  1094. async getState(options) {
  1095. return await inventory(options);
  1096. },
  1097. async getApp(target) {
  1098. return await bindApp(target);
  1099. },
  1100. async listApps(options) {
  1101. return (await inventory(options)).apps;
  1102. },
  1103. computer: Object.freeze(computer),
  1104. async requestAccess(capabilities) {
  1105. const result = await call("request_access", capabilities ? { capabilities } : {});
  1106. assertOk("request_access", result);
  1107. const texts = textBlocks(result);
  1108. return parseJsonRecord(texts[0]) ?? { ready: true };
  1109. },
  1110. async stop(reason) {
  1111. const result = await call("stop_computer_control", reason ? { reason } : {});
  1112. assertOk("stop_computer_control", result);
  1113. },
  1114. };
  1115. // 未文档化成员:窗口绑定。窗口寻址各平台差异很大(有的平台没有窗口寻址,有的整套
  1116. // 以 Window 对象寻址),ZCode 三平台统一命名,不按平台分裂公开面,
  1117. // 所以窗口寻址留在逃逸口 + 这个未文档化入口。
  1118. Object.defineProperty(cua, "getWindow", {
  1119. enumerable: false,
  1120. value: async (target, windowId) => await bindApp(target, windowId),
  1121. });
  1122. // 入口是 `agent.computerUse`(ZCode 自己的命名空间约定,与 agent.documentation /
  1123. // agent.browsers 并列),不注入裸 `cua` 全局。
  1124. // 平铺的 14 个工具在 `agent.computerUse.computer.*` 下(COMPUTER_METHOD_NAMES)。
  1125. const agent = (globals.agent ??= {});
  1126. agent.computerUse = cua;
  1127. const previousDocumentation = agent.documentation;
  1128. const previousGet =
  1129. previousDocumentation && typeof previousDocumentation.get === "function"
  1130. ? previousDocumentation.get.bind(previousDocumentation)
  1131. : undefined;
  1132. agent.documentation = Object.freeze({
  1133. get: async (name) => {
  1134. // Browser Use 的文档 loader 必须原样转交 —— CUA 只认自己那一个名字。
  1135. if (name !== "computer-use") {
  1136. if (previousGet) return await previousGet(name);
  1137. throw new Error(`Unknown documentation entry: ${name}`);
  1138. }
  1139. if (typeof bridge.documentationRoot !== "string") {
  1140. throw new Error("Computer Use documentation is unavailable");
  1141. }
  1142. return await readFile(join(bridge.documentationRoot, "computer-use.md"), "utf8");
  1143. },
  1144. });
  1145. return cua;
  1146. }
  1147. export { COMPUTER_METHOD_NAMES, PLATFORM_EXCLUDED_METHODS, ComputerUseError, normalizeKeyChord, KEY_ALIASES };