computer-use-client.mjs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. });
  688. },
  689. async pressKey(key, options) {
  690. if (typeof key !== "string" || !key.trim()) {
  691. throw new ComputerUseError("pressKey requires a key or chord", { code: "INTERNAL" });
  692. }
  693. await act("key", {
  694. text: normalizeKeyChord(key, ctx.platform),
  695. app_ref: binding.appRef,
  696. ...(options?.holdSeconds !== undefined ? { hold_seconds: options.holdSeconds } : {}),
  697. ...(options?.strategy ? { strategy: options.strategy } : {}),
  698. });
  699. },
  700. async scroll(target, direction, pages, options) {
  701. const dir = typeof direction === "string" ? direction.trim().toLowerCase() : "";
  702. if (!DIRECTIONS.has(dir)) {
  703. throw new ComputerUseError(
  704. `scroll direction must be up, down, left or right (got ${direction})`,
  705. { code: "INTERNAL" },
  706. );
  707. }
  708. await act("scroll", {
  709. target: bindTarget(binding, target, "scroll"),
  710. app_ref: binding.appRef,
  711. scroll_direction: LONG_DIRECTION[dir] ?? dir,
  712. scroll_amount: pages === undefined ? 1 : pages,
  713. ...(options?.strategy ? { strategy: options.strategy } : {}),
  714. });
  715. },
  716. async selectText(elementIndex, text, options) {
  717. const bound = bindTarget(binding, elementIndex, "selectText");
  718. // 签名按内容匹配(传要选中的文本)。range 由 SDK 在**已观察到的元素 value** 上本地算出,
  719. // 不需要额外的 broker 往返:value 就在上一次 getAXState 的结构化结果里。
  720. const range = resolveTextRange(binding, elementIndex, text, options);
  721. await act("select_text", { target: bound, app_ref: binding.appRef, text_range: range });
  722. },
  723. async setValue(elementIndex, value) {
  724. if (typeof value !== "string") {
  725. throw new ComputerUseError("setValue requires a string value", { code: "INTERNAL" });
  726. }
  727. await act("set_value", {
  728. target: bindTarget(binding, elementIndex, "setValue"),
  729. app_ref: binding.appRef,
  730. value,
  731. });
  732. },
  733. async typeText(text) {
  734. if (typeof text !== "string") {
  735. throw new ComputerUseError("typeText requires text", { code: "INTERNAL" });
  736. }
  737. await act("type", { text, app_ref: binding.appRef });
  738. },
  739. async performSecondaryAction(elementIndex, action) {
  740. if (typeof action !== "string" || !action.trim()) {
  741. throw new ComputerUseError(
  742. "performSecondaryAction requires an action advertised by the element; do not guess one",
  743. { code: "ACTION_UNAVAILABLE" },
  744. );
  745. }
  746. await act("perform_action", {
  747. target: bindTarget(binding, elementIndex, "performSecondaryAction"),
  748. app_ref: binding.appRef,
  749. action,
  750. });
  751. },
  752. };
  753. }
  754. /**
  755. * 按内容定位 [start, length]。
  756. *
  757. * `prefix` / `suffix` 用来消歧重复匹配;`selectionType` 把选区折叠成光标位置。
  758. * 匹配不唯一时抛 NOT_SELECTABLE 并报候选数 —— 静默取第一个会让模型在错的位置编辑。
  759. */
  760. function resolveTextRange(binding, elementIndex, text, options) {
  761. if (text && typeof text === "object" && Number.isInteger(text.start)) {
  762. return [text.start, text.length ?? 0];
  763. }
  764. if (typeof text !== "string" || text.length === 0) {
  765. throw new ComputerUseError("selectText requires the text to locate", { code: "INTERNAL" });
  766. }
  767. const element = binding.elements?.[elementIndex];
  768. const value = typeof element?.value === "string" ? element.value : undefined;
  769. if (value === undefined) {
  770. throw new ComputerUseError(
  771. `selectText cannot locate text in element ${elementIndex}: the latest accessibility state exposed no value for it. Observe again, or use a range { start, length }.`,
  772. { code: "NOT_SELECTABLE", details: { elementIndex } },
  773. );
  774. }
  775. const needle = `${options?.prefix ?? ""}${text}${options?.suffix ?? ""}`;
  776. const hits = [];
  777. for (let at = value.indexOf(needle); at !== -1; at = value.indexOf(needle, at + 1)) {
  778. hits.push(at);
  779. }
  780. if (hits.length === 0) {
  781. throw new ComputerUseError(
  782. `selectText found no occurrence of the requested text in element ${elementIndex}`,
  783. { code: "NOT_SELECTABLE", details: { elementIndex } },
  784. );
  785. }
  786. if (hits.length > 1) {
  787. throw new ComputerUseError(
  788. `selectText matched ${hits.length} occurrences in element ${elementIndex}; disambiguate with prefix/suffix`,
  789. { code: "NOT_SELECTABLE", details: { elementIndex, matches: hits.length } },
  790. );
  791. }
  792. const start = hits[0] + (options?.prefix?.length ?? 0);
  793. const selectionType = options?.selectionType ?? "text";
  794. if (selectionType === "cursor_before") return [start, 0];
  795. if (selectionType === "cursor_after") return [start + text.length, 0];
  796. return [start, text.length];
  797. }
  798. /**
  799. * 键位别名规范化:接受 xdotool / X keysym 写法(模型先验多是这种写法),
  800. * 输出 ZCode 的内部 token 集合。只做输入侧兼容,不改跨平台修饰键规则
  801. * (macOS cmd,Linux / Windows ctrl)。
  802. */
  803. const KEY_ALIASES = Object.freeze({
  804. return: "return", enter: "return", kp_enter: "return",
  805. control_l: "ctrl", control_r: "ctrl", control: "ctrl", ctrl: "ctrl",
  806. alt_l: "alt", alt_r: "alt", meta_l: "alt", alt: "alt",
  807. shift_l: "shift", shift_r: "shift", shift: "shift",
  808. escape: "esc", esc: "esc",
  809. prior: "pageup", next: "pagedown",
  810. period: ".", comma: ",", greater: ">", slash: "/", minus: "-", equal: "=",
  811. });
  812. function normalizeKeyChord(chord, platform) {
  813. return chord
  814. .split("+")
  815. .map((raw) => {
  816. const token = raw.trim();
  817. const lower = token.toLowerCase();
  818. if (lower === "super_l" || lower === "super_r" || lower === "super") {
  819. return platform === "darwin" ? "cmd" : platform === "win32" ? "win" : "super";
  820. }
  821. return KEY_ALIASES[lower] ?? token;
  822. })
  823. .filter(Boolean)
  824. .join("+");
  825. }
  826. // ─────────────────────────────────────────────────────────── 装配
  827. export async function setupComputerUseRuntime({ globals }) {
  828. const bridge = globals[BRIDGE_SYMBOL];
  829. if (!bridge || typeof bridge !== "object" || typeof bridge.call !== "function") {
  830. throw new Error(
  831. "Computer Use runtime bridge is unavailable. Use Computer Use from a ZCode desktop or shared-host session.",
  832. );
  833. }
  834. bridge.assertAvailable?.();
  835. const platform = globals.process?.platform ?? process.platform;
  836. const call = async (methodName, args) => {
  837. // not-ready 是 Helper 冷启动的正常一步,不是失败:payload 明确要求"稍等后重试同一
  838. // 调用"。只在 retryable 为真时重试 —— possibly_sent 的动作绝不重放(见常量注释)。
  839. for (let attempt = 0; ; attempt += 1) {
  840. bridge.assertAvailable?.();
  841. const result = await bridge.call(methodName, args ?? {});
  842. const notReady = notReadyEnvelopeOf(result);
  843. if (!notReady) {
  844. projectToHost(globals, result);
  845. return result;
  846. }
  847. if (notReady.retryable !== true || attempt >= NOT_READY_MAX_ATTEMPTS - 1) {
  848. // 不可重试,或已等到上限:把 producer 自己的话和 reasonCode 交给模型,
  849. // 不要替换成通用句子(那正是今天反复出问题的地方)。
  850. throw new ComputerUseError(
  851. `${methodName}: ${notReady.message ?? "Computer Use is not ready."}`,
  852. {
  853. code: notReady.retryable === true ? "TIMEOUT" : "CONTROLLER_BUSY",
  854. details: {
  855. method: methodName,
  856. reasonCode: notReady.reasonCode,
  857. retryable: notReady.retryable === true,
  858. attempts: attempt + 1,
  859. },
  860. },
  861. );
  862. }
  863. await sleep(NOT_READY_BACKOFF_MS[Math.min(attempt, NOT_READY_BACKOFF_MS.length - 1)]);
  864. }
  865. };
  866. const ctx = { call, globals, platform };
  867. /** 每个绑定目标在 Worker 内的视图;跨 cell 的真身由 shared host 的 session 持有。 */
  868. const createBinding = (label, appRef) => ({
  869. label,
  870. appRef,
  871. stateId: undefined,
  872. frameId: undefined,
  873. elements: undefined,
  874. // delta 的基线是否是模型**看过**的那棵树。见 createTarget 的 observe()。
  875. treeSeen: false,
  876. });
  877. const bindApp = async (target, windowId) => {
  878. let objectRef;
  879. let label = typeof target === "string" ? target : "";
  880. // 也接受工具层那种 app_ref 对象。SKILL 把绑定面和逃逸口并排放着,模型学到
  881. // `{bundle_id: ...}` 之后很自然会把它传给 getApp(2026-09-11 真机就是这样,
  882. // 撞了 "getApp requires an app display name or bundle id")。对象形态没有歧义,
  883. // 直接透传比让它退回去改写更省一次往返。
  884. if (target && typeof target === "object" && !Array.isArray(target)) {
  885. const direct = windowId === undefined ? { ...target } : { ...target, window_id: windowId };
  886. if (
  887. typeof direct.name !== "string" &&
  888. typeof direct.bundle_id !== "string" &&
  889. typeof direct.pid !== "number"
  890. ) {
  891. throw new ComputerUseError(
  892. "getApp needs an app display name, a bundle id, or {name|bundle_id|pid}",
  893. { code: "INVALID_APP" },
  894. );
  895. }
  896. objectRef = direct;
  897. label = String(direct.name ?? direct.bundle_id ?? direct.pid);
  898. } else if (typeof target !== "string" || !target.trim()) {
  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. let appRef = objectRef ?? appRefFor(target, windowId);
  905. const binding = createBinding(label, appRef);
  906. const app = createTarget(ctx, binding);
  907. // 绑定即观察:返回前展示该 app 的**全量** AX 树。
  908. let result = await call("get_app_state", {
  909. app_ref: appRef,
  910. include_screenshot: false,
  911. disable_diffing: true,
  912. // 这棵树不展示给模型(下面 981 行那段注释说明为什么),所以它**不能**被算作
  913. // 「模型看到过的树」。不标的后果(2026-09-15 探针实测):索引位移校验拿当前树
  914. // 跟当前树自比,必然一致,静默点错元素的保护完全失效。
  915. tree_shown_to_model: false,
  916. });
  917. if (isAppNotFound(result) && objectRef === undefined) {
  918. // 只有字符串需要猜字段;对象形态是显式的,猜错的是调用方而不是我们。
  919. const alternate = alternateAppRef(target, windowId);
  920. if (alternate) {
  921. appRef = alternate;
  922. binding.appRef = alternate;
  923. result = await call("get_app_state", {
  924. app_ref: alternate,
  925. include_screenshot: false,
  926. disable_diffing: true,
  927. tree_shown_to_model: false,
  928. });
  929. }
  930. }
  931. assertOk("get_app_state", result);
  932. const state = appStateOf("get_app_state", result);
  933. binding.stateId = state.state_id;
  934. binding.elements = state.elements;
  935. // 绑定成功后把 app_ref 收敛成**解析出来的身份**,不再继续拿模型给的原始字符串。
  936. //
  937. // Bug 原因(2026-09-12 真机):模型写 `getApp("地图")`(Maps 的中文本地化名)。观察成功了
  938. // —— capture_app 按名字找不到活动应用会走透明拉起分支,那里的 LaunchServices 查表能把
  939. // "地图" 解成 com.apple.Maps。但同一个 cell 里紧接着的 pressKey 失败:
  940. // press_key_to_app: app_ref did not resolve to a unique live application
  941. // 因为活动应用列表里 Maps 的 name 字段是英文 "Maps",{name:"地图"} 匹配零行,而键盘路径
  942. // 只按活动应用严格匹配。观察路径宽容、输入路径严格,两边就此分叉。
  943. //
  944. // 观察结果里本来就带着已解析的身份(state.app.pid / bundle_id),此前只是没用。收敛之后
  945. // 本地化名、模糊名、大小写差异都只在第一跳解决一次,后续所有路径拿到的都是无歧义身份。
  946. // 两个字段都给:pid 精确(同 cell 内进程不会换),bundle_id 供 broker 侧交叉校验身份。
  947. // window_id 若已绑定必须保留 —— 它决定 macOS 后台键盘的 synthetic-focus session。
  948. const resolvedPid = typeof state.app?.pid === "number" ? state.app.pid : undefined;
  949. const resolvedBundleId =
  950. typeof state.app?.bundle_id === "string" && state.app.bundle_id.trim()
  951. ? state.app.bundle_id
  952. : undefined;
  953. if (resolvedPid !== undefined || resolvedBundleId !== undefined) {
  954. const boundWindowId =
  955. typeof appRef?.window_id === "number" ? { window_id: appRef.window_id } : {};
  956. appRef = {
  957. ...(resolvedPid !== undefined ? { pid: resolvedPid } : {}),
  958. ...(resolvedBundleId !== undefined ? { bundle_id: resolvedBundleId } : {}),
  959. ...boundWindowId,
  960. };
  961. binding.appRef = appRef;
  962. }
  963. // 判据取自**最终的 appRef**,不是位置参数 windowId。
  964. //
  965. // Bug 根因(2026-09-17 复查):这里原先写 `windowId !== undefined`,只认
  966. // getWindow(target, id) 那种位置参数形态。而 `getApp({pid, window_id})` 也能钉窗口
  967. // (objectRef 直接透传,见上面的 direct),走那条路时 windowId 恒为 undefined,
  968. // 于是这道 fail-closed 被整个跳过:Helper 静默降级到最前窗口、只回一句 note,
  969. // 模型在错窗口上继续操作。两种钉法必须同一套校验。
  970. const boundWindow = typeof appRef?.window_id === "number" ? appRef.window_id : windowId;
  971. if (boundWindow !== undefined && state.window?.window_id_fallback === true) {
  972. // 现状会静默降级到最前窗口并只回一句 note,模型极易读漏后在错窗口上继续操作。
  973. throw new ComputerUseError(
  974. `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.`,
  975. { code: "STALE_STATE", details: { app: label, windowId: boundWindow } },
  976. );
  977. }
  978. // getApp 不展示状态(2026-09-13)。它仍然做一次观察 —— 身份解析、窗口校验与索引解析
  979. // 基线都要它 —— 但不再把那棵树写进输出。
  980. //
  981. // 根因:「getApp 自动输出结果」只在 kernel **持久**时划算 —— `const app = await
  982. // cua.getApp(...)` 跨 cell 存活,一个会话只调一次 getApp,那次展示确实省掉一次单独观察。
  983. // ZCode 的 node_repl 每个 cell 都是全新 Worker,绑定不跨 cell,于是**每个 cell 都要重新
  984. // getApp**,那次"顺便展示"就从"一次性省一个往返"变成了"每个 cell 都多一棵注定作废的树"。
  985. //
  986. // 代价不只是 token。真机实测(会话 sess_f14c07fd):8 个 cell 里 5 个吐两棵树,
  987. // 36% 的工具输出(43902/120854 字符)是被同 cell 后续观察直接覆盖的前序树;更糟的是
  988. // 同一个 `[35]` 在一个 cell 的输出里指向两个不同元素(先出现的 79 元素树里是
  989. // `genericelement Yanbao Maquanying Homeland`,后出现的 105 元素树里才是
  990. // `button Tsinghua University`),而**只有最后那棵**是索引解析真正会用的,输出里却
  991. // 没有任何标记说明这件事。读错就点到无关元素,且不会报错 —— 那个索引在旧树里合法。
  992. //
  993. // 想看状态就显式 getAXState(),与其它观察方法一致。
  994. //
  995. // 结构化元素视图。Target 的公开观察方法只给字符串,但模型写的是代码,单 cell 内
  996. // 「观察 → 找元素 → 动作」能省一次往返;树被按优先级裁剪(targeting/format.ts 的
  997. // `indices are sparse` 注记)时,它还是模型拿到隐藏元素索引的唯一途径。因此它已被
  998. // 提为**文档化成员**(SKILL 的 Keyboard 段 + docs/computer-use.md 的 API 段),
  999. // 保持 enumerable:false 只是为了不进 Object.keys —— R2 的「Target 附加成员为 0」
  1000. // 说的是冻结的**可枚举**公开面,不是禁止具名逃逸口。
  1001. Object.defineProperty(app, "elements", {
  1002. enumerable: false,
  1003. value: async () => {
  1004. // 与 getScreenshot 同档的静默观察(见 createTarget 的 observe):结果只回给 JS、
  1005. // 不 emit 任何东西,所以两条声明都必须给。
  1006. //
  1007. // Bug 原因(2026-09-16 评审):这里过去两条都没给。
  1008. // 1. 漏 tree_shown_to_model=false ⇒ producer 默认按「模型看过」记账
  1009. // (observation.ts 的 `treeShownToModel !== false`),索引位移台账被一棵模型
  1010. // 没看过的树覆盖,校验退化成当前树跟当前树自比,静默点错元素的保护失效。
  1011. // 2. 这次 capture 还把 Helper 的 diff 基线推到了这棵未展示的树上,而 binding.treeSeen
  1012. // 仍是 true ⇒ 下一次 getAXState 会拿到相对未展示树的增量,SKILL 承诺的
  1013. // 「diff 只相对本 cell 展示过的树」就成了假话。清 treeSeen 让它强制整树。
  1014. const fresh = appStateOf(
  1015. "get_app_state",
  1016. await call("get_app_state", { app_ref: appRef, tree_shown_to_model: false }),
  1017. );
  1018. binding.stateId = fresh.state_id;
  1019. binding.elements = fresh.elements;
  1020. binding.treeSeen = false;
  1021. return fresh.elements;
  1022. },
  1023. });
  1024. return app;
  1025. };
  1026. const inventory = async (options) => {
  1027. const result = await call("list_apps", {});
  1028. assertOk("list_apps", result);
  1029. const apps = [];
  1030. for (const text of textBlocks(result)) {
  1031. const parsed = parseJsonValue(text);
  1032. if (Array.isArray(parsed?.apps)) apps.push(...parsed.apps);
  1033. else if (Array.isArray(parsed)) apps.push(...parsed);
  1034. }
  1035. const state = { apps };
  1036. emitText(globals, JSON.stringify(state, null, 2), options);
  1037. return state;
  1038. };
  1039. // `cua.computer` —— 平台特定逃逸口,暴露额外的平台相关 computer API。
  1040. // 内容是存活的 14 个工具,入参 schema 逐字保留。
  1041. //
  1042. // 返回值**解封**(2026-09-16):此前原样返回 MCP envelope,于是模型拿到的是
  1043. // `{content:[{type:"text",text:"[...]"}],_meta:{…}}`,还得自己 `JSON.parse(r.content[0].text)`。
  1044. // 真机代价(list_windows):4964 字符里有用载荷只 1723(35%),另外 65% 是信封与
  1045. // `_meta` 里的 app 图标 base64(上限 24KiB ⇒ base64 最坏 ~32KiB)。而 `_meta` 按设计
  1046. // 就是**宿主专用**的(target-app-display 设计文档:host-only、"stripped before handlers
  1047. // observe responses"),projectToHost 已经单独把它送给宿主展示 —— 所以泄漏给模型是
  1048. // 契约违规,不是契约选择。连设计文档自己的示例都写成 `wins[1].window_id`(把它当裸数组),
  1049. // 可见"保留信封"从来不是有人依赖的行为;全仓 grep 也确认零消费者。
  1050. const unwrapEnvelope = (result) => {
  1051. if (result === null || typeof result !== "object") return result;
  1052. if (!Array.isArray(result.content)) return result;
  1053. const textBlocks = result.content.filter(
  1054. (block) => block && block.type === "text" && typeof block.text === "string",
  1055. );
  1056. // 只在"单一 text block"这种明确形态上解封;多块 / 图像等一律原样返回,
  1057. // 避免把一个我们不认识的形状猜成裸值。
  1058. if (textBlocks.length !== 1 || result.content.length !== 1) return result;
  1059. const text = textBlocks[0].text;
  1060. try {
  1061. return JSON.parse(text);
  1062. } catch {
  1063. return text;
  1064. }
  1065. };
  1066. const computer = Object.create(null);
  1067. Object.defineProperty(computer, "target", {
  1068. enumerable: true,
  1069. value: platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux",
  1070. });
  1071. const excluded = new Set(PLATFORM_EXCLUDED_METHODS[platform] ?? []);
  1072. for (const methodName of COMPUTER_METHOD_NAMES) {
  1073. if (excluded.has(methodName)) continue;
  1074. Object.defineProperty(computer, methodName, {
  1075. enumerable: true,
  1076. value: async (args = {}) => unwrapEnvelope(await call(methodName, args)),
  1077. });
  1078. }
  1079. const cua = {
  1080. async getState(options) {
  1081. return await inventory(options);
  1082. },
  1083. async getApp(target) {
  1084. return await bindApp(target);
  1085. },
  1086. async listApps(options) {
  1087. return (await inventory(options)).apps;
  1088. },
  1089. computer: Object.freeze(computer),
  1090. async requestAccess(capabilities) {
  1091. const result = await call("request_access", capabilities ? { capabilities } : {});
  1092. assertOk("request_access", result);
  1093. const texts = textBlocks(result);
  1094. return parseJsonRecord(texts[0]) ?? { ready: true };
  1095. },
  1096. async stop(reason) {
  1097. const result = await call("stop_computer_control", reason ? { reason } : {});
  1098. assertOk("stop_computer_control", result);
  1099. },
  1100. };
  1101. // 未文档化成员:窗口绑定。窗口寻址各平台差异很大(有的平台没有窗口寻址,有的整套
  1102. // 以 Window 对象寻址),ZCode 三平台统一命名,不按平台分裂公开面,
  1103. // 所以窗口寻址留在逃逸口 + 这个未文档化入口。
  1104. Object.defineProperty(cua, "getWindow", {
  1105. enumerable: false,
  1106. value: async (target, windowId) => await bindApp(target, windowId),
  1107. });
  1108. // 入口是 `agent.computerUse`(ZCode 自己的命名空间约定,与 agent.documentation /
  1109. // agent.browsers 并列),不注入裸 `cua` 全局。
  1110. // 平铺的 14 个工具在 `agent.computerUse.computer.*` 下(COMPUTER_METHOD_NAMES)。
  1111. const agent = (globals.agent ??= {});
  1112. agent.computerUse = cua;
  1113. const previousDocumentation = agent.documentation;
  1114. const previousGet =
  1115. previousDocumentation && typeof previousDocumentation.get === "function"
  1116. ? previousDocumentation.get.bind(previousDocumentation)
  1117. : undefined;
  1118. agent.documentation = Object.freeze({
  1119. get: async (name) => {
  1120. // Browser Use 的文档 loader 必须原样转交 —— CUA 只认自己那一个名字。
  1121. if (name !== "computer-use") {
  1122. if (previousGet) return await previousGet(name);
  1123. throw new Error(`Unknown documentation entry: ${name}`);
  1124. }
  1125. if (typeof bridge.documentationRoot !== "string") {
  1126. throw new Error("Computer Use documentation is unavailable");
  1127. }
  1128. return await readFile(join(bridge.documentationRoot, "computer-use.md"), "utf8");
  1129. },
  1130. });
  1131. return cua;
  1132. }
  1133. export { COMPUTER_METHOD_NAMES, PLATFORM_EXCLUDED_METHODS, ComputerUseError, normalizeKeyChord };